getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule method

int getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(
  1. ATNConfigSet configs,
  2. ParserRuleContext outerContext
)

This method is used to improve the localization of error messages by choosing an alternative rather than throwing a NoViableAltException in particular prediction scenarios where the {@link #ERROR} state 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 [ParserRuleContext] returned by the calling rule will be complete and valid, and the syntax error will be reported later at a more localized location.

  • If a syntactically valid path or paths reach the end of the decision rule and they are semantically valid if predicated, return the min associated alt.
  • Else, if a semantically invalid but syntactically valid path exist or paths exist, return the minimum associated alt.
  • Otherwise, return {@link ATN#INVALID_ALT_NUMBER}.

In some scenarios, the algorithm described above could predict an alternative which will result in a [FailedPredicateException] in the 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 within {@link #adaptivePredict} instead of throwing a [NoViableAltException], the resulting [FailedPredicateException] in 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.

@param configs The ATN configurations which were valid immediately before the {@link #ERROR} state was reached @param outerContext The is the \gamma_0 initial parser context from the paper or the parser stack at the instant before prediction commences.

@return The value to return from {@link #adaptivePredict}, or {@link ATN#INVALID_ALT_NUMBER} if a suitable alternative was not identified and {@link #adaptivePredict} should report an error instead.

Implementation

int getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(
    ATNConfigSet configs, ParserRuleContext outerContext) {
  final sets = splitAccordingToSemanticValidity(configs, outerContext);
  final semValidConfigs = sets.a;
  final semInvalidConfigs = sets.b;
  var alt = getAltThatFinishedDecisionEntryRule(semValidConfigs);
  if (alt != ATN.INVALID_ALT_NUMBER) {
    // semantically/syntactically viable path exists
    return alt;
  }
  // Is there a syntactically valid path with a failed pred?
  if (semInvalidConfigs.isNotEmpty) {
    alt = getAltThatFinishedDecisionEntryRule(semInvalidConfigs);
    if (alt != ATN.INVALID_ALT_NUMBER) {
      // syntactically viable path exists
      return alt;
    }
  }
  return ATN.INVALID_ALT_NUMBER;
}