aboutsummaryrefslogtreecommitdiff
path: root/examples/expr.g
diff options
context:
space:
mode:
Diffstat (limited to 'examples/expr.g')
-rw-r--r--examples/expr.g21
1 files changed, 21 insertions, 0 deletions
diff --git a/examples/expr.g b/examples/expr.g
new file mode 100644
index 0000000..ae807b7
--- /dev/null
+++ b/examples/expr.g
@@ -0,0 +1,21 @@
+parser Calculator:
+ token END: "$"
+ token NUM: "[0-9]+"
+
+ rule goal: expr END {{ return expr }}
+
+ # An expression is the sum and difference of factors
+ rule expr: factor {{ v = factor }}
+ ( "[+]" factor {{ v = v+factor }}
+ | "-" factor {{ v = v-factor }}
+ )* {{ return v }}
+
+ # A factor is the product and division of terms
+ rule factor: term {{ v = term }}
+ ( "[*]" term {{ v = v*term }}
+ | "/" term {{ v = v/term }}
+ )* {{ return v }}
+
+ # A term is either a number or an expression surrounded by parentheses
+ rule term: NUM {{ return atoi(NUM) }}
+ | "\\(" expr "\\)" {{ return expr }}