Skip to Main Content
Language Implementation Patterns
book

Language Implementation Patterns

by Terence Parr
December 2009
Intermediate to advanced content levelIntermediate to advanced
380 pages
9h 2m
English
Pragmatic Bookshelf
Content preview from Language Implementation Patterns

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Implementation Patterns

Implementation Patterns

Kent Beck

Publisher Resources

ISBN: 9781680500097Errata Page