Reputation: 87
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);
}
}
Upvotes: 0
Views: 231