Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active October 23, 2016 04:33
Show Gist options
  • Save DmitrySoshnikov/ab6ed4d41505c579cee9af759e77ead9 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/ab6ed4d41505c579cee9af759e77ead9 to your computer and use it in GitHub Desktop.
Calculator grammar
/**
* Calculator grammar for a parser in Python.
*
* syntax-cli -g calculator.grammar.js -m LALR1 -o calcparser.py
*
* >>> import calcparser
* >>> calcparser.parse('2 + 2 * 2')
* >>> 6
*/
{
"lex": {
"rules": [
["\\s+", "# skip whitespace"],
["\\d+", "return 'NUMBER'"],
["\\*", "return '*'"],
["\\+", "return '+'"],
["\\(", "return '('"],
["\\)", "return ')'"],
]
},
"operators": [
["left", "+"],
["left", "*"],
],
"bnf": {
"E": [
["E + E", "$$ = $1 + $3"],
["E * E", "$$ = $1 * $3"],
["NUMBER", "$$ = int($1)"],
["( E )", "$$ = $2"],
],
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment