Java Runtime Model


Programmer's Interface

In this section, we describe what ANTLR generates after reading your grammar file and how to use that output to parse input. The classes from which your lexer, token, and parser classes are derived are provided as well.

What ANTLR generates

ANTLR generates the following types of files, where MyParser, MyLexer, and MyTreeParser are names of grammar classes specified in the grammar file. You may have an arbitrary number of parsers, lexers, and tree-parsers per grammar file; a separate class file will be generated for each. In addition, token type files will be generated containing the token vocabularies used in the parsers and lexers. One or more token vocabularies may be defined in a grammar file, and shared between different grammars. For example, given the grammar file:

class MyParser extends Parser;
options {
  exportVocab=My;
}
... rules ...

class MyLexer extends Lexer;
options {
  exportVocab=My;
}
... rules ...

class MyTreeParser extends TreeParser;
options {
  exportVocab=My;
}
... rules ...

The following files will be generated:

The programmer uses the classes by referring to them:

  1. Create a lexical analyzer. The constructor with no arguments implies that you want to read from standard input.
  2. Create a parser and attach it to the lexer (or other TokenStream).
  3. Call one of the methods in the parser to begin parsing.

If your parser generates an AST, then get the AST value, create a tree-parser, and invoke one of the tree-parser rules using the AST.

MyLexer lex = new MyLexer();
MyParser p =
  new MyParser(lex,user-defined-args-if-any);
p.start-rule();
// and, if you are tree parsing the result...
MyTreeParser tp = new MyTreeParser();
tp.start-rule(p.getAST());

You can also specify the name of the token and/or AST objects that you want the lexer/parser to create. Java's support of dynamic programming makes this quite painless:

MyLexer lex = new MyLexer();
lex.setTokenObjectClass("mypackage.MyToken");
  // defaults to "antlr.CommonToken"
...
parser.setASTNodeClass("mypackage.MyASTNode");
  // defaults to "antlr.CommonAST"

Make sure you give a fully-qualified class name.

The lexer and parser can cause IOExceptions as well as RecognitionExceptions, which you must catch:

  CalcLexer lexer =
    new CalcLexer(new DataInputStream(System.in));
  CalcParser parser = new CalcParser(lexer);
  // Parse the input expression
  try {
    parser.expr();
  }
  catch (IOException io) {
    System.err.println("IOException");
  }
  catch(RecognitionException e) {
    System.err.println("exception: "+e);
  }

Multiple Lexers/Parsers With Shared Input State

Occasionally, you will want two parsers or two lexers to share input state; that is, you will want them to pull input from the same source token stream or character stream.   The section on multiple lexer "states" describes such a situation.

ANTLR factors the input variables such as line number, guessing state, input stream, etc... into a separate object so that another lexer or parser could same that state.  The LexerSharedInputState and ParserSharedInputState embody this factoring.   Method getInputState() can be used on either CharScanner or Parser objects.  Here is how to construct two lexers sharing the same input stream:

// create Java lexer
JavaLexer mainLexer = new JavaLexer(input);
// create javadoc lexer; attach to shared
// input state of java lexer
JavaDocLexer doclexer =
  new JavaDocLexer(mainLexer.getInputState());

Parsers with shared input state can be created similarly:

JavaDocParser jdocparser =
  new JavaDocParser(getInputState());
jdocparser.content(); // go parse the comment

Sharing state is easy, but what happens upon exception during the execution of the "subparser"?  What about syntactic predicate execution?  It turns out that invoking a subparser with the same input state is exactly the same as calling another rule in the same parser as far as error handling and syntactic predicate guessing are concerned.  If the parser is guessing before the call to the subparser, the subparser must continue guessing, right?  Exceptions thrown inside the subparser must exit the subparser and return to enclosing erro handler or syntactic predicate handler.

Parser Implementation

Parser Class

ANTLR generates a parser class (an extension of LLkParser) that contains a method for every rule in your grammar. The general format looks like:

public class MyParser extends LLkParser
    implements MyLexerTokenTypes
{
  protected P(TokenBuffer tokenBuf, int k) {
    super(tokenBuf,k);
    tokenNames = _tokenNames;
  }
  public P(TokenBuffer tokenBuf) {  
    this(tokenBuf,1);
  }
  protected P(TokenStream lexer, int k) {
    super(lexer,k);
    tokenNames = _tokenNames;       
  }
  public P(TokenStream lexer) {  
    this(lexer,1);
  }
  public P(ParserSharedInputState state) {
    super(state,1);
    tokenNames = _tokenNames;
  }
  ...
  // add your own constructors here...
  rule-definitions
}
  

Parser Methods

ANTLR generates recursive-descent parsers, therefore, every rule in the grammar will result in a method that applies the specified grammatical structure to the input token stream. The general form of a parser method looks like:

public void rule()
  throws RecognitionException,
         TokenStreamException
{
  init-action-if-present
  if ( lookahead-predicts-production-1 ) {
     code-to-match-production-1
  }
  else if ( lookahead-predicts-production-2 ) {
     code-to-match-production-2
  }
  ...
  else if ( lookahead-predicts-production-n ) {
     code-to-match-production-n
  }
  else {
    // syntax error
    throw new NoViableAltException(LT(1));
  }
}
  This code results from a rule of the form:  
rule:   production-1
    |   production-2
   ...
    |   production-n
    ;
  

If you have specified arguments and a return type for the rule, the method header changes to:

/* generated from:
 *    rule(user-defined-args)
 *      returns return-type : ... ;
 */
public return-type rule(user-defined-args)
  throws RecognitionException,
         TokenStreamException
{
  ...
}
  

Token types are integers and we make heavy use of bit sets and range comparisons to avoid excessively-long test expressions.

EBNF Subrules

Subrules are like unlabeled rules, consequently, the code generated for an EBNF subrule mirrors that generated for a rule. The only difference is induced by the EBNF subrule operators that imply optionality or looping.

(...)? optional subrule. The only difference between the code generated for an optional subrule and a rule is that there is no default else-clause to throw an exception--the recognition continues on having ignored the optional subrule.

{
  init-action-if-present
  if ( lookahead-predicts-production-1 ) {
     code-to-match-production-1
  }
  else if ( lookahead-predicts-production-2 ) {
     code-to-match-production-2
  }
  ...
  else if ( lookahead-predicts-production-n ) {
     code-to-match-production-n
  }
}
  

Not testing the optional paths of optional blocks has the potential to delay the detection of syntax errors.

(...)* closure subrule. A closure subrule is like an optional looping subrule, therefore, we wrap the code for a simple subrule in a "forever" loop that exits whenever the lookahead is not consistent with any of the alternative productions.

{
  init-action-if-present
loop:
  do {
    if ( lookahead-predicts-production-1 ) {
       code-to-match-production-1
    }
    else if ( lookahead-predicts-production-2 ) {
       code-to-match-production-2
    }
    ...
    else if ( lookahead-predicts-production-n ) {
       code-to-match-production-n
    }
    else {
      break loop;
    }
  }
  while (true);
}
  

While there is no need to explicity test the lookahead for consistency with the exit path, the grammar analysis phase computes the lookahead of what follows the block. The lookahead of what follows much be disjoint from the lookahead of each alternative otherwise the loop will not know when to terminate. For example, consider the following subrule that is nondeterministic upon token A.

( A | B )* A
  

Upon A, should the loop continue or exit? One must also ask if the loop should even begin. Because you cannot answer these questions with only one symbol of lookahead, the decision is non-LL(1).

Not testing the exit paths of closure loops has the potential to delay the detection of syntax errors.

As a special case, a closure subrule with one alternative production results in:

{
  init-action-if-present
loop:
  while ( lookahead-predicts-production-1 ) {
       code-to-match-production-1
  }
}
   

This special case results in smaller, faster, and more readable code.

(...)+ positive closure subrule. A positive closure subrule is a loop around a series of production prediction tests like a closure subrule. However, we must guarantee that at least one iteration of the loop is done before proceeding to the construct beyond the subrule.

{
  int _cnt = 0;
  init-action-if-present
loop:
  do {
    if ( lookahead-predicts-production-1 ) {
       code-to-match-production-1
    }
    else if ( lookahead-predicts-production-2 ) {
       code-to-match-production-2
    }
    ...
    else if ( lookahead-predicts-production-n ) {
       code-to-match-production-n
    }
    else if ( _cnt>1 ) {
      // lookahead predicted nothing and we've
      // done an iteration
      break loop;
    }
    else {
      throw new NoViableAltException(LT(1));
    }
    _cnt++;  // track times through the loop
  }
  while (true);
}
  

While there is no need to explicity test the lookahead for consistency with the exit path, the grammar analysis phase computes the lookahead of what follows the block. The lookahead of what follows much be disjoint from the lookahead of each alternative otherwise the loop will not know when to terminate. For example, consider the following subrule that is nondeterministic upon token A.

( A | B )+ A
  

Upon A, should the loop continue or exit? Because you cannot answer this with only one symbol of lookahead, the decision is non-LL(1).

Not testing the exit paths of closure loops has the potential to delay the detection of syntax errors.

You might ask why we do not have a while loop that tests to see if the lookahead is consistent with any of the alternatives (rather than having series of tests inside the loop with a break). It turns out that we can generate smaller code for a series of tests than one big one. Moreover, the individual tests must be done anyway to distinguish between alternatives so a while condition would be redundant.

As a special case, if there is only one alternative, the following is generated:

{
  init-action-if-present
  do {
    code-to-match-production-1
  }
  while ( lookahead-predicts-production-1 );
}
  

Optimization. When there are a large (where large is user-definable) number of strictly LL(1) prediction alternatives, then a switch-statement can be used rather than a sequence of if-statements. The non-LL(1) cases are handled by generating the usual if-statements in the default case. For example:

switch ( LA(1) ) {
  case KEY_WHILE :
  case KEY_IF :
  case KEY_DO :
    statement();
    break;
  case KEY_INT :
  case KEY_FLOAT :
    declaration();
    break;
  default :
    // do whatever else-clause is appropriate
}
  

