Class Parser
- java.lang.Object
- 
- org.antlr.v4.runtime.Recognizer<Token,ParserATNSimulator>
- 
- org.antlr.v4.runtime.Parser
 
 
- 
- Direct Known Subclasses:
- ParserInterpreter
 
 public abstract class Parser extends Recognizer<Token,ParserATNSimulator> This is all the parsing support code essentially; most of it is error recovery stuff.
- 
- 
Nested Class SummaryNested Classes Modifier and Type Class Description classParser.TraceListenerstatic classParser.TrimToSizeListener
 - 
Field SummaryFields Modifier and Type Field Description protected boolean_buildParseTreesSpecifies whether or not the parser should construct a parse tree during the parsing process.protected ParserRuleContext_ctxTheParserRuleContextobject for the currently executing rule.protected ANTLRErrorStrategy_errHandlerThe error handling strategy for the parser.protected TokenStream_inputThe input stream.protected List<ParseTreeListener>_parseListenersThe list ofParseTreeListenerlisteners registered to receive events during the parse.protected IntegerStack_precedenceStackprotected int_syntaxErrorsThe number of syntax errors reported during parsing.protected booleanmatchedEOFIndicates parser has match()ed EOF token.- 
Fields inherited from class org.antlr.v4.runtime.Recognizer_interp, EOF
 
- 
 - 
Constructor SummaryConstructors Constructor Description Parser(TokenStream input)
 - 
Method SummaryAll Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description protected voidaddContextToParseTree()voidaddParseListener(ParseTreeListener listener)Registerslistenerto receive events during the parsing process.ParseTreePatterncompileParseTreePattern(String pattern, int patternRuleIndex)The preferred method of getting a tree pattern.ParseTreePatterncompileParseTreePattern(String pattern, int patternRuleIndex, Lexer lexer)The same ascompileParseTreePattern(String, int)but specify aLexerrather than trying to deduce it from this parser.Tokenconsume()Consume and return the current symbol.ErrorNodecreateErrorNode(ParserRuleContext parent, Token t)How to create an error node, given a token, associated with a parent.TerminalNodecreateTerminalNode(ParserRuleContext parent, Token t)How to create a token leaf node associated with a parent.voiddumpDFA()voiddumpDFA(PrintStream dumpStream)For debugging and other purposes.voidenterOuterAlt(ParserRuleContext localctx, int altNum)voidenterRecursionRule(ParserRuleContext localctx, int ruleIndex)Deprecated.UseenterRecursionRule(ParserRuleContext, int, int, int)instead.voidenterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence)voidenterRule(ParserRuleContext localctx, int state, int ruleIndex)Always called by generated parsers upon entry to a rule.voidexitRule()ATNgetATNWithBypassAlts()The ATN with bypass alternatives is expensive to create so we create it lazily.booleangetBuildParseTree()Gets whether or not a complete parse tree will be constructed while parsing.ParserRuleContextgetContext()TokengetCurrentToken()Match needs to return the current input symbol, which gets put into the label for the associated token ref; e.g., x=ID.List<String>getDFAStrings()For debugging and other purposes.ANTLRErrorStrategygetErrorHandler()IntervalSetgetExpectedTokens()Computes the set of input symbols which could follow the current parser state and context, as given byRecognizer.getState()andgetContext(), respectively.IntervalSetgetExpectedTokensWithinCurrentRule()TokenStreamgetInputStream()ParserRuleContextgetInvokingContext(int ruleIndex)intgetNumberOfSyntaxErrors()Gets the number of syntax errors reported during parsing.ParseInfogetParseInfo()If profiling during the parse/lex, this will return DecisionInfo records for each decision in recognizer in a ParseInfo object.List<ParseTreeListener>getParseListeners()intgetPrecedence()Get the precedence level for the top-most precedence rule.ParserRuleContextgetRuleContext()intgetRuleIndex(String ruleName)Get a rule's index (i.e.,RULE_ruleNamefield) or -1 if not found.List<String>getRuleInvocationStack()Return List<String> of the rule names in your parser instance leading up to a call to the current rule.List<String>getRuleInvocationStack(RuleContext p)StringgetSourceName()TokenFactory<?>getTokenFactory()TokenStreamgetTokenStream()booleangetTrimParseTree()booleaninContext(String context)booleanisExpectedToken(int symbol)Checks whether or notsymbolcan follow the current state in the ATN.booleanisMatchedEOF()booleanisTrace()Gets whether aParser.TraceListeneris registered as a parse listener for the parser.Tokenmatch(int ttype)Match current input symbol againstttype.TokenmatchWildcard()Match current input symbol as a wildcard.voidnotifyErrorListeners(String msg)voidnotifyErrorListeners(Token offendingToken, String msg, RecognitionException e)booleanprecpred(RuleContext localctx, int precedence)voidpushNewRecursionContext(ParserRuleContext localctx, int state, int ruleIndex)LikeenterRule(org.antlr.v4.runtime.ParserRuleContext, int, int)but for recursive rules.voidremoveParseListener(ParseTreeListener listener)Removelistenerfrom the list of parse listeners.voidremoveParseListeners()Remove all parse listeners.voidreset()reset the parser's statevoidsetBuildParseTree(boolean buildParseTrees)Track theParserRuleContextobjects during the parse and hook them up using theParserRuleContext.childrenlist so that it forms a parse tree.voidsetContext(ParserRuleContext ctx)voidsetErrorHandler(ANTLRErrorStrategy handler)voidsetInputStream(IntStream input)voidsetProfile(boolean profile)voidsetTokenFactory(TokenFactory<?> factory)Tell our token source and error strategy about a new way to create tokens.voidsetTokenStream(TokenStream input)Set the token stream and reset the parser.voidsetTrace(boolean trace)During a parse is sometimes useful to listen in on the rule entry and exit events as well as token matches.voidsetTrimParseTree(boolean trimParseTrees)Trim the internal lists of the parse tree during parsing to conserve memory.protected voidtriggerEnterRuleEvent()Notify any parse listeners of an enter rule event.protected voidtriggerExitRuleEvent()Notify any parse listeners of an exit rule event.voidunrollRecursionContexts(ParserRuleContext _parentctx)- 
Methods inherited from class org.antlr.v4.runtime.Recognizeraction, addErrorListener, getATN, getErrorHeader, getErrorListenerDispatch, getErrorListeners, getGrammarFileName, getInterpreter, getRuleIndexMap, getRuleNames, getSerializedATN, getState, getTokenErrorDisplay, getTokenNames, getTokenType, getTokenTypeMap, getVocabulary, removeErrorListener, removeErrorListeners, sempred, setInterpreter, setState
 
