{"record":{"id":"2a5cb285d20a258b","repo":"antlr/antlr4","slug":"failed-predicate-predicate","errorCode":null,"errorMessage":"failed predicate: {predicate}?","messagePattern":"failed predicate: (.+?)\\?","errorType":"exception","errorClass":"FailedPredicateException","httpStatus":null,"severity":"error","filePath":"runtime/Python3/src/antlr4/ParserInterpreter.py","lineNumber":143,"sourceCode":"\n        elif tt==Transition.WILDCARD:\n\n            self.matchWildcard()\n\n        elif tt==Transition.RULE:\n\n            ruleStartState = transition.target\n            ruleIndex = ruleStartState.ruleIndex\n            ctx = InterpreterRuleContext(self._ctx, p.stateNumber, ruleIndex)\n            if ruleStartState.isPrecedenceRule:\n                self.enterRecursionRule(ctx, ruleStartState.stateNumber, ruleIndex, transition.precedence)\n            else:\n                self.enterRule(ctx, transition.target.stateNumber, ruleIndex)\n\n        elif tt==Transition.PREDICATE:\n\n            if not self.sempred(self._ctx, transition.ruleIndex, transition.predIndex):\n                raise FailedPredicateException(self)\n\n        elif tt==Transition.ACTION:\n\n            self.action(self._ctx, transition.ruleIndex, transition.actionIndex)\n\n        elif tt==Transition.PRECEDENCE:\n\n            if not self.precpred(self._ctx, transition.precedence):\n                msg = \"precpred(_ctx, \" + str(transition.precedence) + \")\"\n                raise FailedPredicateException(self, msg)\n\n        else:\n            raise UnsupportedOperationException(\"Unrecognized ATN transition type.\")\n\n        self.state = transition.target.stateNumber\n\n    def visitRuleStopState(self, p:ATNState):\n        ruleStartState = self.atn.ruleToStartState[p.ruleIndex]","sourceCodeStart":125,"sourceCodeEnd":161,"githubUrl":"https://github.com/antlr/antlr4/blob/7d5770395bb7b02eb56e7c62662cb1d7c08f42a3/runtime/Python3/src/antlr4/ParserInterpreter.py#L125-L161","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Subclass the interpreter (or the recognizer it drives) and override sempred(...) to supply the same predicate logic the generated parser uses","Initialize any external state (symbol table, flags, input context) the predicates read before running the interpreter","If predicates are context-dependent, prefer the generated parser for those inputs instead of the interpreter","Catch FailedPredicateException at the interpret entry point and report the failing rule/predicate from its context"],"exampleFix":"# before\ninterp = ParserInterpreter(grammar_name, tokenNames, ruleNames, atn, tokens)\ntree = interp.parse(startRule)  # FailedPredicateException on {x>0}?\n\n# after\nclass MyInterpreter(ParserInterpreter):\n    def sempred(self, localctx, ruleIndex, actionIndex):\n        if ruleIndex == MyParser.RULE_expr:\n            return self.expr_sempred(localctx, actionIndex)  # real predicate logic\n        return super().sempred(localctx, ruleIndex, actionIndex)\n\ninterp = MyInterpreter(grammar_name, tokenNames, ruleNames, atn, tokens)","handlingStrategy":"try-catch","validationCode":"# Python: pre-flight the predicates you control before interpreting\nstate_ok = my_predicate_state.is_ready()  # external state predicates read\nif not state_ok:\n    raise ValueError(\"predicate state not initialized for interpretation\")","typeGuard":null,"tryCatchPattern":"from antlr4.error.Errors import FailedPredicateException\ntry:\n    tree = interpreter.parse(start_rule)\nexcept FailedPredicateException as ex:\n    # report which rule/predicate failed from ex.ctx / ex.msg, then fall back to generated parser\n    log.warning(\"predicate failed in interpreter: %s (rule ctx=%s)\", ex.msg, type(ex.ctx).__name__)\n    tree = generated_parser.startRule()","preventionTips":["Initialize all external state predicates depend on before interpreter runs","Override sempred() in the interpreter subclass to mirror generated predicate logic","Reserve ParserInterpreter for prototyping; use generated parsers where predicates matter"],"tags":["antlr","python","parser-interpreter","semantic-predicates"],"backgroundTag":null,"analyzedSha":"7d5770395bb7b02eb56e7c62662cb1d7c08f42a3","analyzedAt":"2026-08-14T14:47:56.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}