| 1 |
/* |
| 2 |
* Simple Arithmetics Grammar |
| 3 |
* ========================== |
| 4 |
* |
| 5 |
* Accepts expressions like "2 * (3 + 4)" and computes their value. |
| 6 |
*/ |
| 7 |
|
| 8 |
Expression |
| 9 |
= head:Term tail:(_ ("+" / "-") _ Term)* { |
| 10 |
var result = head, i; |
| 11 |
|
| 12 |
for (i = 0; i < tail.length; i++) { |
| 13 |
if (tail[i][1] === "+") { result += tail[i][3]; } |
| 14 |
if (tail[i][1] === "-") { result -= tail[i][3]; } |
| 15 |
} |
| 16 |
|
| 17 |
return result; |
| 18 |
} |
| 19 |
|
| 20 |
Term |
| 21 |
= head:Factor tail:(_ ("*" / "/") _ Factor)* { |
| 22 |
var result = head, i; |
| 23 |
|
| 24 |
for (i = 0; i < tail.length; i++) { |
| 25 |
if (tail[i][1] === "*") { result *= tail[i][3]; } |
| 26 |
if (tail[i][1] === "/") { result /= tail[i][3]; } |
| 27 |
} |
| 28 |
|
| 29 |
return result; |
| 30 |
} |
| 31 |
|
| 32 |
Factor |
| 33 |
= "(" _ expr:Expression _ ")" { return expr; } |
| 34 |
/ Integer |
| 35 |
|
| 36 |
Integer "integer" |
| 37 |
= [0-9]+ { return parseInt(text(), 10); } |
| 38 |
|
| 39 |
_ "whitespace" |
| 40 |
= [ \t\n\r]* |