pegjs/examples/arithmetics.pegjs

31 lines
781 B
Plaintext
Raw Normal View History

2016-09-17 16:28:28 +02:00
// Simple Arithmetics Grammar
// ==========================
//
// Accepts expressions like "2 * (3 + 4)" and computes their value.
2010-03-07 20:41:02 +01:00
Expression
= head:Term tail:(_ @("+" / "-") _ @Term)* {
return tail.reduce(function(result, element) {
if (element[0] === "+") return result + element[1];
if (element[0] === "-") return result - element[1];
}, head);
}
2010-03-07 20:41:02 +01:00
Term
= head:Factor tail:(_ @("*" / "/") _ @Factor)* {
return tail.reduce(function(result, element) {
if (element[0] === "*") return result * element[1];
if (element[0] === "/") return result / element[1];
}, head);
}
Factor
= "(" _ @Expression _ ")"
/ Integer
Integer "integer"
= _ [0-9]+ { return parseInt(text(), 10); }
_ "whitespace"
= [ \t\n\r]*