January 2013
Intermediate to advanced
328 pages
8h 5m
English
For our first grammar, we’re going to build a simple calculator. Doing something with expressions makes sense because they’re so common. To keep things simple, we’ll allow only the basic arithmetic operators (add, subtract, multiply, and divide), parenthesized expressions, integer numbers, and variables. We’ll also restrict ourselves to integers instead of allowing floating-point numbers.
Here’s some sample input that illustrates all language features:
| | 193 |
| | a = 5 |
| | b = 6 |
| | a+b*2 |
| | (1+2)*3 |
In English, a program in our expression language is a sequence of statements terminated by newlines. A statement is either an expression, an assignment, or a blank line. Here’s an ANTLR grammar that’ll parse ...
Read now
Unlock full access