0

I'm trying to use Antlr to parse C# source files. Started with the grammar files that I got from https://github.com/antlr/grammars-v4/tree/master/csharp, and was able to get the auto-generate CS files. I'm trying to parse a simple class definition, but keep getting an error "line 4:0 mismatched input '' expecting '{'" at the line that reads "var context = parser.class_body();". My intention is to get the class context, pass it to the Visitor, then walk the parse tree of the class. Does someone spot an issue with the code below?

    private static void Main(string[] args)
    {
        try
        {
            StringBuilder text = new StringBuilder();
            text.AppendLine("class Boo{");
            text.AppendLine("");
            text.AppendLine("}");

            AntlrInputStream inputStream = new AntlrInputStream(text.ToString());
            CSharpLexer lexer = new CSharpLexer(inputStream);
            CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
            CSharpParser parser = new CSharpParser(commonTokenStream);

            var c = parser.BuildParseTree;
            Console.WriteLine(c.ToString()); // true

            //var context = parser.class_base(); // line 1:0 mismatched input 'class' expecting ':'
            var context = parser.class_body(); // line 4:0 mismatched input '<EOF>' expecting '{'
            var visitor = new CSharpParserBaseVisitor<object>();
            visitor.VisitClass_body(context);
            // ...

        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex);
        }
    }
samsu
  • 63
  • 8
  • Clearly the entry point is `compilation_unit` if you read the grammar file. Also note that this grammar file is for C# 6 only. – Lex Li Aug 02 '22 at 02:29
  • There are two ways to get the entry point in an Antlr grammars-v4 grammar. (1) In pom.xml, and find the `/project/build/plugins/plugin/configuration/entryPoint` element. The build looks at the pom to determine where to start the parse. (2) In the parser .g4 file and find the rule with the EOF `//parserRuleSpec[ruleBlock//TOKEN_REF/text()="EOF"]`. If you need an entry point for anything other than `compilation_unit`, you should augment the rule with an EOF like `compilation_unit`. If you need to find the `class_definition`, parse as `compilation_unit`, then find the node using a visitor. – kaby76 Aug 02 '22 at 10:31

0 Answers0