antlr/antlr4 · error · NotSupportedException

Parser can't discover a lexer to use

Error message

Parser can't discover a lexer to use

What it means

Error "Parser can't discover a lexer to use" thrown in antlr/antlr4.

Source

Thrown at runtime/CSharp/src/Parser.cs:605

        /// <pre>
        /// ParseTree t = parser.expr();
        /// ParseTreePattern p = parser.compileParseTreePattern("&lt;ID&gt;+0", MyParser.RULE_expr);
        /// ParseTreeMatch m = p.match(t);
        /// String id = m.get("ID");
        /// </pre>
        /// </remarks>
        public virtual ParseTreePattern CompileParseTreePattern(string pattern, int patternRuleIndex)
        {
            if (((ITokenStream)InputStream) != null)
            {
                ITokenSource tokenSource = ((ITokenStream)InputStream).TokenSource;
                if (tokenSource is Lexer)
                {
                    Lexer lexer = (Lexer)tokenSource;
                    return CompileParseTreePattern(pattern, patternRuleIndex, lexer);
                }
            }
            throw new NotSupportedException("Parser can't discover a lexer to use");
        }

        /// <summary>
        /// The same as
        /// <see cref="CompileParseTreePattern(string, int)"/>
        /// but specify a
        /// <see cref="Lexer"/>
        /// rather than trying to deduce it from this parser.
        /// </summary>
        public virtual ParseTreePattern CompileParseTreePattern(string pattern, int patternRuleIndex, Lexer lexer)
        {
            ParseTreePatternMatcher m = new ParseTreePatternMatcher(lexer, this);
            return m.Compile(pattern, patternRuleIndex);
        }

        public virtual IAntlrErrorStrategy ErrorHandler
        {
            get

View on GitHub (pinned to 7d5770395b)

Solutions

  1. Provide the matching lexer explicitly: create the lexer, feed it a CharStream, wrap it in a CommonTokenStream, and pass that to the parser constructor.
  2. Ensure the lexer class name follows the grammar naming convention (<grammarName>Lexer) so discovery can succeed.

Example fix

var lexer = new MyGrammarLexer(new AntlrInputStream(input));
var parser = new MyGrammarParser(new CommonTokenStream(lexer));

When it happens

Trigger: Parser.BypassAltsAtnCache/lexer discovery path cannot locate a lexer type for the combined grammar.

Common situations: Ensure the combined grammar's generated lexer class is available and named per convention (GrammarNameLexer).


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