pegjs/examples/arithmetics.pegjs
David Majda f5443d2bf1 Complete rewrite of the arithmetics example grammar
This is a complete rewrite of the arithmetics example grammar. It now
allows whitespace between tokens, supports "-" and "/" operators, and
gets the operator associativity right. Also, rule names now match the usual
conventions (term, factor,...).

Beside this, the rewrite reflects how I write grammars today (as opposed
to few years ago) and what style I would recommend to others.
2014-03-12 20:55:04 +01:00

45 lines
967 B
JavaScript

/*
* Simple Arithmetics Grammar
* ==========================
*
* Accepts expressions like "2 * (3 + 4)" and computes their value.
*/
{
function combine(first, rest, combiners) {
var result = first, i;
for (i = 0; i < rest.length; i++) {
result = combiners[rest[i][1]](result, rest[i][3]);
}
return result;
}
}
Expression
= first:Term rest:(_ ("+" / "-") _ Term)* {
return combine(first, rest, {
"+": function(left, right) { return left + right; },
"-": function(left, right) { return left - right; }
});
}
Term
= first:Factor rest:(_ ("*" / "/") _ Factor)* {
return combine(first, rest, {
"*": function(left, right) { return left * right; },
"/": function(left, right) { return left / right; }
});
}
Factor
= "(" _ expr:Expression _ ")" { return expr; }
/ Integer
Integer "integer"
= [0-9]+ { return parseInt(text(), 10); }
_ = "whitespace"
[ \t\n\r]*