- 
 
- 
- 
- 
Field Detail- 
_errHandlerprotected ANTLRErrorStrategy _errHandler The error handling strategy for the parser. The default value is a new instance ofDefaultErrorStrategy.
 - 
_inputprotected TokenStream _input The input stream.
 - 
_precedenceStackprotected final IntegerStack _precedenceStack 
 - 
_ctxprotected ParserRuleContext _ctx TheParserRuleContextobject for the currently executing rule. This is always non-null during the parsing process.
 - 
_buildParseTreesprotected boolean _buildParseTrees Specifies whether or not the parser should construct a parse tree during the parsing process. The default value istrue.- See Also:
- getBuildParseTree(),- setBuildParseTree(boolean)
 
 - 
_parseListenersprotected List<ParseTreeListener> _parseListeners The list ofParseTreeListenerlisteners registered to receive events during the parse.
 - 
_syntaxErrorsprotected int _syntaxErrors The number of syntax errors reported during parsing. This value is incremented each timenotifyErrorListeners(java.lang.String)is called.
 - 
matchedEOFprotected boolean matchedEOF Indicates parser has match()ed EOF token. SeeexitRule().
 
- 
 - 
Constructor Detail- 
Parserpublic Parser(TokenStream input) 
 
- 
 - 
Method Detail- 
resetpublic void reset() reset the parser's state
 - 
matchpublic Token match(int ttype) throws RecognitionException Match current input symbol againstttype. If the symbol type matches,ANTLRErrorStrategy.reportMatch(org.antlr.v4.runtime.Parser)andconsume()are called to complete the match process.If the symbol type does not match, ANTLRErrorStrategy.recoverInline(org.antlr.v4.runtime.Parser)is called on the current error strategy to attempt recovery. IfgetBuildParseTree()istrueand the token index of the symbol returned byANTLRErrorStrategy.recoverInline(org.antlr.v4.runtime.Parser)is -1, the symbol is added to the parse tree by callingcreateErrorNode(ParserRuleContext, Token)thenParserRuleContext.addErrorNode(ErrorNode).- Parameters:
- ttype- the token type to match
- Returns:
- the matched symbol
- Throws:
- RecognitionException- if the current input symbol did not match- ttypeand the error strategy could not recover from the mismatched symbol
 
 - 
matchWildcardpublic 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(org.antlr.v4.runtime.Parser)andconsume()are called to complete the match process.If the symbol type does not match, ANTLRErrorStrategy.recoverInline(org.antlr.v4.runtime.Parser)is called on the current error strategy to attempt recovery. IfgetBuildParseTree()istrueand the token index of the symbol returned byANTLRErrorStrategy.recoverInline(org.antlr.v4.runtime.Parser)is -1, the symbol is added to the parse tree by callingcreateErrorNode(ParserRuleContext, Token). thenParserRuleContext.addErrorNode(ErrorNode)- Returns:
- the matched symbol
- Throws:
- RecognitionException- if the current input symbol did not match a wildcard and the error strategy could not recover from the mismatched symbol
 
 - 
setBuildParseTreepublic void setBuildParseTree(boolean buildParseTrees) Track theParserRuleContextobjects during the parse and hook them up using theParserRuleContext.childrenlist so that it forms a parse tree. TheParserRuleContextreturned 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.childrenlist. Contexts are then not candidates for garbage collection.
 - 
getBuildParseTreepublic boolean getBuildParseTree() Gets whether or not a complete parse tree will be constructed while parsing. This property istruefor a newly constructed parser.- Returns:
- trueif a complete parse tree will be constructed while parsing, otherwise- false
 
 - 
setTrimParseTreepublic void setTrimParseTree(boolean trimParseTrees) Trim the internal lists of the parse tree during parsing to conserve memory. This property is set tofalseby default for a newly constructed parser.- Parameters:
- trimParseTrees-- trueto trim the capacity of the- ParserRuleContext.childrenlist to its size after a rule is parsed.
 
 - 
getTrimParseTreepublic boolean getTrimParseTree() - Returns:
- trueif the- ParserRuleContext.childrenlist is trimmed using the default- Parser.TrimToSizeListenerduring the parse process.
 
 - 
getParseListenerspublic List<ParseTreeListener> getParseListeners() 
 - 
addParseListenerpublic void addParseListener(ParseTreeListener listener) Registerslistenerto 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.DEFAULTused 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- the listener to add
- Throws:
- NullPointerException- if listener is- null
 
 - 
removeParseListenerpublic void removeParseListener(ParseTreeListener listener) Removelistenerfrom the list of parse listeners.If listenerisnullor has not been added as a parse listener, this method does nothing.- Parameters:
- listener- the listener to remove
- See Also:
- addParseListener(org.antlr.v4.runtime.tree.ParseTreeListener)
 
 - 
removeParseListenerspublic void removeParseListeners() Remove all parse listeners.
 - 
triggerEnterRuleEventprotected void triggerEnterRuleEvent() Notify any parse listeners of an enter rule event.
 - 
triggerExitRuleEventprotected void triggerExitRuleEvent() Notify any parse listeners of an exit rule event.
 - 
getNumberOfSyntaxErrorspublic int getNumberOfSyntaxErrors() Gets the number of syntax errors reported during parsing. This value is incremented each timenotifyErrorListeners(java.lang.String)is called.- See Also:
- notifyErrorListeners(java.lang.String)
 
 - 
getTokenFactorypublic TokenFactory<?> getTokenFactory() - Specified by:
- getTokenFactoryin class- Recognizer<Token,ParserATNSimulator>
 
 - 
setTokenFactorypublic void setTokenFactory(TokenFactory<?> factory) Tell our token source and error strategy about a new way to create tokens.- Specified by:
- setTokenFactoryin class- Recognizer<Token,ParserATNSimulator>
 
 - 
getATNWithBypassAltspublic ATN getATNWithBypassAlts() The ATN with bypass alternatives is expensive to create so we create it lazily.- Throws:
- UnsupportedOperationException- if the current parser does not implement the- Recognizer.getSerializedATN()method.
 
 - 
compileParseTreePatternpublic 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");
 - 
compileParseTreePatternpublic ParseTreePattern compileParseTreePattern(String pattern, int patternRuleIndex, Lexer lexer) The same ascompileParseTreePattern(String, int)but specify aLexerrather than trying to deduce it from this parser.
 - 
getErrorHandlerpublic ANTLRErrorStrategy getErrorHandler() 
 - 
setErrorHandlerpublic void setErrorHandler(ANTLRErrorStrategy handler) 
 - 
getInputStreampublic TokenStream getInputStream() - Specified by:
- getInputStreamin class- Recognizer<Token,ParserATNSimulator>
 
 - 
setInputStreampublic final void setInputStream(IntStream input) - Specified by:
- setInputStreamin class- Recognizer<Token,ParserATNSimulator>
 
 - 
getTokenStreampublic TokenStream getTokenStream() 
 - 
setTokenStreampublic void setTokenStream(TokenStream input) Set the token stream and reset the parser.
 - 
getCurrentTokenpublic 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.
 - 
notifyErrorListenerspublic final void notifyErrorListeners(String msg) 
 - 
notifyErrorListenerspublic void notifyErrorListeners(Token offendingToken, String msg, RecognitionException e) 
 - 
consumepublic Token consume() Consume and return the current symbol.E.g., given the following input with Abeing the current lookahead symbol, this function moves the cursor toBand returnsA.A B ^ If the parser is not in error recovery mode, the consumed symbol is added to the parse tree usingParserRuleContext.addChild(TerminalNode), andParseTreeListener.visitTerminal(org.antlr.v4.runtime.tree.TerminalNode)is called on any parse listeners. If the parser is in error recovery mode, the consumed symbol is added to the parse tree usingcreateErrorNode(ParserRuleContext, Token)thenParserRuleContext.addErrorNode(ErrorNode)andParseTreeListener.visitErrorNode(org.antlr.v4.runtime.tree.ErrorNode)is called on any parse listeners.
 - 
createTerminalNodepublic 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
 
 - 
createErrorNodepublic 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
 
 - 
addContextToParseTreeprotected void addContextToParseTree() 
 - 
enterRulepublic void enterRule(ParserRuleContext localctx, int state, int ruleIndex) Always called by generated parsers upon entry to a rule. Access field_ctxget the current context.
 - 
exitRulepublic void exitRule() 
 - 
enterOuterAltpublic void enterOuterAlt(ParserRuleContext localctx, int altNum) 
 - 
getPrecedencepublic final int getPrecedence() Get the precedence level for the top-most precedence rule.- Returns:
- The precedence level for the top-most precedence rule, or -1 if the parser context is not nested within a precedence rule.
 
 - 
enterRecursionRule@Deprecated public void enterRecursionRule(ParserRuleContext localctx, int ruleIndex) Deprecated.UseenterRecursionRule(ParserRuleContext, int, int, int)instead.
 - 
enterRecursionRulepublic void enterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence) 
 - 
pushNewRecursionContextpublic void pushNewRecursionContext(ParserRuleContext localctx, int state, int ruleIndex) LikeenterRule(org.antlr.v4.runtime.ParserRuleContext, int, int)but for recursive rules. Make the current context the child of the incoming localctx.
 - 
unrollRecursionContextspublic void unrollRecursionContexts(ParserRuleContext _parentctx) 
 - 
getInvokingContextpublic ParserRuleContext getInvokingContext(int ruleIndex) 
 - 
getContextpublic ParserRuleContext getContext() 
 - 
setContextpublic void setContext(ParserRuleContext ctx) 
 - 
precpredpublic boolean precpred(RuleContext localctx, int precedence) - Overrides:
- precpredin class- Recognizer<Token,ParserATNSimulator>
 
 - 
inContextpublic boolean inContext(String context) 
 - 
isExpectedTokenpublic boolean isExpectedToken(int symbol) Checks whether or notsymbolcan 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- the symbol type to check
- Returns:
- trueif- symbolcan follow the current state in the ATN, otherwise- false.
 
 - 
isMatchedEOFpublic boolean isMatchedEOF() 
 - 
getExpectedTokenspublic IntervalSet getExpectedTokens() Computes the set of input symbols which could follow the current parser state and context, as given byRecognizer.getState()andgetContext(), respectively.- See Also:
- ATN.getExpectedTokens(int, RuleContext)
 
 - 
getExpectedTokensWithinCurrentRulepublic IntervalSet getExpectedTokensWithinCurrentRule() 
 - 
getRuleIndexpublic int getRuleIndex(String ruleName) Get a rule's index (i.e.,RULE_ruleNamefield) or -1 if not found.
 - 
getRuleContextpublic ParserRuleContext getRuleContext() 
 - 
getRuleInvocationStackpublic 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.
 - 
getRuleInvocationStackpublic List<String> getRuleInvocationStack(RuleContext p) 
 - 
dumpDFApublic void dumpDFA() 
 - 
dumpDFApublic void dumpDFA(PrintStream dumpStream) For debugging and other purposes.
 - 
getSourceNamepublic String getSourceName() 
 - 
getParseInfopublic ParseInfo getParseInfo() Description copied from class:RecognizerIf profiling during the parse/lex, this will return DecisionInfo records for each decision in recognizer in a ParseInfo object.- Overrides:
- getParseInfoin class- Recognizer<Token,ParserATNSimulator>
 
 - 
setProfilepublic void setProfile(boolean profile) - Since:
- 4.3
 
 - 
setTracepublic 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.
 - 
isTracepublic boolean isTrace() Gets whether aParser.TraceListeneris registered as a parse listener for the parser.- See Also:
- setTrace(boolean)
 
 
- 
 
-