将 Antlr 语法树转换为有用的对象
我目前正在考虑如何最好地获取使用 Antlr 生成的 AST,并将其转换为可以在我的程序中使用的有用对象。
我语法的目的(除了学习之外)是创建一种可执行(运行时解释的)语言。
例如,我将如何获取属性子树并实例化特定的属性类。例如,
以下代码用我的语言:
Print(message:"Hello stackoverflow")
将产生以下 AST:
我目前的想法是工厂类可以读取树,提取名称(message
)和类型(STRING
)value(“Hello stackoverflow”)
”)。现在,知道了类型,我可以实例化正确的类(例如 StringAttribute 类)并传入所需的属性数据 - name
和 value
。
相同的方法可用于定义工厂,提取定义名称 (Print
),实例化 Print 类,然后传入从属性工厂生成的属性。
对于更复杂的程序,事情确实会变得更复杂:
Program(args:[1,2,3,4,5])
{
If(isTrue:IsInArray(array:{Program.args} value:5))
{
Then {
Print(message:"5 is in the array")
} Else {
Print(message:"More complex " + "message")
}
}
}
非常欢迎任何/所有帮助或想法。非常感谢。
我以前提出的相关问题(可能有用):
I'm currently pondering how best to take an AST generated using Antlr and convert it into useful objects which I can use in my program.
The purpose of my grammar (apart from learning) is to create an executable (runtime interpretted) language.
For example, how would I take an attribute sub-tree and have a specific Attribute class instanciated. E.g.
The following code in my language:
Print(message:"Hello stackoverflow")
would product the following AST:
My current line of thinking is that a factory class could read the tree, pull out the name (message
), and type(STRING
) value("Hello stackoverflow
"). Now, knowing the type I could instanciate the correct class (e.g. A StringAttribute class) and pass in the required attribute data - the name
and value
.
The same approach could be used for a definition factory, pulling out the definition name (Print
), instanciating the Print class, and then passing in the attributes generated from the attribute factory.
Things do get a bit more complicated with a more complicated program:
Program(args:[1,2,3,4,5])
{
If(isTrue:IsInArray(array:{Program.args} value:5))
{
Then {
Print(message:"5 is in the array")
} Else {
Print(message:"More complex " + "message")
}
}
}
ANY/ALL help or thoughts are very welcome. Many thanks.
Previous related questions by me (Could be useful):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议阅读第 9 章,构建高级解释器,来自 语言实现模式,作者:Terence Parr。
编辑
好的,为了让您度过等待那本书的时间,这就是您(至少)需要的:
以及浮现在脑海中的类(以UML-ish风格):
class Interpreter
<李>...
内存空间类
<李>...
类函数
I recommend reading chapter 9, Building High-Level Interpreters, from Language Implementation Patterns by Terence Parr.
EDIT
Okay, to get you through the time waiting for that book, here's what you're (at least) going to need:
and classes that spring to mind (in UML-ish style):
class Interpreter
class MemorySpace
class Function
这是 ANTLR -> 的一个LLVM:
Here's one with ANTLR -> LLVM:
一旦你有了 AST,你所需要的只是一个迭代器来遍历树和模板来发出你想要的对象。
Once you have the AST, all you need is an iterator to walk the tree and the template to emit the objects you want.
本教程基于 Flex 和 Bison,但是最后他详细介绍了如何将 AST 转换为 LLVM 汇编代码,这可能会有所帮助。
This Tutorial is based on Flex and Bison but at the end he details how he converts his AST to LLVM assembly code, it might be helpful.