我现在如何在 Irony 中使用 AST? [英] How do I work with the AST in Irony now?
问题描述
我有一个语法可以在 Irony 控制台中正常工作和解析,但是我在 AST 树视图中没有得到任何信息.我正在关注此处找到的 BASIC->Javascript 文章:http://www.codeproject.com/Articles/25069/JSBasic-A-BASIC-to-JavaScript-Compiler,但似乎 Ast 的东西都被移动/删除了.我找到了 Irony.Interpreter .dll,其中包含一些 Ast 内容,但似乎都与 Expression 示例实现相关联.
我在这里错过了什么?我想遍历我的树并生成源代码,但我不知道从哪里开始.
我已经看到有人提到使用访问者模式,我很满意,但我不知道如何实现它并以 Irony 喜欢的方式运行它.
查看名为 Sarcasm 的项目以获取参考实现构建在 Irony 之上的语法、解析器和 AST.我找到了这个 博客条目 作者有助于构建 AST.
以下是启动和运行 AST 的通用指南.
- 定义语法(示例)
- 创建一个从
AstNode
派生的抽象基类 (MyBaseNode
) (示例).复制/粘贴示例中的方法 为每个终端和非终端创建一个从
派生的新类MyBaseNode
和- 覆盖
Accept
方法(示例):
public override void Accept(IMyNodeVisitorvisitor) {visitor.Visit(this);}
- 覆盖
Init
(大多数情况下)在终端上)或InitChildren
- 终端)视情况而定.这就是 AST 魔法发生的地方.
- 覆盖
添加一个接口
IMyNodeVisitor
,并为上一步中定义的每个类添加一个Visit
方法(示例):void Visit(MyDerivedNode1 node);
为步骤 1 中的语法中的每个终结符和非终结符设置
ASTNodeType
.在语法中启用 AST 创建:(example)
LanguageFlags = LanguageFlags.CreateAst;
I have a grammar that works and parses in the Irony console just fine, but I don't get anything in the AST treeview. I was following along with the BASIC->Javascript article found here: http://www.codeproject.com/Articles/25069/JSBasic-A-BASIC-to-JavaScript-Compiler, but it seems that the Ast stuff has all been moved/removed. I found the Irony.Interpreter .dll, which has some Ast stuff in it, but it seems all tied up in the Expression sample implementation.
What am I missing here? I want to walk my tree and generate source code, and I'm not sure where to start.
I've seen some mention of using the visitor pattern, which I'm fine with, but I don't know how to implement it and run it in a way that Irony likes.
Check out the aptly named Sarcasm project for a reference implementation of a grammar, parser, and AST built on Irony. I found this blog entry by the author to be helpful in building the AST.
The following is a general purpose guide to getting the AST up and running.
- Define your grammar (example)
- Create an abstract base class (
MyBaseNode
) deriving fromAstNode
(example). Copy/Paste the methods from the example For each terminal and non-terminal create a new class derived from
MyBaseNode
and- Override
Accept
method (example):
public override void Accept(IMyNodeVisitor visitor) { visitor.Visit(this); }
- Override
Init
(mostly on terminals) orInitChildren
(non-terminals) as appropriate. This is where the AST magic happens.
- Override
Add an interface
IMyNodeVisitor
and add aVisit
method for each class defined in the previous step (example):void Visit(MyDerivedNode1 node);
Set the
ASTNodeType
for each of your terminals and non-terminals in your grammar from step 1.In the grammar enable AST creation: (example)
LanguageFlags = LanguageFlags.CreateAst;
这篇关于我现在如何在 Irony 中使用 AST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!