feat: 增强字节码显示

This commit is contained in:
zhangxun 2025-06-25 11:44:26 +08:00
parent c7a953995a
commit bb5ba2218f
2 changed files with 42 additions and 2 deletions

View File

@ -22,6 +22,11 @@ public final class OpHelper {
*/
private static final Map<String, String> OPCODE_MAP;
/**
* opcode 字符串 指令名 的静态映射表
*/
private static final Map<Integer, String> OPCODE_NAME_MAP;
static {
Map<String, String> map = new HashMap<>();
map.put("I_ADD", Integer.toString(VMOpCode.I_ADD));
@ -127,6 +132,13 @@ public final class OpHelper {
map.put("RET", Integer.toString(VMOpCode.RET));
map.put("HALT", Integer.toString(VMOpCode.HALT));
OPCODE_MAP = Collections.unmodifiableMap(map);
Map<Integer, String> revmap = new HashMap<>(); // reverse map
OPCODE_MAP.forEach((key, value) -> {
revmap.put(Integer.parseInt(value), key);
});
OPCODE_NAME_MAP = Collections.unmodifiableMap(revmap);
}
/**
@ -170,5 +182,27 @@ public final class OpHelper {
throw new IllegalStateException("Unknown const type: " + v.getClass());
}
/**
* 根据 opcode 数值的字符串形式获取指令名
* @param code 字符串形式的 opcode 数值
* @return opcode 对应的指令名
*/
public static String opcodeName(String code) {
return opcodeName(Integer.parseInt(code));
}
/**
* 根据 opcode 获取指令名
* @param code opcode
* @return opcode 对应的指令名
*/
public static String opcodeName(int code) {
String name = OPCODE_NAME_MAP.get(code);
if (name == null) {
throw new IllegalStateException("Unknown opcode: " + name);
}
return name;
}
// endregion
}

View File

@ -1,7 +1,7 @@
package org.jcnc.snow.pkg.tasks;
import org.jcnc.snow.cli.commands.CompileCommand;
import org.jcnc.snow.pkg.model.Project;
import org.jcnc.snow.compiler.backend.util.OpHelper;
import org.jcnc.snow.compiler.backend.alloc.RegisterAllocator;
import org.jcnc.snow.compiler.backend.builder.VMCodeGenerator;
import org.jcnc.snow.compiler.backend.builder.VMProgramBuilder;
@ -18,6 +18,7 @@ import org.jcnc.snow.compiler.parser.context.ParserContext;
import org.jcnc.snow.compiler.parser.core.ParserEngine;
import org.jcnc.snow.compiler.parser.function.ASTPrinter;
import org.jcnc.snow.compiler.semantic.core.SemanticAnalyzerRunner;
import org.jcnc.snow.pkg.model.Project;
import org.jcnc.snow.vm.VMLauncher;
import java.nio.charset.StandardCharsets;
@ -198,7 +199,12 @@ public final class CompileTask implements Task {
List<String> finalCode = builder.build();
System.out.println("### VM code");
finalCode.forEach(System.out::println);
for (int i = 0; i < finalCode.size(); i++) {
String[] parts = finalCode.get(i).split(" ");
String name = OpHelper.opcodeName(parts[0]);
parts = Arrays.copyOfRange(parts, 1, parts.length);
System.out.printf("%04d: %-10s %s\n", i, name, String.join(" ", parts));
}
// ---------------- 5. 写出 .water 文件 ----------------
Path outputFile = deriveOutputPath(sources, outputName, dir);