ANTLR v3 printable documentation
An inline version of ANTLR v3 documentation.
ANTLR3 Code Generation Targets
Code generation for the following target languages is currently in development, testing or is complete. Visit the page for each target language for more information - hopefully the persons dealing with each target language will update their respective rows in this table with their current status.
See also Target API documentation and How to build an ANTLR code generation target.
Language | Irresponsible Person | Status |
|---|---|---|
Luke A. Guest | Currently dormant. | |
George Scott (initial port, not actively maintaining) | In sync up to 3.2, but currently not in active development. | |
Jim Idle | In sync with ANTLR3 development. Use the .tgz files under the | |
Gokulakannan Somasundaram (was Jim Idle & Ric Klaren) | Created on antlr-3.4 and hence in sync with only antlr-3.4 | |
Maintainer: Johannes Luber | In sync with ANTLR3 Development to 3.3, but a few errors make it beta for 3.3. There are separate targets for .NET 1.1 and .NET 2. | |
Maintainer: Sam Harwell | (Added post-release 3.1.3) In sync with ANTLR3 Development, except no support for the | |
? | ? | |
Ola Bini | He's working on this at the moment; http://github.com/olabini/antlr-elisp | |
Alan Condit, Kay Roepke | Current with 3.3 version. | |
Terence (parrt at cs usfca edu) | In sync with ANTLR3 Development | |
Joey Hurst | In sync with ANTLR3 Development | |
Benjamin Niemann | Current with 3.1.3 | |
Kyle Yetter, previously Martin Traverso | Current with 3.3 | |
Bernhard Schmalhofer Bernhard.Schmalhofer@gmx.de | Inactive. No code produced yet. Takers wanted. | |
Ron Blaschke ron at rblasch.org | Early prototyping. Simple lexer is working. | |
Sidharth Kuruvila, Yauhen Yakimovich, Geoff Speicher, Rolland Brunec | Primary milstone is aimed at verification of Lexer, Parser generation. The work towards implementation of StringTemplate is in progress | |
Dominik Holenstein | Planning and analyzing. First version expected for | |
Matthew Lloyd |
|
Command line options
Usage:
java org.antlr.Tool [args] file.g [file2.g file3.g ...]
Option | description |
|---|---|
-o outputDir | specify output directory where all output is generated; search for token vocabularies in here also |
-fo outputDir | same as -o but force even files with relative paths to dir |
-depend | generate file dependencies; don't actually run antlr |
-lib dir | specify location of token files and important grammars |
-report | print out a report about the grammar(s) processed |
print out the grammar without actions | |
-trace | generate a parser with trace output - if the default output is not enough, you can override the traceIn and traceOut methods |
-debug | generate a parser that emits debugging events |
-profile | generate a parser that computes profiling information |
-nfa | generate an NFA for each rule |
-dfa | generate a DFA for each decision point |
-message-format name | specify output style for messages |
-X | display extended option list |
There are a bunch of less often used "extended" options as well.
Extended option | description |
|---|---|
-Xgrtree | print the grammar AST |
-Xdfa | print DFA as text |
-Xnoprune | do not test EBNF block exit branches |
-Xnocollapse | collapse incident edges into DFA states |
-Xdbgconversion | dump lots of info during NFA conversion |
-Xmultithreaded | run the analysis in 2 threads |
-Xnomergestopstates | do not merge stop states |
-Xdfaverbose | generate DFA states in DOT with NFA configs |
-Xwatchconversion | print a message for each NFA before converting |
-XdbgST | put tags at start/stop of all templates in output |
-Xm m | max number of rule invocations during conversion |
-Xmaxdfaedges m | max "comfortable" number of edges for single DFA state |
-Xconversiontimeout t | set NFA conversion timeout for each decision |
-Xmaxinlinedfastates m | max DFA states before table used rather than inlining |
-Xnfastates | for nondeterminisms, list NFA states for each path |
Attribute and Dynamic Scopes
Token attributes
attribute | description |
|---|---|
text |
|
type |
|
line |
|
index |
|
pos |
|
channel |
|
tree |
|
int |
|
Rule attributes
Parsers
attribute | description |
|---|---|
text |
|
start |
|
stop |
|
tree |
|
st |
|
Tree parsers
attribute | description |
|---|---|
text |
|
start |
|
tree |
|
st |
|
Lexers
attribute | description |
|---|---|
text |
|
type |
|
line |
|
index |
|
pos |
|
channel |
|
start |
|
stop |
|
int |
|
The Rule text Attribute in Tree Grammars
In a parser grammar, the relationship between the elements matched by a rule and the associated input text is very clear. A rule begins parsing at a particular token and stops parsing at a particular token. The text attribute for a rule, $text, is simply the concatenated text from all tokens in that range, including hidden channel tokens. What does $text mean in a tree grammar, though?
Tree grammar rules match nodes and trees not tokens. Fortunately, each node has an associated token start and stop index (See TreeAdaptor). As the parser builds trees, each rule sets the token indexes for its return AST to the start and stop token of that rule. We can then define the text attribute for a tree grammar rule to be the text concatenated from the range of tokens indicated by the range in the root of the first tree matched by the rule. This rule may seem strange, but is the most efficient implementation and works in almost all situations. Here are a few examples:
/** match tree created from, e.g., "int x;"
* $text would, therefore, be "int x;"
* $start node is VAR node.
*/
variable
: ^(VAR type ID) // $text derived from indexes in VAR node
;
/** match tree node created from, e.g., "int"
* $text would, therefore, be "int"
* $start node is 'int' node.
*/
type: 'int' // $text derived from indexes in 'int' node
| 'void'
;
The following code embodies the text attribute definition. The token range from a rule's start node defines the range of text for the entire rule.
// input is a TreeNodeStream implementation
int start = input.getTreeAdaptor().getTokenStartIndex($start);
int stop = input.getTreeAdaptor().getTokenStopIndex($start);
String text = input.getTokenStream().toString(start, stop);
Be careful when referencing the text of a rule that happens to be the root of a tree. The text of a rule is the text of all tokens underneath the first rout matched by the rule. In the following example, rule @r op matches a single node, but $op.text will include the text associated with the two operands as well. The parser that build the plus and multiply operator nodes will set the token range to include all tokens for that expression.
/** match subtrees for + and * created from input such as "1+4*2"
* $text and $op.text is "1+4*2" for first alternative.
* $text is just the INT node for second alternative.
*/
expr: ^(op expr expr) ; // $op.text is same as $text!
| INT
;
op : o='+' | o='*' // $text includes text of operands
; // $o.text is just node's text
Note that the text for a node label is always just the string returned from getText() invoked on that node whereas the text for a rule reference is always the text for the tree rooted at that labeled node.
Finally, here is the case where the definition of the text attribute does not do what you expect. The text attribute is derived from the first node matched by a rule, but a rule such as rule slist that matches multiple subtrees has an ill-defined text attribute because it only gives you the text for the first statement subtree:
func: 'void' ID '()' slist ; // $slist.text is text from first tree only
slist: stat+ ;
In general, you just need to keep this in mind--the text attribute is natural in most cases.
Rule scopes
Global shared scopes
Lexical filters
ANTLR has a lexical filter mode that lets you sift through an input file looking for certain grammatical structures. The rules are prioritized in the order specified in case an input construct matches more than a single rule, with the first rule having the highest priority. The filter proceeds character-by-character looking for a match among the rules. If no match, consume that char and try again. The following example, prints found var foo for every field foo in the input:
lexer grammar FuzzyJava;
options {filter=true;}
FIELD
: TYPE WS name=ID '[]'? WS? (';'|'=')
{System.out.println("found var "+$name.text);}
;
fragment
TYPE : ID ('.' ID)*
;
fragment
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
;
WS : (' '|'\t'|'\n')+
;
Don't forget that you must ignore text in comments, so add another rule:
COMMENT
: '/*' (options {greedy=false;} : . )* '*/'
{System.out.println("found comment "+getText());}
;
Grammars
Grammar syntax
All grammars are of the form:
/** This is a grammar doc comment */
grammar-type grammar name;
options { name1 = value; name2 = value2; ... }
import delegateName1=grammar1, ..., delegateNameN=grammarN; // can omit delegateName
tokens { token-name1; token-name2 = value; ... }
scope global-scope-name-1 { «attribute-definitions» }
scope global-scope-name-2 { «attribute-definitions» }
...
@header { ... }
@lexer::header { ... }
@members { ... }
«rules»
The type of the grammar, specified via the grammar-type modifier above, can be one of: lexer, parser, tree, and combined (no modifier). To set the superclass of the generated parser class, use the superClass option. See Grammar options for a list of valid grammar options and their semantics.
Rule syntax
/** rule comment */
access-modifier rule-name[«arguments»] returns [«return-values»] throws name1, name2, ...
options {...}
scope {...}
scope global-scope-name, ..., global-scope-nameN;
@init {...}
@after {...}
: «alternative-1» -> «rewrite-rule-1»
| «alternative-2» -> «rewrite-rule-2»
...
| «alternative-n» -> «rewrite-rule-n»
;
catch [«exception-arg-1»] {...}
catch [«exception-arg-2»] {...}
finally {...}
See Rule and subrule options for a list of valid rule options and their semantics.
Lexer, Parser and Tree Parser rules
Rules in a grammar are special cases of identifier names. Lexer rules must start with an upper case letter, parser and tree parser rules must start with a lower case letter.
LexerRuleName : ('A'..'Z') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ;
ParserRuleName : ('a'..'z') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ;
TreeParserRuleName : ('a'..'z') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* ;Here are some common lexical rules for programming languages:
WS : (' '|'\r'|'\t'|'\u000C'|'\n') {$channel=HIDDEN;}
;
COMMENT
: '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;}
;
LINE_COMMENT
: '//' ~('\n'|'\r')* '\r'? '\n' {$channel=HIDDEN;}
;The $channel=HIDDEN; action places those tokens on a hidden channel. They are still sent to the parser, but the parser does not see them. Actions, however, can ask for the hidden channel tokens. If you want to literally throw out tokens then use action skip(); (see org.antlr.runtime.Lexer.skip()).
Sometimes you will need some help or rules to make your lexer grammar more readable. Use the fragment modifier in front of the rule:
HexLiteral : '0' ('x'|'X') HexDigit+ ;
fragment HexDigit : ('0'..'9'|'a'..'f'|'A'..'F') ;
In this case, HexDigit is not a token in its own right; it can only be called from HexLiteral.
Warning: T__ is considered a reserved token name and token name prefix. please don't use it as one of your rule names.
Tree grammar rules
Rules in tree grammars are identical to parser grammars except that they can specify a tree element to match. The syntax is ^( root child1 child2 ... childn ). For example:
decl : ^(DECL type declarator) {System.out.println($type.text+" "+$declarator.text);}
;
Attribute scope syntax
Attribute scopes are a set of attribute definitions of the form:
scope name {
type1 attribute-name1;
type2 attribute-name2;
}
Grammar action syntax
Grammar actions are, in general, of the form:
@action-name { ... }
@scope-name::action-name { ... }
The default scope-name is parser. For instance, @header is the same as @parser::header. Valid scope-name 's differ depending on the target, but most targets should support parser and lexer. Two common action-name 's are header and members. The header action is placed at the top of a generated class definition and the members action is inserted within the body of a generated class definition. For example, the following grammar actions would ensure generated parser and lexer Java classes include a package declaration:
@parser::header { package my.example.package; }
@lexer::header { package my.example.package; }
Rule elements
Rules may reference:
Element | Description |
|---|---|
T | Token reference. An uppercase identifier; lexer grammars may use optional arguments for fragment token rules. |
T<node=V> or T<V> | Token reference with the optional token option |
T[«args»] | Lexer rule (token rule) reference. Lexer grammars may use optional arguments for fragment token rules. |
r [«args»] | Rule reference. A lowercase identifier with optional arguments. |
'«one-or-more-char»' | String or char literal in single quotes. In parser, a token reference; in lexer, match that string. |
{«action»} | An action written in target language. Executed right after previous element and right before next element. |
{«action»}? | Semantic predicate. |
{«action»}?=> | Gated semantic predicate. |
(«subrule»)=> | Syntactic predicate. |
(«x»|«y»|«z») | Subrule. Like a call to a rule with no name. |
(«x»|«y»|«z»)? | Optional subrule. |
(«x»|«y»|«z»)* | Zero-or-more subrule. |
(«x»|«y»|«z»)+ | One-or-more subrule. |
«x»? | Optional element. |
«x»* | Zero-or-more element. |
«x»+ | One-or-more element. |
Grammar options
Taken from /org/antlr/tool/Grammar.java all allowed options are
Option | Description |
|---|---|
| The target language for code generation. Default is |
| Where ANTLR should get predefined tokens and token types. Tree grammars need it to get the token types from the parser that creates its trees. TODO: Default value? Example? |
| The type of output the generated parser should return. Valid values are |
| Set the type of all tree labels and tree-valued expressions. Without this option, trees are of type |
| Set the type of all token-valued expressions. Without this option, tokens are of type org.antlr.runtime.Token in Java ( |
| Set the superclass of the generated recognizer. TODO: Default value (org.antlr.runtime.Parser in Java)? |
| In the lexer, this allows you to try a list of lexer rules in order. The first one that matches, wins. This is the token that |
| Valid values are |
| Limit the lookahead depth for the recognizer to at most |
| Valid values are |
| Valid values are |