Instantly share code, notes, and snippets.

# zaach/calc.html Created Dec 30, 2009

What would you like to do?
 Test parser from web

 var Parser = require("jison").Parser; var system = require("system"); var fs = require("file"); var grammar = { "comment": "Parses end executes mathematical expressions.", "lex": { "rules": [ ["\\s+", "/* skip whitespace */"], ["[0-9]+(?:\\.[0-9]+)?\\b", "return 'NUMBER';"], ["\\*", "return '*';"], ["\\/", "return '/';"], ["-", "return '-';"], ["\\+", "return '+';"], ["\\^", "return '^';"], ["\\(", "return '(';"], ["\\)", "return ')';"], ["PI\\b", "return 'PI';"], ["E\\b", "return 'E';"], ["\$", "return 'EOF';"] ] }, "operators": [ ["left", "+", "-"], ["left", "*", "/"], ["left", "^"], ["left", "UMINUS"] ], "bnf": { "S" :[[ "e EOF", "return \$1;" ]], "e" :[[ "e + e", "\$\$ = \$1+\$3;" ], [ "e - e", "\$\$ = \$1-\$3;" ], [ "e * e", "\$\$ = \$1*\$3;" ], [ "e / e", "\$\$ = \$1/\$3;" ], [ "e ^ e", "\$\$ = Math.pow(\$1, \$3);" ], [ "- e", "\$\$ = -\$2;", {"prec": "UMINUS"} ], [ "( e )", "\$\$ = \$2;" ], [ "NUMBER", "\$\$ = Number(yytext);" ], [ "E", "\$\$ = Math.E;" ], [ "PI", "\$\$ = Math.PI;" ]] } }; var parser = new Parser(grammar), source = parser.generate({moduleName: "calc"}), stream = fs.path(fs.cwd()).join("calc.js").open("w"); stream.print(source).close();