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
|
|
|
|
2014-03-12 19:05:26 +01:00
|
|
|
Expression
|
2015-10-09 17:09:33 +02:00
|
|
|
= head:Term tail:(_ ("+" / "-") _ Term)* {
|
2016-09-01 13:55:41 +02:00
|
|
|
return tail.reduce(function(result, element) {
|
|
|
|
if (element[1] === "+") { return result + element[3]; }
|
|
|
|
if (element[1] === "-") { return result - element[3]; }
|
|
|
|
}, head);
|
2014-03-12 19:05:26 +01:00
|
|
|
}
|
2010-03-07 20:41:02 +01:00
|
|
|
|
2014-03-12 19:05:26 +01:00
|
|
|
Term
|
2015-10-09 17:09:33 +02:00
|
|
|
= head:Factor tail:(_ ("*" / "/") _ Factor)* {
|
2016-09-01 13:55:41 +02:00
|
|
|
return tail.reduce(function(result, element) {
|
|
|
|
if (element[1] === "*") { return result * element[3]; }
|
|
|
|
if (element[1] === "/") { return result / element[3]; }
|
|
|
|
}, head);
|
2014-03-12 19:05:26 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
Factor
|
|
|
|
= "(" _ expr:Expression _ ")" { return expr; }
|
|
|
|
/ Integer
|
|
|
|
|
|
|
|
Integer "integer"
|
2017-03-20 16:39:57 +01:00
|
|
|
= _ [0-9]+ { return parseInt(text(), 10); }
|
2015-08-28 14:01:30 +02:00
|
|
|
|
2014-04-21 10:23:42 +02:00
|
|
|
_ "whitespace"
|
|
|
|
= [ \t\n\r]*
|