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
|
2018-09-18 08:27:21 +02:00
|
|
|
= head:Term tail:(_ @("+" / "-") _ @Term)* {
|
2018-09-25 18:59:38 +02:00
|
|
|
return tail.reduce(function(result, element) {
|
|
|
|
if (element[0] === "+") return result + element[1];
|
|
|
|
if (element[0] === "-") return result - element[1];
|
2016-09-01 13:55:41 +02:00
|
|
|
}, 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
|
2018-09-18 08:27:21 +02:00
|
|
|
= head:Factor tail:(_ @("*" / "/") _ @Factor)* {
|
2018-09-25 18:59:38 +02:00
|
|
|
return tail.reduce(function(result, element) {
|
|
|
|
if (element[0] === "*") return result * element[1];
|
|
|
|
if (element[0] === "/") return result / element[1];
|
2016-09-01 13:55:41 +02:00
|
|
|
}, head);
|
2014-03-12 19:05:26 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
Factor
|
2018-09-18 08:27:21 +02:00
|
|
|
= "(" _ @Expression _ ")"
|
2014-03-12 19:05:26 +01:00
|
|
|
/ 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]*
|