Constructing ASTs with ANTLR Grammars

To learn about ANTLR’s AST construction mechanism, let’s build ASTs for a simple vector math language with addition, multiplication, and dot product.

To design our grammar, we need to look at some sample sentences. Here are some valid vector math statements:

 
x = 1+2
 
y = 1*2+3
 
z = [1, 2] + [3, 4]
 
a = [1, 2] . [3, 4]
 
b = 3 * [1, 2]
 
print x+2

At the coarsest level, that looks like a series of assignment and print statements. We can express that syntax grammatically as follows:

IR/Vec/VecMath.g
 
statlist : stat+ ; ​// match multiple statements
 
stat: ID ​'='​ expr ​// match an assignment like "x=3+4"
 
| ​'print'​ expr ​// match a print statement like "print 4"
 
;

Within the statements, we find various ...

Get Language Implementation Patterns 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.