Parser in C# and printing AST

左心房为你撑大大i 提交于 2019-12-25 07:09:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!