Packageorg.antlr.runtime
Classpublic class BaseRecognizer
SubclassesLexer, Parser, TreeParser

A generic recognizer that can handle recognizers generated from lexer, parser, and tree grammars. This is all the parsing support code essentially; most of it is error recovery stuff and backtracking.



Public Properties
 PropertyDefined by
  backtrackingLevel : int
[read-only]
BaseRecognizer
  grammarFileName : String
[read-only] For debugging and other purposes, might want the grammar name.
BaseRecognizer
  numberOfSyntaxErrors : int
[read-only] Get number of recognition errors (lexer, parser, tree parser).
BaseRecognizer
  sourceName : String
[read-only]
BaseRecognizer
  state : RecognizerSharedState
State of a lexer, parser, or tree parser are collected into a state object so the state can be shared.
BaseRecognizer
  tokenNames : Array
[read-only] Used to print out token names like ID during debugging and error reporting.
BaseRecognizer
Public Methods
 MethodDefined by
  
BaseRecognizer
  
alreadyParsedRule(input:IntStream, ruleIndex:int):Boolean
Has this rule already parsed input at the current index in the input stream? Return the stop token index or MEMO_RULE_UNKNOWN.
BaseRecognizer
  
beginResync():void
A hook to listen in on the token consumption during error recovery.
BaseRecognizer
  
consumeUntil(input:IntStream, bitSet:BitSet):void
Consume tokens until one matches the given token set
BaseRecognizer
  
consumeUntilToken(input:IntStream, tokenType:int):void
BaseRecognizer
  
BaseRecognizer
  
emitErrorMessage(msg:String):void
Override this method to change where error messages go
BaseRecognizer
  
endResync():void
BaseRecognizer
  
What is the error header, normally line/character position information?
BaseRecognizer
  
getErrorMessage(e:RecognitionException, tokenNames:Array):String
What error message should be generated for the various exception types? Not very object-oriented code, but I like having all error message generation within one method rather than spread among all of the exception classes.
BaseRecognizer
  
getRuleMemoization(ruleIndex:int, ruleStartIndex:int):int
Given a rule number and a start token index number, return MEMO_RULE_UNKNOWN if the rule has not parsed input starting from start index.
BaseRecognizer
  
return how many rule/input-index pairs there are in total.
BaseRecognizer
  
How should a token be displayed in an error message? The default is to display just the text, but during development you might want to have a lot of information spit out.
BaseRecognizer
  
Match the wildcard: in a symbol
BaseRecognizer
  
matchStream(input:IntStream, ttype:int, follow:BitSet):Object
Match current input symbol against ttype.
BaseRecognizer
  
memoize(input:IntStream, ruleIndex:int, ruleStartIndex:int):void
Record whether or not this rule parsed the input at this position successfully.
BaseRecognizer
  
mismatchIsMissingToken(input:IntStream, follow:BitSet):Boolean
BaseRecognizer
  
mismatchIsUnwantedToken(input:IntStream, ttype:int):Boolean
BaseRecognizer
  
Not currently used
BaseRecognizer
  
recoverFromMismatchedToken(input:IntStream, ttype:int, follow:BitSet):Object
Attempt to recover from a single missing or extra token.
BaseRecognizer
  
Recover from an error found on the input stream.
BaseRecognizer
  
Report a recognition problem.
BaseRecognizer
  
reset():void
reset the parser's state; subclasses must rewinds the input stream
BaseRecognizer
  
toStrings(tokens:Array):Array
A convenience method for use most often with template rewrites.
BaseRecognizer
  
traceInSymbol(ruleName:String, ruleIndex:int, inputSymbol:Object):void
BaseRecognizer
  
traceOutSymbol(ruleName:String, ruleIndex:int, inputSymbol:Object):void
BaseRecognizer
Protected Methods
 MethodDefined by
  
combineFollows(exact:Boolean):BitSet
BaseRecognizer
  
Compute the context-sensitive FOLLOW set for current rule.
BaseRecognizer
  
BaseRecognizer
  
Match needs to return the current input symbol, which gets put into the label for the associated token ref; e.g., x=ID.
BaseRecognizer
  
getMissingSymbol(input:IntStream, e:RecognitionException, expectedTokenType:int, follow:BitSet):Object
Conjure up a missing token during error recovery.
BaseRecognizer
  
mismatch(input:IntStream, ttype:int, follow:BitSet):void
Factor out what to do upon token mismatch so tree parsers can behave differently.
BaseRecognizer
  
pushFollow(fset:BitSet):void
Push a rule's follow set using our own hardcoded stack
BaseRecognizer
Public Constants
 ConstantDefined by
  DEFAULT_TOKEN_CHANNEL : int = 0
[static]
BaseRecognizer
  HIDDEN : int = 99
[static]
BaseRecognizer
  INITIAL_FOLLOW_STACK_SIZE : int = 100
[static]
BaseRecognizer
  MEMO_RULE_FAILED : int = -2
[static]
BaseRecognizer
  MEMO_RULE_UNKNOWN : int = -1
[static]
BaseRecognizer
  NEXT_TOKEN_RULE_NAME : String = "nextToken"
[static]
BaseRecognizer
Property detail
backtrackingLevelproperty
backtrackingLevel:int  [read-only]Implementation
    public function get backtrackingLevel():int
grammarFileNameproperty 
grammarFileName:String  [read-only]

For debugging and other purposes, might want the grammar name. Have ANTLR generate an implementation for this method.

Implementation
    public function get grammarFileName():String
numberOfSyntaxErrorsproperty 
numberOfSyntaxErrors:int  [read-only]

Get number of recognition errors (lexer, parser, tree parser). Each recognizer tracks its own number. So parser and lexer each have separate count. Does not count the spurious errors found between an error and next valid token match See also reportError()

Implementation
    public function get numberOfSyntaxErrors():int
sourceNameproperty 
sourceName:String  [read-only]Implementation
    public function get sourceName():String
stateproperty 
public var state:RecognizerSharedState

State of a lexer, parser, or tree parser are collected into a state object so the state can be shared. This sharing is needed to have one grammar import others and share same error variables and other state variables. It's a kind of explicit multiple inheritance via delegation of methods and shared state.

tokenNamesproperty 
tokenNames:Array  [read-only]

Used to print out token names like ID during debugging and error reporting. The generated parsers implement a method that overrides this to point to their String[] tokenNames.

Implementation
    public function get tokenNames():Array
Constructor detail
BaseRecognizer()constructor
public function BaseRecognizer(state:RecognizerSharedState = null)Parameters
state:RecognizerSharedState (default = null)
Method detail
alreadyParsedRule()method
public function alreadyParsedRule(input:IntStream, ruleIndex:int):Boolean

Has this rule already parsed input at the current index in the input stream? Return the stop token index or MEMO_RULE_UNKNOWN. If we attempted but failed to parse properly before, return MEMO_RULE_FAILED. This method has a side-effect: if we have seen this input for this rule and successfully parsed before, then seek ahead to 1 past the stop token matched for this rule last time.

Parameters
input:IntStream
 
ruleIndex:int

Returns
Boolean
beginResync()method 
public function beginResync():void

A hook to listen in on the token consumption during error recovery. The DebugParser subclasses this to fire events to the listenter.

combineFollows()method 
protected function combineFollows(exact:Boolean):BitSetParameters
exact:Boolean

Returns
BitSet
computeContextSensitiveRuleFOLLOW()method 
protected function computeContextSensitiveRuleFOLLOW():BitSet

Compute the context-sensitive FOLLOW set for current rule. This is set of token types that can follow a specific rule reference given a specific call chain. You get the set of viable tokens that can possibly come next (lookahead depth 1) given the current call chain. Contrast this with the definition of plain FOLLOW for rule r: FOLLOW(r)={x | S=>lpha r beta in G and x in FIRST(beta)} where x in Tand alpha, beta in V T is set of terminals and V is the set of terminals and nonterminals. In other words, FOLLOW(r) is the set of all tokens that can possibly follow references to r in nysentential form (context). At runtime, however, we know precisely which context applies as we have the call chain. We may compute the exact (rather than covering superset) set of following tokens. For example, consider grammar: stat : ID '=' expr ';' // FOLLOW(stat)=={EOF} | "return" expr '.' ; expr : atom ('+' atom); // FOLLOW(expr)=={';','.',')'} atom : INT // FOLLOW(atom)=={'+',')',';','.'} | '(' expr ')' ; The FOLLOW sets are all inclusive whereas context-sensitive FOLLOW sets are precisely what could follow a rule reference. For input input "i=(3);", here is the derivation: stat => ID '=' expr ';' => ID '=' atom ('+' atom)';' => ID '=' '(' expr ')' ('+' atom)';' => ID '=' '(' atom ')' ('+' atom)';' => ID '=' '(' INT ')' ('+' atom)';' => ID '=' '(' INT ')' ';' At the "3" token, you'd have a call chain of stat -> expr -> atom -> expr -> atom What can follow that specific nested ref to atom? Exactly ')' as you can see by looking at the derivation of this specific input. Contrast this with the FOLLOW(atom)={'+',')',';','.'}. You want the exact viable token set when recovering from a token mismatch. Upon token mismatch, if LA(1) is member of the viable next token set, then you know there is most likely a missing token in the input stream. "Insert" one by just not throwing an exception.

Returns
BitSet
computeErrorRecoverySet()method 
protected function computeErrorRecoverySet():BitSet

Returns
BitSet
consumeUntil()method 
public function consumeUntil(input:IntStream, bitSet:BitSet):void

Consume tokens until one matches the given token set

Parameters
input:IntStream
 
bitSet:BitSet
consumeUntilToken()method 
public function consumeUntilToken(input:IntStream, tokenType:int):voidParameters
input:IntStream
 
tokenType:int
displayRecognitionError()method 
public function displayRecognitionError(tokenNames:Array, e:RecognitionException):voidParameters
tokenNames:Array
 
e:RecognitionException
emitErrorMessage()method 
public function emitErrorMessage(msg:String):void

Override this method to change where error messages go

Parameters
msg:String
endResync()method 
public function endResync():void
getCurrentInputSymbol()method 
protected function getCurrentInputSymbol(input:IntStream):Object

Match needs to return the current input symbol, which gets put into the label for the associated token ref; e.g., x=ID. Token and tree parsers need to return different objects. Rather than test for input stream type or change the IntStream interface, I use a simple method to ask the recognizer to tell me what the current input symbol is. This is ignored for lexers.

Parameters
input:IntStream

Returns
Object
getErrorHeader()method 
public function getErrorHeader(e:RecognitionException):String

What is the error header, normally line/character position information?

Parameters
e:RecognitionException

Returns
String
getErrorMessage()method 
public function getErrorMessage(e:RecognitionException, tokenNames:Array):String

What error message should be generated for the various exception types? Not very object-oriented code, but I like having all error message generation within one method rather than spread among all of the exception classes. This also makes it much easier for the exception handling because the exception classes do not have to have pointers back to this object to access utility routines and so on. Also, changing the message for an exception type would be difficult because you would have to subclassing exception, but then somehow get ANTLR to make those kinds of exception objects instead of the default. This looks weird, but trust me--it makes the most sense in terms of flexibility. For grammar debugging, you will want to override this to add more information such as the stack frame with getRuleInvocationStack(e, this.getClass().getName()) and, for no viable alts, the decision description and state etc... Override this to change the message generated for one or more exception types.

Parameters
e:RecognitionException
 
tokenNames:Array

Returns
String
getMissingSymbol()method 
protected function getMissingSymbol(input:IntStream, e:RecognitionException, expectedTokenType:int, follow:BitSet):Object

Conjure up a missing token during error recovery. The recognizer attempts to recover from single missing symbols. But, actions might refer to that missing symbol. For example, x=ID {f($x);}. The action clearly assumes that there has been an identifier matched previously and that $x points at that token. If that token is missing, but the next token in the stream is what we want we assume that this token is missing and we keep going. Because we have to return some token to replace the missing token, we have to conjure one up. This method gives the user control over the tokens returned for missing tokens. Mostly, you will want to create something special for identifier tokens. For literals such as '{' and ',', the default action in the parser or tree parser works. It simply creates a CommonToken of the appropriate type. The text will be the token. If you change what tokens must be created by the lexer, override this method to create the appropriate tokens.

Parameters
input:IntStream
 
e:RecognitionException
 
expectedTokenType:int
 
follow:BitSet

Returns
Object
getRuleMemoization()method 
public function getRuleMemoization(ruleIndex:int, ruleStartIndex:int):int

Given a rule number and a start token index number, return MEMO_RULE_UNKNOWN if the rule has not parsed input starting from start index. If this rule has parsed input starting from the start index before, then return where the rule stopped parsing. It returns the index of the last token matched by the rule. For now we use a hashtable and just the slow Object-based one. Later, we can make a special one for ints and also one that tosses out data after we commit past input position i.

Parameters
ruleIndex:int
 
ruleStartIndex:int

Returns
int
getRuleMemoizationCacheSize()method 
public function getRuleMemoizationCacheSize():int

return how many rule/input-index pairs there are in total. TODO: this includes synpreds. :(

Returns
int
getTokenErrorDisplay()method 
public function getTokenErrorDisplay(t:Token):String

How should a token be displayed in an error message? The default is to display just the text, but during development you might want to have a lot of information spit out. Override in that case to use t.toString() (which, for CommonToken, dumps everything about the token). This is better than forcing you to override a method in your token objects because you don't have to go modify your lexer so that it creates a new Java type.

Parameters
t:Token

Returns
String
matchAnyStream()method 
public function matchAnyStream(input:IntStream):void

Match the wildcard: in a symbol

Parameters
input:IntStream
matchStream()method 
public function matchStream(input:IntStream, ttype:int, follow:BitSet):Object

Match current input symbol against ttype. Attempt single token insertion or deletion error recovery. If that fails, throw MismatchedTokenException. To turn off single token insertion or deletion error recovery, override mismatchRecover() and have it call plain mismatch(), which does not recover. Then any error in a rule will cause an exception and immediate exit from rule. Rule would recover by resynchronizing to the set of symbols that can follow rule ref.

Parameters
input:IntStream
 
ttype:int
 
follow:BitSet

Returns
Object
memoize()method 
public function memoize(input:IntStream, ruleIndex:int, ruleStartIndex:int):void

Record whether or not this rule parsed the input at this position successfully. Use a standard java hashtable for now.

Parameters
input:IntStream
 
ruleIndex:int
 
ruleStartIndex:int
mismatch()method 
protected function mismatch(input:IntStream, ttype:int, follow:BitSet):void

Factor out what to do upon token mismatch so tree parsers can behave differently. Override and call mismatchRecover(input, ttype, follow) to get single token insertion and deletion. Use this to turn of single token insertion and deletion. Override mismatchRecover to call this instead.

Parameters
input:IntStream
 
ttype:int
 
follow:BitSet
mismatchIsMissingToken()method 
public function mismatchIsMissingToken(input:IntStream, follow:BitSet):BooleanParameters
input:IntStream
 
follow:BitSet

Returns
Boolean
mismatchIsUnwantedToken()method 
public function mismatchIsUnwantedToken(input:IntStream, ttype:int):BooleanParameters
input:IntStream
 
ttype:int

Returns
Boolean
pushFollow()method 
protected function pushFollow(fset:BitSet):void

Push a rule's follow set using our own hardcoded stack

Parameters
fset:BitSet
recoverFromMismatchedSet()method 
public function recoverFromMismatchedSet(input:IntStream, e:RecognitionException, follow:BitSet):Object

Not currently used

Parameters
input:IntStream
 
e:RecognitionException
 
follow:BitSet

Returns
Object
recoverFromMismatchedToken()method 
public function recoverFromMismatchedToken(input:IntStream, ttype:int, follow:BitSet):Object

Attempt to recover from a single missing or extra token. EXTRA TOKEN LA(1) is not what we are looking for. If LA(2) has the right token, however, then assume LA(1) is some extra spurious token. Delete it and LA(2) as if we were doing a normal match(), which advances the input. MISSING TOKEN If current token is consistent with what could come after ttype then it is ok to "insert" the missing token, else throw exception For example, Input "i=(3;" is clearly missing the ')'. When the parser returns from the nested call to expr, it will have call chain: stat -> expr -> atom and it will be trying to match the ')' at this point in the derivation: => ID '=' '(' INT ')' ('+' atom)';' ^ match() will see that ';' doesn't match ')' and report a mismatched token error. To recover, it sees that LA(1)==';' is in the set of tokens that can follow the ')' token reference in rule atom. It can assume that you forgot the ')'.

