修复
This commit is contained in:
parent
b2e5665bf6
commit
cb1780327c
@ -60,16 +60,18 @@ public final class BasicIRBuilder {
|
||||
* 处理单个顶层节点。
|
||||
* 可能是:模块(ModuleNode)、函数(FunctionNode)、单条语句(StatementNode)。
|
||||
*
|
||||
* @param node AST 顶层节点
|
||||
* @param node AST 顶层节点
|
||||
* @param irProgram 正在构建的 IRProgram
|
||||
*/
|
||||
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))
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user