Building a Calculator with Grammar Actions

Let’s revisit the expression grammar from ​Building a Calculator Using a Visitor​ to learn about actions. In that section, we built a calculator using a tree visitor that evaluated expressions such as the following:

​ x = 1
​ x
​ x+2*3

Our goal here is to reproduce that same functionality, but without using a visitor and without even building a parse tree. Moreover, we’ll employ a little trick to make it interactive, meaning we get results when we hit Return, not at the end of the input. Our examples so far have scarfed up the entire input and then processed the resulting parse trees.

As we go through this section, we’re going to learn how to put generated parsers into ...

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.