O'Reilly logo

The Definitive ANTLR 4 Reference, 2nd Edition by Terence Parr

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Parser Rules

Parsers consist of a set of parser rules in either a parser or a combined grammar. A Java application launches a parser by invoking the rule function, generated by ANTLR, associated with the desired start rule. The most basic rule is just a rule name followed by a single alternative terminated with a semicolon.

 
/** Javadoc comment can precede rule */
 
retstat : ​'return'​ expr ​';'​ ;

Rules can also have alternatives separated by the | operator.

 
stat: retstat
 
| ​'break'​ ​';'
 
| ​'continue'​ ​';'
 
;

Alternatives are either a list of rule elements or empty. For example, here’s a rule with an empty alternative that makes the entire rule optional:

 
superClass
 
: ​'extends'​ ID
 
| ​// empty means other alternative(s) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required