将Antlr语法树转换为有用的对象 [英] Converting Antlr syntax tree into useful objects
问题描述
我正在考虑如何最好地使用Antlr生成AST并将其转换为有用的对象,我可以在我的程序中使用它。
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.
例如,我如何获取属性子树并实例化特定的Attribute类。例如。
For example, how would I take an attribute sub-tree and have a specific Attribute class instanciated. E.g.
以下语言代码:
Print(message:"Hello stackoverflow")
将产生以下AST:
alt text http://img36.imageshack.us/img36/1672 /simpleast.png
我目前的想法是工厂类可以读取树,拉出名称(消息
),并键入( STRING
)值( Hello stackoverflow
)。现在,知道我可以实现正确类的类型(例如,一个StringAttribute类)并传入所需的属性数据 - 名称
和值
。
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
.
同样的方法可以用于定义工厂,拉出定义名称( Print
),实现Print类,然后传入属性工厂生成的属性。
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.
对于更复杂的程序,事情会变得更复杂: / p>
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")
}
}
}
alt text http://img205.imageshack页面没有自动跳转/ img205 / 3452 /复杂ast.png
非常欢迎任何/所有帮助或想法。非常感谢。
ANY/ALL help or thoughts are very welcome. Many thanks.
我之前的相关问题(可能有用):
Previous related questions by me (Could be useful):
- How do I make a tree parser
- Solving LL recursion problem
- Antrl3 conditional tree rewrites
推荐答案
我建议阅读第9章构建高级解释器,来自Terence Parr的语言实施模式。
I recommend reading chapter 9, Building High-Level Interpreters, from Language Implementation Patterns by Terence Parr.
编辑
好的,为了让您度过等待该书的时间,这里是你是什么(a至少)需要:
Okay, to get you through the time waiting for that book, here's what you're (at least) going to need:
- 一个全局存储空间;
- 函数空间(每个函数)空间也将有一个(本地)内存空间);
和想到的类(在 UML-ish style):
and classes that spring to mind (in UML-ish style):
-
class Interpreter
- global:MemorySpace
- 函数:Stack< Function>
- ...
class Interpreter
- global : MemorySpace
- functions : Stack<Function>
- ...
- vars:Map< String,Object>
- ...
- local:MemorySpace
- execute():void
- ...
这篇关于将Antlr语法树转换为有用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!