Created
September 7, 2010 17:09
-
-
Save fitzgen/568682 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 FILE = require("file"); | |
| require.paths.unshift(FILE.join(FILE.dirname(module.path), | |
| "jsmacros/vendor/jison/lib")); | |
| var Parser = require("jison").Parser; | |
| require.paths.shift(); | |
| var grammar = { | |
| lex: { | |
| rules: [ | |
| ["\\s+", "/* skip whitespace */"], | |
| ["\\d+", "return 'NUMBER'"], | |
| ["\\+", "return '+'"], | |
| ["$", "return 'EOF'"] | |
| ] | |
| }, | |
| operators: [ | |
| ["left", "+"] | |
| ], | |
| bnf: { | |
| expressions: [ | |
| ["e EOF", "return $1"] | |
| ], | |
| e: [ | |
| ["e + e", "$$ = '' + $1 + $2 + $3"], | |
| ["NUMBER", "$$ = new Number($1)"] | |
| ] | |
| } | |
| }; | |
| exports.generateParser = function () { | |
| return new Parser(grammar); | |
| }; | |
| exports.parse = function (code) { | |
| return exports.generateParser().parse(code); | |
| }; | |
| exports.addExpression = function (pattern, rule, pos) { | |
| pos = pos || grammar.bnf.e.length; | |
| grammar.bnf.e.splice.apply(grammar.bnf.e, [pos, 0, [pattern, rule]]); | |
| }; | |
| exports.addLex = function (pattern, rule) { | |
| grammar.lex.rules.push([pattern, rule]); | |
| }; | |
| exports.addOp = function (direction, op, pos) { | |
| pos = pos || grammar.operators.length; | |
| var opRule; | |
| if ( (opRule = grammar.operators[pos]) && opRule[0] === direction ) { | |
| opRule.push(op); | |
| } else { | |
| grammar.operators.splice.apply(grammar.operators, [pos, 0, [direction, op]]); | |
| } | |
| }; | |
| print(exports.parse("9 + 3")); | |
| exports.addOp("left", "-", 0); | |
| exports.addLex("\\-", "return '-'"); | |
| exports.addExpression("e - e", "$$ = '' + $1 + $2 + $3", 1); | |
| print(exports.parse("9 - 3")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment