This commit is contained in:
Luke 2025-04-29 16:14:54 +08:00
parent b2e5665bf6
commit cb1780327c
2 changed files with 13 additions and 11 deletions

View File

@ -65,11 +65,13 @@ public final class BasicIRBuilder {
*/
private void dispatchTop(Node node, IRProgram irProgram) {
switch (node) {
case ModuleNode moduleNode -> moduleNode.functions().forEach(f -> dispatchTop(f, irProgram)); // 递归处理模块内的函数
case FunctionNode functionNode -> irProgram.add(buildFunction(functionNode)); // 将函数编译成 IRFunction 并加入 IRProgram
case ModuleNode moduleNode ->
moduleNode.functions().forEach(functionNode -> dispatchTop(functionNode, irProgram)); // 递归处理模块内的函数
case FunctionNode functionNode ->
irProgram.add(buildFunction(functionNode)); // 将函数编译成 IRFunction 并加入 IRProgram
case StatementNode statementNode -> { // 单条语句如脚本式 main
FunctionNode fake = new FunctionNode("main", List.of(), "void", List.of(statementNode));
irProgram.add(buildFunction(fake));
FunctionNode functionNode = new FunctionNode("main", List.of(), "void", List.of(statementNode));
irProgram.add(buildFunction(functionNode));
}
default -> throw new IllegalStateException("Unsupported top-level node: " + node);
}
@ -78,20 +80,20 @@ public final class BasicIRBuilder {
/**
* 将一个 FunctionNode 编译成 IRFunction
*
* @param fn AST 中的函数节点
* @param functionNode AST 中的函数节点
* @return 生成的 IRFunction
*/
private IRFunction buildFunction(FunctionNode fn) {
currentFn = new IRFunction(fn.name()); // 创建新 IRFunction
private IRFunction buildFunction(FunctionNode functionNode) {
currentFn = new IRFunction(functionNode.name()); // 创建新 IRFunction
variables.clear(); // 清空变量表每个函数独立
// 将函数参数映射为新的寄存器未进一步使用参数但保留未来拓展空间
for (ParameterNode p : fn.parameters()) {
for (ParameterNode p : functionNode.parameters()) {
variables.put(p.name(), currentFn.newRegister());
}
// 编译函数体中的每条语句
for (StatementNode stmt : fn.body()) stmt(stmt);
for (StatementNode stmt : functionNode.body()) stmt(stmt);
// 如果函数末尾没有 return自动添加一个 return无返回值
if (currentFn.body().isEmpty() || !(currentFn.body().getLast() instanceof ReturnInstruction))

2
test
View File

@ -1,5 +1,5 @@
module: CommonTasks
function: main
function: main1
parameter:
declare num1: int
declare num2: int