将抽象语法树转换为字节码
我正在尝试学习构建一个简单的编译器作为一种爱好。我的目标是 Java 虚拟机。
我使用 Eclipse 的 ANTLR 插件编写了一个简单的语法。
有人告诉我,Antlr 生成的 AST 上有一个称为方法节点的东西,必须调用它。 我打算使用 ASM 来生成字节码。 那么什么是方法节点以及如何从 ASM 调用它并使其访问方法指令?
还有编译器的语义分析器呢?应该手动编写还是有任何生成器?
I am trying to learn to build a simple compiler as a hobby. I am targeting the Java virtual machine.
I have written a simple grammar using ANTLR plugin for Eclipse .
Someone told me that there is something known as a method node on the AST generated by Antlr, and that has to be called.
I am planning to use ASM to generate the bytecode.
So what is the method node and How do I call it from ASM and make it visit method instructions?
Also what about the semantic analyzer of a compiler. Should that be manually written or are there any generators for it?
你在这里问了很多不相关的问题。根据您定义的语言,您的语言中可能有一个方法节点,或者如果您的语言无条件编译为
main(String[])
方法,则不会有任何方法节点。有多种方法可以将 AST 转换为目标语言。大多数情况下,您不会直接生成代码,而是为您的目标平台生成 AST,并使用一个漂亮的打印机使用 Treewalker 从中生成代码。
语义分析是编译器的编程。在语法层面上阅读和理解输入就是解析。您需要自己编写语义分析器,否则您根本就不会编写编译器。 ;-)
我假设您使用 Jasmin 来编译汇编代码?一个很好的开始是为您的输入语言和目标语言(Jasmin)编写语法,并考虑哪些输入结构将呈现哪些输出。如何在 Jasmin 中编写
for i := 1 to 10
循环?解决小问题并根据需要扩展编译器,但要慢慢地,尽早彻底地测试新实现的转换。非常很好的读物:让我们构建一个编译器,作者:Jack Crenshaw。
You ask many unrelated questions in here. Depending on the language you define, there may be a method node in your language or there won't be any, say, if your language compiles to a
main(String[])
method unconditionally.There are multiple approaches to transform an AST to a target language. Mostly you would not generate code directly, but generate an AST for your target platform and have a pretty printer generate code out of it, using a treewalker.
The semantic analysis is the programming of a compiler. Reading and understanding the input on a syntactically level is the parsing. You will need to write the semantic analyzer on your own or you would not have written a compiler at all. ;-)
I presume you use Jasmin to compile the assembly code? A very good start would be writing grammars for your input language and the target language (Jasmin) and think about, which input structures would render what output. How would one write a
for i := 1 to 10
loop in Jasmin? Tackle small problems and expand your compiler as needed, but slowly, testing newly implemented transformations early and thoroughly.A very good reading: Let's Build a Compiler, by Jack Crenshaw.