Matching an Arithmetic Expression Language

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 ...

Get The Definitive ANTLR 4 Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.