Files
spl/stage1/test16_methods.spl
zzy 459b6188a9 stage1 - 全面重构 stage1 编译器架构:类型系统(arena + items)、IR 发射层(spl_emit.h/c)、统一所有 emit 调用点。
- 实现 as 类型转换运算符、修复 &&/|| 短路求值 bug。
- 在 splc1.spl 中实现 Vec/Map/Emit 基础库(~50 个方法)。
- 修复实例方法调用中 self 参数被错误丢弃的 bug。
2026-07-20 20:53:41 +08:00

49 lines
1.1 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ===== 模块7高级特性 =====
* test16_methods — 类型关联方法
* 难度3/5
* 验证点struct 方法、enum 方法、self 参数自动填充、方法调用
*/
@extern(vm) fn vm_printf(fmt: *u8, ...) void;
type Point = struct {
x: i32,
y: i32,
fn init(x: i32, y: i32) Point {
ret Point { .x = x, .y = y };
}
fn dump(self: *Point) void {
vm_printf("Point(%d, %d)\n", self.x, self.y);
}
}
type Expr = enum {
Int: i32,
Add: struct { left: *Expr, right: *Expr },
fn eval(self: *Expr) i32 {
match self {
.Int(val) => ret val,
.Add(left, right) => ret eval(left) + eval(right),
}
ret 0;
}
}
fn main() i32 {
/* struct 方法调用 */
var p: Point = Point.init(3, 4);
p.dump(&p);
/* enum 方法 + match */
var expr_l := Expr { .Int = 3 };
var expr_r := Expr { .Int = 4 };
var expr := Expr { .Add = { .left = expr_l, .right = expr_r } };
var result := expr.eval(&expr);
vm_printf("eval result: %d\n", result);
if result != 7 { ret 1; }
ret 0;
}