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

Grammar Structure

A grammar is essentially a grammar declaration followed by a list of rules but has the following general form:

 
/** Optional Javadoc-style comment */
​ 
grammar​ Name;
 
options​ {...}
 
import​ ... ;
 
tokens​ {...}
 
@actionName​ {...}
 
 
rule1 ​// parser and lexer rules, possibly intermingled
 
...
 
ruleN

The filename containing grammar X must be called Xg4. You can specify options, imports, token specifications, and actions in any order. There can be at most one each of options, imports, and token specifications. All of those elements are optional except for the header ​​ and at least one rule. Rules take the following basic form:

 
ruleName : alternative1 | ... | alternativeN ;

Parser rule names must start with ...

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