antlr/antlr4 · error · FailedPredicateException

failed predicate: {predicate}?

Error message

failed predicate: {predicate}?

What it means

In ParserInterpreter.visitState, a PREDICATE transition evaluates the rule's semantic predicate via sempred(); when it returns false, FailedPredicateException is raised (with the default 'failed predicate: ...' message). Interpreters run pre-compiled grammars without generated predicate code, so any context-dependent or side-effecting predicate that cannot be satisfied during interpretation surfaces here.

Source

Thrown at runtime/Python3/src/antlr4/ParserInterpreter.py:143

        elif tt==Transition.WILDCARD:

            self.matchWildcard()

        elif tt==Transition.RULE:

            ruleStartState = transition.target
            ruleIndex = ruleStartState.ruleIndex
            ctx = InterpreterRuleContext(self._ctx, p.stateNumber, ruleIndex)
            if ruleStartState.isPrecedenceRule:
                self.enterRecursionRule(ctx, ruleStartState.stateNumber, ruleIndex, transition.precedence)
            else:
                self.enterRule(ctx, transition.target.stateNumber, ruleIndex)

        elif tt==Transition.PREDICATE:

            if not self.sempred(self._ctx, transition.ruleIndex, transition.predIndex):
                raise FailedPredicateException(self)

        elif tt==Transition.ACTION:

            self.action(self._ctx, transition.ruleIndex, transition.actionIndex)

        elif tt==Transition.PRECEDENCE:

            if not self.precpred(self._ctx, transition.precedence):
                msg = "precpred(_ctx, " + str(transition.precedence) + ")"
                raise FailedPredicateException(self, msg)

        else:
            raise UnsupportedOperationException("Unrecognized ATN transition type.")

        self.state = transition.target.stateNumber

    def visitRuleStopState(self, p:ATNState):
        ruleStartState = self.atn.ruleToStartState[p.ruleIndex]

View on GitHub (pinned to 7d5770395b)

Solutions

  1. Subclass the interpreter (or the recognizer it drives) and override sempred(...) to supply the same predicate logic the generated parser uses
  2. Initialize any external state (symbol table, flags, input context) the predicates read before running the interpreter
  3. If predicates are context-dependent, prefer the generated parser for those inputs instead of the interpreter
  4. Catch FailedPredicateException at the interpret entry point and report the failing rule/predicate from its context

Example fix

# before
interp = ParserInterpreter(grammar_name, tokenNames, ruleNames, atn, tokens)
tree = interp.parse(startRule)  # FailedPredicateException on {x>0}?

# after
class MyInterpreter(ParserInterpreter):
    def sempred(self, localctx, ruleIndex, actionIndex):
        if ruleIndex == MyParser.RULE_expr:
            return self.expr_sempred(localctx, actionIndex)  # real predicate logic
        return super().sempred(localctx, ruleIndex, actionIndex)

interp = MyInterpreter(grammar_name, tokenNames, ruleNames, atn, tokens)
Defensive patterns

Strategy: try-catch

Validate before calling

# Python: pre-flight the predicates you control before interpreting
state_ok = my_predicate_state.is_ready()  # external state predicates read
if not state_ok:
    raise ValueError("predicate state not initialized for interpretation")

Try / catch

from antlr4.error.Errors import FailedPredicateException
try:
    tree = interpreter.parse(start_rule)
except FailedPredicateException as ex:
    # report which rule/predicate failed from ex.ctx / ex.msg, then fall back to generated parser
    log.warning("predicate failed in interpreter: %s (rule ctx=%s)", ex.msg, type(ex.ctx).__name__)
    tree = generated_parser.startRule()

Prevention

When it happens

Trigger: Interpreting a grammar containing {predicate}? on a transition where the embedded predicate evaluates false at runtime; predicates depending on external state (symbol tables, application flags) not set up in the interpreter environment; the same grammar parsing fine with the generated parser but failing in the interpreter because a custom context/sempred override was not applied.

Common situations: Using ParserInterpreter for grammar prototyping/debugging on grammars with semantic predicates; version-drift where the interpreter's sempred dispatch (Parser.sempred / rule-specific methods) does not match generated-parser behavior; predicate state leaking between runs because the interpreter reuses a Recognizer.

Related errors


AI-assisted analysis of antlr/antlr4@7d5770395b (2026-08-14). Data as JSON: /api/errors/2a5cb285d20a258b. Report an issue: GitHub.