feat: 实现对布尔变量声明并赋值的完整支持

This commit is contained in:
luke 2025-06-11 22:12:24 +08:00
parent 20183be93d
commit 2047e97655
3 changed files with 23 additions and 12 deletions

View File

@ -1,11 +1,11 @@
module: Main
function: main
parameter:
return_type: int
return_type: boolean
body:
declare b1: boolean
declare b1: boolean =true
return 0
return b1
end body
end function
end module

View File

@ -64,6 +64,7 @@ public class LoadConstGenerator implements InstructionGenerator<LoadConstInstruc
case Byte _ -> 'B'; // 字节型
case Double _ -> 'D'; // 双精度浮点型
case Float _ -> 'F'; // 单精度浮点型
case Boolean _ -> 'I'; // 布尔作为 0/1 整型存储
case null, default ->
throw new IllegalStateException("Unknown const type: " + (value != null ? value.getClass() : null));
};

View File

@ -44,23 +44,27 @@ public record ExpressionBuilder(IRContext ctx) {
*/
public IRVirtualRegister build(ExpressionNode expr) {
return switch (expr) {
// 数字字面量 "123", "1.0f"
// 数字字面量
case NumberLiteralNode n -> buildNumberLiteral(n.value());
// 标识符如变量x直接查作用域
// 布尔字面量
case BoolLiteralNode b -> buildBoolLiteral(b.getValue());
// 标识符
case IdentifierNode id -> {
IRVirtualRegister reg = ctx.getScope().lookup(id.name());
if (reg == null) throw new IllegalStateException("未定义标识符: " + id.name());
if (reg == null)
throw new IllegalStateException("未定义标识符: " + id.name());
yield reg;
}
// 二元表达式 "a + b"
// 二元表达式
case BinaryExpressionNode bin -> buildBinary(bin);
// 函数调用 foo(a, b)
// 函数调用
case CallExpressionNode call -> buildCall(call);
// 其它不支持
default -> throw new IllegalStateException("不支持的表达式类型: " + expr.getClass().getSimpleName());
default -> throw new IllegalStateException(
"不支持的表达式类型: " + expr.getClass().getSimpleName());
};
}
/**
* 直接将表达式计算结果写入指定的目标寄存器dest
* <p>
@ -91,8 +95,6 @@ public record ExpressionBuilder(IRContext ctx) {
}
}
// ===================== 内部私有方法 =====================
/**
* 构建二元表达式的IR生成新寄存器存储结果
* <p>
@ -179,4 +181,12 @@ public record ExpressionBuilder(IRContext ctx) {
ctx.addInstruction(new LoadConstInstruction(reg, constant));
return reg;
}
/** 布尔字面量 → CONST true=1false=0*/
private IRVirtualRegister buildBoolLiteral(boolean value) {
IRConstant constant = new IRConstant(value ? 1 : 0);
IRVirtualRegister reg = ctx.newRegister();
ctx.addInstruction(new LoadConstInstruction(reg, constant));
return reg;
}
}