{"record":{"id":"4ff81e80653fa550","repo":"antlr/antlr4","slug":"invalid-state-number-4ff81e","errorCode":null,"errorMessage":"Invalid state number.","messagePattern":"Invalid state number\\.","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"runtime/Python3/src/antlr4/atn/ATN.py","lineNumber":115,"sourceCode":"    # considers the complete parser context, but does not evaluate semantic\n    # predicates (i.e. all predicates encountered during the calculation are\n    # assumed true). If a path in the ATN exists from the starting state to the\n    # {@link RuleStopState} of the outermost context without matching any\n    # symbols, {@link Token#EOF} is added to the returned set.\n    #\n    # <p>If {@code context} is {@code null}, it is treated as\n    # {@link ParserRuleContext#EMPTY}.</p>\n    #\n    # @param stateNumber the ATN state number\n    # @param context the full parse context\n    # @return The set of potentially valid input symbols which could follow the\n    # specified state in the specified context.\n    # @throws IllegalArgumentException if the ATN does not contain a state with\n    # number {@code stateNumber}\n    #/\n    def getExpectedTokens(self, stateNumber:int, ctx:RuleContext ):\n        if stateNumber < 0 or stateNumber >= len(self.states):\n            raise Exception(\"Invalid state number.\")\n        s = self.states[stateNumber]\n        following = self.nextTokens(s)\n        if Token.EPSILON not in following:\n            return following\n        expected = IntervalSet()\n        expected.addSet(following)\n        expected.removeOne(Token.EPSILON)\n        while (ctx != None and ctx.invokingState >= 0 and Token.EPSILON in following):\n            invokingState = self.states[ctx.invokingState]\n            rt = invokingState.transitions[0]\n            following = self.nextTokens(rt.followState)\n            expected.addSet(following)\n            expected.removeOne(Token.EPSILON)\n            ctx = ctx.parentCtx\n        if Token.EPSILON in following:\n            expected.addOne(Token.EOF)\n        return expected\n","sourceCodeStart":97,"sourceCodeEnd":133,"githubUrl":"https://github.com/antlr/antlr4/blob/7d5770395bb7b02eb56e7c62662cb1d7c08f42a3/runtime/Python3/src/antlr4/atn/ATN.py#L97-L133","documentation":"ATN.getExpectedTokens(stateNumber, ctx) validates that stateNumber addresses an existing state in the ATN (0 <= stateNumber < len(atn.states)). The ATN is the deserialized serialization of your grammar; a state number outside it means the caller passed garbage, an index from a different grammar's ATN, or a state number from an incompatible serialized ATN.","triggerScenarios":"Calling parser.getExpectedTokens() / atn.getExpectedTokens() with a state number obtained from another parser's ATN, a hand-picked int, or after mismatched tool/runtime versions produced a misaligned ATN.","commonSituations":"Cross-grammar state numbers (lexer ATN state used against parser ATN); version skew between the ANTLR tool that generated the .tokens/serialized ATN and the Python runtime that deserializes it; custom error listeners that reuse ctx.invokingState from a different parse.","solutions":["Pass only state numbers sourced from the same parser instance/ATN (e.g. ctx.invokingState of the active parse or recognizer.getATN().states lookups).","Check 0 <= stateNumber < len(atn.states) before calling.","Regenerate parser/lexer with the ANTLR tool version matching the runtime, then rebuild/recopy the generated files."],"exampleFix":"# before\natn.getExpectedTokens(9999, ctx)  # arbitrary int -> Exception\n\n# after\natn = parser.getATN()\nstate = ctx.invokingState\nif 0 <= state < len(atn.states):\n    expected = atn.getExpectedTokens(state, ctx)","handlingStrategy":"validation","validationCode":"atn = parser.getATN()\nif 0 <= state_number < len(atn.states):\n    expected = atn.getExpectedTokens(state_number, ctx)","typeGuard":"def is_valid_atn_state(atn, n):\n    return isinstance(n, int) and 0 <= n < len(atn.states)","tryCatchPattern":"try:\n    expected = atn.getExpectedTokens(state, ctx)\nexcept Exception as e:\n    if str(e) == 'Invalid state number.':\n        expected = None  # degrade gracefully in diagnostics\n    else:\n        raise","preventionTips":["Only use state numbers produced by the same parser's ATN","Never hardcode state numbers; they change when the grammar changes","Keep tool and runtime versions aligned so ATN layouts match generated code"],"tags":["antlr4","python","atn","state-number","validation"],"backgroundTag":null,"analyzedSha":"7d5770395bb7b02eb56e7c62662cb1d7c08f42a3","analyzedAt":"2026-08-14T14:47:56.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}