Files
spl/stage3/builtins/builtins.spl
T

95 lines
3.3 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.
#!builtin
#!role(builtins)
type meta = @import("meta");
// splc3 的预置头:把编译器底层能力以 `#builtin` 声明暴露给用户/comptime 代码。
// `#builtin(<id>)` 的 id 必须命中 stage3/intrinsic.spl 的 intrinsic_of_id。
// 查询 / 断言类。静态类型实参由 sema 折成常量;动态类型值
// (comptime VM 里的 type 句柄)走宿主桥,因此同时声明为 extern。
#builtin(sizeof) #extern(builtin) comptime fn sizeof(t: type): usize;
#builtin(bitsizeof) #extern(builtin) comptime fn bitsizeof(t: type): usize;
#builtin(alignof) #extern(builtin) comptime fn alignof(t: type): usize;
#builtin(field_count) #extern(builtin) comptime fn field_count(t: type): usize;
#builtin(type_of) comptime fn type_of(v: any): type;
#builtin(self) comptime fn self(): type;
// spl_ir 接口:单写/单读,经编译器生成的 VM ABI 调用(无显式桥)。
// `#extern(builtin)` 表示后端外部实现(等价于当前后端的 `#extern(vm)`)。
#builtin(echo) #extern(builtin) comptime fn echo(x: u8): u8;
// 运行期 panic:消息是动态切片,由宿主打印并终止。
#extern(vm) fn panic(msg: []u8): void;
type Ref = @import("./spl_ir.spl").Ref;
type Node = @import("./spl_ir.spl").Node;
#builtin(inspect) #extern(builtin) comptime fn inspect(n: Ref): Node;
#builtin(construct) #extern(builtin) comptime fn construct(n: Node): Ref;
// receiver hook:@Self 只挂在方法的第一个参数上。
// 参数类型是 *T 时取地址,是 T 时按值传递;implicit 本身已是指向接收者的指针时直接复用。
#hook(param)
macro fn Self(callee: Ref, value: Ref, implicit: Ref): Ref {
if implicit == 0 {
if value != 0 { ret value; }
ret 0;
}
var cn = @meta.inspect(callee);
match cn.kind {
.FnDecl(f) => {
var pn = @meta.inspect(f.params[0]);
match pn.kind {
.ParamDecl(p) => {
var tn = @meta.inspect(p.ty);
match tn.kind {
.PtrType(_) => {
if @ptr_ref(implicit) { ret implicit; }
ret @meta.construct(.{ .kind = .Addr(implicit) });
},
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
// implicit 已是 `*T` 形式(局部变量或参数)时不再二次取地址。
comptime fn ptr_ref(r: Ref): bool {
var n = @meta.inspect(r);
var decl: Ref = 0;
match n.kind {
.Addr(_) => { ret true; },
.Local(p) => { decl = p; },
_ => {},
}
if decl == 0 { ret false; }
var dn = @meta.inspect(decl);
var ty: Ref = 0;
match dn.kind {
.ParamDecl(p) => { ty = p.ty; },
.VarDecl(v) => { ty = v.ty; },
_ => {},
}
if ty == 0 { ret false; }
var tn = @meta.inspect(ty);
match tn.kind {
.PtrType(_) => { ret true; },
.ShapeUse(x) => {
var sn = @meta.inspect(x.shapes[0]);
match sn.kind { .PtrType(_) => { ret true; }, _ => {} }
},
.ShapeNoDefault(xs) => {
var sn = @meta.inspect(xs[0]);
match sn.kind { .PtrType(_) => { ret true; }, _ => {} }
},
_ => {},
}
ret false;
}