public
Created

  • Download Gist
calc.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<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>
generatecalc.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
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();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.