问题
I am implementing an AST (Abstract Syntax Tree) in C# for a complex grammar, however, to make this question simple, I will use a very simple grammar.
Consider this grammar:
rules Expr ::= Term "+" Term
| Term ;
rules Term ::= Ident
| Integer ;
I have used bnfc and generated the parser/lexer and got to the point that I can parse a piece of code and can print the parse tree. Now I want to map it to AST, and print the Abstract Syntax Tree. here is what I have done so far in a sample project.
However, currently when I test the program, my AST comes back as NULL.
var astGen = new gplex.VisitSkeleton.ExprVisitor<Expr1, gplex.Absyn.Expr1>();
var ast = astGen.Visit((gplex.Absyn.Expr1)parse_tree, (gplex.Absyn.Expr1)parse_tree);
Here, ast is null. Can someone with experience in C# help me get on track with this?
回答1:
At your project, I noticed that all your generic Visit methods end up returning the same constant result no matter what the rest of those methods' bodies has done prior to that:
return default(R);
For concrete types of R that are reference types, this "default(R)" return value will indeed be always null.
'HTH,
来源:https://stackoverflow.com/questions/36231040/parser-in-c-sharp-and-printing-ast