This optimization relies on the compiler building a more direct jump (via jump table or hash table) to the ith production matching code. This is also more readable and faster than a series of bit set membership tests.

Production Prediction

LL(1) prediction. Any LL(1) prediction test is a simple set membership test. If the set is a singleton set (a set with only one element), then an integer token type == comparison is done. If the set degree is greater than one, a bit set is created and the single input token type is tested for membership against that set. For example, consider the following rule:

a : A | b ;
b : B | C | D | E | F;
  

The lookahead that predicts production one is {A} and the lookahead that predicts production two is {B,C,D,E,F}. The following code would be generated by ANTLR for rule a (slightly cleaned up for clarity):

public void a() {
  if ( LA(1)==A ) {
    match(A);
  }
  else if (token_set1.member(LA(1))) {
    b();
  }
}
  

The prediction for the first production can be done with a simple integer comparison, but the second alternative uses a bit set membership test for speed, which you probably didn't recognize as testing LA(1) member {B,C,D,E,F}. The complexity threshold above which bitset-tests are generated is user-definable.

We use arrays of long ints (64 bits) to hold bit sets. The ith element of a bitset is stored in the word number i/64 and the bit position within that word is i % 64. The divide and modulo operations are extremely expensive and, but fortunately, a strength reduction can be done. Dividing by a power of two is the same as shifting right and modulo a power of two is the same as masking with that power minus one. All of these details are hidden inside the implementation of the BitSet class in the package antlr.collections.impl.

The various bit sets needed by ANTLR are created and initialized in the generated parser (or lexer) class.

Approximate LL(k) prediction. An extension of LL(1)...basically we do a series of up to k bit set tests rather than a single as we do in LL(1) prediction. Each decision will use a different amount of lookahead, with LL(1) being the dominant decision type.

Production Element Recognition

Token references. Token references are translated to:

match(token-type);
  

For example, a reference to token KEY_BEGIN results in:

match(KEY_BEGIN);
  

where KEY_BEGIN will be an integer constant defined in the MyParserTokenType interface generated by ANTLR.

String literal references. String literal references are references to automatically generated tokens to which ANTLR automatically assigns a token type (one for each unique string). String references are translated to:

match(T);
  

where T is the token type assigned by ANTLR to that token.

Character literal references. Referencing a character literal implies that the current rule is a lexical rule. Single characters, 't', are translated to:

match('t');
  

which can be manually inlined with:

if ( c=='t' ) consume();
else throw new MismatchedCharException(
               "mismatched char: '"+(char)c+"'");
   

if the method call proves slow (at the cost of space).

Wildcard references. In lexical rules, the wildcard is translated to:

consume();
  

which simply gets the next character of input without doing a test.

References to the wildcard in a parser rule results in the same thing except that the consume call will be with respect to the parser.

Not operator. When operating on a token, ~T is translated to:

matchNot(T);
 

When operating on a character literal, 't' is translated to:

matchNot('t');
  

Range operator. In parser rules, the range operator (T1..T2) is translated to:

matchRange(T1,T2);
   

In a lexical rule, the range operator for characters c1..c2 is translated to:

matchRange(c1,c2);
  

Labels. Element labels on atom references become Token references in parser rules and ints in lexical rules. For example, the parser rule:

a : id:ID {System.out.println("id is "+id);} ;
  would be translated to:  
public void a() {
  Token id = null;
  id = LT(1);
  match(ID);
  System.out.println("id is "+id);
}
  For lexical rules such as:  
ID : w:. {System.out.println("w is "+(char)w);};
  the following code would result:  
public void ID() {
  int w = 0;
  w = c;
  consume(); // match wildcard (anything)
  System.out.println("w is "+(char)w);
}
  

Labels on rule references result in AST references, when generating trees, of the form label_ast.

Rule references. Rule references become method calls. Arguments to rules become arguments to the invoked methods. Return values are assigned like Java assignments. Consider rule reference i=list[1] to rule:

list[int scope] returns int
    :   { return scope+3; }
    ;
  The rule reference would be translated to:  
i = list(1);
  

Semantic actions. Actions are translated verbatim to the output parser or lexer except for the translations required for AST generation and the following:

Omitting the rule argument implies you mean the current rule. The result type is a BitSet, which you can test via $FIRST(a).member(LBRACK) etc...

Here is a sample rule:

a : A {System.out.println($FIRST(a));} B
  exception
    catch [RecognitionException e] {    
        if ( $FOLLOW.member(SEMICOLON) ) {
        consumeUntil(SEMICOLON);
    }
    else {
        consume();
    }
    }
  ;
Results in
public final void a() throws RecognitionException, TokenStreamException {  
    try {
        match(A);
        System.out.println(_tokenSet_0);
        match(B);
    }
    catch (RecognitionException e) {
        if ( _tokenSet_1.member(SEMICOLON) ) {
            consumeUntil(SEMICOLON);
        }
        else {
            consume();
        }
    }
}

To add members to a lexer or parser class definition, add the class member definitions enclosed in {} immediately following the class specification, for example:

class MyParser;
{
   protected int i;
   public MyParser(TokenStream lexer,
        int aUsefulArgu