Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active May 14, 2021 08:36
Show Gist options
  • Save DmitrySoshnikov/2ed1bda2abaff28cb50e3f344ba74bcf to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/2ed1bda2abaff28cb50e3f344ba74bcf to your computer and use it in GitHub Desktop.
calculator.ast.js
/**
* Calculator grammar for a parser in JavaScript.
*
* syntax-cli -g calculator.ast.js -m LALR1 -o CalcParser.js
*
* const CalcParser = require('./CalcParser.js');
* console.log(CalcParser.parse('2 + 2 * 2')); // AST
*/
{
"lex": {
"rules": [
["\\s+", "/* skip whitespace */"],
["\\d+", "return 'NUMBER'"],
["\\*", "return '*'"],
["\\+", "return '+'"],
["\\(", "return '('"],
["\\)", "return ')'"],
]
},
"operators": [
["left", "+"],
["left", "*"],
],
"bnf": {
"E": [
["E + E", "$$ = {type: 'Binary', left: $1, right: $3, op: '+'}"],
["E * E", "$$ = {type: 'Binary', left: $1, right: $3, op: '*'}"],
["NUMBER", "$$ = {type: 'Primary', value: Number($1)}"],
["( E )", "$$ = $2"],
],
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment