Package antlr3

ANTLR3 runtime package. More...


Classes

class  BacktrackingFailed
 Raised to signal failed backtrack attempt. More...
class  RecognitionException
 The root of the ANTLR exception hierarchy. More...
class  MismatchedTokenException
 A mismatched char or Token or tree node. More...
class  UnwantedTokenException
 An extra token while parsing a TokenStream. More...
class  MissingTokenException
 We were expecting a token but it's not found. More...
class  MismatchedRangeException
 The next token does not match a range of expected types. More...
class  MismatchedSetException
 The next token does not match a set of expected types. More...
class  MismatchedNotSetException
 Used for remote debugger deserialization. More...
class  NoViableAltException
 Unable to decide which alternative to choose. More...
class  EarlyExitException
 The recognizer did not match anything for a (. More...
class  FailedPredicateException
 A semantic predicate failed during validation. More...
class  MismatchedTreeNodeException
 The next tree mode does not match the expected type. More...
class  Token
 Abstract token baseclass. More...
class  CommonToken
 Basic token implementation. More...
class  ClassicToken
 Alternative token implementation. More...
class  IntStream
 Base interface for streams of integer values. More...
class  CharStream
 A source of characters for an ANTLR lexer. More...
class  TokenStream
 A stream of tokens accessing tokens from a TokenSource. More...
class  ANTLRStringStream
 CharStream that pull data from a unicode string. More...
class  ANTLRFileStream
 CharStream that opens a file to read the data. More...
class  ANTLRInputStream
 CharStream that reads data from a file-like object. More...
class  CommonTokenStream
 The most common stream of tokens. More...
class  RewriteOperation
 Internal helper class. More...
class  InsertBeforeOp
 Internal helper class. More...
class  ReplaceOp
 Internal helper class. More...
class  DeleteOp
 Internal helper class. More...
class  TokenRewriteStream
 CommonTokenStream that can be modified. More...
class  RecognizerSharedState
 The set of fields needed by an abstract recognizer to recognize input and recover from errors etc. More...
class  BaseRecognizer
 Common recognizer functionality. More...
class  TokenSource
 if self._state.failed: sys.stdout.write(" failed=%s" % self._state.failed) More...
class  Lexer
 Baseclass for generated lexer classes. More...
class  Parser
 Baseclass for generated parser classes. More...
class  RuleReturnScope
 Rules can return start/stop info as well as possible trees and templates. More...
class  ParserRuleReturnScope
 Rules that return more than a single value must return an object containing all the values. More...

Packages

package  tree
 ANTLR3 runtime package, tree module.
package  treewizard

Functions

def version_str_to_tuple
def reportError
 def mismatchRecover(self, input, ttype, follow): if self.mismatchIsUnwantedToken(input, ttype): mte = UnwantedTokenException(ttype, input)
def displayRecognitionError
def getErrorMessage
 What error message should be generated for the various exception types?
def getNumberOfSyntaxErrors
 Get number of recognition errors (lexer, parser, tree parser).
def getErrorHeader
 What is the error header, normally line/character position information?
def getTokenErrorDisplay
 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.
def emitErrorMessage
 Override this method to change where error messages go.
def recover
 Recover from an error found on the input stream.
def beginResync
 A hook to listen in on the token consumption during error recovery.
def endResync
 A hook to listen in on the token consumption during error recovery.
def computeErrorRecoverySet
 Compute the error recovery set for the current rule.
def computeContextSensitiveRuleFOLLOW
 Compute the context-sensitive FOLLOW set for current rule.
def combineFollows
def recoverFromMismatchedToken
 Attempt to recover from a single missing or extra token.
def recoverFromMismatchedSet
 Not currently used.
def getCurrentInputSymbol
 Match needs to return the current input symbol, which gets put into the label for the associated token ref; e.g., x=ID.
def getMissingSymbol
 Conjure up a missing token during error recovery.
def consumeUntil
 def recoverFromMissingElement(self, input, e, follow): """ This code is factored out from mismatched token and mismatched set recovery.
def getRuleInvocationStack
def _getRuleInvocationStack
 A more general version of getRuleInvocationStack where you can pass in, for example, a RecognitionException to get it's rule stack trace.
def getBacktrackingLevel
def getGrammarFileName
 For debugging and other purposes, might want the grammar name.
def getSourceName
def toStrings
 A convenience method for use most often with template rewrites.
def getRuleMemoization
 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.
def alreadyParsedRule
 Has this rule already parsed input at the current index in the input stream? Return the stop token index or MEMO_RULE_UNKNOWN.
def memoize
 Record whether or not this rule parsed the input at this position successfully.
def traceIn
def traceOut
 if self._state.failed: sys.stdout.write(" failed=%s" % self._state.failed)

Variables

string __version__ = '3.1.1'
 runtime_version_str = __version__
tuple runtime_version = version_str_to_tuple(runtime_version_str)
int EOF = 1
int DEFAULT_CHANNEL = 0
 All tokens go to the parser (unless skip() is called in that rule) on a particular "channel".
int HIDDEN_CHANNEL = 99
 Anything on different channel than DEFAULT_CHANNEL is not parsed by parser.
int EOR_TOKEN_TYPE = 1
int DOWN = 2
 imaginary tree navigation type; traverse "get child" link
int UP = 3
 imaginary tree navigation type; finish with a child list
int MIN_TOKEN_TYPE = 1
int INVALID_TOKEN_TYPE = 0
tuple EOF_TOKEN = CommonToken(type=EOF)
tuple INVALID_TOKEN = CommonToken(type=INVALID_TOKEN_TYPE)
tuple SKIP_TOKEN = CommonToken(type=INVALID_TOKEN_TYPE)
 StringStream = ANTLRStringStream
 FileStream = ANTLRFileStream
 InputStream = ANTLRInputStream
tuple _getRuleInvocationStack = classmethod(_getRuleInvocationStack)


Detailed Description

ANTLR3 runtime package.

This module contains all support classes, which are needed to use recognizers generated by ANTLR3.


Function Documentation

def antlr3._getRuleInvocationStack (   cls,
  module 
) [private]

A more general version of getRuleInvocationStack where you can pass in, for example, a RecognitionException to get it's rule stack trace.

This routine is shared with all recognizers, hence, static.

TODO: move to a utility class or something; weird having lexer call this

Definition at line 3320 of file antlr3.py.

def antlr3.alreadyParsedRule (   self,
  input,
  ruleIndex 
)

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.

Definition at line 3408 of file antlr3.py.

def antlr3.beginResync (   self  ) 

A hook to listen in on the token consumption during error recovery.

The DebugParser subclasses this to fire events to the listenter.

Definition at line 2939 of file antlr3.py.

def antlr3.combineFollows (   self,
  exact 
)

Definition at line 3111 of file antlr3.py.

def antlr3.computeContextSensitiveRuleFOLLOW (   self  ) 

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=>*alpha r beta in G and x in FIRST(beta)}

where x in T* and 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 *any* sentential 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.

Definition at line 3106 of file antlr3.py.

def antlr3.computeErrorRecoverySet (   self  ) 

Compute the error recovery set for the current rule.

During rule invocation, the parser pushes the set of tokens that can follow that rule reference on the stack; this amounts to computing FIRST of what follows the rule reference in the enclosing rule. This local follow set only includes tokens from within the rule; i.e., the FIRST computation done by ANTLR stops at the end of a rule.

EXAMPLE

When you find a "no viable alt exception", the input is not consistent with any of the alternatives for rule r. The best thing to do is to consume tokens until you see something that can legally follow a call to r *or* any rule that called r. You don't want the exact set of viable next tokens because the input might just be missing a token--you might consume the rest of the input looking for one of the missing tokens.

Consider grammar:

a : '[' b ']' | '(' b ')' ; b : c '^' INT ; c : ID | INT ;

At each rule invocation, the set of tokens that could follow that rule is pushed on a stack. Here are the various "local" follow sets:

FOLLOW(b1_in_a) = FIRST(']') = ']' FOLLOW(b2_in_a) = FIRST(')') = ')' FOLLOW(c_in_b) = FIRST('^') = '^'

Upon erroneous input "[]", the call chain is

a -> b -> c

and, hence, the follow context stack is:

depth local follow set after call to rule 0 <EOF> a (from main()) 1 ']' b 3 '^' c

Notice that ')' is not included, because b would have to have been called from a different context in rule a for ')' to be included.

For error recovery, we cannot consider FOLLOW(c) (context-sensitive or otherwise). We need the combined set of all context-sensitive FOLLOW sets--the set of all tokens that could follow any reference in the call chain. We need to resync to one of those tokens. Note that FOLLOW(c)='^' and if we resync'd to that token, we'd consume until EOF. We need to sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}. In this case, for input "[]", LA(1) is in this set so we would not consume anything and after printing an error rule c would return normally. It would not find the required '^' though. At this point, it gets a mismatched token error and throws an exception (since LA(1) is not in the viable following token set). The rule exception handler tries to recover, but finds the same recovery set and doesn't consume anything. Rule b exits normally returning to rule a. Now it finds the ']' (and with the successful match exits errorRecovery mode).

So, you cna see that the parser walks up call chain looking for the token that was a member of the recovery set.

Errors are not generated in errorRecovery mode.

ANTLR's error recovery mechanism is based upon original ideas:

"Algorithms + Data Structures = Programs" by Niklaus Wirth

and

"A note on error recovery in recursive descent parsers": http://portal.acm.org/citation.cfm?id=947902.947905

Later, Josef Grosch had some good ideas:

"Efficient and Comfortable Error Recovery in Recursive Descent Parsers": ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip

Like Grosch I implemented local FOLLOW sets that are combined at run-time upon error to avoid overhead during parsing.

Definition at line 3047 of file antlr3.py.

def antlr3.consumeUntil (   self,
  input,
  tokenTypes 
)

def recoverFromMissingElement(self, input, e, follow): """ This code is factored out from mismatched token and mismatched set recovery.

It handles "single token insertion" error recovery for both. No tokens are consumed to recover from insertions. Return true if recovery was possible else return false. """ if self.mismatchIsMissingToken(input, follow): self.reportError(e) return True # nothing to do; throw exception return False Consume tokens until one matches the given token or token set

tokenTypes can be a single token type or a set of token types

Definition at line 3273 of file antlr3.py.

def antlr3.displayRecognitionError (   self,
  tokenNames,
  e 
)

Definition at line 2745 of file antlr3.py.

def antlr3.emitErrorMessage (   self,
  msg 
)

Override this method to change where error messages go.

Definition at line 2903 of file antlr3.py.

def antlr3.endResync (   self  ) 

A hook to listen in on the token consumption during error recovery.

The DebugParser subclasses this to fire events to the listenter.

Definition at line 2949 of file antlr3.py.

def antlr3.getBacktrackingLevel (   self  ) 

Definition at line 3348 of file antlr3.py.

def antlr3.getCurrentInputSymbol (   self,
  input 
)

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.

Definition at line 3220 of file antlr3.py.

def antlr3.getErrorHeader (   self,
  e 
)

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

Definition at line 2874 of file antlr3.py.

def antlr3.getErrorMessage (   self,
  e,
  tokenNames 
)

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.

Definition at line 2775 of file antlr3.py.

def antlr3.getGrammarFileName (   self  ) 

For debugging and other purposes, might want the grammar name.

Have ANTLR generate an implementation for this method.

Definition at line 3357 of file antlr3.py.

def antlr3.getMissingSymbol (   self,
  input,
  e,
  expectedTokenType,
  follow 
)

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.

Definition at line 3245 of file antlr3.py.

def antlr3.getNumberOfSyntaxErrors (   self  ) 

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()

Definition at line 2866 of file antlr3.py.

def antlr3.getRuleInvocationStack (   self  ) 

Definition at line 3284 of file antlr3.py.

def antlr3.getRuleMemoization (   self,
  ruleIndex,
  ruleStartIndex 
)

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.

Definition at line 3387 of file antlr3.py.

def antlr3.getSourceName (   self  ) 

Definition at line 3362 of file antlr3.py.

def antlr3.getTokenErrorDisplay (   self,
  t 
)

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.

Definition at line 2889 of file antlr3.py.

def antlr3.memoize (   self,
  input,
  ruleIndex,
  ruleStartIndex,
  success 
)

Record whether or not this rule parsed the input at this position successfully.

Definition at line 3428 of file antlr3.py.

def antlr3.recover (   self,
  input,
  re 
)

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.

Definition at line 2915 of file antlr3.py.

def antlr3.recoverFromMismatchedSet (   self,
  input,
  e,
  follow 
)

Not currently used.

Definition at line 3198 of file antlr3.py.

def antlr3.recoverFromMismatchedToken (   self,
  input,
  ttype,
  follow 
)

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 ')'.

Definition at line 3160 of file antlr3.py.

def antlr3.reportError (   self,
  e 
)

def mismatchRecover(self, input, ttype, follow): if self.mismatchIsUnwantedToken(input, ttype): mte = UnwantedTokenException(ttype, input)

elif self.mismatchIsMissingToken(input, follow): mte = MissingTokenException(ttype, input) else: mte = MismatchedTokenException(ttype, input) self.recoverFromMismatchedToken(input, mte, ttype, follow) 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.

Definition at line 2732 of file antlr3.py.

def antlr3.toStrings (   self,
  tokens 
)

A convenience method for use most often with template rewrites.

Convert a List<Token> to List<String>

Definition at line 3371 of file antlr3.py.

def antlr3.traceIn (   self,
  ruleName,
  ruleIndex,
  inputSymbol 
)

Definition at line 3439 of file antlr3.py.

def antlr3.traceOut (   self,
  ruleName,
  ruleIndex,
  inputSymbol 
)

if self._state.failed: sys.stdout.write(" failed=%s" % self._state.failed)

Definition at line 3451 of file antlr3.py.

def antlr3.version_str_to_tuple (   version_str  ) 

Definition at line 144 of file antlr3.py.


Variable Documentation

string antlr3.__version__ = '3.1.1'

Definition at line 142 of file antlr3.py.

Definition at line 3345 of file antlr3.py.

All tokens go to the parser (unless skip() is called in that rule) on a particular "channel".

The parser tunes to a particular channel so that whitespace etc... can go to the parser on a "hidden" channel.

Definition at line 529 of file antlr3.py.

int antlr3.DOWN = 2

imaginary tree navigation type; traverse "get child" link

Definition at line 540 of file antlr3.py.

int antlr3.EOF = 1

Definition at line 524 of file antlr3.py.

Definition at line 947 of file antlr3.py.

Definition at line 536 of file antlr3.py.

Definition at line 1544 of file antlr3.py.

Anything on different channel than DEFAULT_CHANNEL is not parsed by parser.

Definition at line 533 of file antlr3.py.

Definition at line 1545 of file antlr3.py.

Definition at line 949 of file antlr3.py.

Definition at line 547 of file antlr3.py.

Definition at line 545 of file antlr3.py.

tuple antlr3.runtime_version = version_str_to_tuple(runtime_version_str)

Definition at line 164 of file antlr3.py.

Definition at line 163 of file antlr3.py.

Definition at line 953 of file antlr3.py.

Definition at line 1543 of file antlr3.py.

int antlr3.UP = 3

imaginary tree navigation type; finish with a child list

Definition at line 543 of file antlr3.py.


Generated on Wed Oct 1 14:13:52 2008 for ANTLR Python API by  doxygen 1.5.5