Skip to content

Instantly share code, notes, and snippets.

@alexstrat
Created April 25, 2012 22:03
Show Gist options
  • Save alexstrat/2493871 to your computer and use it in GitHub Desktop.
Save alexstrat/2493871 to your computer and use it in GitHub Desktop.
/*
* Classic example grammar, which recognizes simple arithmetic expressions like
* "2*(3+4)". The parser generated from this grammar then computes their value.
*/
start
= additive
additive
= left:multiplicative tail:(additive_op multiplicative)* { return tail.reduce(function(n,t){return t[0](n,t[1])},left); }
/ multiplicative
multiplicative
= left:primary "*" right:multiplicative { return left * right; }
/ primary
primary
= integer
/ "(" additive:additive ")" { return additive; }
integer "integer"
= digits:[0-9]+ { return parseInt(digits.join(""), 10); }
additive_op
= "+" { return function(a,b){return a+b;}; }
/ "-" { return function(a,b){return a-b;}; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment