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 aUsefulArgument) {
      i = aUsefulArgument;
   }
}
... rules ...

ANTLR collects everything inside the {...} and inserts it in the class definition before the rule-method definitions. When generating C++, this may have to be extended to allow actions after the rules due to the wacky ordering restrictions of C++.

Standard Classes

ANTLR constructs parser classes that are subclasses of the antlr.LLkParser class, which is a subclass of the antlr.Parser class. We summarize the more important members of these classes here. See Parser.java and LLkParser.java for details of the implementation.

public abstract class Parser {
   protected ParserSharedInputState inputState;
   protected ASTFactory ASTFactory;
   public abstract int LA(int i);
   public abstract Token LT(int i);
   public abstract void consume();
   public void consumeUntil(BitSet set) { ... }
   public void consumeUntil(int tokenType) { ... }
   public void match(int t)
      throws MismatchedTokenException { ... }
   public void matchNot(int t)
      throws MismatchedTokenException { ... }
   ...
}

public class LLkParser extends Parser {
   public LLkParser(TokenBuffer tokenBuf, int k_)
     { ... }
   public LLkParser(TokenStream lexer, int k_)
     { ... }
   public int LA(int i) { return input.LA(i); }
   public Token LT(int i) { return input.LT(i); }
   public void consume() { input.consume(); }
   ...
}

Lexer Implementation

Lexer Form

The lexers produced by ANTLR are a lot like the parsers produced by ANTLR. They only major differences are that (a) scanners use characters instead of tokens, and (b) ANTLR generates a special nextToken rule for each scanner which is a production containing each public lexer rule as an alternate. The name of the lexical grammar class provided by the programmer results in a subclass of CharScanner, for example

public class MyLexer extends antlr.CharScanner
  implements LTokenTypes, TokenStream
{
  public L(InputStream in) {
          this(new ByteBuffer(in));
  }
  public L(Reader in) {
          this(new CharBuffer(in));
  }
  public L(InputBuffer ib) {
          this(new LexerSharedInputState(ib));
  }
  public L(LexerSharedInputState state) {
          super(state);
          caseSensitiveLiterals = true;
          setCaseSensitive(true);
          literals = new Hashtable();
  }

  public Token nextToken() throws TokenStreamException {
     scanning logic
    ...
  }
  recursive and other non-inlined lexical methods
  ...
}
  

When an ANTLR-generated parser needs another token from its lexer, it calls a method called nextToken. The general form of the nextToken method is:

public Token nextToken()
  throws TokenStreamException {
  int tt;
  for (;;) {
     try {
        resetText();
        switch ( c ) {
        case for each char predicting lexical rule
           call lexical rule gets token type -> tt
        default :
           throw new NoViableAltForCharException(
               "bad char: '"+(char)c+"'");
        }
        if ( tt!=Token.SKIP ) {
           return makeToken(tt);
        }
     }
     catch (RecognitionException ex) {
        reportError(ex.toString());
     }
  }
}
  

For example, the lexical rules:

lexclass Lex;

WS   : ('\t' | '\r' | ' ') {_ttype=Token.SKIP;} ;
PLUS : '+';
MINUS: '-';
INT  : ( '0'..'9' )+ ;
ID   : ( 'a'..'z' )+ ;
UID  : ( 'A'..'Z' )+ ;
  would result in something like:  
public class Lex extends CharScanner
  implements TTokenTypes {
...
public Token nextToken()
    throws TokenStreamException {
    int _tt = Token.EOF_TYPE;
    for (;;) {
    try {
       resetText();
       switch ( _c ) {
       case '\t': case '\r': case ' ': 
           _tt=mWS();
           break;
       case '+': 
           _tt=mPLUS();
           break;
       case '-': 
           _tt=mMINUS();
           break;
       case '0': case '1': case '2': case '3': 
       case '4': case '5': case '6': case '7': 
       case '8': case '9': 
           _tt=mINT();
           break;
       case 'a': case 'b': case 'c': case 'd': 
       case 'e': case 'f': case 'g': case 'h': 
       case 'i': case 'j': case 'k': case 'l': 
       case 'm': case 'n': case 'o': case 'p': 
       case 'q': case 'r': case 's': case 't': 
       case 'u': case 'v': case 'w': case 'x': 
       case 'y': case 'z': 
           _tt=mID();
           break;
       case 'A': case 'B': case 'C': case 'D': 
       case 'E': case 'F': case 'G': case 'H': 
       case 'I': case 'J': case 'K': case 'L': 
       case 'M': case 'N': case 'O': case 'P': 
       case 'Q': case 'R': case 'S': case 'T': 
       case 'U': case 'V': case 'W': case 'X': 
       case 'Y': case 'Z': 
           _tt=mUID();
           break;
       case EOF_CHAR :
           _tt = Token.EOF_TYPE;
           break;
       default :
          throw new NoViableAltForCharException(
               "invalid char "+_c);
       }
       if ( _tt!=Token.SKIP ) {
           return makeToken(_tt);
       }
    }  // try
	catch (RecognitionException ex) {
	  reportError(ex.toString());
	}
	}  // for
}

public int mWS()
    throws RecognitionException,
           CharStreamException,
           TokenStreamException {
    int _ttype = WS;
    switch ( _c) {
    case '\t': 
        match('\t');
        break;
    case '\r': 
        match('\r');
        break;
    case ' ': 
        match(' ');
        break;
    default :
    {
        throw new NoViableAltForException(
               "no viable for char: "+(char)_c);
    }
    }
     _ttype = Token.SKIP;
    return _ttype;
}

public int mPLUS()
    throws RecognitionException,
           CharStreamException,
           TokenStreamException {
    int _ttype = PLUS;
    match('+');
    return _ttype;
}

public int mMINUS()
    throws RecognitionException,
           CharStreamException,
           TokenStreamException {

    int _ttype = MINUS;
    match('-');
    return _ttype;
}

public int mINT()
    throws RecognitionException,
           CharStreamException,
           TokenStreamException {

    int _ttype = INT;
    {
    int _cnt=0;
    _loop:
    do {
        if ( _c>='0' && _c<='9')
          { matchRange('0','9'); }
        else
        if ( _cnt>=1 ) break _loop;
        else {
           throw new ScannerException(
              "no viable alternative for char: "+
                (char)_c);
        }
        _cnt++;
    } while (true);
    }
    return _ttype;
}

public int mID()
    throws RecognitionException,
           CharStreamException,
           TokenStreamException {
    int _ttype = ID;
    {
    int _cnt=0;
    _loop:
    do {
        if ( _c>='a' && _c<='z')
        { matchRange('a','z'); }
        else
        if ( _cnt>=1 ) break _loop;
        else {
            throw new NoViableAltForCharException(
               "no viable alternative for char: "+
                 (char)_c);
        }
        _cnt++;
        } while (true);
    }
    return _ttype;
}

public int mUID()
    throws RecognitionException,
           CharStreamException,
           TokenStreamException {

    int _ttype = UID;
    {
    int _cnt=0;
    _loop:
    do {
        if ( _c>='A' && _c<='Z')
        { matchRange('A','Z'); }
        else
        if ( _cnt>=1 ) break _loop;
        else {
            throw new NoViableAltForCharException(
               "no viable alternative for char: "+
                 (char)_c);
        }
        _cnt++;
    } while (true);
    }
    return _ttype;
}

}
  

ANTLR-generated lexers assume that you will be reading streams of characters. If this is not the case, you must create your own lexer.

Creating Your Own Lexer

To create your own lexer, your Java class that will doing the lexing must implement interface TokenStream, which simply states that you must be able to return a stream of tokens via nextToken:

/**This interface allows any object to
 * pretend it is a stream of tokens.
 * @author Terence Parr, MageLang Institute
 */
public interface TokenStream {
  public Token nextToken();
}
  

ANTLR will not generate a lexer if you do not specify a lexical class.

Launching a parser with a non-ANTLR-generated lexer is the same as launching a parser with an ANTLR-generated lexer:

HandBuiltLexer lex = new HandBuiltLexer(...);
MyParser p = new MyParser(lex);
p.start-rule();

The parser does not care what kind of object you use for scanning as as long as it can answer nextToken.

If you build your own lexer, and the token values are also generated by that lexer, then you should inform the ANTLR-generated parsers about the token type values generated by that lexer. Use the importVocab in the parsers that use the externally-generated token set, and create a token definition file following the requirements of the importVocab option.

Lexical Rules

Lexical rules are essentially the same as parser rules except that lexical rules apply a structure to a series of characters rather than a series of tokens. As with parser rules, each lexical rule results in a method in the output lexer class.

Alternative blocks. Consider a simple series of alternatives within a block:

FORMAT : 'x' | 'f' | 'd';
  

The lexer would contain the following method:

public int mFORMAT() {
  if ( c=='x' ) {
    match('x');
  }
  else if ( c=='x' ) {
    match('x');
  }
  else if ( c=='f' ) {
    match('f');
  }
  else if ( c=='d' ) {
    match('d');
  }
  else {
    throw new NoViableAltForCharException(
        "no viable alternative: '"+(char)c+"'");
  }
  return FORMAT;
}
  

The only real differences between lexical methods and grammar methods are that lookahead prediction expressions do character comparisons rather than LA(i) comparisons, match matches characters instead of tokens, a return is added to the bottom of the rule, and lexical methods throw CharStreamException objects in addition to TokenStreamException and RecognitionException objects.

Optimization: Non-Recursive lexical rules. Rules that do not directly or indirectly call themselves can be inlined into the lexer entry method: nextToken. For example, the common identifier rule would be placed directly into the nextToken method. That is, rule:

ID  :   ( 'a'..'z' | 'A'..'Z' )+
    ;
 

would not result in a method in your lexer class. This rule would become part of the resulting lexer as it would be probably inlined by ANTLR:

public Token nextToken() {
  switch ( c ) {
  cases for operators and such here
  case '0': // chars that predict ID token
  case '1':
  case '2':
  case '3':
  case '4':
  case '5':
  case '6':
  case '7':
  case '8':
  case '9':
    while ( c>='0' && c<='9' ) {
      matchRange('0','9');
    }
    return makeToken(ID);
  default :
    check harder stuff here like rules
      beginning with a..z
}
  

If not inlined, the method for scanning identifiers would look like:

public int mID() {
  while ( c>='0' && c<='9' ) {
    matchRange('0','9');
  }
  return ID;
}
  

where token names are converted to method names by prefixing them with the letter m. The nextToken method would become:

public Token nextToken() {
  switch ( c ) {
  cases for operators and such here
  case '0': // chars that predict ID token
  case '1':
  case '2':
  case '3':
  case '4':
  case '5':
  case '6':
  case '7':
  case '8':
  case '9':
    return makeToken(mID());
  default :
    check harder stuff here like rules
      beginning with a..z
}
  

Note that this type of range loop is so common that it should probably be optimized to:

while ( c>='0' && c<='9' ) {
  consume();
}
  

Optimization: Recursive lexical rules. Lexical rules that are directly or indirectly recursive are not inlined. For example, consider the following rule that matches nested actions:

ACTION
    :   '{' ( ACTION | ~'}' )* '}'
    ;
  

ACTION would be result in (assuming a character vocabulary of 'a'..'z', '{', '}'):

public int mACTION()
    throws RecognitionException,
           CharStreamException,
           TokenStreamException {

    int _ttype = ACTION;
    match('{');
    {
    _loop:
    do {
        switch ( _c) {
        case '{':
            mACTION();
            break;
        case 'a': case 'b': case 'c': case 'd':
        case 'e': case 'f': case 'g': case 'h':
        case 'i': case 'j': case 'k': case 'l':
        case 'm': case 'n': case 'o': case 'p':
        case 'q': case 'r': case 's': case 't':
        case 'u': case 'v': case 'w': case 'x':
        case 'y': case 'z':
            matchNot('}');
            break;
        default :
            break _loop;
        }
    } while (true);
    }
    match('}');
    return _ttype;
}
       

Token Objects

The basic token knows only about a token type:

public class Token {
  // constants
  public static final int MIN_USER_TYPE = 3;
  public static final int INVALID_TYPE = 0;
  public static final int EOF_TYPE = 1;
  public static final int SKIP = -1;
  
  // each Token has at least a token type
  int type=INVALID_TYPE;
  
  // the illegal token object
  public static Token badToken =
    new Token(INVALID_TYPE, "");
  
  public Token() {;}
  public Token(int t) { type = t; }
  public Token(int t, String txt) {
    type = t; setText(txt);
  }

  public void setType(int t) { type = t; }
  public void setLine(int l) {;}
  public void setColumn(int c) {;}
  public void setText(String t) {;}
  
  public int getType() { return type; }
  public int getLine() { return 0; }
  public int getColumn() { return 0; }
  public String getText() {...}
}

The raw Token class is not very useful.  ANTLR supplies a "common" token class that it uses by default, which contains the line number and text associated with the token:

public class CommonToken extends Token {
  // most tokens will want line, text information
  int line;
  String text = null;
 
  public CommonToken() {}
  public CommonToken(String s)  { text = s; }
  public CommonToken(int t, String txt) {
    type = t;
    setText(txt);
  }

  public void setLine(int l)    { line = l; }
  public int  getLine()         { return line; }
  public void setText(String s) { text = s; }
  public String getText()       { return text; }
}

ANTLR will generate an interface that defines the types of tokens in a token vocabulary. Parser and lexers that share this token vocabulary are generated such that they implement the resulting token types interface:

public interface MyLexerTokenTypes {
  public static final int ID = 2;
  public static final int BEGIN = 3;
  ...
}

ANTLR defines a token object for use with the TokenStreamHiddenTokenFilter object called CommonHiddenStreamToken:

public class CommonHiddenStreamToken
  extends CommonToken {
  protected CommonHiddenStreamToken hiddenBefore;
  protected CommonHiddenStreamToken hiddenAfter;

  public CommonHiddenStreamToken
    getHiddenAfter() {...}
  public CommonHiddenStreamToken
    getHiddenBefore() {...}
}

Hidden tokens are weaved amongst the normal tokens.  Note that, for garbage collection reasons, hidden tokens never point back to normal tokens (preventing a linked list of the entire token stream).

Token Lookahead Buffer

The parser must always have fast access to k symbols of lookahead. In a world without syntactic predicates, a simple buffer of k Token references would suffice. However, given that even LL(1) ANTLR parsers must be able to backtrack, an arbitrarily-large buffer of Token references must be maintained. LT(i) looks into the token buffer.

Fortunately, the parser itself does not implement the token-buffering and lookahead algorithm. That is handled by the TokenBuffer object. We begin the discussion of lookahead by providing an LL(k) parser framework:

public class LLkParser extends Parser {
   TokenBuffer input;
   public int LA(int i) {
      return input.LA(i);
   }
   public Token LT(int i) {
      return input.LT(i);
   }
   public void consume() {
      input.consume();
   }
}
       

All lookahead-related calls are simply forwarded to the TokenBuffer object. In the future, some simple caching may be performed in the parser itself to avoid the extra indirection, or ANTLR may generate the call to input.LT(i) directly.

The TokenBuffer object caches the token stream emitted by the scanner. It supplies LT() and LA() methods for accessing the kth lookahead token or token type, as well as methods for consuming tokens, guessing, and backtracking.

public class TokenBuffer {
   ...
   /** Mark another token for
    *  deferred consumption */
   public final void consume() {...}

   /** Get a lookahead token */
   public final Token LT(int i) { ... }

   /** Get a lookahead token value */
   public final int LA(int i) { ... }

   /**Return an integer marker that can be used to
    * rewind the buffer to its current state. */
   public final int mark() { ... }

   /**Rewind the token buffer to a marker.*/
   public final void rewind(int mark) { ... }
}

To begin backtracking, a mark is issued, which makes the TokenBuffer record the current position so that it can rewind the token stream. A subsequent rewind directive will reset the internal state to the point before the last mark.

Consider the following rule that employs backtracking:

stat:   (list EQUAL) => list EQUAL list
    |   list
    ;
list:   LPAREN (ID)* RPAREN
    ;
 

Something like the following code would be generated:

public void stat()
  throws RecognitionException,
         TokenStreamException
{
  boolean synPredFailed;
  if ( LA(1)==LPAREN ) { // check lookahead
    int marker = tokenBuffer.mark();
    try {
      list();
      match(EQUAL);
      synPredFailed = false;
    }
    catch (RecognitionException e) {
      tokenBuffer.rewind(marker);
      synPredFailed = true;
    }
  }
  if ( LA(1)==LPAREN && !synPredFailed ) {
    // test prediction of alt 1
    list();
    match(EQUAL);
    list();
  }
  else if ( LA(1)==LPAREN ) {
    list();
  }
}
      

The token lookahead buffer uses a circular token buffer to perform quick indexed access to the lookahead tokens. The circular buffer is expanded as necessary to calculate LT(i) for arbitrary i. TokenBuffer.consume() does not actually read more tokens. Instead, it defers the read by counting how many tokens have been consumed, and then adjusts the token buffer and/or reads new tokens when LA() or LT() is called.

Version: $Id: //depot/code/org.antlr/release/antlr-2.7.5/doc/runtime.html#1 $