A Parade of Errors

The best way to describe ANTLR’s error recovery strategy is to watch an ANTLR-generated parser respond to erroneous input. Let’s look at a grammar for a simple Java-like language containing class definitions with field and method members. The methods have simple statements and expressions. We’ll use it as the core of the examples in this section and the remainder of the chapter.

​ ​grammar​ Simple​;​
​ 
​ prog​:​ classDef​+​ ​;​ ​// match one or more class definitions​
​ 
​ classDef
​  ​:​ ​'class'​ ID ​'{'​ member​+​ ​'}'​ ​// a class has one or more members​
​  ​{​System​.​out​.​println​(​​"class "​​+$​ID​.​text​ ...

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.