Class ParserATNSimulator
- Direct Known Subclasses:
ProfilingATNSimulator
The basic complexity of the adaptive strategy makes it harder to understand. We begin with ATN simulation to build paths in a DFA. Subsequent prediction requests go through the DFA first. If they reach a state without an edge for the current symbol, the algorithm fails over to the ATN simulation to complete the DFA path for the current input (until it finds a conflict state or uniquely predicting state).
All of that is done without using the outer context because we want to create a DFA that is not dependent upon the rule invocation stack when we do a prediction. One DFA works in all contexts. We avoid using context not necessarily because it's slower, although it can be, but because of the DFA caching problem. The closure routine only considers the rule invocation stack created during prediction beginning in the decision rule. For example, if prediction occurs without invoking another rule's ATN, there are no context stacks in the configurations. When lack of context leads to a conflict, we don't know if it's an ambiguity or a weakness in the strong LL(*) parsing strategy (versus full LL(*)).
When SLL yields a configuration set with conflict, we rewind the input and retry the ATN simulation, this time using full outer context without adding to the DFA. Configuration context stacks will be the full invocation stacks from the start rule. If we get a conflict using full context, then we can definitively say we have a true ambiguity for that input sequence. If we don't get a conflict, it implies that the decision is sensitive to the outer context. (It is not context-sensitive in the sense of context-sensitive grammars.)
The next time we reach this DFA state with an SLL conflict, through DFA simulation, we will again retry the ATN simulation using full context mode. This is slow because we can't save the results and have to "interpret" the ATN each time we get that input.
CACHING FULL CONTEXT PREDICTIONS
We could cache results from full context to predicted alternative easily and that saves a lot of time but doesn't work in presence of predicates. The set of visible predicates from the ATN start state changes depending on the context, because closure can fall off the end of a rule. I tried to cache tuples (stack context, semantic context, predicted alt) but it was slower than interpreting and much more complicated. Also required a huge amount of memory. The goal is not to create the world's fastest parser anyway. I'd like to keep this algorithm simple. By launching multiple threads, we can improve the speed of parsing across a large number of files.
There is no strict ordering between the amount of input used by SLL vs LL, which makes it really hard to build a cache for full context. Let's say that we have input A B C that leads to an SLL conflict with full context X. That implies that using X we might only use A B but we could also use A B C D to resolve conflict. Input A B C D could predict alternative 1 in one position in the input and A B C E could predict alternative 2 in another position in input. The conflicting SLL configurations could still be non-unique in the full context prediction, which would lead us to requiring more input than the original A B C. To make a prediction cache work, we have to track the exact input used during the previous prediction. That amounts to a cache that maps X to a specific DFA for that context.
Something should be done for left-recursive expression predictions. They are likely LL(1) + pred eval. Easier to do the whole SLL unless error and retry with full LL thing Sam does.
AVOIDING FULL CONTEXT PREDICTION
We avoid doing full context retry when the outer context is empty, we did not dip into the outer context by falling off the end of the decision state rule, or when we force SLL mode.
As an example of the not dip into outer context case, consider as super constructor calls versus function calls. One grammar might look like this:
ctorBody
: '{' superCall? stat* '}'
;
Or, you might see something like
stat : superCall ';' | expression ';' | ... ;
In both cases I believe that no closure operations will dip into the outer context. In the first case ctorBody in the worst case will stop at the '}'. In the 2nd case it should stop at the ';'. Both cases should stay within the entry rule and not dip into the outer context.
PREDICATES
Predicates are always evaluated if present in either SLL or LL both. SLL and LL simulation deals with predicates differently. SLL collects predicates as it performs closure operations like ANTLR v3 did. It delays predicate evaluation until it reaches and accept state. This allows us to cache the SLL ATN simulation whereas, if we had evaluated predicates on-the-fly during closure, the DFA state configuration sets would be different and we couldn't build up a suitable DFA.
When building a DFA accept state during ATN simulation, we evaluate any predicates and return the sole semantically valid alternative. If there is more than 1 alternative, we report an ambiguity. If there are 0 alternatives, we throw an exception. Alternatives without predicates act like they have true predicates. The simple way to think about it is to strip away all alternatives with false predicates and choose the minimum alternative that remains.
When we start in the DFA and reach an accept state that's predicated, we test those and return the minimum semantically viable alternative. If no alternatives are viable, we throw an exception.
During full LL ATN simulation, closure always evaluates predicates and on-the-fly. This is crucial to reducing the configuration set size during closure. It hits a landmine when parsing with the Java grammar, for example, without this on-the-fly evaluation.
SHARING DFA
All instances of the same parser share the same decision DFAs through a
static field. Each instance gets its own ATN simulator but they share the
same ATN.decisionToDFA field. They also share a
PredictionContextCache object that makes sure that all
PredictionContext objects are shared among the DFA states. This makes
a big size difference.
THREAD SAFETY
The ParserATNSimulator locks on the ATN.decisionToDFA field when
it adds a new DFA object to that array. addDFAEdge(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.dfa.DFAState, int, org.antlr.v4.runtime.misc.IntegerList, org.antlr.v4.runtime.atn.ATNConfigSet, org.antlr.v4.runtime.atn.PredictionContextCache)
locks on the DFA for the current decision when setting the
DFAState.edges field. addDFAState(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.atn.ATNConfigSet, org.antlr.v4.runtime.atn.PredictionContextCache) locks on
the DFA for the current decision when looking up a DFA state to see if it
already exists. We must make sure that all requests to add DFA states that
are equivalent result in the same shared DFA object. This is because lots of
threads will be trying to update the DFA at once. The
addDFAState(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.atn.ATNConfigSet, org.antlr.v4.runtime.atn.PredictionContextCache) method also locks inside the DFA lock
but this time on the shared context cache when it rebuilds the
configurations' PredictionContext objects using cached
subgraphs/nodes. No other locking occurs, even during DFA simulation. This is
safe as long as we can guarantee that all threads referencing
s.edge[t] get the same physical target DFAState, or
null. Once into the DFA, the DFA simulation does not reference the
DFA.states map. It follows the DFAState.edges field to new
targets. The DFA simulator will either find DFAState.edges to be
null, to be non-null and dfa.edges[t] null, or
dfa.edges[t] to be non-null. The
addDFAEdge(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.dfa.DFAState, int, org.antlr.v4.runtime.misc.IntegerList, org.antlr.v4.runtime.atn.ATNConfigSet, org.antlr.v4.runtime.atn.PredictionContextCache) method could be racing to set the field
but in either case the DFA simulator works; if null, and requests ATN
simulation. It could also race trying to get dfa.edges[t], but either
way it will work because it's not doing a test and set operation.
Starting with SLL then failing to combined SLL/LL (Two-Stage Parsing)
Sam pointed out that if SLL does not give a syntax error, then there is no
point in doing full LL, which is slower. We only have to try LL if we get a
syntax error. For maximum speed, Sam starts the parser set to pure SLL
mode with the BailErrorStrategy:
parser.getInterpreter().setPredictionMode(PredictionMode.SLL); parser.setErrorHandler(newBailErrorStrategy());
If it does not get a syntax error, then we're done. If it does get a syntax error, we need to retry with the combined SLL/LL strategy.
The reason this works is as follows. If there are no SLL conflicts, then the grammar is SLL (at least for that input set). If there is an SLL conflict, the full LL analysis must yield a set of viable alternatives which is a subset of the alternatives reported by SLL. If the LL set is a singleton, then the grammar is LL but not SLL. If the LL set is the same size as the SLL set, the decision is SLL. If the LL set has size > 1, then that decision is truly ambiguous on the current input. If the LL set is smaller, then the SLL conflict resolution might choose an alternative that the full LL would rule out as a possibility based upon better context information. If that's the case, then the SLL parse will definitely get an error because the full LL analysis says it's not viable. If SLL conflict resolution chooses an alternative within the LL set, them both SLL and LL would choose the same alternative because they both choose the minimum of multiple conflicting alternatives.
Let's say we have a set of SLL conflicting alternatives {1, 2, 3} and
a smaller LL set called s. If s is {2, 3}, then SLL
parsing will get an error because SLL will pursue alternative 1. If
s is {1, 2} or {1, 3} then both SLL and LL will
choose the same alternative because alternative one is the minimum of either
set. If s is {2} or {3} then SLL will get a syntax
error. If s is {1} then SLL will succeed.
Of course, if the input is invalid, then we will get an error for sure in both SLL and LL parsing. Erroneous input will therefore require 2 passes over the input.
-
Field Summary
FieldsModifier and TypeFieldDescriptionbooleanstatic final booleanprivate DFAstatic final booleanbooleanDetermines whether the DFA is used for full-context predictions.private final EpsilonClosureEpsilon-closure engine for this simulator.booleanbooleanDeprecated.This flag is not currently used by the ATN simulator.booleanbooleanbooleanprotected final Parserprivate PredictionModeprivate final ReachComputationReach / target-state engine: retained config sets and the edge computation forcomputeTargetState(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.dfa.DFAState, org.antlr.v4.runtime.ParserRuleContext, int, boolean, org.antlr.v4.runtime.atn.PredictionContextCache).booleanWhentrue, ambiguous alternatives are reported when they are encountered withinexecATN(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.TokenStream, int, org.antlr.v4.runtime.atn.SimulatorState).private final PredictionContextCacheRetained prediction-context cache for ATN simulation.private final ClearableIntObjectHashMap<PredictionContext>static final booleanprivate static final Comparator<ATNConfig>private final booleanA subclass that overridesgetExistingTargetState(org.antlr.v4.runtime.dfa.DFAState, int)(the profiler) must see full-context DFA edges.booleanbooleanprotected booleanBy default we do full context-sensitive LL(*) parsing not Strong LL(*) parsing.Fields inherited from class org.antlr.v4.runtime.atn.ATNSimulator
atn, ERROR, RULE_LF_VARIANT_MARKER, RULE_NOLF_VARIANT_MARKER, RULE_VARIANT_DELIMITER, SERIALIZED_UUID, SERIALIZED_VERSION -
Constructor Summary
ConstructorsConstructorDescriptionParserATNSimulator(ATN atn) Testing only!ParserATNSimulator(Parser parser, ATN atn) -
Method Summary
Modifier and TypeMethodDescriptionprotected ATNConfigactionTransition(ATNConfig config, ActionTransition t) intadaptivePredict(TokenStream input, int decision, ParserRuleContext outerContext) intadaptivePredict(TokenStream input, int decision, ParserRuleContext outerContext, boolean useContext) protected DFAStateaddDFAContextState(DFA dfa, ATNConfigSet configs, int returnContext, PredictionContextCache contextCache) See comment on LexerInterpreter.addDFAState.protected DFAStateaddDFAEdge(DFA dfa, DFAState fromState, int t, IntegerList contextTransitions, ATNConfigSet toConfigs, PredictionContextCache contextCache) protected voidaddDFAEdge(DFAState p, int t, DFAState q) protected DFAStateaddDFAState(DFA dfa, ATNConfigSet configs, PredictionContextCache contextCache) See comment on LexerInterpreter.addDFAState.protected ATNConfigSetapplyPrecedenceFilter(ATNConfigSet configs, ParserRuleContext globalContext, PredictionContextCache contextCache) This method transforms the start state computed bycomputeStartState(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.ParserRuleContext, boolean)to the special start state used by a precedence DFA for a particular precedence value.protected voidclosure(ATNConfig config, ATNConfigSet configs, ATNConfigSet intermediate, Set<ATNConfig> closureBusy, boolean collectPredicates, boolean hasMoreContexts, PredictionContextCache contextCache, int depth, boolean treatEofAsEpsilon) Recursive helper forclosure(ATNConfigSet, ATNConfigSet, boolean, boolean, PredictionContextCache, boolean).protected voidclosure(ATNConfigSet sourceConfigs, ATNConfigSet configs, boolean collectPredicates, boolean hasMoreContext, PredictionContextCache contextCache, boolean treatEofAsEpsilon) Compute the epsilon closure of every configuration insourceConfigs, adding the resulting non-epsilon (or EOF-as-epsilon) configurations toconfigs.protected SimulatorStatecomputeReachSet(DFA dfa, SimulatorState previous, int t, PredictionContextCache contextCache) protected SimulatorStatecomputeStartState(DFA dfa, ParserRuleContext globalContext, boolean useContext) protected Tuple2<DFAState,ParserRuleContext> computeTargetState(DFA dfa, DFAState s, ParserRuleContext remainingGlobalContext, int t, boolean useContext, PredictionContextCache contextCache) Compute a target state for an edge in the DFA, and attempt to add the computed state and corresponding edge to the DFA.protected booleanconfigWithAltAtStopState(Collection<ATNConfig> configs, int alt) protected DFAStatecreateDFAState(DFA dfa, ATNConfigSet configs) void(package private) final EpsilonClosurePackage-private access to the epsilon-closure engine (same-package tests).protected booleanevalSemanticContext(SemanticContext pred, ParserRuleContext parserCallStack, int alt) Evaluate a semantic context within a specific parser context.protected BitSetevalSemanticContext(DFAState.PredPrediction[] predPredictions, ParserRuleContext outerContext, boolean complete) Look through a list of predicate/alt pairs, returning alts for the pairs that win.protected intexecATN(DFA dfa, TokenStream input, int startIndex, SimulatorState initialState) Performs ATN simulation to compute a predicted alternative based upon the remaining input, but also updates the DFA cache to avoid having to traverse the ATN again for the same input sequence.protected intexecDFA(DFA dfa, TokenStream input, int startIndex, SimulatorState state) private intexecDFA(DFA dfa, TokenStream input, int startIndex, ParserRuleContext outerContext, DFAState s0, boolean useContext, ParserRuleContext remainingOuterContext) DFA walk.private IntegerfindFirstValidAltUsingPredicates(TokenStream input, int startIndex, SimulatorState previous, BitSet alts, SemanticContext[] altToPred) protected BitSet(package private) final DFACurrent DFA under construction during prediction, if any.protected ATNConfiggetEpsilonTarget(ATNConfig config, Transition t, boolean collectPredicates, boolean inContext, PredictionContextCache contextCache, boolean treatEofAsEpsilon) Compute the target configuration after traversing epsilon transitiontfromconfig, ornulliftis not an epsilon (or EOF-as-epsilon) edge applicable in the current mode.protected DFAStategetExistingTargetState(DFAState s, int t) Get an existing target state for an edge in the DFA.getLookaheadName(TokenStream input) protected DFAState.PredPrediction[]getPredicatePredictions(BitSet ambigAlts, SemanticContext[] altToPred) final PredictionModeprotected SemanticContext[]getPredsForAmbigAlts(BitSet ambigAlts, ATNConfigSet configs, int nalts) protected ATNStategetReachableTarget(ATNConfig source, Transition trans, int ttype) protected final intgetReturnState(RuleContext context) getRuleName(int index) protected SimulatorStategetStartState(DFA dfa, TokenStream input, ParserRuleContext outerContext, boolean useContext) Local- or full-context DFA start, ornullif it is not yet built.getTokenName(int t) protected intgetUniqueAlt(Collection<ATNConfig> configs) protected inthandleNoViableAlt(TokenStream input, int startIndex, SimulatorState previous) This method is used to improve the localization of error messages by choosing an alternative rather than throwing aNoViableAltExceptionin particular prediction scenarios where theATNSimulator.ERRORstate was reached during ATN simulation.protected booleanisAcceptState(DFAState state, boolean useContext) Determines if a particular DFA state should be treated as an accept state for the current prediction mode.private ConflictInfoisConflicted(ATNConfigSet configset, PredictionContextCache contextCache) protected NoViableAltExceptionnoViableAlt(TokenStream input, ParserRuleContext outerContext, ATNConfigSet configs, int startIndex) private PredictionContextCacheReturns the retained prediction-context cache after clearing it.protected ATNConfigprecedenceTransition(ATNConfig config, PrecedencePredicateTransition pt, boolean collectPredicates, boolean inContext) protected DFAState.PredPrediction[]predicateDFAState(DFAState D, ATNConfigSet configs, int nalts) collect and set D's semantic contextprotected ATNConfigpredTransition(ATNConfig config, PredicateTransition pt, boolean collectPredicates, boolean inContext) protected ATNConfigSetremoveAllConfigsNotInRuleStopState(ATNConfigSet configs, PredictionContextCache contextCache) Return a configuration set containing only the configurations fromconfigswhich are in aRuleStopState.private static booleanrepeatedEof(ArrayList<DFAState> states, ArrayList<ParserRuleContext> contexts, DFAState state, ParserRuleContext ctx, boolean useContext) protected voidreportAmbiguity(DFA dfa, DFAState D, int startIndex, int stopIndex, boolean exact, BitSet ambigAlts, ATNConfigSet configs) If context sensitive parsing, we know it's ambiguity not conflictprotected voidreportAttemptingFullContext(DFA dfa, BitSet conflictingAlts, SimulatorState conflictState, int startIndex, int stopIndex) protected voidreportContextSensitivity(DFA dfa, int prediction, SimulatorState acceptState, int startIndex, int stopIndex) voidreset()(package private) final ReachConfigSourceRetainedReachConfigSourceafter construction.protected ATNConfigruleTransition(ATNConfig config, RuleTransition t, PredictionContextCache contextCache) Build the configuration that results from traversing rule transitiontfromconfig.final voidsetPredictionMode(PredictionMode predictionMode) protected final ParserRuleContextskipTailCalls(ParserRuleContext context) protected booleanWhetheradaptivePredict(org.antlr.v4.runtime.TokenStream, int, org.antlr.v4.runtime.ParserRuleContext)must callgetStartState(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.TokenStream, org.antlr.v4.runtime.ParserRuleContext, boolean)so a subclass can observe the start snapshot.private inttryLL1Prediction(TokenStream input, int decision) Single-token LL(1) cache probe against the denseATN.ll1Densetable (no hash, no boxing).private inttryPrecedenceLL1(TokenStream input, DFA dfa) Precedence LL(1) probe.Methods inherited from class org.antlr.v4.runtime.atn.ATNSimulator
checkCondition, checkCondition, clearDFA, deserialize, edgeFactory, stateFactory, toInt, toInt32, toLong, toUUID
-
Field Details
-
debug
public static final boolean debug- See Also:
-
dfa_debug
public static final boolean dfa_debug- See Also:
-
retry_debug
public static final boolean retry_debug- See Also:
-
predictionMode
-
force_global_context
public boolean force_global_context -
always_try_local_context
public boolean always_try_local_context -
enable_global_context_dfa
public boolean enable_global_context_dfaDetermines whether the DFA is used for full-context predictions. Whentrue, the DFA stores transition information for both full-context and SLL parsing; otherwise, the DFA only stores SLL transition information.For some grammars, enabling the full-context DFA can result in a substantial performance improvement. However, this improvement typically comes at the expense of memory used for storing the cached DFA states, configuration sets, and prediction contexts.
The default value is
false. -
optimize_unique_closure
public boolean optimize_unique_closure -
optimize_ll1
public boolean optimize_ll1 -
optimize_tail_calls
public boolean optimize_tail_calls -
tail_call_preserves_sll
public boolean tail_call_preserves_sll -
treat_sllk1_conflict_as_ambiguity
public boolean treat_sllk1_conflict_as_ambiguity -
parser
-
subclassObservesDfaEdge
private final boolean subclassObservesDfaEdgeA subclass that overridesgetExistingTargetState(org.antlr.v4.runtime.dfa.DFAState, int)(the profiler) must see full-context DFA edges. The base class reuses the edge it already loaded. One class test at construction, not per edge. -
reportAmbiguities
public boolean reportAmbiguitiesWhentrue, ambiguous alternatives are reported when they are encountered withinexecATN(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.TokenStream, int, org.antlr.v4.runtime.atn.SimulatorState). Whenfalse, these messages are suppressed. The default isfalse.When messages about ambiguous alternatives are not required, setting this to
falseenables additional internal optimizations which may lose this information. -
userWantsCtxSensitive
protected boolean userWantsCtxSensitiveBy default we do full context-sensitive LL(*) parsing not Strong LL(*) parsing. If we fail with Strong LL(*) we try full LL(*). That means we rewind and use context information when closure operations fall off the end of the rule that holds the decision were evaluating. -
dfa
-
epsilonClosure
Epsilon-closure engine for this simulator. Package-private access forEpsilonClosure; not part of the public API. -
reachComputation
Reach / target-state engine: retained config sets and the edge computation forcomputeTargetState(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.dfa.DFAState, org.antlr.v4.runtime.ParserRuleContext, int, boolean, org.antlr.v4.runtime.atn.PredictionContextCache). Package-private; not part of the public API. -
retainedContextCache
Retained prediction-context cache for ATN simulation. Cleared at the start of eachexecATN/computeStartStateuse so one simulator thread reuses map capacity without retaining stale contexts across predictions. Never shared across threads. -
retainedPrecedenceAlt1
Retained alt-1 context index forapplyPrecedenceFilter(org.antlr.v4.runtime.atn.ATNConfigSet, org.antlr.v4.runtime.ParserRuleContext, org.antlr.v4.runtime.atn.PredictionContextCache). Empty clear is O(1); capacity is kept across precedence-DFA starts. Storage is a package-private primitive map (no third-party type on any public/protected signature). -
STATE_ALT_SORT_COMPARATOR
-
-
Constructor Details
-
ParserATNSimulator
Testing only! -
ParserATNSimulator
-
-
Method Details
-
getDfaForClosure
Current DFA under construction during prediction, if any. Package-private forEpsilonClosureprecedence-filter suppression. -
epsilonClosure
Package-private access to the epsilon-closure engine (same-package tests). -
getPredictionMode
-
setPredictionMode
-
reset
public void reset()- Specified by:
resetin classATNSimulator
-
adaptivePredict
public int adaptivePredict(@NotNull TokenStream input, int decision, @Nullable ParserRuleContext outerContext) -
adaptivePredict
public int adaptivePredict(@NotNull TokenStream input, int decision, @Nullable ParserRuleContext outerContext, boolean useContext) -
tryLL1Prediction
Single-token LL(1) cache probe against the denseATN.ll1Densetable (no hash, no boxing). Subclass writes throughATN.LL1Tablestill updateATN.ll1Cache; the hot path never touches it.- Returns:
- predicted alternative, or
ATN.INVALID_ALT_NUMBERon miss
-
tryPrecedenceLL1
Precedence LL(1) probe. The alternative depends on the parser's current precedence as well as LA(1), so it does not shareATN.ll1Dense.- Returns:
- predicted alternative, or
ATN.INVALID_ALT_NUMBERon miss
-
getStartState
protected SimulatorState getStartState(@NotNull DFA dfa, @NotNull TokenStream input, @NotNull ParserRuleContext outerContext, boolean useContext) Local- or full-context DFA start, ornullif it is not yet built. Returns a newSimulatorState(ornull); never a recycled instance. -
snapshotStartState
protected boolean snapshotStartState()WhetheradaptivePredict(org.antlr.v4.runtime.TokenStream, int, org.antlr.v4.runtime.ParserRuleContext)must callgetStartState(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.TokenStream, org.antlr.v4.runtime.ParserRuleContext, boolean)so a subclass can observe the start snapshot. Production returnsfalseand inlines the warm SLL DFA start. -
execDFA
protected int execDFA(@NotNull DFA dfa, @NotNull TokenStream input, int startIndex, @NotNull SimulatorState state) -
execDFA
private int execDFA(@NotNull DFA dfa, @NotNull TokenStream input, int startIndex, @NotNull ParserRuleContext outerContext, @NotNull DFAState s0, boolean useContext, ParserRuleContext remainingOuterContext) DFA walk. Private so the warm SLL path can pass locals without aSimulatorStateallocation; the protected overload unpacks one. -
isAcceptState
Determines if a particular DFA state should be treated as an accept state for the current prediction mode. In addition to theuseContextparameter, thegetPredictionMode()method provides the prediction mode controlling the prediction algorithm as a whole.The default implementation simply returns the value of
DFAState.isAcceptState()except for conflict states whenuseContextistrueandgetPredictionMode()isPredictionMode.LL_EXACT_AMBIG_DETECTION. In that case, only conflict states whereATNConfigSet.isExactConflict()istrueare considered accept states.- Parameters:
state- The DFA state to check.useContext-trueif the prediction algorithm is currently considering the full parser context; otherwise,falseif the algorithm is currently performing a local context prediction.- Returns:
trueif the specifiedstateis an accept state; otherwise,false.
-
execATN
protected int execATN(@NotNull DFA dfa, @NotNull TokenStream input, int startIndex, @NotNull SimulatorState initialState) Performs ATN simulation to compute a predicted alternative based upon the remaining input, but also updates the DFA cache to avoid having to traverse the ATN again for the same input sequence. There are some key conditions we're looking for after computing a new set of ATN configs (proposed DFA state): if the set is empty, there is no viable alternative for current symbol does the state uniquely predict an alternative? does the state have a conflict that would prevent us from putting it on the work list? if in non-greedy decision is there a config at a rule stop state? We also have some key operations to do: add an edge from previous DFA state to potentially new DFA state, D, upon current symbol but only if adding to work list, which means in all cases except no viable alternative (and possibly non-greedy decisions?) collecting predicates and adding semantic context to DFA accept states adding rule context to context-sensitive DFA accept states consuming an input symbol reporting a conflict reporting an ambiguity reporting a context sensitivity reporting insufficient predicates We should isolate those operations, which are side-effecting, to the main work loop. We can isolate lots of code into other functions, but they should be side effect free. They can return package that indicates whether we should report something, whether we need to add a DFA edge, whether we need to augment accept state with semantic context or rule invocation context. Actually, it seems like we always add predicates if they exist, so that can simply be done in the main loop for any accept state creation or modification request. cover these cases: dead end single alt single alt + preds conflict conflict + preds TODO: greedy + those -
repeatedEof
private static boolean repeatedEof(ArrayList<DFAState> states, ArrayList<ParserRuleContext> contexts, DFAState state, ParserRuleContext ctx, boolean useContext) - Returns:
truewhen this EOF step repeats a state the walk has already seen with the same remaining outer context. Full-context prediction reuses one DFA state after a context pop; that pop is progress, so the context object is part of the key. SLL passesuseContext falseand any repeat of the state is a cycle. Identity, notstateNumber: outermost states stay at-1when the global-context DFA is disabled, andaddDFAStatethen returns a new object on every reach. Those compare equal by configuration set.
-
handleNoViableAlt
protected int handleNoViableAlt(@NotNull TokenStream input, int startIndex, @NotNull SimulatorState previous) This method is used to improve the localization of error messages by choosing an alternative rather than throwing aNoViableAltExceptionin particular prediction scenarios where theATNSimulator.ERRORstate was reached during ATN simulation.The default implementation of this method uses the following algorithm to identify an ATN configuration which successfully parsed the decision entry rule. Choosing such an alternative ensures that the
ParserRuleContextreturned by the calling rule will be complete and valid, and the syntax error will be reported later at a more localized location.- If no configuration in
configsreached the end of the decision rule, returnATN.INVALID_ALT_NUMBER. - If all configurations in
configswhich reached the end of the decision rule predict the same alternative, return that alternative. - If the configurations in
configswhich reached the end of the decision rule predict multiple alternatives (call this S), choose an alternative in the following order.- Filter the configurations in
configsto only those configurations which remain viable after evaluating semantic predicates. If the set of these filtered configurations which also reached the end of the decision rule is not empty, return the minimum alternative represented in this set. - Otherwise, choose the minimum alternative in S.
- Filter the configurations in
In some scenarios, the algorithm described above could predict an alternative which will result in a
FailedPredicateExceptionin parser. Specifically, this could occur if the only configuration capable of successfully parsing to the end of the decision rule is blocked by a semantic predicate. By choosing this alternative withinadaptivePredict(org.antlr.v4.runtime.TokenStream, int, org.antlr.v4.runtime.ParserRuleContext)instead of throwing aNoViableAltException, the resultingFailedPredicateExceptionin the parser will identify the specific predicate which is preventing the parser from successfully parsing the decision rule, which helps developers identify and correct logic errors in semantic predicates.- Parameters:
input- The inputTokenStreamstartIndex- The start index for the current prediction, which is the input index where any semantic context inconfigsshould be evaluatedprevious- The ATN simulation state immediately before theATNSimulator.ERRORstate was reached- Returns:
- The value to return from
adaptivePredict(org.antlr.v4.runtime.TokenStream, int, org.antlr.v4.runtime.ParserRuleContext), orATN.INVALID_ALT_NUMBERif a suitable alternative was not identified andadaptivePredict(org.antlr.v4.runtime.TokenStream, int, org.antlr.v4.runtime.ParserRuleContext)should report an error instead.
- If no configuration in
-
findFirstValidAltUsingPredicates
private Integer findFirstValidAltUsingPredicates(TokenStream input, int startIndex, SimulatorState previous, BitSet alts, SemanticContext[] altToPred) -
computeReachSet
protected SimulatorState computeReachSet(DFA dfa, SimulatorState previous, int t, PredictionContextCache contextCache) -
getExistingTargetState
Get an existing target state for an edge in the DFA. If the target state for the edge has not yet been computed or is otherwise not available, this method returnsnull.- Parameters:
s- The current DFA statet- The next input symbol- Returns:
- The existing target DFA state for the given input symbol
t, ornullif the target state for this edge is not already cached
-
computeTargetState
@NotNull protected Tuple2<DFAState,ParserRuleContext> computeTargetState(@NotNull DFA dfa, @NotNull DFAState s, ParserRuleContext remainingGlobalContext, int t, boolean useContext, PredictionContextCache contextCache) Compute a target state for an edge in the DFA, and attempt to add the computed state and corresponding edge to the DFA.Delegates to package-private
ReachComputation, which owns the retained reach / intermediate sets and the full-context config view.- Parameters:
dfa- the DFA owning this decisions- the current DFA stateremainingGlobalContext- remaining full context, ornullt- the next input symboluseContext- whether full-context prediction is activecontextCache- prediction-context cache for this simulation- Returns:
- The computed target DFA state for the given input symbol
t. Iftdoes not lead to a valid DFA state, this method returnsATNSimulator.ERROR.
-
retainedReachConfigs
RetainedReachConfigSourceafter construction. Same-package tests may observe rewrite-list identity across full-context edges. -
removeAllConfigsNotInRuleStopState
@NotNull protected ATNConfigSet removeAllConfigsNotInRuleStopState(@NotNull ATNConfigSet configs, PredictionContextCache contextCache) Return a configuration set containing only the configurations fromconfigswhich are in aRuleStopState. If all configurations inconfigsare already in a rule stop state, this method simply returnsconfigs.- Parameters:
configs- the configuration set to updatecontextCache- thePredictionContextcache- Returns:
configsif all configurations inconfigsare in a rule stop state, otherwise return a new configuration set containing only the configurations fromconfigswhich are in a rule stop state
-
computeStartState
@NotNull protected SimulatorState computeStartState(DFA dfa, ParserRuleContext globalContext, boolean useContext) -
applyPrecedenceFilter
@NotNull protected ATNConfigSet applyPrecedenceFilter(@NotNull ATNConfigSet configs, ParserRuleContext globalContext, PredictionContextCache contextCache) This method transforms the start state computed bycomputeStartState(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.ParserRuleContext, boolean)to the special start state used by a precedence DFA for a particular precedence value. The transformation process applies the following changes to the start state's configuration set.- Evaluate the precedence predicates for each configuration using
SemanticContext.evalPrecedence(org.antlr.v4.runtime.Recognizer<?, ?>, org.antlr.v4.runtime.RuleContext). - When
ATNConfig.isPrecedenceFilterSuppressed()isfalse, remove all configurations which predict an alternative greater than 1, for which another configuration that predicts alternative 1 is in the same ATN state with the same prediction context. This transformation is valid for the following reasons:- The closure block cannot contain any epsilon transitions which bypass the body of the closure, so all states reachable via alternative 1 are part of the precedence alternatives of the transformed left-recursive rule.
- The "primary" portion of a left recursive rule cannot contain an
epsilon transition, so the only way an alternative other than 1 can exist
in a state that is also reachable via alternative 1 is by nesting calls
to the left-recursive rule, with the outer calls not being at the
preferred precedence level. The
ATNConfig.isPrecedenceFilterSuppressed()property marks ATN configurations which do not meet this condition, and therefore are not eligible for elimination during the filtering process.
The prediction context must be considered by this filter to address situations like the following.
grammar TA; prog: statement* EOF; statement: letterA | statement letterA 'b' ; letterA: 'a';
If the above grammar, the ATN state immediately before the token reference
'a'inletterAis reachable from the left edge of both the primary and closure blocks of the left-recursive rulestatement. The prediction context associated with each of these configurations distinguishes between them, and prevents the alternative which stepped out toprog(and then back in tostatementfrom being eliminated by the filter.Alt-1 prediction contexts are indexed by ATN state number in a retained primitive
int-keyed map (implementation detail of this method only) so filtering of higher alternatives avoidsIntegerboxing on each state-number lookup. The protected signature uses only JDK and ANTLR types.- Parameters:
configs- The configuration set computed bycomputeStartState(org.antlr.v4.runtime.dfa.DFA, org.antlr.v4.runtime.ParserRuleContext, boolean)as the start state for the DFA.- Returns:
- The transformed configuration set representing the start state
for a precedence DFA at a particular precedence level (determined by
calling
Parser.getPrecedence()).
- Evaluate the precedence predicates for each configuration using
-
obtainContextCache
Returns the retained prediction-context cache after clearing it. One simulator owns the cache for the duration of a single ATN simulation. -
getReachableTarget
-
predicateDFAState
collect and set D's semantic context -
getPredsForAmbigAlts
protected SemanticContext[] getPredsForAmbigAlts(@NotNull BitSet ambigAlts, @NotNull ATNConfigSet configs, int nalts) -
getPredicatePredictions
protected DFAState.PredPrediction[] getPredicatePredictions(BitSet ambigAlts, SemanticContext[] altToPred) -
evalSemanticContext
protected BitSet evalSemanticContext(@NotNull DFAState.PredPrediction[] predPredictions, ParserRuleContext outerContext, boolean complete) Look through a list of predicate/alt pairs, returning alts for the pairs that win. Anullpredicate indicates an alt containing an unpredicated config which behaves as "always true." -
evalSemanticContext
protected boolean evalSemanticContext(@NotNull SemanticContext pred, ParserRuleContext parserCallStack, int alt) Evaluate a semantic context within a specific parser context.This method might not be called for every semantic context evaluated during the prediction process. In particular, we currently do not evaluate the following but it may change in the future:
- Precedence predicates (represented by
SemanticContext.PrecedencePredicate) are not currently evaluated through this method. - Operator predicates (represented by
SemanticContext.ANDandSemanticContext.OR) are evaluated as a single semantic context, rather than evaluating the operands individually. Implementations which require evaluation results from individual predicates should override this method to explicitly handle evaluation of the operands within operator predicates.
- Parameters:
pred- The semantic context to evaluateparserCallStack- The parser context in which to evaluate the semantic contextalt- The alternative which is guarded bypred- Since:
- 4.3
- Precedence predicates (represented by
-
closure
protected void closure(ATNConfigSet sourceConfigs, @NotNull ATNConfigSet configs, boolean collectPredicates, boolean hasMoreContext, @Nullable PredictionContextCache contextCache, boolean treatEofAsEpsilon) Compute the epsilon closure of every configuration insourceConfigs, adding the resulting non-epsilon (or EOF-as-epsilon) configurations toconfigs.Delegates to
EpsilonClosurefor busy-set sizing, predicate vs BFS control split, and double-buffered intermediate layers. Subclasses may override this method or the recursive single-configclosure(ATNConfig, ...)entry point.- Parameters:
sourceConfigs- configurations from which to start the closureconfigs- destination set that receives closed configurationscollectPredicates- whether semantic predicates should be collected into configuration semantic contexts (start-state construction) or ignored for DFA edge computationhasMoreContext- whether outer/global context remains available when a configuration falls off the end of a rulecontextCache- prediction-context cache for the current prediction, ornullto usePredictionContextCache.UNCACHEDtreatEofAsEpsilon- whether EOF-matching atom/range/set transitions should be treated as epsilon edges
-
closure
protected void closure(@NotNull ATNConfig config, @NotNull ATNConfigSet configs, @Nullable ATNConfigSet intermediate, @NotNull Set<ATNConfig> closureBusy, boolean collectPredicates, boolean hasMoreContexts, @NotNull PredictionContextCache contextCache, int depth, boolean treatEofAsEpsilon) Recursive helper forclosure(ATNConfigSet, ATNConfigSet, boolean, boolean, PredictionContextCache, boolean). Walks epsilon edges fromconfig, adding leaf configurations toconfigsand optionally deferring rule transitions tointermediatefor breadth-first processing.Default implementation delegates to
EpsilonClosure. Subclasses may override to customize edge walking.PERF: Production callers pass the retained busy
Setowned byEpsilonClosure(anOpenAddressedHashSetwrapping an open-addressed HPPC table) so right-recursion / EOF* guards avoid per-insertjava.util.HashMap.Node<K extends Object,allocation. The parameter is typed asV extends Object> Setso this protected SPI never exposes HPPC types; subclasses may supply anySetimplementation. Callers outside the closure engine should not allocate a fresh set per config.- Parameters:
closureBusy- busy set for right-recursion / EOF* cycle guards;Set.add(E)must returnfalsewhen an equal config is already present
-
getRuleName
-
getEpsilonTarget
@Nullable protected ATNConfig getEpsilonTarget(@NotNull ATNConfig config, @NotNull Transition t, boolean collectPredicates, boolean inContext, PredictionContextCache contextCache, boolean treatEofAsEpsilon) Compute the target configuration after traversing epsilon transitiontfromconfig, ornulliftis not an epsilon (or EOF-as-epsilon) edge applicable in the current mode.PERF: The switch is ordered with the most common epsilon edge types (
Transition.EPSILON,Transition.RULE) first so the interpreter/JIT can keep those paths monomorphic and hot. -
actionTransition
-
precedenceTransition
-
predTransition
-
ruleTransition
@NotNull protected ATNConfig ruleTransition(@NotNull ATNConfig config, @NotNull RuleTransition t, @Nullable PredictionContextCache contextCache) Build the configuration that results from traversing rule transitiontfromconfig.PERF: Tail-call elimination reuses
config's prediction context when enabled. Otherwise the child context is obtained throughcontextCacheso repeated rule invocations share internedPredictionContextnodes. -
isConflicted
private ConflictInfo isConflicted(@NotNull ATNConfigSet configset, PredictionContextCache contextCache) -
getConflictingAltsFromConfigSet
-
getTokenName
-
getLookaheadName
-
dumpDeadEndConfigs
-
noViableAlt
@NotNull protected NoViableAltException noViableAlt(@NotNull TokenStream input, @NotNull ParserRuleContext outerContext, @NotNull ATNConfigSet configs, int startIndex) -
getUniqueAlt
-
configWithAltAtStopState
-
addDFAEdge
@NotNull protected DFAState addDFAEdge(@NotNull DFA dfa, @NotNull DFAState fromState, int t, IntegerList contextTransitions, @NotNull ATNConfigSet toConfigs, PredictionContextCache contextCache) -
addDFAEdge
-
addDFAContextState
@NotNull protected DFAState addDFAContextState(@NotNull DFA dfa, @NotNull ATNConfigSet configs, int returnContext, PredictionContextCache contextCache) See comment on LexerInterpreter.addDFAState. -
addDFAState
@NotNull protected DFAState addDFAState(@NotNull DFA dfa, @NotNull ATNConfigSet configs, PredictionContextCache contextCache) See comment on LexerInterpreter.addDFAState. -
createDFAState
-
reportAttemptingFullContext
-
reportContextSensitivity
protected void reportContextSensitivity(@NotNull DFA dfa, int prediction, @NotNull SimulatorState acceptState, int startIndex, int stopIndex) -
reportAmbiguity
protected void reportAmbiguity(@NotNull DFA dfa, DFAState D, int startIndex, int stopIndex, boolean exact, @NotNull BitSet ambigAlts, @NotNull ATNConfigSet configs) If context sensitive parsing, we know it's ambiguity not conflict -
getReturnState
-
skipTailCalls
-
getParser
- Since:
- 4.3
-