使用 ANTLR 构建自己的 C# 编译器:编译单元 [英] Building own C# compiler using ANTLR: Compilation Unit

查看:41
本文介绍了使用 ANTLR 构建自己的 C# 编译器:编译单元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Create a scanner that reads from the input stream passed to us
 CSLexer lexer = new CSLexer(new ANTLRFileStream(f));
tokens.TokenSource = lexer;

// Create a parser that reads from the scanner
CSParser parser = new CSParser(tokens);

// start parsing at the compilationUnit rule
CSParser.compilation_unit_return x = parser.compilation_unit();
object ast = x.Tree;

我可以用 compiler_unit_return 类型的 x 做什么来提取它的根、它的类、它的方法等?我是否必须将其适配器取出?我怎么做?请注意,在我的 CSParser(由 ANTLR 自动生成)中,compiler_unit_return 是这样定义的:

What can I do with the x which is of compilation_unit_return type, to extract its root, its classes, its methods etc? Do I have to extract its Adaptor out? How do I do that? Note that the compilation_unit_return is defined as such in my CSParser (which is automatically generated by ANTLR):

public class compilation_unit_return : ParserRuleReturnScope
    {
        private object tree;
        override public object Tree
        {
            get { return tree; }
            set { tree = (object) value; }
        }
    };

但是我得到的树是对象类型.我使用调试器运行,似乎看到它是 BaseTree 类型.但是 BaseTree 是一个接口!我不知道它与 BaseTree 有什么关系,也不知道如何从这棵树中提取细节.

However the tree I am getting is of the type object. I run using the debugger and seemed to see that it is of the type BaseTree. But BaseTree is an interface! I don't know how it relates to BaseTree and don't know how to extract details out from this tree.

我需要编写一个访问者,它可以访问它的类、方法、变量等.ParserRuleReturn 类从 RuleReturnScope 扩展而来,并且有一个开始和停止对象,我不知道它是什么.

I need to write a visitor which has visit to its class, method, variables, etc. The ParserRuleReturn class extends from RuleReturnScope and has a start and stop object, which I don't know what it is.

此外,ANTLR 提供的这个 TreeVisitor 类看起来很混乱.它需要一个适配器作为参数传递给它的构造函数(如果不是,它将使用默认的 CommonTreeAdaptor),这就是为什么我询问如何获得适配器的原因.还有其他问题.API可以参考http://www.antlr.org/api/CSharp/annotated.html

Furthermore, there is this TreeVisitor class provided by ANTLR which looks confusing. It requires an Adaptor to be pass as a parameter to its constructor (if not it will use the default CommonTreeAdaptor), tt's why I asked about the how to obtain the Adaptor eariler on. And other issues too. For the API, you can refer to http://www.antlr.org/api/CSharp/annotated.html

推荐答案

我从未使用过 C# 中的 ANTLR,但是按照您的 API 链接,BaseTree 显然不是一个接口 - 它是一个 class,它具有公共属性:Type 获取节点的类型, Text 获取(我假设)与其对应的源文本,以及 Children 获取子节点.你还需要什么来走路?

I haven't ever worked with ANTLR from C#, but following your link to API, BaseTree is clearly not an interface - it's a class, and it has public properties: Type to get type of the node, Text to get (I assume) source text corresponding to it, and Children to get the child nodes. What else do you need to walk it?

这篇关于使用 ANTLR 构建自己的 C# 编译器:编译单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