Top Description Inners Fields Constructors Methods
org.antlr.v4.runtime

public abstract Class Parser

extends Recognizer<Token, ParserATNSimulator>
Class Inheritance
Known Direct Subclasses
org.antlr.v4.runtime.ParserInterpreter
Imports
org.antlr.v4.runtime.atn.ATN, .ATNDeserializationOptions, .ATNDeserializer, .ATNSimulator, .ATNState, .ParseInfo, .ParserATNSimulator, .ProfilingATNSimulator, .RuleTransition, org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.misc.IntegerStack, .IntervalSet, .NotNull, .Nullable, org.antlr.v4.runtime.tree.ErrorNode, .ErrorNodeImpl, .ParseTreeListener, .ParseTreeWalker, .TerminalNode, .TerminalNodeImpl, org.antlr.v4.runtime.tree.pattern.ParseTreePattern, .ParseTreePatternMatcher, java.util.ArrayList, .Collections, .List, .Map, .WeakHashMap

This is all the parsing support code essentially; most of it is error recovery stuff.

Nested and Inner Type Summary

Modifier and TypeClass and Description
public class
public static class

Field Summary

Modifier and TypeField and Description
protected boolean
_buildParseTrees

Specifies whether or not the parser should construct a parse tree during the parsing process.

protected ParserRuleContext
_ctx

The ParserRuleContext object for the currently executing rule.

protected ANTLRErrorStrategy
_errHandler

The error handling strategy for the parser.

protected TokenStream
_input

The input stream.

protected List<ParseTreeListener>
_parseListeners

The list of ParseTreeListener listeners registered to receive events during the parse.

protected final IntegerStack
protected int
_syntaxErrors

The number of syntax errors reported during parsing.

private Parser.TraceListener
_tracer

When setTrace(true) is called, a reference to the TraceListener is stored here so it can be easily removed in a later call to setTrace(false).

private static final Map<String, ATN>
bypassAltsAtnCache

This field maps from the serialized ATN string to the deserialized ATN with bypass alternatives.

protected boolean
matchedEOF

Indicates parser has match()ed EOF token.

Inherited from org.antlr.v4.runtime.Recognizer:
_interpEOF

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
protected void
public void
addParseListener(ParseTreeListener
the listener to add
listener
)

Registers listener to receive events during the parsing process.

public ParseTreePattern
compileParseTreePattern(String pattern, int patternRuleIndex)

The preferred method of getting a tree pattern.

public ParseTreePattern
compileParseTreePattern(String pattern, int patternRuleIndex, Lexer lexer)

The same as compileParseTreePattern(String, int) but specify a Lexer rather than trying to deduce it from this parser.

public Token
consume()

Consume and return the current symbol.

public ErrorNode
createErrorNode(ParserRuleContext parent, Token t)

How to create an error node, given a token, associated with a parent.

public TerminalNode
createTerminalNode(ParserRuleContext parent, Token t)

How to create a token leaf node associated with a parent.

public void
dumpDFA()

For debugging and other purposes.

public void
enterLeftFactoredRule(ParserRuleContext localctx, int state, int ruleIndex)

public void
enterOuterAlt(ParserRuleContext localctx, int altNum)

public void
public void
enterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence)

public void
enterRule(ParserRuleContext localctx, int state, int ruleIndex)

Always called by generated parsers upon entry to a rule.

public void
public ATN
getATNWithBypassAlts()

The ATN with bypass alternatives is expensive to create so we create it lazily.

public boolean

Returns:

true if a complete parse tree will be constructed while parsing, otherwise false
getBuildParseTree
()

Gets whether or not a complete parse tree will be constructed while parsing.

public ParserRuleContext
public Token
getCurrentToken()

Match needs to return the current input symbol, which gets put into the label for the associated token ref; e.g., x=ID.

public List<String>
getDFAStrings()

For debugging and other purposes.

public ANTLRErrorStrategy
public ParserErrorListener
public IntervalSet
getExpectedTokens()

Computes the set of input symbols which could follow the current parser state and context, as given by getState and getContext, respectively.

public IntervalSet
public TokenStream
public ParserRuleContext
getInvokingContext(int ruleIndex)

public int
getNumberOfSyntaxErrors()

Gets the number of syntax errors reported during parsing.

public ParseInfo
getParseInfo()

Overrides org.antlr.v4.runtime.Recognizer.getParseInfo.

If profiling during the parse/lex, this will return DecisionInfo records for each decision in recognizer in a ParseInfo object.
public List<ParseTreeListener>
public final int

Returns:

The precedence level for the top-most precedence rule, or -1 if the parser context is not nested within a precedence rule.
getPrecedence
()

Get the precedence level for the top-most precedence rule.

public ParserRuleContext
public int
getRuleIndex(String ruleName)

Get a rule's index (i.e., RULE_ruleName field) or -1 if not found.

public List<String>
getRuleInvocationStack()

Return List<String> of the rule names in your parser instance leading up to a call to the current rule.

public List<String>
public String
public TokenFactory
public boolean

Returns:

true if the ParserRuleContext#children list is trimmed using the default Parser.TrimToSizeListener during the parse process.
getTrimParseTree
()

public boolean
inContext(String context)

public boolean

Returns:

true if symbol can follow the current state in the ATN, otherwise false.
isExpectedToken
(int
the symbol type to check
symbol
)

Checks whether or not symbol can follow the current state in the ATN.

public boolean
public boolean
isTrace()

Gets whether a TraceListener is registered as a parse listener for the parser.

public Token

Returns:

the matched symbol
match
(int
the token type to match
ttype
)

Match current input symbol against ttype.

public Token

Returns:

the matched symbol
matchWildcard
()

Match current input symbol as a wildcard.

public final void
public void
public boolean
public void
pushNewRecursionContext(ParserRuleContext localctx, int state, int ruleIndex)

Like enterRule but for recursive rules.

public void
removeParseListener(ParseTreeListener
the listener to remove
listener
)

Remove listener from the list of parse listeners.

public void
removeParseListeners()

Remove all parse listeners.

public void
reset()

reset the parser's state

public void
setBuildParseTree(boolean buildParseTrees)

Track the ParserRuleContext objects during the parse and hook them up using the ParserRuleContext#children list so that it forms a parse tree.

public void
public void
public void
setInputStream(TokenStream input)

Set the token stream and reset the parser.

public void
setProfile(boolean profile)

public void
setTrace(boolean trace)

During a parse is sometimes useful to listen in on the rule entry and exit events as well as token matches.

public void
setTrimParseTree(boolean
true to trim the capacity of the ParserRuleContext#children list to its size after a rule is parsed.
trimParseTrees
)

Trim the internal lists of the parse tree during parsing to conserve memory.

protected void
triggerEnterRuleEvent()

Notify any parse listeners of an enter rule event.

protected void
triggerExitRuleEvent()

Notify any parse listeners of an exit rule event.

public void
Inherited from org.antlr.v4.runtime.Recognizer:
actionaddErrorListenergetATNgetErrorHeadergetErrorListenersgetGrammarFileNamegetInterpretergetRuleIndexMapgetRuleNamesgetSerializedATNgetStategetTokenErrorDisplaygetTokenNamesgetTokenTypegetTokenTypeMapgetVocabularyremoveErrorListenerremoveErrorListenerssempredsetInterpretersetState

Field Detail

_buildParseTreesback to summary
protected boolean _buildParseTrees

Specifies whether or not the parser should construct a parse tree during the parsing process. The default value is true.

See Also
getBuildParseTree, setBuildParseTree
_ctxback to summary
protected ParserRuleContext _ctx

The ParserRuleContext object for the currently executing rule. This is always non-null during the parsing process.

_errHandlerback to summary
protected ANTLRErrorStrategy _errHandler

The error handling strategy for the parser. The default value is a new instance of DefaultErrorStrategy.

Annotations
@NotNull
See Also
getErrorHandler, setErrorHandler
_inputback to summary
protected TokenStream _input

