C#中的解析器并打印AST [英] Parser in C# and printing AST
问题描述
我正在用C#实现复杂语法的AST(抽象语法树),但是,为了使这个问题更简单,我将使用非常简单的语法.
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.
考虑以下语法:
rules Expr ::= Term "+" Term
| Term ;
rules Term ::= Ident
| Integer ;
我使用了bnfc并生成了解析器/词法分析器,直指我可以解析一段代码并可以打印解析树.现在,我想将其映射到AST,并打印抽象语法树". 此处是我到目前为止在一个示例项目中所做的.
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.
但是,目前,当我测试程序时,我的AST返回为NULL.
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);
在这里,ast为空.拥有C#经验的人可以帮助我做到这一点吗?
Here, ast is null. Can someone with experience in C# help me get on track with this?
推荐答案
在您的项目中,我注意到您所有的通用Visit方法最终都会返回相同的常量结果,无论这些方法的其余主体在此之前做了什么.
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);
对于作为引用类型的R的具体类型,此"default(R)"返回值的确将始终为空.
For concrete types of R that are reference types, this "default(R)" return value will indeed be always null.
'HTH,
这篇关于C#中的解析器并打印AST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!