Quick Introduction to ANTLR

Once you know how to build lexers and parsers by hand, it’s a good idea to use a parser generator to make your life easier. This section gets you started using ANTLR[12] and its grammar DSL. (You can skip to the next chapter if you’re already familiar with it.) We’re going to build a simple grammar, run it through ANTLR, and write a test rig to exercise the generated lexer and parser.

Let’s build a grammar for a simple graphics DSL with a single command for drawing lines. Here’s how we’d draw a box 10 units on a side:

parsing/antlr/box
 
line from 0,0 to 0,10
 
line from 0,10 to 10,10
 
line from 10,10 to 10,0
 
line from 10,0 to 0,0

The syntax of the DSL is a list of line commands:

parsing/antlr/Graphics.g
 
grammar​ Graphics; ...

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.