4 ms·
Have you tried Parsing Expression Grammars (PEGs)? Most implementations allow use to name arbitrary sub-parsers, often using the programming language's native v
by jnbiche 7y ago
Have you tried Parsing Expression Grammars (PEGs)? Most implementations allow use to name arbitrary sub-parsers, often using the programming language's native variables.
See for example Peg.js, LPEG (lua), etc. However, PEGs don't natively permit left recursion (note: some PEG implementations do add that on). If that's a problem, Earley parsers are a nice alternative.
Example of a calculator using Peg.js:
start
= additive
additive
= left:multiplicative "+" right:additive { return left + right; }
/ 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); }