Java-从ANTLR 4访问者实现生成JVM字节码

问题描述 投票:0回答:1

我正在开发一种语言,该语言已在ANTLR 4及其访问者模式的帮助下在Java中实现。现在,我想从访问者模式中的已实现代码中生成JVM字节码,以后可以在Java虚拟机上执行。

因此,例如,给出以下代码(假设这是我正在创建的语言):

int a = 1;
int b = 2;
int c = 3;
int d = 4;
if (a == b && c == d && a == d) {
    System.out.println("b = c");
} else {
    System.out.println("No!");
}

而且我在ANTLR 4的访问者模式中实现了以下功能,该功能处理我的语言的不同指令(分配,如果,逻辑和关系比较等):

// ...
void if(...) {
    // ...
}
// &&, ||, !
void logicalComparison(...) {
    // ...
}
// ==, !=, <=, >=, <, >
void relationalComparison(...) {
    // ...
}
//...

我遇到的问题是,当我为if语句生成代码时,我需要一种返回方法来记住比较的位置,以便在生成else语句以放置其位置后返回,以便如果不满足条件,则可能会跳转。

生成字节码的最佳方法是什么?

java jvm antlr4 bytecode visitor-pattern
1个回答
0
投票

您可以将标签与goto字节码一起使用。取决于您使用的是哪种代码生成工具,它可能是某种类型的

// Visit your condition so its result is pushed on the stack

// Create three new labels
int iflab   = ++labels; // Label to jump to if the condition was true
int elselab = ++labels; // Label to jump to if the condition was false
int donelab = ++labels; // Label to jump to once done executing either branches

generate("ifne label" + iflab);
generate("goto label" + elselab);

generate("label" + iflab + ":");
// visit the statement needing to be executed if the condition was true
generate("goto label" + donelab);

generate("label" + elselab + ":");
// visit the statement needing to be executed if the condition was false (if there is one)
generate("goto label" + donelab);

println("label" + donelab + ":");
// You are done with this statement, keep visiting the following statements.

这是未优化的(创建了太多标签,并且没有太多标签),但是应该清楚。 generate方法只是将字节码写入文件,我在编写此代码时使用的是Jasmin。使用ASM或任何其他JVM字节码工具应与之相似。

© www.soinside.com 2019 - 2024. All rights reserved.