Mercurial > jsparser
diff parser-demo.js @ 10:8de776b8ed31
made the demo work on the web instead of the command line.
author | Atul Varma <varmaa@toolness.com> |
---|---|
date | Sat, 30 May 2009 16:08:25 -0700 |
parents | |
children | 49145e1db3e5 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parser-demo.js Sat May 30 16:08:25 2009 -0700 @@ -0,0 +1,68 @@ +var MyLexicon = [ + new Parsing.BinaryOrUnaryOp({name: 'plus', + match: '+', + leftBindingPower: 60}), + + new Parsing.BinaryOrUnaryOp({name: 'minus', + match: '-', + leftBindingPower: 60}), + + new Parsing.Symbol({name: 'left parenthesis', + match: '(', + nullDenotation: function(parser) { + var contents = parser.expression(0); + parser.advance('right parenthesis'); + return contents; + }}), + + new Parsing.Symbol({name: 'right parenthesis', + match: ')'}), + + new Parsing.BinaryOp({name: 'multiply', + match: '*', + leftBindingPower: 70}), + + new Parsing.BinaryOp({name: 'divide', + match: '/', + leftBindingPower: 70}), + + new Parsing.Symbol({name: 'number', + match: /^[0-9]+/, + nullDenotation: function() { + return this; + }, + toString: function() { + return this.value; + }}), + + new Parsing.Symbol({name: 'whitespace', + match: /^\s+/, + ignore: true}) +]; + +$(window).ready( + function() { + function print(text) { + var node = document.createTextNode(text.toString() + '\n'); + $('.output').append(node); + } + + var code = $('.input').text(); + var tokens = Parsing.tokenize({lexicon: MyLexicon, + text: code}); + + function printTokens(tokens) { + tokens.forEach( + function(token) { + var repr = token.name; + if (token.value) + repr += ":" + token.value; + repr += " @L" + token.lineNo + ":" + token.charNo; + print(repr); + }); + } + + printTokens(tokens); + var parser = new Parsing.Parser(tokens); + print(parser.parse()); + });