Parameters
input:IntStream
 
ttype:int
 
follow:BitSet

Returns
Object
recoverStream()method 
public function recoverStream(input:IntStream, re:RecognitionException):void

Recover from an error found on the input stream. This is for NoViableAlt and mismatched symbol exceptions. If you enable single token insertion and deletion, this will usually not handle mismatched symbol exceptions but there could be a mismatched token that the match() routine could not recover from.

Parameters
input:IntStream
 
re:RecognitionException
reportError()method 
public function reportError(e:RecognitionException):void

Report a recognition problem. This method sets errorRecovery to indicate the parser is recovering not parsing. Once in recovery mode, no errors are generated. To get out of recovery mode, the parser must successfully match a token (after a resync). So it will go: 1. error occurs 2. enter recovery mode, report error 3. consume until token found in resynch set 4. try to resume parsing 5. next match() will reset errorRecovery mode If you override, make sure to update syntaxErrors if you care about that.

Parameters
e:RecognitionException
reset()method 
public function reset():void

reset the parser's state; subclasses must rewinds the input stream

toStrings()method 
public function toStrings(tokens:Array):Array

A convenience method for use most often with template rewrites. Convert a List to List

Parameters
tokens:Array

Returns
Array
traceInSymbol()method 
public function traceInSymbol(ruleName:String, ruleIndex:int, inputSymbol:Object):voidParameters
ruleName:String
 
ruleIndex:int
 
inputSymbol:Object
traceOutSymbol()method 
public function traceOutSymbol(ruleName:String, ruleIndex:int, inputSymbol:Object):voidParameters
ruleName:String
 
ruleIndex:int
 
inputSymbol:Object
Constant detail
DEFAULT_TOKEN_CHANNELconstant
public static const DEFAULT_TOKEN_CHANNEL:int = 0
HIDDENconstant 
public static const HIDDEN:int = 99
INITIAL_FOLLOW_STACK_SIZEconstant 
public static const INITIAL_FOLLOW_STACK_SIZE:int = 100
MEMO_RULE_FAILEDconstant 
public static const MEMO_RULE_FAILED:int = -2
MEMO_RULE_UNKNOWNconstant 
public static const MEMO_RULE_UNKNOWN:int = -1
NEXT_TOKEN_RULE_NAMEconstant 
public static const NEXT_TOKEN_RULE_NAME:String = "nextToken"