You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

30 lines
781 B

11 years ago
11 years ago
  1. // Simple Arithmetics Grammar
  2. // ==========================
  3. //
  4. // Accepts expressions like "2 * (3 + 4)" and computes their value.
  5. Expression
  6. = head:Term tail:(_ @("+" / "-") _ @Term)* {
  7. return tail.reduce(function(result, element) {
  8. if (element[0] === "+") return result + element[1];
  9. if (element[0] === "-") return result - element[1];
  10. }, head);
  11. }
  12. Term
  13. = head:Factor tail:(_ @("*" / "/") _ @Factor)* {
  14. return tail.reduce(function(result, element) {
  15. if (element[0] === "*") return result * element[1];
  16. if (element[0] === "/") return result / element[1];
  17. }, head);
  18. }
  19. Factor
  20. = "(" _ @Expression _ ")"
  21. / Integer
  22. Integer "integer"
  23. = _ [0-9]+ { return parseInt(text(), 10); }
  24. _ "whitespace"
  25. = [ \t\n\r]*