Created
December 30, 2009 04:41
-
-
Save zaach/265842 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> | |
<title>Test parser from web</title> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> | |
<script src="calc.js"></script> | |
<script> | |
$(function () { | |
$("button").click(function () { | |
var result = calc.parse($("input").val()) | |
$("p").html(result); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<p> | |
<input type="text" /><button>=</button> | |
<span></span> | |
</p> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment