Currently, our parser interprets the input code and evaluates it in the same pass. Most compilers and interpreters; however, create an intermediate data structure before actually running the program: an Abstract Syntax Tree (AST). Using an AST offers some interesting possibilities; for example, it provides you with a structured representation of your program that you can then analyze. Also, you can use the AST and transform it back into a text-based program (maybe of another language).
An AST is a tree that represents the structure of a program. The first step to building an AST-based parser is to design the tree's object model: which classes are needed and in which way are they associated to another. The following figure shows the first draft for an object model that can be used to describe mathematical expressions:
In this model, nearly all classes implement the Expression
interface. This interface...