The input stream.

See Also
getInputStream, setInputStream
_parseListenersback to summary
protected List<ParseTreeListener> _parseListeners

The list of ParseTreeListener listeners registered to receive events during the parse.

Annotations
@Nullable
See Also
addParseListener
_precedenceStackback to summary
protected final IntegerStack _precedenceStack
_syntaxErrorsback to summary
protected int _syntaxErrors

The number of syntax errors reported during parsing. This value is incremented each time notifyErrorListeners is called.

_tracerback to summary
private Parser.TraceListener _tracer

When setTrace(true) is called, a reference to the TraceListener is stored here so it can be easily removed in a later call to setTrace(false). The listener itself is implemented as a parser listener so this field is not directly used by other parser methods.

bypassAltsAtnCacheback to summary
private static final Map<String, ATN> bypassAltsAtnCache

This field maps from the serialized ATN string to the deserialized ATN with bypass alternatives.

See Also
ATNDeserializationOptions#isGenerateRuleBypassTransitions()
matchedEOFback to summary
protected boolean matchedEOF

Indicates parser has match()ed EOF token. See exitRule().

Constructor Detail

Parserback to summary
public Parser(TokenStream input)

Method Detail

addContextToParseTreeback to summary
protected void addContextToParseTree()
addParseListenerback to summary
public void addParseListener(ParseTreeListener listener)

Registers listener to receive events during the parsing process.

To support output-preserving grammar transformations (including but not limited to left-recursion removal, automated left-factoring, and optimized code generation), calls to listener methods during the parse may differ substantially from calls made by ParseTreeWalker#DEFAULT used after the parse is complete. In particular, rule entry and exit events may occur in a different order during the parse than after the parser. In addition, calls to certain rule entry methods may be omitted.

With the following specific exceptions, calls to listener events are deterministic, i.e. for identical input the calls to listener methods will be the same.

  • Alterations to the grammar used to generate code may change the behavior of the listener calls.
  • Alterations to the command line options passed to ANTLR 4 when generating the parser may change the behavior of the listener calls.
  • Changing the version of the ANTLR Tool used to generate the parser may change the behavior of the listener calls.
Parameters
listener:ParseTreeListener

the listener to add

Exceptions
NullPointerException:
if listener is null
compileParseTreePatternback to summary
public ParseTreePattern compileParseTreePattern(String pattern, int patternRuleIndex)

The preferred method of getting a tree pattern. For example, here's a sample use:

ParseTree t = parser.expr();
ParseTreePattern p = parser.compileParseTreePattern("<ID>+0", MyParser.RULE_expr);
ParseTreeMatch m = p.match(t);
String id = m.get("ID");
compileParseTreePatternback to summary
public ParseTreePattern compileParseTreePattern(String pattern, int patternRuleIndex, Lexer lexer)

The same as compileParseTreePattern(String, int) but specify a Lexer rather than trying to deduce it from this parser.

consumeback to summary
public Token consume()

Consume and return the current symbol.

E.g., given the following input with A being the current lookahead symbol, this function moves the cursor to B and returns A.

 A B
 ^
If the parser is not in error recovery mode, the consumed symbol is added to the parse tree using ParserRuleContext#addChild(TerminalNode), and ParseTreeListener#visitTerminal is called on any parse listeners. If the parser is in error recovery mode, the consumed symbol is added to the parse tree using createErrorNode(ParserRuleContext, Token) then ParserRuleContext#addErrorNode(ErrorNode) and ParseTreeListener#visitErrorNode is called on any parse listeners.
createErrorNodeback to summary
public ErrorNode createErrorNode(ParserRuleContext parent, Token t)

How to create an error node, given a token, associated with a parent. Typically, the error node to create is not a function of the parent.

Since
4.7
createTerminalNodeback to summary
public TerminalNode createTerminalNode(ParserRuleContext parent, Token t)

How to create a token leaf node associated with a parent. Typically, the terminal node to create is not a function of the parent.

Since
4.7
dumpDFAback to summary
public void dumpDFA()

For debugging and other purposes.

enterLeftFactoredRuleback to summary
public void enterLeftFactoredRule(ParserRuleContext localctx, int state, int ruleIndex)
enterOuterAltback to summary
public void enterOuterAlt(ParserRuleContext localctx, int altNum)
enterRecursionRuleback to summary
public void enterRecursionRule(ParserRuleContext localctx, int ruleIndex)
Annotations
@Deprecated
enterRecursionRuleback to summary
public void enterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence)
enterRuleback to summary
public void enterRule(ParserRuleContext localctx, int state, int ruleIndex)

Always called by generated parsers upon entry to a rule. Access field _ctx get the current context.

exitRuleback to summary
public void exitRule()
getATNWithBypassAltsback to summary
public ATN getATNWithBypassAlts()

The ATN with bypass alternatives is expensive to create so we create it lazily.

Annotations
@NotNull
Exceptions
UnsupportedOperationException:
if the current parser does not implement the getSerializedATN() method.
getBuildParseTreeback to summary
public boolean getBuildParseTree()

Gets whether or not a complete parse tree will be constructed while parsing. This property is true for a newly constructed parser.

Returns:boolean

true if a complete parse tree will be constructed while parsing, otherwise false

getContextback to summary
public ParserRuleContext getContext()
getCurrentTokenback to summary
public Token getCurrentToken()

Match needs to return the current input symbol, which gets put into the label for the associated token ref; e.g., x=ID.

Annotations
@NotNull
getDFAStringsback to summary
public List<String> getDFAStrings()

For debugging and other purposes.

getErrorHandlerback to summary
public ANTLRErrorStrategy getErrorHandler()
Annotations
@NotNull
getErrorListenerDispatchback to summary
public ParserErrorListener getErrorListenerDispatch()

Overrides org.antlr.v4.runtime.Recognizer.getErrorListenerDispatch.

Annotations
@Override
getExpectedTokensback to summary
public IntervalSet getExpectedTokens()

Computes the set of input symbols which could follow the current parser state and context, as given by getState and getContext, respectively.

Annotations
@NotNull
See Also
ATN#getExpectedTokens(int, RuleContext)
getExpectedTokensWithinCurrentRuleback to summary
public IntervalSet getExpectedTokensWithinCurrentRule()
Annotations
@NotNull
getInputStreamback to summary
public TokenStream getInputStream()

Implements abstract org.antlr.v4.runtime.Recognizer.getInputStream.

Annotations
@Override
getInvokingContextback to summary
public ParserRuleContext getInvokingContext(int ruleIndex)
getNumberOfSyntaxErrorsback to summary
public int getNumberOfSyntaxErrors()

Gets the number of syntax errors reported during parsing. This value is incremented each time notifyErrorListeners is called.

See Also
notifyErrorListeners
getParseInfoback to summary
public ParseInfo getParseInfo()

Overrides org.antlr.v4.runtime.Recognizer.getParseInfo.

Doc from org.antlr.v4.runtime.Recognizer.getParseInfo.

If profiling during the parse/lex, this will return DecisionInfo records for each decision in recognizer in a ParseInfo object.

Annotations
@Override
getParseListenersback to summary
public List<ParseTreeListener> getParseListeners()
Annotations
@NotNull
getPrecedenceback to summary
public final int getPrecedence()

Get the precedence level for the top-most precedence rule.

Returns:int

The precedence level for the top-most precedence rule, or -1 if the parser context is not nested within a precedence rule.

getRuleContextback to summary
public ParserRuleContext getRuleContext()
getRuleIndexback to summary
public int getRuleIndex(String ruleName)

Get a rule's index (i.e., RULE_ruleName field) or -1 if not found.

getRuleInvocationStackback to summary
public List<String> getRuleInvocationStack()

Return List<String> of the rule names in your parser instance leading up to a call to the current rule. You could override if you want more details such as the file/line info of where in the ATN a rule is invoked. This is very useful for error messages.

getRuleInvocationStackback to summary
public List<String> getRuleInvocationStack(RuleContext p)
getSourceNameback to summary
public String getSourceName()
getTokenFactoryback to summary
public TokenFactory getTokenFactory()
getTrimParseTreeback to summary
public boolean getTrimParseTree()
Returns:boolean

true if the ParserRuleContext#children list is trimmed using the default Parser.TrimToSizeListener during the parse process.

inContextback to summary
public boolean inContext(String context)
isExpectedTokenback to summary
public boolean isExpectedToken(int symbol)

Checks whether or not symbol can follow the current state in the ATN. The behavior of this method is equivalent to the following, but is implemented such that the complete context-sensitive follow set does not need to be explicitly constructed.

return getExpectedTokens().contains(symbol);
Parameters
symbol:int

the symbol type to check

Returns:boolean

true if symbol can follow the current state in the ATN, otherwise false.

isMatchedEOFback to summary
public boolean isMatchedEOF()
isTraceback to summary
public boolean isTrace()

Gets whether a TraceListener is registered as a parse listener for the parser.

See Also
setTrace(boolean)
matchback to summary
public Token match(int ttype) throws RecognitionException

Match current input symbol against ttype. If the symbol type matches, ANTLRErrorStrategy#reportMatch and consume are called to complete the match process.

If the symbol type does not match, ANTLRErrorStrategy#recoverInline is called on the current error strategy to attempt recovery. If getBuildParseTree is true and the token index of the symbol returned by ANTLRErrorStrategy#recoverInline is -1, the symbol is added to the parse tree by calling createErrorNode(ParserRuleContext, Token) then ParserRuleContext#addErrorNode(ErrorNode).

Parameters
ttype:int

the token type to match

Returns:Token

the matched symbol

Annotations
@NotNull
Exceptions
RecognitionException:
if the current input symbol did not match ttype and the error strategy could not recover from the mismatched symbol
matchWildcardback to summary
public Token matchWildcard() throws RecognitionException

Match current input symbol as a wildcard. If the symbol type matches (i.e. has a value greater than 0), ANTLRErrorStrategy#reportMatch and consume are called to complete the match process.

If the symbol type does not match, ANTLRErrorStrategy#recoverInline is called on the current error strategy to attempt recovery. If getBuildParseTree is true and the token index of the symbol returned by ANTLRErrorStrategy#recoverInline is -1, the symbol is added to the parse tree by calling Parser#createErrorNode(ParserRuleContext, Token). then ParserRuleContext#addErrorNode(ErrorNode)

Returns:Token

the matched symbol

Annotations
@NotNull
Exceptions
RecognitionException:
if the current input symbol did not match a wildcard and the error strategy could not recover from the mismatched symbol
notifyErrorListenersback to summary
public final void notifyErrorListeners(String msg)
notifyErrorListenersback to summary
public void notifyErrorListeners(Token offendingToken, String msg, RecognitionException e)
precpredback to summary
public boolean precpred(RuleContext localctx, int precedence)

Overrides org.antlr.v4.runtime.Recognizer.precpred.

Annotations
@Override
pushNewRecursionContextback to summary
public void pushNewRecursionContext(ParserRuleContext localctx, int state, int ruleIndex)

Like enterRule but for recursive rules. Make the current context the child of the incoming localctx.

removeParseListenerback to summary
public void removeParseListener(ParseTreeListener listener)

Remove listener from the list of parse listeners.

If listener is null or has not been added as a parse listener, this method does nothing.

Parameters
listener:ParseTreeListener

the listener to remove

See Also
addParseListener
removeParseListenersback to summary
public void removeParseListeners()

Remove all parse listeners.

See Also
addParseListener
resetback to summary
public void reset()

reset the parser's state

setBuildParseTreeback to summary
public void setBuildParseTree(boolean buildParseTrees)

Track the ParserRuleContext objects during the parse and hook them up using the ParserRuleContext#children list so that it forms a parse tree. The ParserRuleContext returned from the start rule represents the root of the parse tree.

Note that if we are not building parse trees, rule contexts only point upwards. When a rule exits, it returns the context but that gets garbage collected if nobody holds a reference. It points upwards but nobody points at it.

When we build parse trees, we are adding all of these contexts to ParserRuleContext#children list. Contexts are then not candidates for garbage collection.

setContextback to summary
public void setContext(ParserRuleContext ctx)
setErrorHandlerback to summary
public void setErrorHandler(ANTLRErrorStrategy handler)
setInputStreamback to summary
public void setInputStream(TokenStream input)

Set the token stream and reset the parser.

setProfileback to summary
public void setProfile(boolean profile)
Since
4.3
setTraceback to summary
public void setTrace(boolean trace)

During a parse is sometimes useful to listen in on the rule entry and exit events as well as token matches. This is for quick and dirty debugging.

setTrimParseTreeback to summary
public void setTrimParseTree(boolean trimParseTrees)

Trim the internal lists of the parse tree during parsing to conserve memory. This property is set to false by default for a newly constructed parser.

Parameters
trimParseTrees:boolean

true to trim the capacity of the ParserRuleContext#children list to its size after a rule is parsed.

triggerEnterRuleEventback to summary
protected void triggerEnterRuleEvent()

Notify any parse listeners of an enter rule event.

See Also
addParseListener
triggerExitRuleEventback to summary
protected void triggerExitRuleEvent()

Notify any parse listeners of an exit rule event.

See Also
addParseListener
unrollRecursionContextsback to summary
public void unrollRecursionContexts(ParserRuleContext _parentctx)
org.antlr.v4.runtime back to summary

public Class Parser.TraceListener

extends Object
implements ParseTreeListener
Class Inheritance
All Implemented Interfaces
org.antlr.v4.runtime.tree.ParseTreeListener

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public void
public void
public void
public void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

TraceListenerback to summary
public TraceListener()

Method Detail

enterEveryRuleback to summary
public void enterEveryRule(ParserRuleContext ctx)

Implements org.antlr.v4.runtime.tree.ParseTreeListener.enterEveryRule.

Annotations
@Override
exitEveryRuleback to summary
public void exitEveryRule(ParserRuleContext ctx)

Implements org.antlr.v4.runtime.tree.ParseTreeListener.exitEveryRule.

Annotations
@Override
visitErrorNodeback to summary
public void visitErrorNode(ErrorNode node)

Implements org.antlr.v4.runtime.tree.ParseTreeListener.visitErrorNode.

Annotations
@Override
visitTerminalback to summary
public void visitTerminal(TerminalNode node)

Implements org.antlr.v4.runtime.tree.ParseTreeListener.visitTerminal.

Annotations
@Override
org.antlr.v4.runtime back to summary

public Class Parser.TrimToSizeListener

extends Object
implements ParseTreeListener
Class Inheritance
All Implemented Interfaces
org.antlr.v4.runtime.tree.ParseTreeListener

Field Summary

Modifier and TypeField and Description
public static final Parser.TrimToSizeListener

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public void
public void
public void
public void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

INSTANCEback to summary
public static final Parser.TrimToSizeListener INSTANCE

Constructor Detail

TrimToSizeListenerback to summary
public TrimToSizeListener()

Method Detail

enterEveryRuleback to summary
public void enterEveryRule(ParserRuleContext ctx)

Implements org.antlr.v4.runtime.tree.ParseTreeListener.enterEveryRule.

Annotations
@Override
exitEveryRuleback to summary
public void exitEveryRule(ParserRuleContext ctx)

Implements org.antlr.v4.runtime.tree.ParseTreeListener.exitEveryRule.

Annotations
@Override
visitErrorNodeback to summary
public void visitErrorNode(ErrorNode node)

Implements org.antlr.v4.runtime.tree.ParseTreeListener.visitErrorNode.

Annotations
@Override
visitTerminalback to summary
public void visitTerminal(TerminalNode node)

Implements org.antlr.v4.runtime.tree.ParseTreeListener.visitTerminal.

Annotations
@Override