spl 编写编译器基础框架 ai修复出现的stage2和stage3问题并提供新语法

This commit is contained in:
zzy committed 2026-11-07 21:52:02 +08:00
1 parent 126b979f72
commit 50ee126d44
87 files changed
+3159 -385

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
type .{ .Vec } = @import("core/vec.spl");
type .{ .Allocator } = @import("core/alloc.spl");
type .{ .String } = @import("core/str.spl");
type .{ .Result } = @import("core/error.spl");
type ptr = @import("core/ptr.spl");
type .{ .File } = @import("compiler/shape.spl");
type SourceId = u32;
pub comptime fn SourceFile(A: Allocator): type {
ret struct {
id: SourceId,
name: @Vec(u8, A),
content: @Vec(u8, A),
line_offsets: @Vec(usize, A),
}
}
type SourceError = enum {
UnknownError,
FileOpenError,
FileAttributeError,
FileReadError,
OutOfMemory,
}
pub comptime fn Source(A: Allocator, F: File): type {
ret struct {
// TODO HashSet 进行去重
files: @Vec(@SourceFile(A), A),
fshape: F,
alloc: A,
pub fn new(alloc: A, fshape: F): @self {
ret .{ .files = @Vec(@SourceFile(A), A).empty(alloc), .alloc = alloc, .fshape = fshape };
}
pub fn add_file(@Self self: *@self, name: []const u8): @Result(SourceId, SourceError) {
var fp = self.fshape.open(name, .Read) catch .Err(_) {
ret .(.Err(.FileOpenError));
};
errdefer { fp.close(); }
var size = fp.size() catch .Err(_) {
ret .(.Err(.FileAttributeError));
};
var content = @Vec(u8, A).with_capacity(self.alloc, size) catch .Err(_) {
ret .(.Err(.OutOfMemory));
};
content._set_len(size);
var read_size = fp.read(content.as_slice()) catch .Err(_) {
ret .(.Err(.FileReadError));
};
if read_size != size {
ret .(.Err(.FileReadError));
}
var owned_name = @Vec(u8, A).with_capacity(self.alloc, name.len()) catch .Err(_) {
ret .(.Err(.OutOfMemory));
};
owned_name._set_len(name.len());
ptr.copy(owned_name.as_slice().as_ptr(), name.as_ptr(), name.len());
ret self.add_virtual(owned_name, content);
}
pub fn add_virtual(@Self self: *@self, name: @Vec(u8, A), content: @Vec(u8, A)): @Result(SourceId, SourceError) {
var id = self.files.len();
var file: @SourceFile(A) = .{
.id = id as u32,
.name = name,
.content = content,
.line_offsets = @Vec(usize, A).empty(self.alloc),
};
self.files.push(file) catch .Err(e) {
ret .(.Err(.OutOfMemory));
};
ret .(.Ok(id as SourceId));
}
}
}
+30
View File
@@ -0,0 +1,30 @@
type .{ .Writer, .Reader, .IOError } = @import("core/io.spl");
type .{ .Result, .Option } = @import("core/error.spl");
pub type FileMode = enum {
Read,
Write,
Append,
}
pub type File = shape: Writer + Reader {
fn open(path: []const u8, mode: FileMode): @Result(@self, IOError);
fn close(@Self self: *@self): @Result((), IOError);
fn size(@Self self: *@self): @Result(usize, IOError);
}
pub type Time = shape {
}
pub type Memory = shape {
}
pub type Process = shape {
}
pub type VM = shape {
}
+197
View File
@@ -0,0 +1,197 @@
#extern(vm) fn vm_fopen(path: *any, mode: *any): *any;
#extern(vm) fn vm_fclose(f: *any): i32;
#extern(vm) fn vm_fread(buf: *any, sz: usize, n: usize, f: *any): usize;
#extern(vm) fn vm_fwrite(buf: *any, sz: usize, n: usize, f: *any): usize;
#extern(vm) fn vm_fsize(f: *any): usize;
#extern(vm) fn vm_fflush(f: *any): i32;
#extern(vm) fn vm_stdin(): *any;
#extern(vm) fn vm_stdout(): *any;
#extern(vm) fn vm_stderr(): *any;
#extern(vm) fn vm_putchar(c: i32): i32;
#extern(vm) fn vm_getchar(): i32;
#extern(vm) fn vm_exit(code: i32);
#extern(vm) fn vm_alloc(sz: usize): *any;
#extern(vm) fn vm_free(p: *any);
#extern(vm) fn vm_realloc(p: *any, sz: usize): *any;
#extern(vm) fn vm_memcpy(dst: *any, src: *any, n: usize): *any;
#extern(vm) fn vm_memcmp(a: *any, b: *any, n: usize): isize;
// 时间/参考量接口(原生 vm_timestamp,case 探测风格,不假设一定可用)。
// available() -> 1 = 时间可用;0 = 不可用(其余 time 相关返回值恒为 0)
// sec() -> 当前秒
// ns() -> 当前纳秒部分
// steps() -> VM 已执行指令数(参考量)
// now_ns() -> 完整纳秒时间戳(单次调用;纪元纳秒 < 2^64,无需 i128)
#extern(vm) fn vm_timestamp(kind: usize): usize;
#extern(vm) fn vm_new(): *any;
#extern(vm) fn vm_drop(vm: *any): void;
#extern(vm) fn vm_load(vm: *any, fpath: *u8): void;
#extern(vm) fn vm_load_from_buffer(vm: *any, buf: *any, len: usize): i32;
#extern(vm) fn vm_push(vm: *any, val: spl_vm_val_t): void;
#extern(vm) fn vm_call(vm: *any, name: *u8, nargs: u64): i32;
#extern(vm) fn vm_run(vm: *any): i32;
#extern(vm) fn vm_ret_val(vm: *any): spl_vm_val_t;
#extern(vm) fn vm_mem_alloc(vm: *any, size: usize): spl_vm_val_t;
#extern(vm) fn vm_mem_read(vm: *any, off: spl_vm_val_t, dst: *any, n: usize): i32;
#extern(vm) fn vm_mem_write(vm: *any, off: spl_vm_val_t, src: *any, n: usize): i32;
#extern(vm) fn vm_stack_get(vm: *any, index: usize): spl_vm_val_t;
#extern(vm) fn vm_set_foreign(vm: *any, entry: []u8, ctx: *any): void;
// 把外部处理器名绑定到宿主函数。SIR 后端按名调用宿主 VM 函数,无需登记;
// 原生后端没有名字到地址的运行时表,需要这里先登记函数指针。
#extern(vm) fn vm_bind_foreign(entry: []u8,
handler: fn(*any, u64, u64, *any, u64, u64): u64): void;
type .{ .Allocator, .AllocError, .Layout } = @import("core/alloc.spl");
type .{ .Writer, .Reader, .IOError } = @import("core/io.spl");
type .{ .Result } = @import("core/error.spl");
pub fn strlen(str: *const u8): usize {
var len: usize = 0;
while (str[len] != 0) {
len = len + 1;
}
ret len;
}
pub type VMAllocator = struct: Allocator {
pub fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError) {
var res = vm_alloc(layout.size);
if res == null {
ret .(.Err(AllocError.OutOfMemory));
}
ret .(.Ok(res));
}
pub fn dealloc(@Self self: *@self, ptr: *any, layout: Layout) {
vm_free(ptr);
}
}
// pub type VMReader = struct: Reader {
// }
pub type VMWriter = struct: Writer {
file: *any;
pub fn with_file(f: *any): VMWriter {
ret VMWriter { .file = f };
}
pub fn with_stdout(): VMWriter {
ret VMWriter { .file = vm_stdout() };
}
pub fn with_stderr(): VMWriter {
ret VMWriter { .file = vm_stderr() };
}
pub fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMWriter file is null");
var result = vm_fwrite(buf.as_ptr() as *any, 1, buf.len(), f);
if result == 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(result));
}
pub fn flush(@Self self: *@self): @Result((), IOError) {
var f = self.file;
@assert(f != null, "VMWriter file is null");
var result = vm_fflush(f);
if result != 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(()));
}
}
type .{ .File, .FileMode, .Time, .Memory, .Process, .VM } = @import("./shape.spl");
type ptr = @import("core/ptr.spl");
type VMFile = struct: File {
file: *any;
pub fn with_stdout(): @self {
ret .{ .file = vm_stdout() };
}
pub fn with_stderr(): @self {
ret .{ .file = vm_stderr() };
}
pub fn open(path: []const u8, mode: FileMode): @Result(@self, IOError) {
var mode_str: []const u8 = match (mode) {
.Read => {"rb\0"},
.Write => {"wb\0"},
.Append => {"ab\0"},
};
// TODO hack it;
var path_cstr: [1024]u8 = .[];
ptr.copy(path_cstr.as_ptr(), path.as_ptr(), path.len());
path_cstr[path.len()] = 0;
var f = vm_fopen(path_cstr.as_ptr() as *any, mode_str.as_ptr() as *any);
if f == null {
ret .(.Err(IOError.UnknownError));
}
ret .(.Ok(VMFile { .file = f }));
}
pub fn read(@Self self: *@self, buf: []u8): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fread(buf.as_ptr() as *any, 1, buf.len(), f);
if result == 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(result));
}
pub fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fwrite(buf.as_ptr() as *any, 1, buf.len(), f);
if result == 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(result));
}
pub fn size(@Self self: *@self): @Result(usize, IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
ret .(.Ok(vm_fsize(f)));
}
pub fn flush(@Self self: *@self): @Result((), IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fflush(f);
if result != 0 {
ret .(.Err(IOError.BufferTooSmall));
}
ret .(.Ok(()));
}
pub fn close(@Self self: *@self): @Result((), IOError) {
var f = self.file;
@assert(f != null, "VMFile file is null");
var result = vm_fclose(f);
if result != 0 {
ret .(.Err(IOError.UnknownError));
}
ret .(.Ok(()));
}
}
+16
View File
@@ -0,0 +1,16 @@
type .{ .Result } = @import("./error.spl");
pub type Layout = struct {
size: usize;
align: usize;
}
pub type AllocError = enum {
OutOfMemory,
InvalidLayout,
}
pub type Allocator = shape {
fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError);
fn dealloc(@Self self: *@self, ptr: *any, layout: Layout);
}
+59
View File
@@ -0,0 +1,59 @@
pub comptime fn Option(T: type): type {
ret enum {
pub Some: T,
pub None: void,
// pub fn unwrap(@Self self: *@self): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { panic("called unwrap on None"); ret undefined; }
// }
// }
// pub fn expect(@Self self: *@self, msg: []u8): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { panic(msg); ret undefined; }
// }
// }
// pub fn unwrap_or_else(@Self self: *@self, f: fn(): T): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { ret f(); }
// }
// }
};
}
pub comptime fn Result(T: type, E: type): type {
ret enum {
#ok
pub Ok: T,
#error
pub Err: E,
// pub fn unwrap(@Self self: *@self): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { panic("called unwrap on Err"); ret undefined; }
// }
// }
// pub fn expect(@Self self: *@self, msg: []u8): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { panic(msg); ret undefined; }
// }
// }
// pub fn unwrap_or_else(@Self self: *@self, f: fn(): T): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { ret f(); }
// }
// }
};
}
+23
View File
@@ -0,0 +1,23 @@
pub type Display = shape {
fn fmt(@Self self: *@self, out: @[*Sink]): bool;
};
pub type Debug = shape {
fn debug(@Self self: *@self, out: @[*Sink]): bool;
};
pub type Sink = shape {
fn write_byte(@Self self: *@self, byte: u8): bool;
// TODO shape default value for `fn write_bytes(@Self self: *@self, bytes: []const u8): bool;`
};
pub comptime fn Formatter(S: Sink): type {
ret struct {
out: S,
pub fn with_sink(out: S): @self {
ret .{ .out = out };
}
};
}
View File
Whitespace-only changes.
+19
View File
@@ -0,0 +1,19 @@
type .{ .Allocator } = @import("./alloc.spl");
type .{ .Result } = @import("./error.spl");
type .{ .static } = @import("./macro.spl");
type IOError = enum {
UnknownError,
OutOfMemory,
BufferTooSmall,
}
pub type Reader = shape {
fn read(@Self self: *@self, buf: []u8): @Result(usize, IOError);
}
pub type Writer = shape {
fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError);
fn flush(@Self self: *@self): @Result((), IOError);
}
+22
View File
@@ -0,0 +1,22 @@
type meta = @import("meta");
type .{ .Ref } = meta;
#hook(param)
macro fn default(callee: Ref, value: Ref, fallback: Ref): Ref {
if value != 0 { ret value; }
if fallback != 0 { @meta.error(704); ret 0; }
// TODO check the same type
ret Ref;
}
#hook(param)
macro fn Self(callee: Ref, value: Ref): Ref {
// TODO value direct not supported
// @meta.
ret @meta.construct(.{ .kind = .Addr(value) });
}
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
pub fn bytes_eq(a: []const u8, b: []const u8): bool {
if a.len() != b.len() { ret false; }
var i: usize = 0;
while i < a.len() {
if a[i] != b[i] { ret false; }
i = i + 1;
}
ret true;
}
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
fn copy(dst: *any, src: *const any, count: usize) {
var _dst = dst as *u8;
var _src = src as *const u8;
var i: usize = 0;
while (i < count) {
_dst[i] = _src[i];
i = i + 1;
}
}
+120
View File
@@ -0,0 +1,120 @@
type .{ .Vec } = @import("./vec.spl");
type .{ .Allocator, .AllocError } = @import("./alloc.spl");
type .{ .Result, .Option } = @import("./error.spl");
type .{ .Format } = @import("./fmt.spl");
type .{ .static } = @import("./macro.spl");
type FromStr = shape {
type Err;
fn from_str(s: []const u8): @Result(@self, Err);
}
pub fn eq(a: []const u8, b: []const u8): bool {
if a.len() != b.len() { ret false; }
var i: usize = 0;
while i < a.len() {
if a[i] != b[i] { ret false; }
i = i + 1;
}
ret true;
}
pub fn starts_with(s: []const u8, prefix: []const u8): bool {
if prefix.len() > s.len() { ret false; }
ret eq(s[0..prefix.len()], prefix);
}
pub fn index_byte(s: []const u8, b: u8, from: usize): @Option(usize) {
var i = from;
while i < s.len() {
if s[i] == b { ret .Some(i); }
i = i + 1;
}
ret .None;
}
pub fn is_space(b: u8): bool {
ret b == ' ' || b == '\t' || b == '\r' || b == '\n';
}
pub fn is_digit(b: u8): bool {
ret b >= '0' && b <= '9';
}
pub fn is_hex_digit(b: u8): bool {
ret is_digit(b) || (b >= 'a' && b <= 'f') || (b >= 'A' && b <= 'F');
}
pub fn is_alpha(b: u8): bool {
ret (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z');
}
pub fn is_ident_start(b: u8): bool {
ret is_alpha(b) || b == '_';
}
pub fn is_ident_continue(b: u8): bool {
ret is_ident_start(b) || is_digit(b);
}
pub fn trim_ascii(s: []const u8): []const u8 {
var a: usize = 0;
var b: usize = s.len();
while a < b && is_space(s[a]) { a = a + 1; }
while b > a && is_space(s[b - 1]) { b = b - 1; }
ret s[a..b];
}
pub comptime fn String(A: Allocator): type {
ret struct {
data: @Vec(u8, A),
pub fn new(alloc: A): @self {
ret .{ .data = @Vec(u8, A).empty(alloc) };
}
pub fn from_slice(alloc: A, s: []const u8): @Result(@self, AllocError) {
var out: @self = .{ .data = @Vec(u8, A).empty(alloc) };
try out.push_str(s);
ret .(.Ok(out));
}
pub fn push_str(@Self self: *@self, s: []const u8): @Result((), AllocError) {
var i: usize = 0;
while i < s.len() {
try self.data.push(s[i]);
i = i + 1;
}
}
pub fn from_cstr(alloc: A, s: *const u8): @Result(@self, AllocError) {
var res: @self = .{ .data = @Vec(u8, A).empty(alloc) };
try res.push_cstr(s);
ret .(.Ok(res));
}
pub fn push_cstr(@Self self: *@self, s: *const u8): @Result((), AllocError) {
var i: usize = 0;
while s[i] != 0 {
try self.data.push(s[i]);
i = i + 1;
}
}
pub fn as_slice(@Self self: *@self): []const u8 {
ret self.data.as_slice();
}
pub fn len(@Self self: *@self): usize {
ret self.data.len();
}
pub fn clear(@Self self: *@self) {
self.data.clear();
}
pub fn drop(@Self self: *@self) {
self.data.drop();
}
};
}
+279
View File
@@ -0,0 +1,279 @@
type .{ .Option, .Result } = @import("./error.spl");
type .{ .Layout, .AllocError, .Allocator } = @import("./alloc.spl");
type ptr = @import("ptr.spl");
comptime fn RawVec(t: type): type {
ret struct {
data: *t,
length: usize,
cap: usize,
pub fn empty(): @self {
ret .{ .data = null, .length = 0, .cap = 0 };
}
pub fn len(@Self self: *@self): usize {
ret self.length;
}
pub fn capacity(@Self self: *@self): usize {
ret self.cap;
}
pub fn as_raw_ptr(@Self self: *@self): *t {
ret self.data;
}
pub fn as_slice(@Self self: *@self): []t {
ret @Slice(t).from_raw_parts(self.data, self.length);
}
pub fn get(@Self self: *@self, i: usize): @Option(t) {
if i >= self.length { ret .None }
ret .Some(self.data[i]);
}
pub fn at(@Self self: *@self, i: usize): @Option(*t) {
if i >= self.length { ret .None }
ret .Some(self.data + i);
}
pub fn set(@Self self: *@self, i: usize, v: t): bool {
if (i >= self.length) { ret false }
self.data[i] = v;
ret true;
}
pub fn clear(@Self self: *@self): () {
self.length = 0;
}
pub fn truncate(@Self self: *@self, n: usize): () {
if n < self.length {
self.length = n;
}
}
pub fn reset(@Self self: *@self): () {
self.data = null;
self.length = 0;
self.cap = 0;
}
pub fn set_unchecked(@Self self: *@self, i: usize, v: t) {
self.data[i] = v;
}
pub fn push_unchecked(@Self self: *@self, v: t): () {
self.data[self.length] = v;
self.length = self.length + 1;
}
pub fn pop_unchecked(@Self self: *@self): t {
self.length = self.length - 1;
ret self.data[self.length];
}
pub fn insert_unchecked(@Self self: *@self, i: usize, v: t): () {
var j = self.length;
while j > i {
self.data[j] = self.data[j - 1];
j = j - 1;
}
self.data[i] = v;
self.length += 1;
}
pub fn remove_unchecked(@Self self: *@self, i: usize): t {
var v = self.data[i];
var j = i;
while j + 1 < self.length {
self.data[j] = self.data[j + 1];
j = j + 1;
}
self.length -= 1;
ret v;
}
};
}
fn layout_of(size: usize, align: usize, n: usize): Layout {
var limit: usize = ~(0 as usize);
@assert(n == 0 || size <= limit / n, "layout overflow");
ret .{ .size = size * n, .align = align };
}
fn grow_capacity(current: usize, min_cap: usize, need: usize): usize {
var cap = current;
if cap < min_cap {
cap = min_cap;
}
while cap < need {
cap = cap * 2;
}
ret cap;
}
comptime fn Grow(T: type, A: Allocator): type {
ret struct {
fn reserve(base: *@RawVec(T), alloc: A, additional: usize): @Result((), AllocError) {
var need = base.len() + additional;
if need <= base.capacity() {
ret;
}
var new_cap = grow_capacity(base.capacity(), 8, need);
var old_layout = layout_of(@sizeof(T), @alignof(T), base.capacity());
var new_layout = layout_of(@sizeof(T), @alignof(T), new_cap);
var p: *u8 = try alloc.alloc(new_layout) as *u8;
if base.capacity() != 0 {
// TODO : Use copy_nonoverlapping to copy the data from the old allocation to the new one
// This is a placeholder for the actual memory copy operation
ptr.copy(p, base.data as *u8, base.len() * @sizeof(T));
alloc.dealloc(base.data as *any, old_layout);
}
base.data = p as *T;
base.cap = new_cap;
}
};
}
pub comptime fn Vec(T: type, A: Allocator): type {
ret struct {
base: @RawVec(T),
alloc: A,
pub fn empty(alloc: A): @self {
ret .{ .base = @RawVec(T).empty(), .alloc = alloc };
}
pub fn with_capacity(alloc: A, n: usize): @Result(@self, AllocError) {
@assert(@sizeof(T) > 0, "zero-size element unsupported");
var v: @self = .{ .base = @RawVec(T).empty(), .alloc = alloc };
if n == 0 {
ret .Ok(v);
}
try @Grow(T, A).reserve(&v.base, v.alloc, n);
ret .Ok(v);
}
pub fn len(@Self self: *@self): usize {
ret self.base.len();
}
pub fn capacity(@Self self: *@self): usize {
ret self.base.capacity();
}
pub fn as_slice(@Self self: *@self): []T {
ret self.base.as_slice();
}
pub fn get(@Self self: *@self, i: usize): @Option(T) {
ret self.base.get(i);
}
pub fn at(@Self self: *@self, i: usize): @Option(*T) {
ret self.base.at(i);
}
pub fn set(@Self self: *@self, i: usize, v: T): bool {
ret @RawVec(T).set(&self.base, i, v);
}
pub fn reserve(@Self self: *@self, additional: usize): @Result((), AllocError){
try @Grow(T, A).reserve(&self.base, self.alloc, additional);
}
pub fn push(@Self self: *@self, v: T): @Result((), AllocError) {
if self.base.len() + 1 > self.base.cap {
try @Grow(T, A).reserve(&self.base, self.alloc, 1);
}
@RawVec(T).push_unchecked(&self.base, v);
ret .Ok(());
}
pub fn pop(@Self self: *@self): @Option(T) {
if self.base.len() == 0 {
ret .None;
}
ret .Some(@RawVec(T).pop_unchecked(&self.base));
}
pub fn append(@Self self: *@self, items: []T): @Result((), AllocError) {
var count = items.len();
if count == 0 {
ret .Ok(());
}
var offset: usize = 0;
var inside = false;
if self.base.len() != 0 {
var base_addr = self.base.data as usize;
var src_addr = items.as_ptr() as usize;
if src_addr >= base_addr && src_addr - base_addr < self.base.len() * @sizeof(T) {
offset = src_addr - base_addr;
inside = true;
}
}
if self.base.len() + count > self.base.capacity() {
try @Grow(T, A).reserve(&self.base, self.alloc, count);
}
var src = items.as_ptr();
if inside {
src = ((self.base.data as *u8) + offset) as *T;
}
var i: usize = 0;
while i < count {
@RawVec(T).push_unchecked(&self.base, src[i]);
i = i + 1;
}
ret .Ok(());
}
pub fn insert(@Self self: *@self, i: usize, v: T): @Result((), AllocError) {
@assert(i <= self.base.len(), "insert out of range");
if self.base.len() + 1 > self.base.capacity() {
try @Grow(T, A).reserve(&self.base, self.alloc, 1);
}
@RawVec(T).insert_unchecked(&self.base, i, v);
ret .Ok(());
}
pub fn remove(@Self self: *@self, i: usize): @Option(T) {
if (i < self.base.len()) {
ret .None;
}
var res = @RawVec(T).remove_unchecked(&self.base, i);
ret .Some(res);
}
pub fn clear(@Self self: *@self): void {
@RawVec(T).clear(&self.base);
}
pub fn truncate(@Self self: *@self, n: usize): bool {
if (n >= self.base.len()) { ret false }
@RawVec(T).truncate(&self.base, n);
ret true;
}
pub fn _set_len(@Self self: *@self, n: usize): bool {
if (n >= self.base.capacity()) { ret false; }
self.base.length = n;
ret true;
}
pub fn drop(@Self self: *@self) {
if self.base.capacity() != 0 {
self.alloc.dealloc(self.base.data as *u8,
layout_of(@sizeof(T), @alignof(T), self.base.capacity()));
}
@RawVec(T).reset(&self.base);
}
pub fn take(@Self self: *@self): @self {
var r = self.*;
@RawVec(T).reset(&self.base);
ret r;
}
};
}
+69
View File
@@ -0,0 +1,69 @@
type .{ .VMWriter, .VMFile, .strlen, .VMAllocator } = @import("compiler/vm.spl");
type .{ .Vec } = @import("core/vec.spl");
type .{ .Source, .SourceError } = @import("lexer/source.spl");
fn spl_main(args: const[] const[] u8): i32 {
var alloc = VMAllocator{};
var writer = VMFile.with_stdout();
// var writer = VMFile.open("output.txt", .Write) catch .Err(_) {
// @assert(false, "Failed to open output.txt for writing");
// };
for arg in args {
writer.write(arg);
writer.write("\n");
}
var vmfile = VMFile{};
var source = @Source(VMAllocator, VMFile).new(alloc, vmfile);
var ft = source.add_file("./src/test.spl") catch .Err(e) {
match e {
.UnknownError => { @assert(false, "unknow error"); },
.FileOpenError => { @assert(false, "fopen error"); },
.FileAttributeError => { @assert(false, "fattr error"); },
.FileReadError => { @assert(false, "fread error"); },
.OutOfMemory => { @assert(false, "oom error"); } ,
_ => { @assert(false, "error"); },
}
ret 1;
};
}
fn main(argc: i32, _argv: const **u8, envp: const **u8): i32 {
// for i in 0..argc {
// var arg = _argv[i];
// var j: usize = 0;
// while (arg[j] != 0) {
// vm_putchar(arg[j] as i32);
// j = j + 1;
// }
// vm_putchar('\n' as i32);
// }
// var writer = VMWriter.with_stdout();
// // var res = writer.write("Hello, World!\n");
// var argv: []const *u8 = @Slice(const *u8).from_raw_parts(_argv as **u8, argc as usize) as []const *u8;
// for arg in argv {
// // var j: usize = 0;
// // while (arg[j] != 0) {
// // vm_putchar(arg[j] as i32);
// // j = j + 1;
// // }
// // vm_putchar('\n' as i32);
// writer.write(@Slice(const u8).from_raw_parts(arg, strlen(arg)));
// writer.write("\n");
// }
var alloc = VMAllocator{};
var argv: @Vec([]u8, VMAllocator) = @Vec([]u8, VMAllocator)
.with_capacity(alloc, argc as usize)
catch .Err(_) { ret 1; };
for arg in @Slice(*u8).from_raw_parts(_argv as **u8, argc as usize) {
var len = strlen(arg);
var arg_slice = @Slice(u8).from_raw_parts(arg, len);
argv.push(arg_slice) catch .Err(_) { ret 1; };
}
ret spl_main(argv.as_slice());
}
+9
View File
@@ -86,6 +86,7 @@ type Body = enum {
}, },
ExprAggregateLit: struct { name: ByteView, fields: Vec }, ExprAggregateLit: struct { name: ByteView, fields: Vec },
ExprComptimeCall: struct { name: ByteView, args: Vec }, ExprComptimeCall: struct { name: ByteView, args: Vec },
ExprShapeApply: struct { adapter: ByteView, shapes: Vec, args: Vec },
ExprTry: struct { value: usize }, // `try expr` ExprTry: struct { value: usize }, // `try expr`
ExprCatch: struct { value: usize, pattern: usize, handler: usize }, // `expr catch <pat> { }` ExprCatch: struct { value: usize, pattern: usize, handler: usize }, // `expr catch <pat> { }`
ExprBlock: struct { stmts: Vec, tail_expr: usize }, ExprBlock: struct { stmts: Vec, tail_expr: usize },
@@ -129,6 +130,7 @@ type Body = enum {
TypeShapeApply: struct { base: ByteView, binds: Vec }, TypeShapeApply: struct { base: ByteView, binds: Vec },
TypeAssocBind: struct { name: ByteView, ty: usize }, TypeAssocBind: struct { name: ByteView, ty: usize },
TypeShapeUse: struct { adapter: ByteView, shapes: Vec }, TypeShapeUse: struct { adapter: ByteView, shapes: Vec },
TypeShapeNoDefault: struct { shapes: Vec },
} }
fn kind_name(body: Body): []u8 { fn kind_name(body: Body): []u8 {
@@ -180,6 +182,7 @@ fn kind_name(body: Body): []u8 {
.ExprArrayLit(_) => { ret "array_literal"; }, .ExprArrayLit(_) => { ret "array_literal"; },
.ExprAggregateLit(_) => { ret "aggregate_literal"; }, .ExprAggregateLit(_) => { ret "aggregate_literal"; },
.ExprComptimeCall(_) => { ret "comptime_call"; }, .ExprComptimeCall(_) => { ret "comptime_call"; },
.ExprShapeApply(_) => { ret "shape_apply"; },
.ExprTry(_) => { ret "try_expr"; }, .ExprTry(_) => { ret "try_expr"; },
.ExprCatch(_) => { ret "catch_expr"; }, .ExprCatch(_) => { ret "catch_expr"; },
.ExprComptimeInit(_) => { ret "comptime_init"; }, .ExprComptimeInit(_) => { ret "comptime_init"; },
@@ -201,6 +204,7 @@ fn kind_name(body: Body): []u8 {
.TypeShapeApply(_) => { ret "type_shape_apply"; }, .TypeShapeApply(_) => { ret "type_shape_apply"; },
.TypeAssocBind(_) => { ret "type_assoc_bind"; }, .TypeAssocBind(_) => { ret "type_assoc_bind"; },
.TypeShapeUse(_) => { ret "type_shape_use"; }, .TypeShapeUse(_) => { ret "type_shape_use"; },
.TypeShapeNoDefault(_) => { ret "type_shape_no_default"; },
.TypeComptimeCall(_) => { ret "type_comptime_call"; }, .TypeComptimeCall(_) => { ret "type_comptime_call"; },
.PatternIdent(_) => { ret "pattern_ident"; }, .PatternIdent(_) => { ret "pattern_ident"; },
.PatternUnderscore => { ret "pattern_underscore"; }, .PatternUnderscore => { ret "pattern_underscore"; },
@@ -530,6 +534,10 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
}, },
.ExprAggregateLit(a) => { ok = dump_list(ast, buf, stack, a.fields); }, .ExprAggregateLit(a) => { ok = dump_list(ast, buf, stack, a.fields); },
.ExprComptimeCall(c) => { ok = dump_list(ast, buf, stack, c.args); }, .ExprComptimeCall(c) => { ok = dump_list(ast, buf, stack, c.args); },
.ExprShapeApply(x) => {
ok = dump_list(ast, buf, stack, x.shapes) &&
dump_list(ast, buf, stack, x.args);
},
.ExprTry(t2) => { ok = dump_opt(ast, buf, stack, t2.value, true); }, .ExprTry(t2) => { ok = dump_opt(ast, buf, stack, t2.value, true); },
.ExprCatch(c2) => { .ExprCatch(c2) => {
ok = dump_opt(ast, buf, stack, c2.value, false) && ok = dump_opt(ast, buf, stack, c2.value, false) &&
@@ -593,6 +601,7 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
.TypeShapeApply(a) => { ok = dump_list(ast, buf, stack, a.binds); }, .TypeShapeApply(a) => { ok = dump_list(ast, buf, stack, a.binds); },
.TypeAssocBind(a) => { ok = dump_opt(ast, buf, stack, a.ty, true); }, .TypeAssocBind(a) => { ok = dump_opt(ast, buf, stack, a.ty, true); },
.TypeShapeUse(a) => { ok = dump_list(ast, buf, stack, a.shapes); }, .TypeShapeUse(a) => { ok = dump_list(ast, buf, stack, a.shapes); },
.TypeShapeNoDefault(a) => { ok = dump_list(ast, buf, stack, a.shapes); },
.TypeComptimeCall(c) => { ok = dump_list(ast, buf, stack, c.args); }, .TypeComptimeCall(c) => { ok = dump_list(ast, buf, stack, c.args); },
.PatternIdent(x) => {}, .PatternIdent(x) => {},
.PatternUnderscore => {}, .PatternUnderscore => {},
+47 -1
View File
@@ -773,6 +773,22 @@ fn parse_param_decl_impl(self: *Parser): usize {
name); name);
} }
var ty = parse_type_expr(self); var ty = parse_type_expr(self);
// `A: X + Y`:参数位的 shape 约束列表。空 adapter 表示纯编译期约束,
// 由 sema 决定它是否只允许出现在类型生成器形参上。
if at_punct(self, .Add) {
var shapes = ref_vec();
match Vec.push(&shapes, &ty as *u8) { .Ok => {}, .Err(error) => {} }
while at_punct(self, .Add) {
advance(self);
var next = parse_type_expr(self);
if next == 0 { break; }
match Vec.push(&shapes, &next as *u8) { .Ok => {}, .Err(error) => {} }
}
ty = new_node(self, .TypeShapeUse(.{
.adapter = ByteView.empty(),
.shapes = shapes,
}), name);
}
ret new_node(self, ret new_node(self,
.ParamDecl(.{ .attr_list = attrs, .is_comptime = is_comptime, .name = name.text, .type_expr = ty }), .ParamDecl(.{ .attr_list = attrs, .is_comptime = is_comptime, .name = name.text, .type_expr = ty }),
name); name);
@@ -1204,6 +1220,13 @@ fn parse_type_comptime_call(self: *Parser): usize {
var ok = kind_is_punct(start.kind, .At) || kind_is_punct(start.kind, .Sharp); var ok = kind_is_punct(start.kind, .At) || kind_is_punct(start.kind, .Sharp);
if !ok { ret 0; } if !ok { ret 0; }
advance(self); advance(self);
if at_punct(self, .LBracket) {
// `@[Shape]`:没有默认 adapter 的 shape 参数。
advance(self);
var shapes = parse_shape_list(self, true);
expect_punct(self, .RBracket, "']' in shape use");
ret new_node(self, .TypeShapeNoDefault(.{ .shapes = shapes }), start);
}
var name = parse_comptime_name(self); var name = parse_comptime_name(self);
if name.len == 0 { ret 0; } if name.len == 0 { ret 0; }
var args = ref_vec(); var args = ref_vec();
@@ -1937,7 +1960,9 @@ fn parse_primary(self: *Parser): usize {
.Match => { ret parse_match_expr(self); }, .Match => { ret parse_match_expr(self); },
.Try => { .Try => {
advance(self); advance(self);
var tv = parse_expr(self); // try 是一元前缀运算符;`try x as T` 必须解析成 `(try x) as T`,
// 不能把 `as` 吞进 try 的操作数。
var tv = parse_prefix(self);
ret new_node(self, .ExprTry(.{ .value = tv }), t); ret new_node(self, .ExprTry(.{ .value = tv }), t);
}, },
.Comptime => { .Comptime => {
@@ -2176,8 +2201,29 @@ fn parse_comptime_call(self: *Parser): usize {
var ok = kind_is_punct(start.kind, .At) || kind_is_punct(start.kind, .Sharp); var ok = kind_is_punct(start.kind, .At) || kind_is_punct(start.kind, .Sharp);
if !ok { ret 0; } if !ok { ret 0; }
advance(self); advance(self);
if at_punct(self, .LBracket) {
parse_error(self, peek(self), "shape parameter requires adapter name in expression");
ret 0;
}
var name = parse_comptime_name(self); var name = parse_comptime_name(self);
if name.len == 0 { ret 0; } if name.len == 0 { ret 0; }
if at_punct(self, .LBracket) {
advance(self);
var shapes = parse_shape_list(self, true);
if !expect_punct(self, .RBracket, "']' in shape application") { ret 0; }
if !at_punct(self, .LParen) {
parse_error(self, peek(self), "shape application requires '('");
ret 0;
}
advance(self);
var sargs = parse_expr_list(self);
if !expect_punct(self, .RParen, "')' in shape application") { ret 0; }
ret new_node(self, .ExprShapeApply(.{
.adapter = name,
.shapes = shapes,
.args = sargs,
}), start);
}
var args = ref_vec(); var args = ref_vec();
if at_punct(self, .LParen) { if at_punct(self, .LParen) {
advance(self); advance(self);
+35 -2
View File
@@ -398,6 +398,16 @@ fn lower_type_inner(self: *Ast2Hir, ref: usize): Ref {
.shapes = finish_list(self, &shapes), .shapes = finish_list(self, &shapes),
}), n.span); }), n.span);
}, },
.TypeShapeNoDefault(x) => {
var shapes = new_vec();
var si: usize = 0;
while si < x.shapes.len {
var sref = (x.shapes.data as *usize)[si];
push_ref(&shapes, lower_type(self, sref));
si = si + 1;
}
ret emit(self, .ShapeNoDefault(finish_list(self, &shapes)), n.span);
},
.TypeComptimeCall(x) => { .TypeComptimeCall(x) => {
if ByteView.eq(x.name, ByteView.from_slice("import")) { if ByteView.eq(x.name, ByteView.from_slice("import")) {
ret emit(self, .Import(comptime_str_arg(self, x.args)), n.span); ret emit(self, .Import(comptime_str_arg(self, x.args)), n.span);
@@ -966,7 +976,8 @@ fn lower_expr(self: *Ast2Hir, ref: usize): Ref {
// comptime 上下文里类型即表达式:类型 AST 节点交给 lower_type(它负责挂 attrs)。 // comptime 上下文里类型即表达式:类型 AST 节点交给 lower_type(它负责挂 attrs)。
match n.body { match n.body {
.TypePath(_), .TypePointer(_), .TypeSlice(_), .TypeArray(_), .TypeFn(_), .TypePath(_), .TypePointer(_), .TypeSlice(_), .TypeArray(_), .TypeFn(_),
.TypeParen(_), .TypeAggregate(_), .TypeShapeApply(_), .TypeShapeUse(_), .TypeComptimeCall(_) => { ret lower_type(self, ref); }, .TypeParen(_), .TypeAggregate(_), .TypeShapeApply(_), .TypeShapeUse(_),
.TypeShapeNoDefault(_), .TypeComptimeCall(_) => { ret lower_type(self, ref); },
_ => {}, _ => {},
} }
var r = lower_expr_inner(self, ref); var r = lower_expr_inner(self, ref);
@@ -1176,7 +1187,11 @@ fn lower_expr_inner(self: *Ast2Hir, ref: usize): Ref {
.ExprCatch(x) => { .ExprCatch(x) => {
var v = lower_expr(self, x.value); var v = lower_expr(self, x.value);
var pat = lower_pattern(self, x.pattern); var pat = lower_pattern(self, x.pattern);
// catch 模式绑定和 match 臂一样,必须在 handler 的 lowering 作用域里。
scope_begin(&self.scopes);
bind_pattern_scope(self, pat);
var handler = lower_block(self, x.handler); var handler = lower_block(self, x.handler);
scope_end(&self.scopes);
ret emit(self, .Catch(.{ .value = v, .pattern = pat, .handler = handler }), n.span); ret emit(self, .Catch(.{ .value = v, .pattern = pat, .handler = handler }), n.span);
}, },
.ExprComptimeCall(x) => { .ExprComptimeCall(x) => {
@@ -1193,6 +1208,23 @@ fn lower_expr_inner(self: *Ast2Hir, ref: usize): Ref {
ret emit(self, .Call(.{ .is_comptime = true, .callee = callee, ret emit(self, .Call(.{ .is_comptime = true, .callee = callee,
.args = finish_list(self, &args) }), n.span); .args = finish_list(self, &args) }), n.span);
}, },
.ExprShapeApply(x) => {
var shapes = new_vec();
var i: usize = 0;
while i < x.shapes.len {
push_ref(&shapes, lower_type(self, (x.shapes.data as *usize)[i]));
i = i + 1;
}
var args = new_vec();
i = 0;
while i < x.args.len {
push_ref(&args, lower_expr(self, (x.args.data as *usize)[i]));
i = i + 1;
}
ret emit(self, .ShapeCall(.{ .adapter = sl(x.adapter),
.shapes = finish_list(self, &shapes),
.args = finish_list(self, &args) }), n.span);
},
.ExprMatch(x) => { .ExprMatch(x) => {
var operand = lower_expr(self, x.matched_expr); var operand = lower_expr(self, x.matched_expr);
var arms = new_vec(); var arms = new_vec();
@@ -1216,7 +1248,8 @@ fn lower_expr_inner(self: *Ast2Hir, ref: usize): Ref {
} }
ret emit(self, .Match(.{ .operand = operand, .arms = finish_list(self, &arms) }), n.span); ret emit(self, .Match(.{ .operand = operand, .arms = finish_list(self, &arms) }), n.span);
}, },
.TypeAggregate(_), .TypeShapeApply(_), .TypeShapeUse(_) => { ret lower_type(self, ref); }, .TypeAggregate(_), .TypeShapeApply(_), .TypeShapeUse(_),
.TypeShapeNoDefault(_) => { ret lower_type(self, ref); },
_ => { ret syntax_err(self, ref); }, _ => { ret syntax_err(self, ref); },
} }
ret 0; ret 0;
+49 -14
View File
@@ -1,6 +1,8 @@
#!builtin #!builtin
#!role(builtins) #!role(builtins)
type meta = @import("meta");
// splc3 的预置头:把编译器底层能力以 `#builtin` 声明暴露给用户/comptime 代码。 // splc3 的预置头:把编译器底层能力以 `#builtin` 声明暴露给用户/comptime 代码。
// `#builtin(<id>)` 的 id 必须命中 stage3/intrinsic.spl 的 intrinsic_of_id。 // `#builtin(<id>)` 的 id 必须命中 stage3/intrinsic.spl 的 intrinsic_of_id。
@@ -27,26 +29,25 @@ type Node = @import("./spl_ir.spl").Node;
#builtin(construct) #extern(builtin) comptime fn construct(n: Node): Ref; #builtin(construct) #extern(builtin) comptime fn construct(n: Node): Ref;
// receiver hook:@Self 只挂在方法的第一个参数上。 // receiver hook:@Self 只挂在方法的第一个参数上。
// 参数类型是 *T 时取地址,是 T 时按值传递;已显式传 &x 的调用不再二次取地址。 // 参数类型是 *T 时取地址,是 T 时按值传递;implicit 本身已是指向接收者的指针时直接复用。
#hook(param) #hook(param)
macro fn Self(callee: Ref, value: Ref): Ref { macro fn Self(callee: Ref, value: Ref, implicit: Ref): Ref {
if value == 0 { ret 0; } if implicit == 0 {
if value != 0 { ret value; }
var vn = @inspect(value); ret 0;
match vn.kind {
.Addr(_) => { ret value; },
_ => {},
} }
var cn = @meta.inspect(callee);
var cn = @inspect(callee);
match cn.kind { match cn.kind {
.FnDecl(f) => { .FnDecl(f) => {
var pn = @inspect(f.params[0]); var pn = @meta.inspect(f.params[0]);
match pn.kind { match pn.kind {
.ParamDecl(p) => { .ParamDecl(p) => {
var tn = @inspect(p.ty); var tn = @meta.inspect(p.ty);
match tn.kind { match tn.kind {
.PtrType(_) => { ret @construct(.{ .kind = .Addr(value) }); }, .PtrType(_) => {
if @ptr_ref(implicit) { ret implicit; }
ret @meta.construct(.{ .kind = .Addr(implicit) });
},
_ => {}, _ => {},
} }
}, },
@@ -55,5 +56,39 @@ macro fn Self(callee: Ref, value: Ref): Ref {
}, },
_ => {}, _ => {},
} }
ret value; 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;
} }
+32 -32
View File
@@ -17,7 +17,7 @@ comptime fn Slice(T: type): type {
_ptr: *T, _ptr: *T,
_len: usize, _len: usize,
fn len(self: @self): usize { fn len(@Self self: @self): usize {
ret self._len; ret self._len;
} }
@@ -53,7 +53,7 @@ comptime fn Slice(T: type): type {
comptime fn Array(T: type, N: usize): type { comptime fn Array(T: type, N: usize): type {
ret struct: IntoIter[Item = T, Iter = @Slice(T)] + Index[Output = T] { ret struct: IntoIter[Item = T, Iter = @Slice(T)] + Index[Output = T] {
#builtin(array_len) #builtin(array_len)
fn len(self: @self): usize; fn len(@Self self: @self): usize;
#builtin(array_index) #builtin(array_index)
fn index(@Self self: *@self, i: usize): *T; fn index(@Self self: *@self, i: usize): *T;
@@ -83,46 +83,46 @@ comptime fn Int(bits: usize, signed: bool): type {
+ Eq[Rhs = @self] + Eq[Rhs = @self]
+ Ord[Rhs = @self] { + Ord[Rhs = @self] {
#op(add) #op(add)
fn add(lhs: @self, rhs: @self): @self; fn add(@Self lhs: @self, rhs: @self): @self;
#op(sub) #op(sub)
fn sub(lhs: @self, rhs: @self): @self; fn sub(@Self lhs: @self, rhs: @self): @self;
#op(mul) #op(mul)
fn mul(lhs: @self, rhs: @self): @self; fn mul(@Self lhs: @self, rhs: @self): @self;
#op(div) #op(div)
fn div(lhs: @self, rhs: @self): @self; fn div(@Self lhs: @self, rhs: @self): @self;
#op(mod) #op(mod)
fn rem(lhs: @self, rhs: @self): @self; fn rem(@Self lhs: @self, rhs: @self): @self;
#op(neg) #op(neg)
fn neg(value: @self): @self; fn neg(@Self value: @self): @self;
#op(bit_and) #op(bit_and)
fn bit_and(lhs: @self, rhs: @self): @self; fn bit_and(@Self lhs: @self, rhs: @self): @self;
#op(bit_or) #op(bit_or)
fn bit_or(lhs: @self, rhs: @self): @self; fn bit_or(@Self lhs: @self, rhs: @self): @self;
#op(bit_xor) #op(bit_xor)
fn bit_xor(lhs: @self, rhs: @self): @self; fn bit_xor(@Self lhs: @self, rhs: @self): @self;
#op(shl) #op(shl)
fn shl(lhs: @self, rhs: @self): @self; fn shl(@Self lhs: @self, rhs: @self): @self;
#op(shr) #op(shr)
fn shr(lhs: @self, rhs: @self): @self; fn shr(@Self lhs: @self, rhs: @self): @self;
#op(bit_not) #op(bit_not)
fn bit_not(value: @self): @self; fn bit_not(@Self value: @self): @self;
#op(eq) #op(eq)
fn eq(lhs: @self, rhs: @self): bool; fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord) #op(ord)
fn cmp(lhs: @self, rhs: @self): Ordering; fn cmp(@Self lhs: @self, rhs: @self): Ordering;
}; };
} }
@@ -137,28 +137,28 @@ comptime fn Float(bits: usize): type {
+ Eq[Rhs = @self] + Eq[Rhs = @self]
+ Ord[Rhs = @self] { + Ord[Rhs = @self] {
#op(add) #op(add)
fn add(lhs: @self, rhs: @self): @self; fn add(@Self lhs: @self, rhs: @self): @self;
#op(sub) #op(sub)
fn sub(lhs: @self, rhs: @self): @self; fn sub(@Self lhs: @self, rhs: @self): @self;
#op(mul) #op(mul)
fn mul(lhs: @self, rhs: @self): @self; fn mul(@Self lhs: @self, rhs: @self): @self;
#op(div) #op(div)
fn div(lhs: @self, rhs: @self): @self; fn div(@Self lhs: @self, rhs: @self): @self;
#op(mod) #op(mod)
fn rem(lhs: @self, rhs: @self): @self; fn rem(@Self lhs: @self, rhs: @self): @self;
#op(neg) #op(neg)
fn neg(value: @self): @self; fn neg(@Self value: @self): @self;
#op(eq) #op(eq)
fn eq(lhs: @self, rhs: @self): bool; fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord) #op(ord)
fn cmp(lhs: @self, rhs: @self): Ordering; fn cmp(@Self lhs: @self, rhs: @self): Ordering;
}; };
} }
@@ -166,10 +166,10 @@ comptime fn Float(bits: usize): type {
comptime fn Bool(): type { comptime fn Bool(): type {
ret struct: Eq[Rhs = @self] + Ord[Rhs = @self] { ret struct: Eq[Rhs = @self] + Ord[Rhs = @self] {
#op(eq) #op(eq)
fn eq(lhs: @self, rhs: @self): bool; fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord) #op(ord)
fn cmp(lhs: @self, rhs: @self): Ordering; fn cmp(@Self lhs: @self, rhs: @self): Ordering;
}; };
} }
@@ -196,16 +196,16 @@ comptime fn Ptr(key: usize): type {
+ Eq[Rhs = @self] + Eq[Rhs = @self]
+ Ord[Rhs = @self] { + Ord[Rhs = @self] {
#op(add) #op(add)
fn add(lhs: @self, rhs: usize): @self; fn add(@Self lhs: @self, rhs: usize): @self;
#op(sub) #op(sub)
fn sub(lhs: @self, rhs: usize): @self; fn sub(@Self lhs: @self, rhs: usize): @self;
#op(eq) #op(eq)
fn eq(lhs: @self, rhs: @self): bool; fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord) #op(ord)
fn cmp(lhs: @self, rhs: @self): Ordering; fn cmp(@Self lhs: @self, rhs: @self): Ordering;
}; };
} }
@@ -213,9 +213,9 @@ comptime fn Ptr(key: usize): type {
comptime fn Fn(key: usize): type { comptime fn Fn(key: usize): type {
ret struct: Eq[Rhs = @self] + Ord[Rhs = @self] { ret struct: Eq[Rhs = @self] + Ord[Rhs = @self] {
#op(eq) #op(eq)
fn eq(lhs: @self, rhs: @self): bool; fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord) #op(ord)
fn cmp(lhs: @self, rhs: @self): Ordering; fn cmp(@Self lhs: @self, rhs: @self): Ordering;
}; };
} }
+14 -14
View File
@@ -14,94 +14,94 @@ type Ordering = enum {
type Add = shape { type Add = shape {
type Rhs; type Rhs;
type Output; type Output;
fn add(lhs: @self, rhs: Rhs): Output; fn add(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(sub) #lang(sub)
type Sub = shape { type Sub = shape {
type Rhs; type Rhs;
type Output; type Output;
fn sub(lhs: @self, rhs: Rhs): Output; fn sub(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(mul) #lang(mul)
type Mul = shape { type Mul = shape {
type Rhs; type Rhs;
type Output; type Output;
fn mul(lhs: @self, rhs: Rhs): Output; fn mul(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(div) #lang(div)
type Div = shape { type Div = shape {
type Rhs; type Rhs;
type Output; type Output;
fn div(lhs: @self, rhs: Rhs): Output; fn div(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(mod) #lang(mod)
type Mod = shape { type Mod = shape {
type Rhs; type Rhs;
type Output; type Output;
fn rem(lhs: @self, rhs: Rhs): Output; fn rem(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(neg) #lang(neg)
type Neg = shape { type Neg = shape {
type Output; type Output;
fn neg(value: @self): Output; fn neg(@Self value: @self): Output;
}; };
#lang(bit_and) #lang(bit_and)
type BitAnd = shape { type BitAnd = shape {
type Rhs; type Rhs;
type Output; type Output;
fn bit_and(lhs: @self, rhs: Rhs): Output; fn bit_and(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(bit_or) #lang(bit_or)
type BitOr = shape { type BitOr = shape {
type Rhs; type Rhs;
type Output; type Output;
fn bit_or(lhs: @self, rhs: Rhs): Output; fn bit_or(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(bit_xor) #lang(bit_xor)
type BitXor = shape { type BitXor = shape {
type Rhs; type Rhs;
type Output; type Output;
fn bit_xor(lhs: @self, rhs: Rhs): Output; fn bit_xor(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(shl) #lang(shl)
type Shl = shape { type Shl = shape {
type Rhs; type Rhs;
type Output; type Output;
fn shl(lhs: @self, rhs: Rhs): Output; fn shl(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(shr) #lang(shr)
type Shr = shape { type Shr = shape {
type Rhs; type Rhs;
type Output; type Output;
fn shr(lhs: @self, rhs: Rhs): Output; fn shr(@Self lhs: @self, rhs: Rhs): Output;
}; };
#lang(bit_not) #lang(bit_not)
type BitNot = shape { type BitNot = shape {
type Output; type Output;
fn bit_not(value: @self): Output; fn bit_not(@Self value: @self): Output;
}; };
#lang(eq) #lang(eq)
type Eq = shape { type Eq = shape {
type Rhs; type Rhs;
fn eq(lhs: @self, rhs: Rhs): bool; fn eq(@Self lhs: @self, rhs: Rhs): bool;
}; };
#lang(ord) #lang(ord)
type Ord = shape { type Ord = shape {
type Rhs; type Rhs;
fn cmp(lhs: @self, rhs: Rhs): Ordering; fn cmp(@Self lhs: @self, rhs: Rhs): Ordering;
}; };
#lang(index) #lang(index)
+2
View File
@@ -148,10 +148,12 @@ type Node = struct {
Binary: struct { op: Op, lval: Ref, rval: Ref }, Binary: struct { op: Op, lval: Ref, rval: Ref },
Unary: struct { op: Op, val: Ref }, Unary: struct { op: Op, val: Ref },
Call: struct { is_comptime: bool, callee: Ref, args: []Ref }, Call: struct { is_comptime: bool, callee: Ref, args: []Ref },
ShapeCall: struct { adapter: []u8, shapes: []Ref, args: []Ref },
Comptime: Ref, Comptime: Ref,
AssocDecl: struct { name: []u8 }, AssocDecl: struct { name: []u8 },
ShapeApply: struct { base: Ref, binds: []Ref }, ShapeApply: struct { base: Ref, binds: []Ref },
ShapeUse: struct { adapter: []u8, shapes: []Ref }, ShapeUse: struct { adapter: []u8, shapes: []Ref },
ShapeNoDefault: []Ref,
AssocBind: struct { name: []u8, ty: Ref }, AssocBind: struct { name: []u8, ty: Ref },
} }
} }
+8
View File
@@ -1856,6 +1856,14 @@ fn emit_match(self: *Hir2Ir, ref: usize): usize {
} }
var ov = emit_expr(self, x.operand); var ov = emit_expr(self, x.operand);
var ol = SemaM.tid_of(self.sema, x.operand); var ol = SemaM.tid_of(self.sema, x.operand);
// 聚合 call 结果可能只在该 sret 槽有效;先复制到 match 自己的稳定槽,
// 避免后续分支/局部写入覆盖操作数。
if LangType.is_agg(&self.sema.types, ol) {
var oir = SemaM.ir_of(self.sema, ol);
var stable = IrBuilder.mem_alloca(self.b, oir, const_usize(self, 1));
ignore_usize(IrBuilder.mem_store(self.b, oir, stable, ov));
ov = stable;
}
var jmps = Vec.blank(@sizeof(usize), @alignof(usize)); var jmps = Vec.blank(@sizeof(usize), @alignof(usize));
var i: usize = 0; var i: usize = 0;
while i < x.arms.len { while i < x.arms.len {
+55 -11
View File
@@ -83,9 +83,10 @@ fn check_hook(self: *Sema, hd: usize, kind: HookKind, at: Ref): bool {
} }
}, },
.Param => { .Param => {
if f.params.len < 2 || if f.params.len < 3 ||
!is_ref_type(self, param_type(self, f.params[0])) || !is_ref_type(self, param_type(self, f.params[0])) ||
!is_ref_type(self, param_type(self, f.params[1])) { !is_ref_type(self, param_type(self, f.params[1])) ||
!is_ref_type(self, param_type(self, f.params[2])) {
ok = false; ok = false;
} }
}, },
@@ -128,7 +129,12 @@ fn run_hook(self: *Sema, hook_decl: usize, args: []Ref): Ref {
var tags: [1]Ref = .[tag]; var tags: [1]Ref = .[tag];
var cn = Bld.node_ptr(&self.hir, call); var cn = Bld.node_ptr(&self.hir, call);
if cn != null { cn.tags = Bld.dup_refs(&self.hir, tags[0..1]); } if cn != null { cn.tags = Bld.dup_refs(&self.hir, tags[0..1]); }
// 参数 hook 必须在分析期拿到值;ct.building 只推迟普通 comptime 表达式,
// 不能推迟 hook 本身,否则 prepare_params 读到 0 并误报缺失。
var saved_building = self.ct.building;
self.ct.building = false;
SemaM.sema_expr(self, call, 0); SemaM.sema_expr(self, call, 0);
self.ct.building = saved_building;
var out: Ref = 0; var out: Ref = 0;
var rn = Bld.node_ptr(&self.hir, call); var rn = Bld.node_ptr(&self.hir, call);
if rn != null { if rn != null {
@@ -223,7 +229,8 @@ fn apply_decorators(user: *any, di: usize) {
} }
} }
fn prepare_params(user: *any, callee_ref: Ref, args: []Ref, out: *HookParamResult) { fn prepare_params(user: *any, callee_ref: Ref, implicit: Ref, args: []Ref,
out: *HookParamResult) {
var self = user as *Sema; var self = user as *Sema;
out.args = args; out.args = args;
out.changed = false; out.changed = false;
@@ -247,10 +254,25 @@ fn prepare_params(user: *any, callee_ref: Ref, args: []Ref, out: *HookParamResul
} }
si = si + 1; si = si + 1;
} }
if !any_hook { ret; } if !any_hook && implicit == 0 { ret; }
var first_has_hook = false;
if f.params.len > 0 {
var fn0 = Bld.node_ptr(&self.hir, f.params[0]);
if fn0 != null {
var fi: usize = 0;
while fi < fn0.tags.len {
var ftn = Bld.node_ptr(&self.hir, fn0.tags[fi]);
if ftn != null {
match ftn.kind { .Tag(x) => { if x.is_at { first_has_hook = true; } }, _ => {} }
}
fi = fi + 1;
}
}
}
var has_implicit = implicit != 0 && first_has_hook;
var buf = Vec.blank(@sizeof(Ref), @alignof(Ref)); var buf = Vec.blank(@sizeof(Ref), @alignof(Ref));
defer { Vec.drop(&buf); } defer { Vec.drop(&buf); }
var changed = false; var changed = has_implicit;
var i: usize = 0; var i: usize = 0;
while i < f.params.len { while i < f.params.len {
var pn = Bld.node_ptr(&self.hir, f.params[i]); var pn = Bld.node_ptr(&self.hir, f.params[i]);
@@ -267,9 +289,16 @@ fn prepare_params(user: *any, callee_ref: Ref, args: []Ref, out: *HookParamResul
} }
ti = ti + 1; ti = ti + 1;
} }
if i >= args.len && !has_any { break; } var arg_i = i;
if has_implicit && i > 0 { arg_i = i - 1; }
var first_implicit = has_implicit && i == 0;
var avail = arg_i < args.len;
if first_implicit { avail = true; }
if !has_any && !avail { break; }
var value: Ref = 0; var value: Ref = 0;
if i < args.len { value = args[i]; } if !first_implicit && arg_i < args.len { value = args[arg_i]; }
var imp: Ref = 0;
if i == 0 { imp = implicit; }
var hi = pn.tags.len; var hi = pn.tags.len;
while hi > 0 { while hi > 0 {
hi = hi - 1; hi = hi - 1;
@@ -285,8 +314,24 @@ fn prepare_params(user: *any, callee_ref: Ref, args: []Ref, out: *HookParamResul
continue; continue;
} }
if !check_hook(self, hd - 1, .Param, f.params[i]) { continue; } if !check_hook(self, hd - 1, .Param, f.params[i]) { continue; }
var hargs: [2]Ref = .[ref_value(self, callee_ref), ref_value(self, value)]; SemaM.ensure_decl(self, hd - 1);
var code = run_hook_tagged(self, hd - 1, hargs[0..2], x.args); var hplen: usize = 0;
var hdnode = Bld.node_ptr(&self.hir, SemaM.decl_at(self, hd - 1).node);
if hdnode != null {
match hdnode.kind { .FnDecl(hf) => { hplen = hf.params.len; }, _ => {} }
}
var code: Ref = 0;
if hplen >= 3 {
var hargs: [3]Ref = .[ref_value(self, callee_ref),
ref_value(self, value),
ref_value(self, imp)];
code = run_hook_tagged(self, hd - 1, hargs[0..3], x.args);
} else {
var v2 = value;
if v2 == 0 { v2 = imp; }
var hargs2: [2]Ref = .[ref_value(self, callee_ref), ref_value(self, v2)];
code = run_hook_tagged(self, hd - 1, hargs2[0..2], x.args);
}
if code == 0 { if code == 0 {
SemaM.sema_error_code_at(self, f.params[i], ErrorCode.ParamHook, SemaM.sema_error_code_at(self, f.params[i], ErrorCode.ParamHook,
"param hook returned no value", x.name); "param hook returned no value", x.name);
@@ -298,12 +343,11 @@ fn prepare_params(user: *any, callee_ref: Ref, args: []Ref, out: *HookParamResul
_ => {}, _ => {},
} }
} }
if i >= args.len && value == 0 { if value == 0 {
SemaM.sema_error_code_at(self, f.params[i], ErrorCode.ParamHook, SemaM.sema_error_code_at(self, f.params[i], ErrorCode.ParamHook,
"missing param has no hook value", ""); "missing param has no hook value", "");
break; break;
} }
if value == 0 { break; }
match Vec.push(&buf, &value as *u8) { match Vec.push(&buf, &value as *u8) {
.Ok => {}, .Ok => {},
.Err(error) => { ret; }, .Err(error) => { ret; },
+6
View File
@@ -119,6 +119,10 @@ fn clone_ref(b: *Bld.HirNodeContainer, s: *CloneState, r: Ref): Ref {
.ShapeUse(x) => { .ShapeUse(x) => {
k = .ShapeUse(.{ .adapter = x.adapter, .shapes = clone_refs(b, s, x.shapes) }); k = .ShapeUse(.{ .adapter = x.adapter, .shapes = clone_refs(b, s, x.shapes) });
}, },
.ShapeCall(x) => {
k = .ShapeCall(.{ .adapter = x.adapter, .shapes = clone_refs(b, s, x.shapes),
.args = clone_refs(b, s, x.args) });
},
.AssocBind(x) => { k = .AssocBind(.{ .name = x.name, .ty = clone_ref(b, s, x.ty) }); }, .AssocBind(x) => { k = .AssocBind(.{ .name = x.name, .ty = clone_ref(b, s, x.ty) }); },
.ArrayType(x) => { k = .ArrayType(.{ .len = clone_ref(b, s, x.len), .elem = clone_ref(b, s, x.elem) }); }, .ArrayType(x) => { k = .ArrayType(.{ .len = clone_ref(b, s, x.len), .elem = clone_ref(b, s, x.elem) }); },
.SliceType(x) => { k = .SliceType(clone_ref(b, s, x)); }, .SliceType(x) => { k = .SliceType(clone_ref(b, s, x)); },
@@ -145,6 +149,8 @@ fn clone_ref(b: *Bld.HirNodeContainer, s: *CloneState, r: Ref): Ref {
_ => {}, _ => {},
} }
var out = Bld.construct(b, .{ .kind = k, .tags = clone_refs(b, s, n.tags) }); var out = Bld.construct(b, .{ .kind = k, .tags = clone_refs(b, s, n.tags) });
var on = Bld.node_ptr(b, out);
if on != null { on.loc = n.loc; }
record(s, r, out); record(s, r, out);
ret out; ret out;
} }
+16
View File
@@ -95,6 +95,14 @@ fn read_node(sema: *Sema, vm: *any, off: u64, tmp: *Arena): Node {
.ShapeUse(x) => { .ShapeUse(x) => {
n = Node { .kind = .ShapeUse(.{ .adapter = read_bytes(sema, vm, x.adapter, tmp), .shapes = read_refs(sema, vm, x.shapes, tmp) }), .tags = tg }; n = Node { .kind = .ShapeUse(.{ .adapter = read_bytes(sema, vm, x.adapter, tmp), .shapes = read_refs(sema, vm, x.shapes, tmp) }), .tags = tg };
}, },
.ShapeCall(x) => {
n = Node { .kind = .ShapeCall(.{ .adapter = read_bytes(sema, vm, x.adapter, tmp),
.shapes = read_refs(sema, vm, x.shapes, tmp),
.args = read_refs(sema, vm, x.args, tmp) }), .tags = tg };
},
.ShapeNoDefault(xs) => {
n = Node { .kind = .ShapeNoDefault(read_refs(sema, vm, xs, tmp)), .tags = tg };
},
.AssocBind(x) => { n = Node { .kind = .AssocBind(.{ .name = read_bytes(sema, vm, x.name, tmp), .ty = x.ty }), .tags = tg }; }, .AssocBind(x) => { n = Node { .kind = .AssocBind(.{ .name = read_bytes(sema, vm, x.name, tmp), .ty = x.ty }), .tags = tg }; },
.FnType(x) => { n = Node { .kind = .FnType(.{ .params = read_refs(sema, vm, x.params, tmp), .ret_ty = x.ret_ty }), .tags = tg }; }, .FnType(x) => { n = Node { .kind = .FnType(.{ .params = read_refs(sema, vm, x.params, tmp), .ret_ty = x.ret_ty }), .tags = tg }; },
.TupleType(xs) => { n = Node { .kind = .TupleType(read_refs(sema, vm, xs, tmp)), .tags = tg }; }, .TupleType(xs) => { n = Node { .kind = .TupleType(read_refs(sema, vm, xs, tmp)), .tags = tg }; },
@@ -183,6 +191,14 @@ fn write_node(sema: *Sema, vm: *any, off: u64, node: Node) {
.ShapeUse(x) => { .ShapeUse(x) => {
n = Node { .kind = .ShapeUse(.{ .adapter = write_bytes(sema, vm, x.adapter), .shapes = write_refs(sema, vm, x.shapes) }), .tags = tg }; n = Node { .kind = .ShapeUse(.{ .adapter = write_bytes(sema, vm, x.adapter), .shapes = write_refs(sema, vm, x.shapes) }), .tags = tg };
}, },
.ShapeCall(x) => {
n = Node { .kind = .ShapeCall(.{ .adapter = write_bytes(sema, vm, x.adapter),
.shapes = write_refs(sema, vm, x.shapes),
.args = write_refs(sema, vm, x.args) }), .tags = tg };
},
.ShapeNoDefault(xs) => {
n = Node { .kind = .ShapeNoDefault(write_refs(sema, vm, xs)), .tags = tg };
},
.AssocBind(x) => { n = Node { .kind = .AssocBind(.{ .name = write_bytes(sema, vm, x.name), .ty = x.ty }), .tags = tg }; }, .AssocBind(x) => { n = Node { .kind = .AssocBind(.{ .name = write_bytes(sema, vm, x.name), .ty = x.ty }), .tags = tg }; },
.FnType(x) => { n = Node { .kind = .FnType(.{ .params = write_refs(sema, vm, x.params), .ret_ty = x.ret_ty }), .tags = tg }; }, .FnType(x) => { n = Node { .kind = .FnType(.{ .params = write_refs(sema, vm, x.params), .ret_ty = x.ret_ty }), .tags = tg }; },
.TupleType(xs) => { n = Node { .kind = .TupleType(write_refs(sema, vm, xs)), .tags = tg }; }, .TupleType(xs) => { n = Node { .kind = .TupleType(write_refs(sema, vm, xs)), .tags = tg }; },
+42 -3
View File
@@ -74,6 +74,33 @@ fn shape_method_hir(self: *Sema, shape_lang: usize, want_idx: usize): usize {
ret out; ret out;
} }
// 方法签名/字段里指回 owner 的类型不能递归展开,否则 *@self 会无限反射。
fn reflect_self_type(self: *Sema, owner: usize, t: usize): usize {
if t == owner {
var nm = LangType.name_of(&self.types, owner);
if nm.len != 0 {
ret Bld.construct(&self.hir, .{ .kind = .NamedType(Bld.dup_bytes(&self.hir, nm)) });
}
}
if LangType.is_ptr(&self.types, t) && LangType.elem_of(&self.types, t) == owner {
var nm2 = LangType.name_of(&self.types, owner);
if nm2.len != 0 {
var en = Bld.construct(&self.hir, .{ .kind = .NamedType(Bld.dup_bytes(&self.hir, nm2)) });
ret Bld.construct(&self.hir, .{ .kind = .PtrType(en) });
}
}
ret lang_to_reflect_hir(self, t);
}
fn reflect_in_progress(self: *Sema, l: usize): bool {
var i: usize = 0;
while i < self.reflect_stack.len {
if (self.reflect_stack.data as *usize)[i] == l { ret true; }
i = i + 1;
}
ret false;
}
fn lang_to_reflect_hir_inner(self: *Sema, l: usize): usize { fn lang_to_reflect_hir_inner(self: *Sema, l: usize): usize {
match LangType.kind_of(&self.types, l) { match LangType.kind_of(&self.types, l) {
.Int => { ret Bld.construct(&self.hir, .{ .kind = .IntType(.{ .Int => { ret Bld.construct(&self.hir, .{ .kind = .IntType(.{
@@ -119,13 +146,24 @@ fn lang_to_reflect_hir_inner(self: *Sema, l: usize): usize {
}) }); }) });
}, },
.Struct, .Union, .Enum, .Shape => { .Struct, .Union, .Enum, .Shape => {
// 互递归类型(如 Point.fmt(*Format)、Format.format(@static[Display]))
// 不能在反射里无限展开;遇到栈上的类型用名字截断。
if reflect_in_progress(self, l) {
var nm0 = LangType.name_of(&self.types, l);
if nm0.len != 0 {
ret Bld.construct(&self.hir, .{ .kind = .NamedType(Bld.dup_bytes(&self.hir, nm0)) });
}
ret Bld.construct(&self.hir, .{ .kind = .Error });
}
match Vec.push(&self.reflect_stack, &l as *u8) { .Ok => {}, .Err(e) => {} }
defer { self.reflect_stack.len = self.reflect_stack.len - 1; }
var fields = Vec.blank(@sizeof(usize), @alignof(usize)); var fields = Vec.blank(@sizeof(usize), @alignof(usize));
defer { Vec.drop(&fields); } defer { Vec.drop(&fields); }
var i: usize = 0; var i: usize = 0;
while i < LangType.member_count(&self.types, l) { while i < LangType.member_count(&self.types, l) {
var fn2 = Bld.construct(&self.hir, .{ .kind = .FieldDecl(.{ var fn2 = Bld.construct(&self.hir, .{ .kind = .FieldDecl(.{
.name = Bld.dup_bytes(&self.hir, LangType.member_name(&self.types, l, i)), .name = Bld.dup_bytes(&self.hir, LangType.member_name(&self.types, l, i)),
.ty = lang_to_reflect_hir(self, LangType.member_lang(&self.types, l, i)), .ty = reflect_self_type(self, l, LangType.member_lang(&self.types, l, i)),
}) }); }) });
match Vec.push(&fields, &fn2 as *u8) { .Ok => {}, .Err(e) => {} } match Vec.push(&fields, &fn2 as *u8) { .Ok => {}, .Err(e) => {} }
i = i + 1; i = i + 1;
@@ -156,7 +194,7 @@ fn lang_to_reflect_hir_inner(self: *Sema, l: usize): usize {
if pt == 0 { break; } if pt == 0 { break; }
var pr = Bld.construct(&self.hir, .{ .kind = .ParamDecl(.{ var pr = Bld.construct(&self.hir, .{ .kind = .ParamDecl(.{
.is_comptime = false, .by_ref = false, .name = "", .is_comptime = false, .by_ref = false, .name = "",
.ty = lang_to_reflect_hir(self, pt), .ty = reflect_self_type(self, l, pt),
}) }); }) });
match Vec.push(&params, &pr as *u8) { .Ok => {}, .Err(e) => {} } match Vec.push(&params, &pr as *u8) { .Ok => {}, .Err(e) => {} }
pi = pi + 1; pi = pi + 1;
@@ -165,9 +203,10 @@ fn lang_to_reflect_hir_inner(self: *Sema, l: usize): usize {
.is_comptime = false, .injected = reflect_empty_refs(self), .is_comptime = false, .injected = reflect_empty_refs(self),
.name = Bld.dup_bytes(&self.hir, name), .name = Bld.dup_bytes(&self.hir, name),
.params = (params.data as *Ref)[0..params.len], .params = (params.data as *Ref)[0..params.len],
.ret_ty = lang_to_reflect_hir(self, LangType.fn_ret_of(&self.types, ft)), .ret_ty = reflect_self_type(self, l, LangType.fn_ret_of(&self.types, ft)),
.body = 0, .body = 0,
}) }); }) });
SemaM.record_reflect_src(self, fd, mr);
match Vec.push(&decls, &fd as *u8) { .Ok => {}, .Err(e) => {} } match Vec.push(&decls, &fd as *u8) { .Ok => {}, .Err(e) => {} }
i = i + 1; i = i + 1;
} }
+110 -18
View File
@@ -75,6 +75,11 @@ type FnSym = struct {
op: usize, // SemaOp 值;0 = 不是语言操作 op: usize, // SemaOp 值;0 = 不是语言操作
} }
type ReflectSrc = struct {
copy: Ref, // @meta.reflect 生成的方法签名副本
src: Ref, // 原始 FnDecl 节点,用于反查 FnSym
}
type TypeSym = struct { type TypeSym = struct {
name: []u8, name: []u8,
lang: usize, lang: usize,
@@ -142,6 +147,7 @@ type GenInstance = struct { fn_ref: Ref, args: Vec, lang: usize };
type ShapeParam = struct { type ShapeParam = struct {
fn_ref: Ref, fn_ref: Ref,
param_index: usize, param_index: usize,
has_adapter: bool,
adapter_decl: usize, adapter_decl: usize,
shape_lang: usize, shape_lang: usize,
shape_ref: Ref, // ShapeApply / NamedType 使用点 shape_ref: Ref, // ShapeApply / NamedType 使用点
@@ -157,6 +163,7 @@ type ShapeInstance = struct {
// shape 使用点的解析结果:`@adapter[Shape]` 里 adapter、shape 和绑定。 // shape 使用点的解析结果:`@adapter[Shape]` 里 adapter、shape 和绑定。
type ShapeUse = struct { type ShapeUse = struct {
is_shape: bool, is_shape: bool,
has_adapter: bool,
adapter_decl: usize, adapter_decl: usize,
shape_lang: usize, shape_lang: usize,
shape_ref: Ref, shape_ref: Ref,
@@ -191,6 +198,12 @@ type ShapeAdapterResult = struct {
adapter_mod: usize, // adapter FnDecl 所属模块 adapter_mod: usize, // adapter FnDecl 所属模块
}; };
// 类型生成器形参的 shape 约束求值结果:lang 是最终绑定进生成器的类型。
type ShapeArgBind = struct {
ok: bool,
lang: usize,
};
// comptime VM 内 IR 函数引用 -> Sema FnSym 的映射,用于把函数值还原为符号。 // comptime VM 内 IR 函数引用 -> Sema FnSym 的映射,用于把函数值还原为符号。
type CtFnRef = struct { ref: Ref, sym: usize }; type CtFnRef = struct { ref: Ref, sym: usize };
@@ -228,6 +241,9 @@ type ShapeState = struct {
type_binds: Vec, // ShapeTypeBind,实例形参 ref -> lang type_binds: Vec, // ShapeTypeBind,实例形参 ref -> lang
assoc_types: Vec, // ShapeAssocType,shape 关联类型占位缓存 assoc_types: Vec, // ShapeAssocType,shape 关联类型占位缓存
composed: Vec, // ShapeComp,A + B 的临时组合 composed: Vec, // ShapeComp,A + B 的临时组合
patch_roots: Vec, // Ref,实例化时只需重解析的语句根
patching: bool,
patch_decl: usize, // 正在 patch 的 decl 下标;嵌套分析其他函数时必须走完整 sema
}; };
// 一次 shape 调用点处理的结果;fn_tid/ret_tid 为实例化后的真实签名。 // 一次 shape 调用点处理的结果;fn_tid/ret_tid 为实例化后的真实签名。
@@ -245,6 +261,9 @@ type ShapeHooks = struct {
check_conforms: fn(*any, Ref, usize): void, check_conforms: fn(*any, Ref, usize): void,
op_method: fn(*any, usize, usize, []u8): usize, op_method: fn(*any, usize, usize, []u8): usize,
has_conformance: fn(*any, usize, usize): bool, has_conformance: fn(*any, usize, usize): bool,
is_shape_lang: fn(*any, usize): bool,
bind_type_arg: fn(*any, Ref, usize, *ShapeArgBind): void,
apply_expr: fn(*any, Ref, []u8, []Ref, []Ref): usize,
}; };
// decorator/param/impl 的挂载与调用由 hook 模块负责;sema 只提供 // decorator/param/impl 的挂载与调用由 hook 模块负责;sema 只提供
@@ -256,13 +275,14 @@ type HookParamResult = struct {
type HookHooks = struct { type HookHooks = struct {
apply_decorators: fn(*any, usize): void, apply_decorators: fn(*any, usize): void,
prepare_params: fn(*any, Ref, []Ref, *HookParamResult): void, prepare_params: fn(*any, Ref, Ref, []Ref, *HookParamResult): void,
is_impl: fn(*any, Ref): bool, is_impl: fn(*any, Ref): bool,
}; };
type ExprHooks = struct { type ExprHooks = struct {
sema_expr: fn(*any, Ref, usize): void, sema_expr: fn(*any, Ref, usize): void,
sema_body: fn(*any, usize, usize): void, sema_body: fn(*any, usize, usize): void,
patch_body: fn(*any, usize, usize): void,
iter_capture_members: fn(*any, Ref): Vec, iter_capture_members: fn(*any, Ref): Vec,
}; };
@@ -288,6 +308,7 @@ type TypeHooks = struct {
resolve_param: fn(*any, Ref): usize, resolve_param: fn(*any, Ref): usize,
type_gen: fn(*any, Ref, Node.Kind.Call, usize): usize, type_gen: fn(*any, Ref, Node.Kind.Call, usize): usize,
instantiate_generator: fn(*any, Ref, Node.Kind.Call, usize, usize): usize, instantiate_generator: fn(*any, Ref, Node.Kind.Call, usize, usize): usize,
type_is_generator: fn(*any, Ref): bool,
type_arg_lang: fn(*any, Ref): usize, type_arg_lang: fn(*any, Ref): usize,
type_value_lang: fn(*any, Ref): usize, type_value_lang: fn(*any, Ref): usize,
type_handle_arg: fn(*any, usize): usize, type_handle_arg: fn(*any, usize): usize,
@@ -306,7 +327,6 @@ type BindingHooks = struct {
builtin_tag_id: fn(*any, Ref): Builtin, builtin_tag_id: fn(*any, Ref): Builtin,
has_tag: fn(*any, Ref, []u8): bool, has_tag: fn(*any, Ref, []u8): bool,
has_builtin_tag: fn(*any, Ref): bool, has_builtin_tag: fn(*any, Ref): bool,
insert_method_receiver: fn(*any, Ref, Ref, []Ref, *HookParamResult): void,
collect_builtins: fn(*any): void, collect_builtins: fn(*any): void,
list_has_tag: fn(*any, []Ref, []u8): bool, list_has_tag: fn(*any, []Ref, []u8): bool,
raw_tag: fn(*any, Ref): []u8, raw_tag: fn(*any, Ref): []u8,
@@ -328,6 +348,8 @@ hir: Bld.HirNodeContainer,
mods: Vec, // Module mods: Vec, // Module
cur_mod: usize, cur_mod: usize,
refs: Vec, // RefInfo,按 Ref 下标;0 号为哨兵 refs: Vec, // RefInfo,按 Ref 下标;0 号为哨兵
reflect_stack: Vec, // 正在反射的 lang;互递归类型用名字截断
reflect_srcs: Vec, // ReflectSrc:反射方法副本 -> 原始 FnDecl
types: LangType, types: LangType,
defs: Vec, // Def defs: Vec, // Def
fn_syms: Vec, // FnSym(函数记录,惰性登记) fn_syms: Vec, // FnSym(函数记录,惰性登记)
@@ -338,6 +360,7 @@ def_global: Vec, // per def id -> gidx+1(0 = 非全局)
loop_results: Vec, // 循环结果 lang 栈(供 break 值) loop_results: Vec, // 循环结果 lang 栈(供 break 值)
current_agg: usize, // 当前所在聚合 lang(`@self`) current_agg: usize, // 当前所在聚合 lang(`@self`)
self_lang: usize, // 非 0:当前实例化目标的 lang;`@self` 优先解析到它 self_lang: usize, // 非 0:当前实例化目标的 lang;`@self` 优先解析到它
ret_override: usize, // 非 0:catch handler 内的 ret 使用外层函数返回类型
lang_attach_depth: usize, lang_attach_depth: usize,
current_container: Ref, // 当前名称空间容器 ref(名字解析用) current_container: Ref, // 当前名称空间容器 ref(名字解析用)
@@ -383,21 +406,32 @@ type_hooks: TypeHooks,
binding_hooks: BindingHooks, binding_hooks: BindingHooks,
dump_hooks: DumpHooks, dump_hooks: DumpHooks,
fn node_loc_of(self: *Sema, ref: Ref, line: *usize, col: *usize): bool {
if ref == 0 { ret false; }
var n = Bld.node_ptr(&self.hir, ref);
if n == null || n.loc.line == 0 { ret false; }
line.* = n.loc.line;
col.* = n.loc.col;
ret true;
}
fn append_error_loc(self: *Sema, b: *ByteBuffer, ref: Ref) { fn append_error_loc(self: *Sema, b: *ByteBuffer, ref: Ref) {
var use = ref; var use = ref;
if use == 0 { use = self.macro_call_ref; }
if use == 0 { use = self.ct_call_ref; }
if use == 0 { use = self.cur_fn_ref; }
var line: usize = 0; var line: usize = 0;
var col: usize = 0; var col: usize = 0;
var has = false; var has = node_loc_of(self, use, &line, &col);
if use != 0 { // 生成/合成节点常常保留 ref 但 loc 为 0;继续向调用点/当前函数回退。
var n = Bld.node_ptr(&self.hir, use); if !has {
if n != null && n.loc.line != 0 { use = self.macro_call_ref;
line = n.loc.line; has = node_loc_of(self, use, &line, &col);
col = n.loc.col;
has = true;
} }
if !has {
use = self.ct_call_ref;
has = node_loc_of(self, use, &line, &col);
}
if !has {
use = self.cur_fn_ref;
has = node_loc_of(self, use, &line, &col);
} }
var path_mod = self.cur_mod; var path_mod = self.cur_mod;
if use != 0 { if use != 0 {
@@ -748,6 +782,17 @@ fn record_ref_mods(self: *Sema, m: usize, refs: []Ref) {
} }
} }
// 克隆产生的新节点继承生成器声明模块,避免分析期 cur_mod 切换后路径漂移。
fn record_new_ref_mods(self: *Sema, m: usize, start: usize) {
var i = start + 1;
var n = Bld.count(&self.hir);
while i <= n {
var ri = ref_info(self, i);
if ri != null { ri.mod = m + 1; }
i = i + 1;
}
}
fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema { fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema {
// 模块路径由 Sema 自己持有,driver 的临时 ModEntry 可以提前释放。 // 模块路径由 Sema 自己持有,driver 的临时 ModEntry 可以提前释放。
var stable_path = ByteView.from_slice(Bld.dup_bytes(&hir, ByteView.as_slice(path))); var stable_path = ByteView.from_slice(Bld.dup_bytes(&hir, ByteView.as_slice(path)));
@@ -760,6 +805,8 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
.mods = Vec.blank(@sizeof(Module), @alignof(Module)), .mods = Vec.blank(@sizeof(Module), @alignof(Module)),
.cur_mod = 0, .cur_mod = 0,
.refs = Vec.blank(@sizeof(RefInfo), @alignof(RefInfo)), .refs = Vec.blank(@sizeof(RefInfo), @alignof(RefInfo)),
.reflect_stack = Vec.blank(@sizeof(usize), @alignof(usize)),
.reflect_srcs = Vec.blank(@sizeof(ReflectSrc), @alignof(ReflectSrc)),
.types = tt, .types = tt,
.defs = Vec.blank(@sizeof(Def), @alignof(Def)), .defs = Vec.blank(@sizeof(Def), @alignof(Def)),
.fn_syms = Vec.blank(@sizeof(FnSym), @alignof(FnSym)), .fn_syms = Vec.blank(@sizeof(FnSym), @alignof(FnSym)),
@@ -770,6 +817,7 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
.loop_results = Vec.blank(@sizeof(usize), @alignof(usize)), .loop_results = Vec.blank(@sizeof(usize), @alignof(usize)),
.current_agg = 0, .current_agg = 0,
.self_lang = 0, .self_lang = 0,
.ret_override = 0,
.lang_attach_depth = 0, .lang_attach_depth = 0,
.current_container = 0, .current_container = 0,
.in_callee = false, .in_callee = false,
@@ -800,11 +848,12 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
.gen_method_binds = Vec.blank(@sizeof(GenBindRec), @alignof(GenBindRec)), .gen_method_binds = Vec.blank(@sizeof(GenBindRec), @alignof(GenBindRec)),
.gen_instances = Vec.blank(@sizeof(GenInstance), @alignof(GenInstance)), .gen_instances = Vec.blank(@sizeof(GenInstance), @alignof(GenInstance)),
.iter_infos = Vec.blank(@sizeof(IterInfo), @alignof(IterInfo)), .iter_infos = Vec.blank(@sizeof(IterInfo), @alignof(IterInfo)),
.expr_hooks = ExprHooks { .sema_expr = null, .sema_body = null, .iter_capture_members = null }, .expr_hooks = ExprHooks { .sema_expr = null, .sema_body = null, .patch_body = null, .iter_capture_members = null },
.decl_hooks = DeclHooks { .ensure_decl = null, .ensure_module = null, .analyze_fn_body = null }, .decl_hooks = DeclHooks { .ensure_decl = null, .ensure_module = null, .analyze_fn_body = null },
.lang_hooks = LangHooks { .record_conforms = null, .copy_conforms = null, .conform_binds = null, .method_sym = null }, .lang_hooks = LangHooks { .record_conforms = null, .copy_conforms = null, .conform_binds = null, .method_sym = null },
.type_hooks = TypeHooks { .type_hooks = TypeHooks {
.resolve_type = null, .resolve_param = null, .type_gen = null, .resolve_type = null, .resolve_param = null, .type_gen = null,
.type_is_generator = null,
.type_arg_lang = null, .type_value_lang = null, .type_handle_arg = null, .type_arg_lang = null, .type_value_lang = null, .type_handle_arg = null,
.type_arg_handle = null, .type_query_int = null, .type_arg_handle = null, .type_query_int = null,
.type_builtin = null, .emit_intrinsic = null, .builtin_tid = null, .type_builtin = null, .emit_intrinsic = null, .builtin_tid = null,
@@ -812,7 +861,7 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
}, },
.binding_hooks = BindingHooks { .binding_hooks = BindingHooks {
.find_binding = null, .builtin_tag_id = null, .has_tag = null, .find_binding = null, .builtin_tag_id = null, .has_tag = null,
.has_builtin_tag = null, .insert_method_receiver = null, .has_builtin_tag = null,
.collect_builtins = null, .list_has_tag = null, .raw_tag = null, .tag_arg = null, .collect_builtins = null, .list_has_tag = null, .raw_tag = null, .tag_arg = null,
}, },
.dump_hooks = DumpHooks { .dump = null }, .dump_hooks = DumpHooks { .dump = null },
@@ -823,6 +872,9 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
.type_binds = Vec.blank(@sizeof(ShapeTypeBind), @alignof(ShapeTypeBind)), .type_binds = Vec.blank(@sizeof(ShapeTypeBind), @alignof(ShapeTypeBind)),
.assoc_types = Vec.blank(@sizeof(ShapeAssocType), @alignof(ShapeAssocType)), .assoc_types = Vec.blank(@sizeof(ShapeAssocType), @alignof(ShapeAssocType)),
.composed = Vec.blank(@sizeof(ShapeComp), @alignof(ShapeComp)), .composed = Vec.blank(@sizeof(ShapeComp), @alignof(ShapeComp)),
.patch_roots = Vec.blank(@sizeof(Ref), @alignof(Ref)),
.patching = false,
.patch_decl = 0,
}, },
.shape_hooks = ShapeHooks { .shape_hooks = ShapeHooks {
.bind_params = null, .bind_params = null,
@@ -831,6 +883,9 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
.check_conforms = null, .check_conforms = null,
.op_method = null, .op_method = null,
.has_conformance = null, .has_conformance = null,
.is_shape_lang = null,
.bind_type_arg = null,
.apply_expr = null,
}, },
.shape_for_item = null, .shape_for_item = null,
.hook_hooks = HookHooks { .hook_hooks = HookHooks {
@@ -914,8 +969,11 @@ fn drop(self: *Sema) {
ci = ci + 1; ci = ci + 1;
} }
Vec.drop(&self.shape_state.composed); Vec.drop(&self.shape_state.composed);
Vec.drop(&self.shape_state.patch_roots);
Vec.drop(&self.ct.fn_refs); Vec.drop(&self.ct.fn_refs);
Vec.drop(&self.refs); Vec.drop(&self.refs);
Vec.drop(&self.reflect_stack);
Vec.drop(&self.reflect_srcs);
var mi: usize = 0; var mi: usize = 0;
while mi < self.mods.len { while mi < self.mods.len {
var mm = (self.mods.data as *Module) + mi; var mm = (self.mods.data as *Module) + mi;
@@ -1216,17 +1274,28 @@ fn scan_namespace_into(self: *Sema, ns_i: usize) {
} }
fn ensure_namespace(self: *Sema, container: Ref): usize { fn ensure_namespace(self: *Sema, container: Ref): usize {
// 容器名空间属于容器声明的模块,不能跟着调用方 cur_mod 走;否则同一个
// 生成 struct 会在调用方模块里重复注册同名 Decl,签名里的模块私有类型
// 也会在错误模块里解析。
var ns_mod = self.cur_mod;
if container != 0 {
var ci = ref_info(self, container);
if ci != null && ci.mod != 0 { ns_mod = ci.mod - 1; }
}
var i: usize = 0; var i: usize = 0;
while i < self.namespaces.len { while i < self.namespaces.len {
var ns0 = (self.namespaces.data as *Namespace)[i]; var ns0 = (self.namespaces.data as *Namespace)[i];
if ns0.container == container && ns0.mod == self.cur_mod { ret i + 1; } if ns0.container == container && ns0.mod == ns_mod { ret i + 1; }
i = i + 1; i = i + 1;
} }
var ns = Namespace { .mod = self.cur_mod, .container = container, var saved = self.cur_mod;
if ns_mod != saved { switch_mod(self, ns_mod); }
var ns = Namespace { .mod = ns_mod, .container = container,
.entries = Vec.blank(@sizeof(NameEntry), @alignof(NameEntry)) }; .entries = Vec.blank(@sizeof(NameEntry), @alignof(NameEntry)) };
match Vec.push(&self.namespaces, &ns as *u8) { .Ok => {}, .Err(error) => {} } match Vec.push(&self.namespaces, &ns as *u8) { .Ok => {}, .Err(error) => {} }
var idx = self.namespaces.len - 1; var idx = self.namespaces.len - 1;
scan_namespace_into(self, idx + 1); scan_namespace_into(self, idx + 1);
if ns_mod != saved { switch_mod(self, saved); }
ret idx + 1; ret idx + 1;
} }
@@ -1302,7 +1371,6 @@ fn find_binding(self: *Sema, s: []u8): usize { if self.binding_hooks.find_bindin
fn builtin_tag_id(self: *Sema, fnref: Ref): Builtin { if self.binding_hooks.builtin_tag_id == null { ret .None; } ret self.binding_hooks.builtin_tag_id(self as *any, fnref); } fn builtin_tag_id(self: *Sema, fnref: Ref): Builtin { if self.binding_hooks.builtin_tag_id == null { ret .None; } ret self.binding_hooks.builtin_tag_id(self as *any, fnref); }
fn has_tag(self: *Sema, fnref: Ref, name: []u8): bool { if self.binding_hooks.has_tag == null { ret false; } ret self.binding_hooks.has_tag(self as *any, fnref, name); } fn has_tag(self: *Sema, fnref: Ref, name: []u8): bool { if self.binding_hooks.has_tag == null { ret false; } ret self.binding_hooks.has_tag(self as *any, fnref, name); }
fn has_builtin_tag(self: *Sema, fnref: Ref): bool { if self.binding_hooks.has_builtin_tag == null { ret false; } ret self.binding_hooks.has_builtin_tag(self as *any, fnref); } fn has_builtin_tag(self: *Sema, fnref: Ref): bool { if self.binding_hooks.has_builtin_tag == null { ret false; } ret self.binding_hooks.has_builtin_tag(self as *any, fnref); }
fn insert_method_receiver(self: *Sema, callee_ref: Ref, callee: Ref, args: []Ref, out: *HookParamResult) { if self.binding_hooks.insert_method_receiver != null { self.binding_hooks.insert_method_receiver(self as *any, callee_ref, callee, args, out); } }
fn collect_builtins(self: *Sema) { if self.binding_hooks.collect_builtins != null { self.binding_hooks.collect_builtins(self as *any); } } fn collect_builtins(self: *Sema) { if self.binding_hooks.collect_builtins != null { self.binding_hooks.collect_builtins(self as *any); } }
fn list_has_tag(self: *Sema, l: []Ref, tag: []u8): bool { if self.binding_hooks.list_has_tag == null { ret false; } ret self.binding_hooks.list_has_tag(self as *any, l, tag); } fn list_has_tag(self: *Sema, l: []Ref, tag: []u8): bool { if self.binding_hooks.list_has_tag == null { ret false; } ret self.binding_hooks.list_has_tag(self as *any, l, tag); }
fn builtin_tag_raw(self: *Sema, fnref: Ref): []u8 { fn builtin_tag_raw(self: *Sema, fnref: Ref): []u8 {
@@ -1339,6 +1407,7 @@ fn ct_lang(self: *Sema, h: tid): usize {
fn resolve_type(self: *Sema, ref: Ref): usize { if self.type_hooks.resolve_type == null { ret 0; } ret self.type_hooks.resolve_type(self as *any, ref); } fn resolve_type(self: *Sema, ref: Ref): usize { if self.type_hooks.resolve_type == null { ret 0; } ret self.type_hooks.resolve_type(self as *any, ref); }
fn resolve_param(self: *Sema, ref: Ref): usize { if self.type_hooks.resolve_param == null { ret 0; } ret self.type_hooks.resolve_param(self as *any, ref); } fn resolve_param(self: *Sema, ref: Ref): usize { if self.type_hooks.resolve_param == null { ret 0; } ret self.type_hooks.resolve_param(self as *any, ref); }
fn type_gen_lang(self: *Sema, ref: Ref, x: Node.Kind.Call, self_lang: usize): usize { if self.type_hooks.type_gen == null { ret 0; } ret self.type_hooks.type_gen(self as *any, ref, x, self_lang); } fn type_gen_lang(self: *Sema, ref: Ref, x: Node.Kind.Call, self_lang: usize): usize { if self.type_hooks.type_gen == null { ret 0; } ret self.type_hooks.type_gen(self as *any, ref, x, self_lang); }
fn type_is_generator(self: *Sema, fn_ref: Ref): bool { if self.type_hooks.type_is_generator == null { ret false; } ret self.type_hooks.type_is_generator(self as *any, fn_ref); }
fn type_arg_lang(self: *Sema, ref: Ref): usize { if self.type_hooks.type_arg_lang == null { ret 0; } ret self.type_hooks.type_arg_lang(self as *any, ref); } fn type_arg_lang(self: *Sema, ref: Ref): usize { if self.type_hooks.type_arg_lang == null { ret 0; } ret self.type_hooks.type_arg_lang(self as *any, ref); }
fn type_value_lang(self: *Sema, ref: Ref): usize { if self.type_hooks.type_value_lang == null { ret 0; } ret self.type_hooks.type_value_lang(self as *any, ref); } fn type_value_lang(self: *Sema, ref: Ref): usize { if self.type_hooks.type_value_lang == null { ret 0; } ret self.type_hooks.type_value_lang(self as *any, ref); }
fn type_handle_arg(self: *Sema, a0: usize): usize { if self.type_hooks.type_handle_arg == null { ret 0; } ret self.type_hooks.type_handle_arg(self as *any, a0); } fn type_handle_arg(self: *Sema, a0: usize): usize { if self.type_hooks.type_handle_arg == null { ret 0; } ret self.type_hooks.type_handle_arg(self as *any, a0); }
@@ -1454,6 +1523,25 @@ fn fn_sym_for_ref(self: *Sema, fn_ref: Ref): usize {
if sym_at(self, i).ref == fn_ref { ret i + 1; } if sym_at(self, i).ref == fn_ref { ret i + 1; }
i = i + 1; i = i + 1;
} }
// @meta.reflect 产出的是方法签名副本;反查原始 FnDecl 的符号。
var src = reflect_src_of(self, fn_ref);
if src != 0 && src != fn_ref { ret fn_sym_for_ref(self, src); }
ret 0;
}
fn record_reflect_src(self: *Sema, copy: Ref, src: Ref) {
if copy == 0 || src == 0 { ret; }
var e = ReflectSrc { .copy = copy, .src = src };
match Vec.push(&self.reflect_srcs, &e as *u8) { .Ok => {}, .Err(error) => {} }
}
fn reflect_src_of(self: *Sema, r: Ref): Ref {
var i: usize = 0;
while i < self.reflect_srcs.len {
var e = (self.reflect_srcs.data as *ReflectSrc)[i];
if e.copy == r { ret e.src; }
i = i + 1;
}
ret 0; ret 0;
} }
@@ -1615,7 +1703,7 @@ fn is_type_value_expr(self: *Sema, ref: Ref): bool {
match n.kind { match n.kind {
.IntType(_), .FloatType(_), .Bool, .Unit, .Any, .Type, .Never, .IntType(_), .FloatType(_), .Bool, .Unit, .Any, .Type, .Never,
.PtrType(_), .SliceType(_), .ArrayType(_), .FnType(_), .TupleType(_), .PtrType(_), .SliceType(_), .ArrayType(_), .FnType(_), .TupleType(_),
.NamedType(_), .AggType(_), .ShapeApply(_), .ShapeUse(_) => { ret true; }, .NamedType(_), .AggType(_), .ShapeApply(_), .ShapeUse(_), .ShapeNoDefault(_) => { ret true; },
.Global(x) => { .Global(x) => {
var d = find_decl(self, x); var d = find_decl(self, x);
ret d != 0 && @enum2int(decl_at(self, d - 1).kind) == @enum2int(DeclKind.Type); ret d != 0 && @enum2int(decl_at(self, d - 1).kind) == @enum2int(DeclKind.Type);
@@ -1801,6 +1889,10 @@ fn sema_body(self: *Sema, body: usize, ret_tid: usize) {
if self.expr_hooks.sema_body != null { self.expr_hooks.sema_body(self as *any, body, ret_tid); } if self.expr_hooks.sema_body != null { self.expr_hooks.sema_body(self as *any, body, ret_tid); }
} }
fn patch_body(self: *Sema, body: usize, ret_tid: usize) {
if self.expr_hooks.patch_body != null { self.expr_hooks.patch_body(self as *any, body, ret_tid); }
}
fn iter_capture_members(self: *Sema, ref: Ref): Vec { fn iter_capture_members(self: *Sema, ref: Ref): Vec {
if self.expr_hooks.iter_capture_members == null { ret Vec.blank(@sizeof(usize), @alignof(usize)); } if self.expr_hooks.iter_capture_members == null { ret Vec.blank(@sizeof(usize), @alignof(usize)); }
ret self.expr_hooks.iter_capture_members(self as *any, ref); ret self.expr_hooks.iter_capture_members(self as *any, ref);
+5 -40
View File
@@ -25,11 +25,11 @@ type tid = usize;
fn hook_find_binding(user: *any, s: []u8): usize { ret find_binding(user as *Sema, s); } fn hook_find_binding(user: *any, s: []u8): usize { ret find_binding(user as *Sema, s); }
fn hook_builtin_tag_id(user: *any, fnref: Ref): Builtin { ret builtin_tag_id(user as *Sema, fnref); } fn hook_builtin_tag_id(user: *any, fnref: Ref): Builtin { ret builtin_tag_id(user as *Sema, fnref); }
fn hook_has_tag(user: *any, fnref: Ref, name: []u8): bool { ret has_tag(user as *Sema, fnref, name); } fn hook_has_tag(user: *any, fnref: Ref, name: []u8): bool { ret has_tag(user as *Sema, fnref, name); }
fn hook_has_builtin_tag(user: *any, fnref: Ref): bool { ret has_builtin_tag(user as *Sema, fnref); } fn hook_has_builtin_tag(user: *any, fnref: Ref): bool { ret has_builtin_tag(user as *Sema, fnref); }
fn hook_insert_method_receiver(user: *any, callee_ref: Ref, callee: Ref, args: []Ref, out: *HookParamResult) {
insert_method_receiver(user as *Sema, callee_ref, callee, args, out);
}
fn hook_collect_builtins(user: *any) { collect_builtins(user as *Sema); } fn hook_collect_builtins(user: *any) { collect_builtins(user as *Sema); }
fn hook_list_has_tag(user: *any, l: []Ref, tag: []u8): bool { ret list_has_tag(user as *Sema, l, tag); } fn hook_list_has_tag(user: *any, l: []Ref, tag: []u8): bool { ret list_has_tag(user as *Sema, l, tag); }
fn builtin_tag_raw(self: *Sema, fnref: Ref): []u8 { ret tag_arg_raw(self, fnref, "builtin"); } fn builtin_tag_raw(self: *Sema, fnref: Ref): []u8 { ret tag_arg_raw(self, fnref, "builtin"); }
@@ -44,7 +44,7 @@ fn hooks(): BindingHooks {
.builtin_tag_id = hook_builtin_tag_id, .builtin_tag_id = hook_builtin_tag_id,
.has_tag = hook_has_tag, .has_tag = hook_has_tag,
.has_builtin_tag = hook_has_builtin_tag, .has_builtin_tag = hook_has_builtin_tag,
.insert_method_receiver = hook_insert_method_receiver,
.collect_builtins = hook_collect_builtins, .collect_builtins = hook_collect_builtins,
.list_has_tag = hook_list_has_tag, .list_has_tag = hook_list_has_tag,
.raw_tag = hook_raw_tag, .raw_tag = hook_raw_tag,
@@ -252,42 +252,7 @@ fn param_has_at(self: *Sema, param: Ref): bool {
ret false; ret false;
} }
// 方法调用 `obj.f(args)`:obj 总是作为隐式 receiver;hook 只负责变换 receiver。
fn insert_method_receiver(self: *Sema, callee_ref: Ref, callee: Ref, args: []Ref,
out: *HookParamResult) {
out.args = args;
out.changed = false;
var fnp = Bld.node_ptr(&self.hir, callee_ref);
if fnp == null { ret; }
var recv: Ref = 0;
var cn = Bld.node_ptr(&self.hir, callee);
if cn == null { ret; }
match cn.kind {
.Field(f) => { recv = f.obj; },
_ => {},
}
if recv == 0 { ret; }
// 模块级函数不是方法;只有聚合/语言类型的方法才插入 receiver。
var csym = SemaM.node_fn(self, callee);
if csym == 0 || SemaM.sym_at(self, csym - 1).owner == 0 { ret; }
match fnp.kind {
.FnDecl(f) => {
if f.params.len == 0 || args.len + 1 != f.params.len { ret; }
var buf = Vec.blank(@sizeof(Ref), @alignof(Ref));
defer { Vec.drop(&buf); }
match Vec.push(&buf, &recv as *u8) { .Ok => {}, .Err(error) => { ret; } }
var i: usize = 0;
while i < args.len {
var a = args[i];
match Vec.push(&buf, &a as *u8) { .Ok => {}, .Err(error) => { ret; } }
i = i + 1;
}
out.args = Bld.dup_refs(&self.hir, (buf.data as *Ref)[0..buf.len]);
out.changed = true;
},
_ => {},
}
}
fn is_meta_module(self: *Sema, m: usize): bool { fn is_meta_module(self: *Sema, m: usize): bool {
var p = SemaM.module_at(self, m).path; var p = SemaM.module_at(self, m).path;
+17
View File
@@ -181,6 +181,14 @@ fn analyze_type_decl(self: *Sema, di: usize) {
// 宏 varargs 的稳定类型标签;fmt 等库按标签选择生成代码。 // 宏 varargs 的稳定类型标签;fmt 等库按标签选择生成代码。
fn analyze_fn_decl(self: *Sema, di: usize) { fn analyze_fn_decl(self: *Sema, di: usize) {
// 签名里的类型名属于声明模块,必须在声明模块里解析;否则从别的模块
// 触发生成方法分析时,模块私有类型会解析成 0,得到错误的 @Result 实例。
var saved_mod = self.cur_mod;
var dmod = SemaM.decl_at(self, di).mod;
if dmod != saved_mod { SemaM.switch_mod(self, dmod); }
defer {
if dmod != saved_mod { SemaM.switch_mod(self, saved_mod); }
}
var node = SemaM.decl_at(self, di).node; var node = SemaM.decl_at(self, di).node;
var container = SemaM.decl_at(self, di).container; var container = SemaM.decl_at(self, di).container;
var n = Bld.node_ptr(&self.hir, node); var n = Bld.node_ptr(&self.hir, node);
@@ -371,12 +379,21 @@ fn analyze_fn_body(self: *Sema, di: usize) {
self.current_container = container; self.current_container = container;
var ret_tid = SemaM.tid_of(self, x.ret_ty); var ret_tid = SemaM.tid_of(self, x.ret_ty);
if ret_tid == 0 { ret_tid = SemaM.decl_at(self, di).ret_lang; } if ret_tid == 0 { ret_tid = SemaM.decl_at(self, di).ret_lang; }
var patch_this = self.shape_state.patching && self.shape_state.patch_decl == di;
var j: usize = 0; var j: usize = 0;
while j < x.params.len { while j < x.params.len {
if patch_this { SemaM.set_def(self, x.params[j], 0); }
bind_param(self, x.params[j]); bind_param(self, x.params[j]);
j = j + 1; j = j + 1;
} }
var saved_ret_override = self.ret_override;
self.ret_override = ret_tid;
if patch_this {
SemaM.patch_body(self, x.body, ret_tid);
} else {
SemaM.sema_body(self, x.body, ret_tid); SemaM.sema_body(self, x.body, ret_tid);
}
self.ret_override = saved_ret_override;
self.cur_fn = saved_fn; self.cur_fn = saved_fn;
self.cur_fn_ref = saved_ref; self.cur_fn_ref = saved_ref;
self.current_agg = saved_agg; self.current_agg = saved_agg;
+248 -19
View File
@@ -11,6 +11,7 @@ type Bld = @import("./spl_ir_builder.spl");
type .{ .Builtin } = @import("./intrinsic.spl"); type .{ .Builtin } = @import("./intrinsic.spl");
type B = @import("./intrinsic.spl"); type B = @import("./intrinsic.spl");
type SemaOpM = @import("./sema_op.spl"); type SemaOpM = @import("./sema_op.spl");
type ReflectType = @import("./reflect_type.spl");
type .{ .SemaOp } = @import("./sema_op.spl"); type .{ .SemaOp } = @import("./sema_op.spl");
type .{ .LangKind, .ReprKind } = @import("./lang_type.spl"); type .{ .LangKind, .ReprKind } = @import("./lang_type.spl");
type .{ .StructMember } = @import("./lang_type.spl"); type .{ .StructMember } = @import("./lang_type.spl");
@@ -26,6 +27,94 @@ type .{
} = @import("./sema.spl"); } = @import("./sema.spl");
type tid = usize; type tid = usize;
fn expr_is_type_value(self: *Sema, ref: Ref): bool {
var n = Bld.node_ptr(&self.hir, ref);
if n == null { ret false; }
match n.kind {
.Field(_), .Local(_), .LitInt(_), .LitFloat(_), .LitBool(_), .LitChar(_),
.LitStr(_), .Index(_), .Addr(_), .Deref(_), .AggLit(_), .ArrayLit(_),
.TupleLit(_), .Binary(_), .Unary(_), .Cast(_), .SliceExpr(_), .Range(_),
.Try(_), .Catch(_), .IsNonNull(_), .OptionalPayload(_), .IsTag(_),
.TagPayload(_), .Match(_), .Block(_), .If(_), .IfVar(_), .Loop(_),
.Iter(_), .Return(_), .Break(_), .Continue(_), .Defer(_), .ErrDefer(_) => { ret false; },
.NamedType(_), .AggType(_), .ShapeApply(_), .ShapeUse(_), .ShapeNoDefault(_),
.Type, .SelfType, .ArrayType(_), .SliceType(_), .PtrType(_), .FnType(_),
.TupleType(_), .IntType(_), .FloatType(_), .Bool => { ret true; },
.Call(x) => {
var cs = SemaM.node_fn(self, x.callee);
if cs == 0 {
var cnn = Bld.node_ptr(&self.hir, x.callee);
if cnn != null {
match cnn.kind {
.Global(g) => {
var d = SemaM.find_decl(self, g);
if d != 0 {
SemaM.ensure_decl(self, d - 1);
cs = SemaM.decl_at(self, d - 1).sym;
}
},
_ => {},
}
}
}
if cs != 0 {
var fr = SemaM.sym_at(self, cs - 1).ref;
if fr != 0 && SemaM.type_is_generator(self, fr) { ret true; }
}
ret false;
},
.Global(_) => {},
_ => { ret false; },
}
var t = SemaM.tid_of(self, ref);
if t == 0 { t = SemaM.resolve_type(self, ref); }
ret t != 0 && LangType.is_type(&self.types, t);
}
fn append_tag(self: *Sema, ref: Ref, name: []u8, args: []Ref) {
var n = Bld.node_ptr(&self.hir, ref);
if n == null { ret; }
var tag = Bld.construct(&self.hir, .{ .kind = .Tag(.{
.is_at = false,
.name = name,
.args = Bld.dup_refs(&self.hir, args),
}) });
var buf = Vec.blank(@sizeof(Ref), @alignof(Ref));
defer { Vec.drop(&buf); }
var i: usize = 0;
while i < n.tags.len {
var t = n.tags[i];
match Vec.push(&buf, &t as *u8) { .Ok => {}, .Err(error) => { ret; } }
i = i + 1;
}
match Vec.push(&buf, &tag as *u8) { .Ok => {}, .Err(error) => { ret; } }
n.tags = Bld.dup_refs(&self.hir, (buf.data as *Ref)[0..buf.len]);
}
fn find_tag(self: *Sema, ref: Ref, name: []u8): Ref {
var n = Bld.node_ptr(&self.hir, ref);
if n == null { ret 0; }
var i: usize = 0;
while i < n.tags.len {
var tn = Bld.node_ptr(&self.hir, n.tags[i]);
if tn != null {
match tn.kind {
.Tag(x) => { if SemaM.eq(x.name, name) { ret n.tags[i]; } },
_ => {},
}
}
i = i + 1;
}
ret 0;
}
// 记录 hook 注入前的 implicit 与显式实参;实例化重解析时据此重新执行 hook。
fn set_param_src(self: *Sema, ref: Ref, implicit: Ref, args: []Ref) {
var tuple = Bld.construct(&self.hir, .{ .kind = .TupleLit(Bld.dup_refs(&self.hir, args)) });
var src: [2]Ref = .[implicit, tuple];
append_tag(self, ref, "param_src", src[0..2]);
}
fn hook_sema_expr(user: *any, ref: Ref, want: usize) { sema_expr(user as *Sema, ref, want); } fn hook_sema_expr(user: *any, ref: Ref, want: usize) { sema_expr(user as *Sema, ref, want); }
fn hook_sema_body(user: *any, body: usize, ret_tid: usize) { sema_body(user as *Sema, body, ret_tid); } fn hook_sema_body(user: *any, body: usize, ret_tid: usize) { sema_body(user as *Sema, body, ret_tid); }
fn hook_iter_capture_members(user: *any, ref: Ref): Vec { ret iter_capture_members(user as *Sema, ref); } fn hook_iter_capture_members(user: *any, ref: Ref): Vec { ret iter_capture_members(user as *Sema, ref); }
@@ -34,6 +123,7 @@ fn hooks(): ExprHooks {
ret ExprHooks { ret ExprHooks {
.sema_expr = hook_sema_expr, .sema_expr = hook_sema_expr,
.sema_body = hook_sema_body, .sema_body = hook_sema_body,
.patch_body = patch_body,
.iter_capture_members = hook_iter_capture_members, .iter_capture_members = hook_iter_capture_members,
}; };
} }
@@ -49,8 +139,13 @@ fn bind_pattern(self: *Sema, ref: Ref, lang: usize) {
match n.kind { match n.kind {
.PatWild => { SemaM.set_tid(self, ref, 0); }, .PatWild => { SemaM.set_tid(self, ref, 0); },
.PatBind(x) => { .PatBind(x) => {
var d = SemaM.new_def(self, lang); // 生成实例/匹配臂可能被重复分析;重复 new_def 会让 arm body
// 的 Local 指向旧 def,而 pattern bind 写新 def 的槽。
var d = SemaM.node_def(self, ref);
if d == 0 {
d = SemaM.new_def(self, lang);
SemaM.set_def(self, ref, d); SemaM.set_def(self, ref, d);
}
SemaM.set_tid(self, ref, lang); SemaM.set_tid(self, ref, lang);
}, },
.PatLit(x) => { sema_expr(self, x, lang); SemaM.set_tid(self, ref, lang); }, .PatLit(x) => { sema_expr(self, x, lang); SemaM.set_tid(self, ref, lang); },
@@ -476,6 +571,33 @@ fn bind_iter_captures(self: *Sema, captures: []Ref, members: []Ref, pattern_type
} }
} }
fn callee_label(self: *Sema, callee: Ref): []u8 {
var n = Bld.node_ptr(&self.hir, callee);
if n == null { ret ""; }
match n.kind {
.Global(g) => { ret g; },
.Field(f) => {
var on = Bld.node_ptr(&self.hir, f.obj);
if on != null {
match on.kind {
.Global(g) => {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
ByteBuffer.append(&b, g);
ByteBuffer.append(&b, ".");
ByteBuffer.append(&b, f.name);
ret Bld.dup_bytes(&self.hir, ByteBuffer.as_slice(b));
},
_ => {},
}
}
ret f.name;
},
_ => {},
}
ret "";
}
fn sema_expr(self: *Sema, ref: Ref, want: usize) { fn sema_expr(self: *Sema, ref: Ref, want: usize) {
if ref == 0 { ret; } if ref == 0 { ret; }
var n = Bld.node_ptr(&self.hir, ref); var n = Bld.node_ptr(&self.hir, ref);
@@ -872,6 +994,14 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
var is_ct_builtin = false; var is_ct_builtin = false;
var native_callee = false; var native_callee = false;
var callee_ref: usize = 0; var callee_ref: usize = 0;
var implicit0: Ref = 0;
var cn0 = Bld.node_ptr(&self.hir, x.callee);
if cn0 != null {
match cn0.kind {
.Field(f) => { if !expr_is_type_value(self, f.obj) { implicit0 = f.obj; } },
_ => {},
}
}
var csi = SemaM.node_fn(self, x.callee); var csi = SemaM.node_fn(self, x.callee);
var cn = Bld.node_ptr(&self.hir, x.callee); var cn = Bld.node_ptr(&self.hir, x.callee);
if cn != null { if cn != null {
@@ -984,29 +1114,64 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
ret_tid = s2.ret_tid; ret_tid = s2.ret_tid;
callee_ref = s2.ref; callee_ref = s2.ref;
} }
// 用户类型生成器在表达式位置也按类型求解;普通 comptime 值调用
// 的形参检查会把 shape 约束参数误当成运行期 shape 值。
if fn_tid != 0 && LangType.is_type(&self.types, ret_tid) &&
callee_ref != 0 && SemaM.type_is_generator(self, callee_ref) {
var tl = SemaM.type_gen_lang(self, ref, x, 0);
SemaM.set_tid(self, ref, tl);
ret;
}
var is_macro = callee_ref != 0 && SemaM.has_tag(self, callee_ref, "macro") && var is_macro = callee_ref != 0 && SemaM.has_tag(self, callee_ref, "macro") &&
!SemaM.has_tag(self, ref, "adapter_call") && !SemaM.has_tag(self, ref, "adapter_call") &&
!SemaM.has_tag(self, ref, "hook_call"); !SemaM.has_tag(self, ref, "hook_call");
if is_macro && !x.is_comptime { if is_macro && !x.is_comptime {
SemaM.sema_error_code_at(self, ref, ErrorCode.MacroCode, "macro call requires @", ""); SemaM.sema_error_code_at(self, ref, ErrorCode.MacroCode, "macro call requires @", "");
} }
if callee_ref != 0 && !is_macro && !x.is_comptime && if callee_ref != 0 && !is_macro &&
!SemaM.has_tag(self, ref, "hook_call") { !SemaM.has_tag(self, ref, "hook_call") {
var rr = HookParamResult { .args = x.args, .changed = false };
SemaM.insert_method_receiver(self, callee_ref, x.callee, x.args, &rr);
if rr.changed {
x.args = rr.args;
var call_node = Bld.node_ptr(&self.hir, ref);
if call_node != null { call_node.kind = .Call(x); }
}
if self.hook_hooks.prepare_params != null { if self.hook_hooks.prepare_params != null {
var hr = HookParamResult { .args = x.args, .changed = false }; // 实例化会改写形参类型,hook 注入结果必须按当前类型重算;
self.hook_hooks.prepare_params(self as *any, callee_ref, x.args, &hr); // param_src 保存注入前的 implicit 和显式实参,保证重算幂等。
var src = find_tag(self, ref, "param_src");
var use_implicit = implicit0;
var use_args = x.args;
var rerun = false;
if src != 0 {
var sn = Bld.node_ptr(&self.hir, src);
if sn != null {
match sn.kind {
.Tag(t) => {
if t.args.len == 2 {
use_implicit = t.args[0];
var an = Bld.node_ptr(&self.hir, t.args[1]);
if an != null {
match an.kind {
.TupleLit(xs) => { use_args = xs; },
_ => {},
}
}
rerun = true;
}
},
_ => {},
}
}
}
var hr = HookParamResult { .args = use_args, .changed = false };
self.hook_hooks.prepare_params(self as *any, callee_ref, use_implicit, use_args, &hr);
if hr.changed { if hr.changed {
x.args = hr.args; x.args = hr.args;
} else if rerun {
x.args = use_args;
}
if rerun || hr.changed {
var call_node2 = Bld.node_ptr(&self.hir, ref); var call_node2 = Bld.node_ptr(&self.hir, ref);
if call_node2 != null { call_node2.kind = .Call(x); } if call_node2 != null { call_node2.kind = .Call(x); }
} }
if !rerun && hr.changed {
set_param_src(self, ref, implicit0, use_args);
}
} }
} }
if is_macro && SemaM.has_tag(self, callee_ref, "variadic") { if is_macro && SemaM.has_tag(self, callee_ref, "variadic") {
@@ -1027,8 +1192,13 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
sema_expr(self, er, 0); sema_expr(self, er, 0);
var kind = SemaM.macro_arg_kind(self, er); var kind = SemaM.macro_arg_kind(self, er);
var kind_node = Bld.construct(&self.hir, .{ .kind = .LitStr(kind) }); var kind_node = Bld.construct(&self.hir, .{ .kind = .LitStr(kind) });
var pair_args: [2]Ref = .[er, kind_node]; // 第三个元素是实参的反射类型节点:库宏据此做类型分派,
var pair = Bld.construct(&self.hir, .{ .kind = .TupleLit(pair_args[0..2]) }); // 编译器不再为具体库维护类型词汇表。
var ty_ref: Ref = 0;
var tl = SemaM.tid_of(self, er);
if tl != 0 { ty_ref = ReflectType.lang_to_reflect_hir(self, tl); }
var pair_args: [3]Ref = .[er, kind_node, ty_ref];
var pair = Bld.construct(&self.hir, .{ .kind = .TupleLit(pair_args[0..3]) });
match Vec.push(&extras, &pair as *u8) { .Ok => {}, .Err(e) => {} } match Vec.push(&extras, &pair as *u8) { .Ok => {}, .Err(e) => {} }
ei = ei + 1; ei = ei + 1;
} }
@@ -1118,7 +1288,8 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
has_signature = true; has_signature = true;
} }
if !has_signature && @enum2int(bid) == @enum2int(Builtin.None) && !native_callee { if !has_signature && @enum2int(bid) == @enum2int(Builtin.None) && !native_callee {
SemaM.sema_error_code_at(self, ref, ErrorCode.NotCallable, "callee is not a function", ""); SemaM.sema_error_code_at(self, ref, ErrorCode.NotCallable,
"callee is not a function", callee_label(self, x.callee));
} else if has_signature && x.args.len != param_count { } else if has_signature && x.args.len != param_count {
SemaM.sema_error_code_at(self, ref, ErrorCode.ArgCount, "argument count mismatch", ""); SemaM.sema_error_code_at(self, ref, ErrorCode.ArgCount, "argument count mismatch", "");
} }
@@ -1183,6 +1354,8 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
self.cur_fn_ref = saved_ref; self.cur_fn_ref = saved_ref;
self.cur_fn = sv; self.cur_fn = sv;
if is_macro { if is_macro {
// 宏已通过 @meta.error 报过诊断:不要再叠加“返回值无效”错误。
if self.had_error { ret; }
var cn = Bld.node_ptr(&self.hir, ref); var cn = Bld.node_ptr(&self.hir, ref);
if cn == null { ret; } if cn == null { ret; }
var code: Ref = 0; var code: Ref = 0;
@@ -1214,6 +1387,15 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
SemaM.set_tid(self, ref, LangType.make_unit(&self.types)); SemaM.set_tid(self, ref, LangType.make_unit(&self.types));
} else { SemaM.set_tid(self, ref, ret_tid); } } else { SemaM.set_tid(self, ref, ret_tid); }
}, },
.ShapeCall(x) => {
if self.shape_hooks.apply_expr == null {
SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape,
"shape apply hook missing", x.adapter);
ret;
}
var t = self.shape_hooks.apply_expr(self as *any, ref, x.adapter, x.shapes, x.args);
if t != 0 { SemaM.set_tid(self, ref, t); }
},
.CompoundAssign(x) => { .CompoundAssign(x) => {
sema_expr(self, x.lval, want); sema_expr(self, x.lval, want);
SemaM.mark_assigned(self, x.lval); SemaM.mark_assigned(self, x.lval);
@@ -1369,8 +1551,20 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
}, },
.Addr(x) => { .Addr(x) => {
sema_expr(self, x, 0); sema_expr(self, x, 0);
var t = want; var ot = SemaM.tid_of(self, x);
if t == 0 { t = LangType.make_ptr(&self.types, SemaM.tid_of(self, x)); } // want 只有在其 pointee 就是操作数类型、或操作数仍是 shape/关联类型时才采用;
// 否则 `&a` 会被 shape 的 `*W` 期望类型覆盖掉真实类型 *A。
var shape_like = false;
if self.shape_hooks.is_shape_lang != null {
shape_like = self.shape_hooks.is_shape_lang(self as *any, ot);
}
if LangType.is_assoc(&self.types, ot) { shape_like = true; }
var t: usize = 0;
if want != 0 && LangType.is_ptr(&self.types, want) {
var we = LangType.elem_of(&self.types, want);
if ot == 0 || we == ot || shape_like { t = want; }
}
if t == 0 { t = LangType.make_ptr(&self.types, ot); }
SemaM.set_tid(self, ref, t); SemaM.set_tid(self, ref, t);
}, },
.Deref(x) => { .Deref(x) => {
@@ -1623,9 +1817,12 @@ fn sema_stmt(self: *Sema, ref: Ref, ret_tid: usize) {
if n == null { ret; } if n == null { ret; }
match n.kind { match n.kind {
.Return(x) => { .Return(x) => {
sema_expr(self, x, ret_tid); // catch handler 的 tail 是 #ok payload,但里面的 ret 仍然返回外层函数。
var rt = self.ret_override;
if rt == 0 { rt = ret_tid; }
sema_expr(self, x, rt);
if x != 0 && !SemaM.current_fn_is_macro(self) { if x != 0 && !SemaM.current_fn_is_macro(self) {
SemaM.require_type(self, x, ret_tid, "return"); SemaM.require_type(self, x, rt, "return");
} }
}, },
.Defer(x) => { sema_stmt(self, x, ret_tid); SemaM.set_tid(self, ref, 0); }, .Defer(x) => { sema_stmt(self, x, ret_tid); SemaM.set_tid(self, ref, 0); },
@@ -1664,7 +1861,7 @@ fn sema_stmt(self: *Sema, ref: Ref, ret_tid: usize) {
} }
sema_expr(self, x.tail, ret_tid); sema_expr(self, x.tail, ret_tid);
}, },
_ => { sema_expr(self, ref, ret_tid); }, _ => { sema_expr(self, ref, 0); },
} }
} }
@@ -1675,3 +1872,35 @@ fn sema_body(self: *Sema, body: usize, ret_tid: usize) {
if body == 0 { ret; } if body == 0 { ret; }
sema_stmt(self, body, ret_tid); sema_stmt(self, body, ret_tid);
} }
fn in_patch_roots(self: *Sema, ref: Ref): bool {
var i: usize = 0;
while i < self.shape_state.patch_roots.len {
if (self.shape_state.patch_roots.data as *Ref)[i] == ref { ret true; }
i = i + 1;
}
ret false;
}
// 实例化 patch:只重解析依赖 shape 形参的语句,其余节点保留模板分析结果。
fn patch_body(user: *any, body: usize, ret_tid: usize) {
var self = user as *Sema;
if body == 0 { ret; }
var n = Bld.node_ptr(&self.hir, body);
if n == null { ret; }
match n.kind {
.Block(b) => {
var i: usize = 0;
while i < b.stmts.len {
if in_patch_roots(self, b.stmts[i]) { sema_stmt(self, b.stmts[i], ret_tid); }
i = i + 1;
}
if b.tail != 0 && in_patch_roots(self, b.tail) {
sema_expr(self, b.tail, ret_tid);
}
},
_ => {
if in_patch_roots(self, body) { sema_stmt(self, body, ret_tid); }
},
}
}
+117 -9
View File
@@ -22,7 +22,7 @@ type .{
.TypeHooks, .GenBind, .GenBindRec, .GenInstance, .ShapeParam, .ShapeInstance, .TypeHooks, .GenBind, .GenBindRec, .GenInstance, .ShapeParam, .ShapeInstance,
.ShapeUse, .ShapeAssocType, .ShapeComp, .IterInfo, .ShapeAdapterResult, .CtFnRef, .ShapeUse, .ShapeAssocType, .ShapeComp, .IterInfo, .ShapeAdapterResult, .CtFnRef,
.ContainerLang, .LangConform, .ShapeBind, .ShapeAdapterEval, .ShapeTypeBind, .ContainerLang, .LangConform, .ShapeBind, .ShapeAdapterEval, .ShapeTypeBind,
.ShapeState, .ShapeCallResult, .ShapeHooks, .HookParamResult, .HookHooks, .CtState, .ShapeArgBind, .ShapeState, .ShapeCallResult, .ShapeHooks, .HookParamResult, .HookHooks, .CtState,
.Decl, .DeclKind, .DeclState, .FnSym, .Binding, .TypeSym, .GlobalSym .Decl, .DeclKind, .DeclState, .FnSym, .Binding, .TypeSym, .GlobalSym
} = @import("./sema.spl"); } = @import("./sema.spl");
type tid = usize; type tid = usize;
@@ -30,6 +30,7 @@ type tid = usize;
fn hook_resolve_type(user: *any, ref: Ref): usize { ret resolve_type(user as *Sema, ref); } fn hook_resolve_type(user: *any, ref: Ref): usize { ret resolve_type(user as *Sema, ref); }
fn hook_resolve_param(user: *any, ref: Ref): usize { ret resolve_param(user as *Sema, ref); } fn hook_resolve_param(user: *any, ref: Ref): usize { ret resolve_param(user as *Sema, ref); }
fn hook_type_gen(user: *any, ref: Ref, x: Node.Kind.Call, self_lang: usize): usize { ret type_gen_lang(user as *Sema, ref, x, self_lang); } fn hook_type_gen(user: *any, ref: Ref, x: Node.Kind.Call, self_lang: usize): usize { ret type_gen_lang(user as *Sema, ref, x, self_lang); }
fn hook_type_is_generator(user: *any, fn_ref: Ref): bool { ret is_type_generator_decl(user as *Sema, fn_ref); }
fn hook_type_arg_lang(user: *any, ref: Ref): usize { ret type_arg_lang(user as *Sema, ref); } fn hook_type_arg_lang(user: *any, ref: Ref): usize { ret type_arg_lang(user as *Sema, ref); }
fn hook_type_value_lang(user: *any, ref: Ref): usize { ret type_value_lang(user as *Sema, ref); } fn hook_type_value_lang(user: *any, ref: Ref): usize { ret type_value_lang(user as *Sema, ref); }
fn hook_type_handle_arg(user: *any, a0: usize): usize { ret type_handle_arg(user as *Sema, a0); } fn hook_type_handle_arg(user: *any, a0: usize): usize { ret type_handle_arg(user as *Sema, a0); }
@@ -51,6 +52,7 @@ fn hooks(): TypeHooks {
.resolve_param = hook_resolve_param, .resolve_param = hook_resolve_param,
.type_gen = hook_type_gen, .type_gen = hook_type_gen,
.instantiate_generator = hook_instantiate_generator, .instantiate_generator = hook_instantiate_generator,
.type_is_generator = hook_type_is_generator,
.type_arg_lang = hook_type_arg_lang, .type_arg_lang = hook_type_arg_lang,
.type_value_lang = hook_type_value_lang, .type_value_lang = hook_type_value_lang,
.type_handle_arg = hook_type_handle_arg, .type_handle_arg = hook_type_handle_arg,
@@ -68,11 +70,13 @@ fn hooks(): TypeHooks {
fn main() {} fn main() {}
fn gen_find(self: *Sema, name: []u8): usize { fn gen_find(self: *Sema, name: []u8): usize {
var i: usize = 0; // gen_binds 是栈:外层生成器先入栈,内层后入栈。同名参数必须命中内层,
while i < self.gen_binds.len { // 否则 `@Result(@self, ...)` 内层的 T 会被外层 Vec/Box 的 T 覆盖。
var i = self.gen_binds.len;
while i > 0 {
i = i - 1;
var b = (self.gen_binds.data as *GenBind) + i; var b = (self.gen_binds.data as *GenBind) + i;
if SemaM.eq(b.name, name) { ret i + 1; } if SemaM.eq(b.name, name) { ret i + 1; }
i = i + 1;
} }
ret 0; ret 0;
} }
@@ -165,6 +169,23 @@ fn gen_instance_push(self: *Sema, fn_ref: Ref, args: []usize, lang: usize) {
// comptime fn `f(params...) type { ... }`:先查生成器声明的内建表示; // comptime fn `f(params...) type { ... }`:先查生成器声明的内建表示;
// 命中 `#repr(...)` 就构造内建布局,否则实例化声明体。 // 命中 `#repr(...)` 就构造内建布局,否则实例化声明体。
// 只有返回 type 的用户 comptime fn 才是类型生成器;内置/外部函数即使
// 声明返回 type(如 @type_of)也不能被克隆求值。
fn is_type_generator_decl(self: *Sema, fn_ref: Ref): bool {
var n = Bld.node_ptr(&self.hir, fn_ref);
if n == null { ret false; }
var ct = false;
var rt: Ref = 0;
match n.kind {
.FnDecl(f) => { ct = f.is_comptime; rt = f.ret_ty; },
_ => {},
}
if !ct || rt == 0 { ret false; }
if SemaM.has_builtin_tag(self, fn_ref) { ret false; }
if SemaM.has_tag(self, fn_ref, "extern") { ret false; }
ret LangType.is_type(&self.types, resolve_type(self, rt));
}
fn type_gen_lang(self: *Sema, ref: Ref, x: Node.Kind.Call, self_lang: usize): usize { fn type_gen_lang(self: *Sema, ref: Ref, x: Node.Kind.Call, self_lang: usize): usize {
var cn = Bld.node_ptr(&self.hir, x.callee); var cn = Bld.node_ptr(&self.hir, x.callee);
if cn == null { ret 0; } if cn == null { ret 0; }
@@ -235,15 +256,17 @@ fn instantiate_generator(self: *Sema, ref: Ref, x: Node.Kind.Call, di: usize, se
var base = self.gen_binds.len; var base = self.gen_binds.len;
var key = Vec.blank(@sizeof(usize), @alignof(usize)); var key = Vec.blank(@sizeof(usize), @alignof(usize));
var key_ok = true; var key_ok = true;
var bad_bound = false;
var j: usize = 0; var j: usize = 0;
while j < params.len { while j < params.len {
var pn = Bld.node_ptr(&self.hir, params[j]); var pn = Bld.node_ptr(&self.hir, params[j]);
if pn == null { break; } if pn == null { break; }
var pname: []u8 = ""; var pname: []u8 = "";
var pty: usize = 0; var pty: usize = 0;
var pty_ref: Ref = 0;
var got = false; var got = false;
match pn.kind { match pn.kind {
.ParamDecl(p) => { pname = p.name; pty = resolve_type(self, p.ty); got = true; }, .ParamDecl(p) => { pname = p.name; pty_ref = p.ty; pty = resolve_type(self, p.ty); got = true; },
_ => {}, _ => {},
} }
if !got { break; } if !got { break; }
@@ -255,11 +278,68 @@ fn instantiate_generator(self: *Sema, ref: Ref, x: Node.Kind.Call, di: usize, se
if al == 0 { key_ok = false; } if al == 0 { key_ok = false; }
match Vec.push(&key, &al as *u8) { .Ok => {}, .Err(error) => {} } match Vec.push(&key, &al as *u8) { .Ok => {}, .Err(error) => {} }
gen_push(self, pname, true, al, 0); gen_push(self, pname, true, al, 0);
} else { } else if self.shape_hooks.is_shape_lang != null &&
// 值实参可能是调用方的 const 表达式,同样在调用方模块求值。 self.shape_hooks.is_shape_lang(self as *any, pty) {
// shape 约束的类型参数:实参在调用方模块解析,约束在生成器模块求值。
if dmod != saved { SemaM.switch_mod(self, saved); } if dmod != saved { SemaM.switch_mod(self, saved); }
var av = lit_u64(self, x.args[j]) as usize; var al = type_arg_lang(self, x.args[j]);
if dmod != saved { SemaM.switch_mod(self, dmod); }
if al == 0 {
SemaM.sema_error_code_at(self, x.args[j], ErrorCode.TypeMismatch,
"cannot resolve type argument", pname);
key_ok = false;
bad_bound = true;
} else {
var sb = ShapeArgBind { .ok = false, .lang = 0 };
var saved_ct_ref = self.ct_call_ref;
var saved_ct_mod = self.ct_call_mod;
self.ct_call_ref = x.args[j];
self.ct_call_mod = saved;
if self.shape_hooks.bind_type_arg != null {
self.shape_hooks.bind_type_arg(self as *any, pty_ref, al, &sb);
}
self.ct_call_ref = saved_ct_ref;
self.ct_call_mod = saved_ct_mod;
if sb.ok {
match Vec.push(&key, &sb.lang as *u8) { .Ok => {}, .Err(error) => {} }
gen_push(self, pname, true, sb.lang, 0);
} else {
key_ok = false;
bad_bound = true;
}
}
} else {
// 值实参可能是外层生成器参数,必须直接从 gen_binds 取值;
// lit_u64/const_eval_usize 不认识生成器绑定,会退化成 0。
if dmod != saved { SemaM.switch_mod(self, saved); }
var av: usize = 0;
var resolved = false;
var an = Bld.node_ptr(&self.hir, x.args[j]); var an = Bld.node_ptr(&self.hir, x.args[j]);
if an != null {
match an.kind {
.Local(p) => {
var pn = Bld.node_ptr(&self.hir, p);
if pn != null {
match pn.kind {
.ParamDecl(pd) => {
var gi = gen_find(self, pd.name);
if gi != 0 {
var gb = (self.gen_binds.data as *GenBind) + (gi - 1);
if !gb.is_type {
av = gb.value;
resolved = true;
}
}
},
_ => {},
}
}
},
_ => {},
}
}
if !resolved {
av = lit_u64(self, x.args[j]) as usize;
var is_lit = false; var is_lit = false;
if an != null { if an != null {
match an.kind { match an.kind {
@@ -272,12 +352,19 @@ fn instantiate_generator(self: *Sema, ref: Ref, x: Node.Kind.Call, di: usize, se
} }
} }
if !is_lit && av == 0 { av = const_eval_usize(self, x.args[j]); } if !is_lit && av == 0 { av = const_eval_usize(self, x.args[j]); }
}
if dmod != saved { SemaM.switch_mod(self, dmod); } if dmod != saved { SemaM.switch_mod(self, dmod); }
match Vec.push(&key, &av as *u8) { .Ok => {}, .Err(error) => {} } match Vec.push(&key, &av as *u8) { .Ok => {}, .Err(error) => {} }
gen_push(self, pname, false, 0, av); gen_push(self, pname, false, 0, av);
} }
j = j + 1; j = j + 1;
} }
if bad_bound {
Vec.drop(&key);
self.gen_binds.len = base;
if dmod != saved { SemaM.switch_mod(self, saved); }
ret 0;
}
if key_ok && key.len == params.len { if key_ok && key.len == params.len {
var cached = gen_instance_find(self, SemaM.decl_at(self, di).node, var cached = gen_instance_find(self, SemaM.decl_at(self, di).node,
(key.data as *usize)[0..key.len]); (key.data as *usize)[0..key.len]);
@@ -291,11 +378,13 @@ fn instantiate_generator(self: *Sema, ref: Ref, x: Node.Kind.Call, di: usize, se
// 每次实例化克隆生成器体:方法 FnDecl 和 @self 必须按实例隔离, // 每次实例化克隆生成器体:方法 FnDecl 和 @self 必须按实例隔离,
// 否则不同实参共用同一组方法节点和 gen_binds 记录。 // 否则不同实参共用同一组方法节点和 gen_binds 记录。
var inst_body = body; var inst_body = body;
var clone_start = Bld.count(&self.hir);
if body != 0 { if body != 0 {
var clone_state = NodeClone.new(); var clone_state = NodeClone.new();
inst_body = NodeClone.clone_ref(&self.hir, &clone_state, body); inst_body = NodeClone.clone_ref(&self.hir, &clone_state, body);
NodeClone.drop(&clone_state); NodeClone.drop(&clone_state);
} }
SemaM.record_new_ref_mods(self, dmod, clone_start);
var saved_self = self.self_lang; var saved_self = self.self_lang;
if self_lang != 0 { self.self_lang = self_lang; } if self_lang != 0 { self.self_lang = self_lang; }
var lang = gen_eval_body(self, inst_body); var lang = gen_eval_body(self, inst_body);
@@ -719,7 +808,20 @@ fn resolve_type(self: *Sema, ref: Ref): usize {
SemaM.set_tid(self, ref, t); SemaM.set_tid(self, ref, t);
ret t; ret t;
}, },
.ShapeNoDefault(xs) => {
if xs.len == 0 { ret 0; }
var t = resolve_type(self, xs[0]);
SemaM.set_tid(self, ref, t);
ret t;
},
.AggType(x) => { .AggType(x) => {
var existing = SemaM.container_lang_find(self, ref);
// 同一个聚合节点只对应一个 lang。生成结构体被多个模块重复解析时,
// 重新 make_struct 会产生不同 cmod 的副本,进而重复注册方法 Decl。
if existing != 0 {
SemaM.set_tid(self, ref, existing);
ret existing;
}
var members = Vec.blank(@sizeof(StructMember), @alignof(StructMember)); var members = Vec.blank(@sizeof(StructMember), @alignof(StructMember));
var i: usize = 0; var i: usize = 0;
while i < x.fields.len { while i < x.fields.len {
@@ -749,7 +851,13 @@ fn resolve_type(self: *Sema, ref: Ref): usize {
} else { } else {
t = LangType.make_struct(&self.types, members); t = LangType.make_struct(&self.types, members);
} }
LangType.set_container(&self.types, t, self.cur_mod, ref); // 生成类型的模块身份取声明它的节点所在模块,不能取当前分析模块;
// 否则同一个生成 struct 在不同模块被重新解析时会得到不同的 cmod,
// 其方法签名里的模块私有类型就会解析失败。
var cmod = self.cur_mod;
var ri = SemaM.ref_info(self, ref);
if ri != null && ri.mod != 0 { cmod = ri.mod - 1; }
LangType.set_container(&self.types, t, cmod, ref);
SemaM.set_container_lang(self, ref, t, false); SemaM.set_container_lang(self, ref, t, false);
// 实例化生成 struct:把参数绑定记到它的每个方法上,供分析方法体时重新激活。 // 实例化生成 struct:把参数绑定记到它的每个方法上,供分析方法体时重新激活。
if self.gen_binds.len > 0 { if self.gen_binds.len > 0 {
+495 -28
View File
@@ -16,13 +16,15 @@ type ShapeInstance = SemaM.ShapeInstance;
type ShapeUse = SemaM.ShapeUse; type ShapeUse = SemaM.ShapeUse;
type ShapeAdapterResult = SemaM.ShapeAdapterResult; type ShapeAdapterResult = SemaM.ShapeAdapterResult;
type ShapeAdapterEval = SemaM.ShapeAdapterEval; type ShapeAdapterEval = SemaM.ShapeAdapterEval;
type ShapeArgBind = SemaM.ShapeArgBind;
type ShapeTypeBind = SemaM.ShapeTypeBind; type ShapeTypeBind = SemaM.ShapeTypeBind;
type CtFnRef = SemaM.CtFnRef; type CtFnRef = SemaM.CtFnRef;
type Decl = SemaM.Decl; type Decl = SemaM.Decl;
type ShapeCallResult = SemaM.ShapeCallResult; type ShapeCallResult = SemaM.ShapeCallResult;
type ShapeHooks = SemaM.ShapeHooks; type ShapeHooks = SemaM.ShapeHooks;
type ShapeComp = SemaM.ShapeComp;
type ShapeBind = SemaM.ShapeBind; type ShapeBind = SemaM.ShapeBind;
type ShapeComp = SemaM.ShapeComp;
type RefInfo = SemaM.RefInfo;
fn shape_bind_find(binds: *Vec, name: []u8): usize { fn shape_bind_find(binds: *Vec, name: []u8): usize {
var i: usize = 0; var i: usize = 0;
@@ -55,6 +57,7 @@ fn shape_use_shape_count(self: *Sema, ref: Ref): usize {
if n == null { ret 0; } if n == null { ret 0; }
match n.kind { match n.kind {
.ShapeUse(x) => { ret x.shapes.len; }, .ShapeUse(x) => { ret x.shapes.len; },
.ShapeNoDefault(xs) => { ret xs.len; },
_ => {}, _ => {},
} }
ret 1; ret 1;
@@ -68,6 +71,10 @@ fn shape_use_shape_at(self: *Sema, ref: Ref, i: usize): Ref {
if i < x.shapes.len { ret x.shapes[i]; } if i < x.shapes.len { ret x.shapes[i]; }
ret 0; ret 0;
}, },
.ShapeNoDefault(xs) => {
if i < xs.len { ret xs[i]; }
ret 0;
},
_ => {}, _ => {},
} }
if i == 0 { ret ref; } if i == 0 { ret ref; }
@@ -338,13 +345,15 @@ fn compose_shapes(self: *Sema, use_ref: Ref): usize {
} }
fn shape_use_of(self: *Sema, ty_ref: Ref): ShapeUse { fn shape_use_of(self: *Sema, ty_ref: Ref): ShapeUse {
var out = ShapeUse { .is_shape = false, .adapter_decl = 0, .shape_lang = 0, .shape_ref = 0 }; var out = ShapeUse { .is_shape = false, .has_adapter = false, .adapter_decl = 0, .shape_lang = 0, .shape_ref = 0 };
if ty_ref == 0 { ret out; } if ty_ref == 0 { ret out; }
var n = Bld.node_ptr(&self.hir, ty_ref); var n = Bld.node_ptr(&self.hir, ty_ref);
if n == null { ret out; } if n == null { ret out; }
var adapter_name: []u8 = ""; var adapter_name: []u8 = "";
var no_default = false;
match n.kind { match n.kind {
.ShapeUse(x) => { adapter_name = x.adapter; }, .ShapeUse(x) => { adapter_name = x.adapter; },
.ShapeNoDefault(_) => { no_default = true; },
_ => { _ => {
var old = at_tag_name(self, ty_ref); var old = at_tag_name(self, ty_ref);
if old.len != 0 { if old.len != 0 {
@@ -355,9 +364,16 @@ fn shape_use_of(self: *Sema, ty_ref: Ref): ShapeUse {
}, },
} }
if shape_use_shape_count(self, ty_ref) == 0 { ret out; } if shape_use_shape_count(self, ty_ref) == 0 { ret out; }
// 空 adapter 的普通 shape 列表是类型参数上的纯编译期约束;
// @[Shape] 是无默认 adapter 的运行期 shape 参数。
if adapter_name.len == 0 && !no_default { ret out; }
var first = shape_use_shape_at(self, ty_ref, 0); var first = shape_use_shape_at(self, ty_ref, 0);
var shape_lang = SemaM.type_arg_lang(self, first); var shape_lang = SemaM.type_arg_lang(self, first);
if shape_lang != 0 && !is_shape_lang(self, shape_lang) { var base_shape = shape_lang;
if LangType.is_ptr(&self.types, base_shape) {
base_shape = LangType.elem_of(&self.types, base_shape);
}
if shape_lang != 0 && !is_shape_lang(self, base_shape) {
SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape, "shape parameter type is not a shape", adapter_name); SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape, "shape parameter type is not a shape", adapter_name);
ret out; ret out;
} }
@@ -367,15 +383,35 @@ fn shape_use_of(self: *Sema, ty_ref: Ref): ShapeUse {
if composed == 0 { ret out; } if composed == 0 { ret out; }
shape_lang = composed; shape_lang = composed;
} }
if no_default {
out = ShapeUse { .is_shape = true, .has_adapter = false, .adapter_decl = 0,
.shape_lang = shape_lang, .shape_ref = ty_ref };
ret out;
}
var d = find_shape_adapter(self, adapter_name); var d = find_shape_adapter(self, adapter_name);
if d == 0 { ret out; } if d == 0 { ret out; }
out = ShapeUse { .is_shape = true, .adapter_decl = d - 1, out = ShapeUse { .is_shape = true, .has_adapter = true, .adapter_decl = d - 1,
.shape_lang = shape_lang, .shape_ref = ty_ref }; .shape_lang = shape_lang, .shape_ref = ty_ref };
ret out; ret out;
} }
// 声明期:把每个 shape 形参的 adapter/shape 固定下来;原函数体按 shape 做类型检查。 // 空 adapter 的 shape 列表是类型参数约束,不是运行期 shape 参数。
fn is_empty_shape_use(self: *Sema, ref: Ref): bool {
var n = Bld.node_ptr(&self.hir, ref);
if n == null { ret false; }
match n.kind {
.ShapeUse(x) => { ret x.adapter.len == 0; },
.ShapeNoDefault(_) => { ret false; },
_ => {},
}
ret false;
}
// 声明期:把每个运行期 shape 形参的 adapter/shape 固定下来;原函数体按 shape 做类型检查。
fn bind_shape_params(self: *Sema, fn_ref: Ref, params: []Ref) { fn bind_shape_params(self: *Sema, fn_ref: Ref, params: []Ref) {
// 类型生成器的形参是类型/编译期值,不是运行期 shape 参数;
// 其约束由 sema_type.instantiate_generator 统一处理。
if SemaM.type_is_generator(self, fn_ref) { ret; }
var j: usize = 0; var j: usize = 0;
while j < params.len { while j < params.len {
var pn = Bld.node_ptr(&self.hir, params[j]); var pn = Bld.node_ptr(&self.hir, params[j]);
@@ -387,11 +423,15 @@ fn bind_shape_params(self: *Sema, fn_ref: Ref, params: []Ref) {
SemaM.set_tid(self, p.ty, su.shape_lang); SemaM.set_tid(self, p.ty, su.shape_lang);
if shape_param_at(self, fn_ref, j) == 0 { if shape_param_at(self, fn_ref, j) == 0 {
var sp = ShapeParam { .fn_ref = fn_ref, .param_index = j, var sp = ShapeParam { .fn_ref = fn_ref, .param_index = j,
.has_adapter = su.has_adapter,
.adapter_decl = su.adapter_decl, .adapter_decl = su.adapter_decl,
.shape_lang = su.shape_lang, .shape_lang = su.shape_lang,
.shape_ref = su.shape_ref }; .shape_ref = su.shape_ref };
match Vec.push(&self.shape_state.params, &sp as *u8) { .Ok => {}, .Err(e) => {} } match Vec.push(&self.shape_state.params, &sp as *u8) { .Ok => {}, .Err(e) => {} }
} }
} else if is_empty_shape_use(self, p.ty) {
SemaM.sema_error_code_at(self, p.ty, ErrorCode.ShapeParamNotShape,
"shape list is only valid on a type parameter", "");
} }
}, },
_ => {}, _ => {},
@@ -461,8 +501,7 @@ fn shape_adapter_eval_type(self: *Sema, adi: usize, arg_lang: usize, shape_lang:
_ => {}, _ => {},
} }
if adapter_ref == 0 { if adapter_ref == 0 {
// Ref 0 表示 identity:不生成 wrapper,装箱类型就是实参类型。 SemaM.sema_error_code(self, ErrorCode.ImplHookBadReturn, "shape adapter returned Ref 0", "");
out.lang = arg_lang;
ret out; ret out;
} }
// 非 0 的包装函数必须由本次 hook 执行生成;旧节点或任意小整数 Ref 不是 wrapper。 // 非 0 的包装函数必须由本次 hook 执行生成;旧节点或任意小整数 Ref 不是 wrapper。
@@ -512,21 +551,51 @@ fn shape_adapter_eval_type(self: *Sema, adi: usize, arg_lang: usize, shape_lang:
} }
// 适配器返回 `(type, wrapper)`:执行 comptime 调用,读取真实结果。 // 适配器返回 `(type, wrapper)`:执行 comptime 调用,读取真实结果。
fn adapter_eval_for(self: *Sema, adi: usize, arg_lang: usize,
shape_lang: usize): ShapeAdapterEval {
var out = ShapeAdapterEval { .lang = 0, .wrapper_sym = 0, .adapter_ref = 0 };
var saved = self.cur_mod;
var amod = SemaM.decl_at(self, adi).mod;
if amod != saved { SemaM.switch_mod(self, amod); }
SemaM.ensure_decl(self, adi);
out = shape_adapter_eval_type(self, adi, arg_lang, shape_lang);
if amod != saved { SemaM.switch_mod(self, saved); }
ret out;
}
fn shape_adapter_result(self: *Sema, sp_i: usize, arg_lang: usize): ShapeAdapterResult { fn shape_adapter_result(self: *Sema, sp_i: usize, arg_lang: usize): ShapeAdapterResult {
var out = ShapeAdapterResult { .lang = 0, .wrapper_sym = 0, .adapter_ref = 0, .adapter_mod = 0 }; var out = ShapeAdapterResult { .lang = 0, .wrapper_sym = 0, .adapter_ref = 0, .adapter_mod = 0 };
if sp_i == 0 || sp_i > self.shape_state.params.len { ret out; } if sp_i == 0 || sp_i > self.shape_state.params.len { ret out; }
var sp = (self.shape_state.params.data as *ShapeParam) + (sp_i - 1); var sp = (self.shape_state.params.data as *ShapeParam) + (sp_i - 1);
var saved = self.cur_mod;
var adi = sp.adapter_decl; var adi = sp.adapter_decl;
var amod = SemaM.decl_at(self, adi).mod; var amod = SemaM.decl_at(self, adi).mod;
if amod != saved { SemaM.switch_mod(self, amod); } var ev = adapter_eval_for(self, adi, arg_lang, sp.shape_lang);
SemaM.ensure_decl(self, adi);
var ev = shape_adapter_eval_type(self, adi, arg_lang, sp.shape_lang);
out = ShapeAdapterResult { .lang = ev.lang, .wrapper_sym = ev.wrapper_sym, .adapter_ref = ev.adapter_ref, .adapter_mod = amod }; out = ShapeAdapterResult { .lang = ev.lang, .wrapper_sym = ev.wrapper_sym, .adapter_ref = ev.adapter_ref, .adapter_mod = amod };
if amod != saved { SemaM.switch_mod(self, saved); }
ret out; ret out;
} }
// 类型生成器形参的约束入口:普通 shape / ShapeApply / 组合列表 / adapter 形式
// 都走这里,避免在 sema_type 里散落 shape 规则。
fn bind_type_arg(user: *any, ty_ref: Ref, arg_lang: usize, out: *ShapeArgBind) {
var self = user as *Sema;
out.ok = false;
out.lang = 0;
if ty_ref == 0 || arg_lang == 0 { ret; }
var adapter_name: []u8 = "";
var n = Bld.node_ptr(&self.hir, ty_ref);
if n != null {
match n.kind {
.ShapeUse(x) => { adapter_name = x.adapter; },
_ => {},
}
}
if !shape_conforms_use(self, ty_ref, arg_lang) { ret; }
// 类型参数只存在于编译期;adapter 是运行期 shape 参数的概念,
// 这里只做 shape 约束匹配,不执行转换。
out.ok = true;
out.lang = arg_lang;
}
// shape 类型与目标方法的签名匹配;关联类型从 binds 取,不做推断。 // shape 类型与目标方法的签名匹配;关联类型从 binds 取,不做推断。
fn shape_type_match(self: *Sema, a: usize, b: usize, shape_lang: usize, value_lang: usize, fn shape_type_match(self: *Sema, a: usize, b: usize, shape_lang: usize, value_lang: usize,
binds: *Vec, reported: *bool): bool { binds: *Vec, reported: *bool): bool {
@@ -658,21 +727,45 @@ fn shape_conforms_use(self: *Sema, use_ref: Ref, value_lang: usize): bool {
// 目标类型是否具备 shape 声明里的方法名与签名;方法体在实例化后继续分析。 // 目标类型是否具备 shape 声明里的方法名与签名;方法体在实例化后继续分析。
fn shape_conforms(self: *Sema, shape_ref: Ref, value_lang: usize): bool { fn shape_conforms(self: *Sema, shape_ref: Ref, value_lang: usize): bool {
var shape_lang = SemaM.resolve_type(self, shape_ref); var shape_lang = SemaM.resolve_type(self, shape_ref);
var want_ptr = false;
if LangType.is_ptr(&self.types, shape_lang) {
var inner = LangType.elem_of(&self.types, shape_lang);
if is_shape_lang(self, inner) {
shape_lang = inner;
want_ptr = true;
}
}
if shape_lang == 0 || !is_shape_lang(self, shape_lang) { if shape_lang == 0 || !is_shape_lang(self, shape_lang) {
SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape, SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape,
"shape parameter type is not a shape", ""); "shape parameter type is not a shape", "");
ret false; ret false;
} }
var vl = value_lang;
if want_ptr {
// `*Shape` 要求实参也是指针;指针深度必须匹配。
if !LangType.is_ptr(&self.types, vl) {
SemaM.sema_error_code(self, ErrorCode.ShapeMismatch,
"pointer shape requires a pointer argument", "");
ret false;
}
vl = LangType.elem_of(&self.types, vl);
}
var binds = Vec.blank(@sizeof(ShapeBind), @alignof(ShapeBind)); var binds = Vec.blank(@sizeof(ShapeBind), @alignof(ShapeBind));
defer { Vec.drop(&binds); } defer { Vec.drop(&binds); }
if !shape_apply_binds(self, shape_ref, &binds) { ret false; } var inner_ref = shape_ref;
if !shape_marker_binds(self, value_lang, shape_lang, &binds) { ret false; } var srn = Bld.node_ptr(&self.hir, shape_ref);
if srn != null {
match srn.kind { .PtrType(x) => { inner_ref = x; }, _ => {} }
}
if !shape_apply_binds(self, inner_ref, &binds) { ret false; }
if !shape_marker_binds(self, vl, shape_lang, &binds) { ret false; }
if !shape_assoc_names_bound(self, shape_lang, &binds) { ret false; } if !shape_assoc_names_bound(self, shape_lang, &binds) { ret false; }
ret shape_conforms_with(self, shape_lang, value_lang, &binds); ret shape_conforms_with(self, shape_lang, vl, &binds);
} }
fn shape_conforms_with(self: *Sema, shape_lang: usize, value_lang: usize, fn shape_conforms_with(self: *Sema, shape_lang: usize, value_lang: usize,
binds: *Vec): bool { binds: *Vec): bool {
var vl = value_lang;
var cont = LangType.container_of(&self.types, shape_lang); var cont = LangType.container_of(&self.types, shape_lang);
if cont == 0 { ret true; } if cont == 0 { ret true; }
var n = Bld.node_ptr(&self.hir, cont); var n = Bld.node_ptr(&self.hir, cont);
@@ -695,18 +788,18 @@ fn shape_conforms_with(self: *Sema, shape_lang: usize, value_lang: usize,
} }
var want_tid = SemaM.sym_at(self, want - 1).fn_tid; var want_tid = SemaM.sym_at(self, want - 1).fn_tid;
var reported = false; var reported = false;
var got = SemaM.method_sym(self, value_lang, f.name); var got = SemaM.method_sym(self, vl, f.name);
var got_tid: usize = 0; var got_tid: usize = 0;
if got != 0 { got_tid = SemaM.sym_at(self, got - 1).fn_tid; } if got != 0 { got_tid = SemaM.sym_at(self, got - 1).fn_tid; }
var matched = false; var matched = false;
if got != 0 { if got != 0 {
matched = shape_type_match(self, want_tid, matched = shape_type_match(self, want_tid,
SemaM.sym_at(self, got - 1).fn_tid, SemaM.sym_at(self, got - 1).fn_tid,
shape_lang, value_lang, shape_lang, vl,
binds, &reported); binds, &reported);
} else { } else {
// dyn 表允许用同名字段承载方法类型。 // dyn 表允许用同名字段承载方法类型。
var field_idx = LangType.member_idx(&self.types, value_lang, f.name); var field_idx = LangType.member_idx(&self.types, vl, f.name);
if field_idx < 0 { if field_idx < 0 {
SemaM.sema_error_code(self, ErrorCode.ShapeMethodMissing, SemaM.sema_error_code(self, ErrorCode.ShapeMethodMissing,
"shape method is missing", f.name); "shape method is missing", f.name);
@@ -714,15 +807,20 @@ fn shape_conforms_with(self: *Sema, shape_lang: usize, value_lang: usize,
break; break;
} }
matched = shape_type_match(self, want_tid, matched = shape_type_match(self, want_tid,
LangType.member_lang(&self.types, value_lang, LangType.member_lang(&self.types, vl,
field_idx as usize), field_idx as usize),
shape_lang, value_lang, shape_lang, vl,
binds, &reported); binds, &reported);
} }
if !matched { if !matched {
if !reported { if !reported {
var db = ByteBuffer.new();
defer { ByteBuffer.drop(&db); }
SemaM.append_type_name(self, &db, vl);
ByteBuffer.append(&db, " vs ");
SemaM.append_type_name(self, &db, value_lang);
SemaM.sema_error_code(self, ErrorCode.ShapeMismatch, SemaM.sema_error_code(self, ErrorCode.ShapeMismatch,
"shape method signature mismatch", f.name); "shape method signature mismatch", ByteBuffer.as_slice(db));
} }
ok = false; ok = false;
break; break;
@@ -736,12 +834,12 @@ fn shape_conforms_with(self: *Sema, shape_lang: usize, value_lang: usize,
}, },
_ => {}, _ => {},
} }
if ok && value_lang != shape_lang { if ok && vl != shape_lang {
match n.kind { match n.kind {
.AggType(a) => { .AggType(a) => {
var pi: usize = 0; var pi: usize = 0;
while pi < a.conforms.len { while pi < a.conforms.len {
if !shape_conforms(self, a.conforms[pi], value_lang) { if !shape_conforms(self, a.conforms[pi], vl) {
ok = false; ok = false;
break; break;
} }
@@ -800,7 +898,15 @@ fn check_conforms(user: *any, agg_ref: Ref, value_lang: usize) {
} }
fn shape_type_node(self: *Sema, lang: usize): usize { fn shape_type_node(self: *Sema, lang: usize): usize {
var r = Bld.construct(&self.hir, .{ .kind = .NamedType("__shape_ty") }); var r: Ref = 0;
// hook 只能 inspect 语法节点;指针 shape 实例必须露出 PtrType,
// 否则 @Self 看不到形参已经是指针并会再次取地址。
if LangType.is_ptr(&self.types, lang) {
var inner = shape_type_node(self, LangType.elem_of(&self.types, lang));
r = Bld.construct(&self.hir, .{ .kind = .PtrType(inner) });
} else {
r = Bld.construct(&self.hir, .{ .kind = .NamedType("__shape_ty") });
}
SemaM.grow_tables(self); SemaM.grow_tables(self);
SemaM.set_tid(self, r, lang); SemaM.set_tid(self, r, lang);
ret r; ret r;
@@ -877,7 +983,218 @@ fn insert_shape_box(self: *Sema, arg: usize, ret_lang: usize, wrapper_sym: usize
ret call; ret call;
} }
fn shape_instance_matches(self: *Sema, si: *ShapeInstance, fn_ref: Ref, args: []usize): bool { // 实例去重 key:模板 + adapter 转换结果类型。
// 暂不做结构去重;Shape 依赖节点在实例化时重解析,key 未来需要纳入解析结果时改这里。
// ---- 实例化依赖 patch ----
fn copy_clone_refinfo(self: *Sema, st: *NodeClone.CloneState) {
SemaM.grow_tables(self);
var i: usize = 0;
while i < st.olds.len {
var o = (st.olds.data as *Ref)[i];
var nw = (st.news.data as *Ref)[i];
if o != 0 && o < self.refs.len && nw < self.refs.len {
var src = (self.refs.data as *RefInfo) + o;
var dst = (self.refs.data as *RefInfo) + nw;
dst.* = src.*;
// 模板 Def 属于模板函数的槽位;实例必须重新分配。
dst.def = 0;
}
i = i + 1;
}
}
fn lang_shape_dep(self: *Sema, t: usize, depth: usize): bool {
if t == 0 || depth > 4 { ret false; }
if is_shape_lang(self, t) || LangType.is_assoc(&self.types, t) { ret true; }
var k = LangType.kind_of(&self.types, t);
match k {
.Ptr, .Slice => { ret lang_shape_dep(self, LangType.elem_of(&self.types, t), depth + 1); },
.Array => { ret lang_shape_dep(self, LangType.elem_of(&self.types, t), depth + 1); },
.Fn => {
var i: usize = 0;
while i < LangType.fn_param_count(&self.types, t) {
if lang_shape_dep(self, LangType.fn_param_of(&self.types, t, i), depth + 1) { ret true; }
i = i + 1;
}
ret lang_shape_dep(self, LangType.fn_ret_of(&self.types, t), depth + 1);
},
.Struct, .Union, .Enum => {
var i: usize = 0;
while i < LangType.member_count(&self.types, t) {
if lang_shape_dep(self, LangType.member_lang(&self.types, t, i), depth + 1) { ret true; }
i = i + 1;
}
},
_ => {},
}
ret false;
}
fn any_shape_dep(self: *Sema, xs: []Ref): bool {
var i: usize = 0;
while i < xs.len {
if ref_shape_dep(self, xs[i]) { ret true; }
i = i + 1;
}
ret false;
}
// 节点是否依赖 shape 形参:直接 tid 是 shape/关联类型,或子树里有这种节点。
fn ref_shape_dep(self: *Sema, ref: Ref): bool {
if ref == 0 { ret false; }
if lang_shape_dep(self, SemaM.tid_of(self, ref), 0) { ret true; }
var n = Bld.node_ptr(&self.hir, ref);
if n == null { ret false; }
// def 已清空:声明和任何局部引用都必须重新分析,保证实例槽位一致。
match n.kind {
.Local(_), .Alloc(_), .VarDecl(_), .ConstDecl(_) => { ret true; },
_ => {},
}
match n.kind {
.Block(x) => { ret any_shape_dep(self, x.stmts) || ref_shape_dep(self, x.tail); },
.If(x) => { ret ref_shape_dep(self, x.cond) || ref_shape_dep(self, x.then) ||
ref_shape_dep(self, x.els); },
.IfVar(x) => { ret ref_shape_dep(self, x.init) || ref_shape_dep(self, x.then) ||
ref_shape_dep(self, x.els); },
.Destructure(x) => { ret ref_shape_dep(self, x.init); },
.Loop(x) => { ret ref_shape_dep(self, x.body); },
.Iter(x) => { ret any_shape_dep(self, x.inputs) || any_shape_dep(self, x.captures) ||
ref_shape_dep(self, x.body) || ref_shape_dep(self, x.else_body); },
.Break(x) => { ret ref_shape_dep(self, x.value); },
.Return(x) => { ret ref_shape_dep(self, x); },
.Defer(x) => { ret ref_shape_dep(self, x); },
.ErrDefer(x) => { ret ref_shape_dep(self, x); },
.Try(x) => { ret ref_shape_dep(self, x); },
.Catch(x) => { ret ref_shape_dep(self, x.value) || ref_shape_dep(self, x.handler); },
.IsNonNull(x) => { ret ref_shape_dep(self, x); },
.OptionalPayload(x) => { ret ref_shape_dep(self, x); },
.IsTag(x) => { ret ref_shape_dep(self, x.value); },
.TagPayload(x) => { ret ref_shape_dep(self, x); },
.Match(x) => { ret ref_shape_dep(self, x.operand) || any_shape_dep(self, x.arms); },
.MatchArm(x) => { ret ref_shape_dep(self, x.pattern) || ref_shape_dep(self, x.body); },
.PatLit(x) => { ret ref_shape_dep(self, x); },
.PatTag(x) => { ret ref_shape_dep(self, x.sub); },
.PatList(xs) => { ret any_shape_dep(self, xs); },
.PatTuple(xs) => { ret any_shape_dep(self, xs); },
.PatField(x) => { ret ref_shape_dep(self, x.sub); },
.Alloc(x) => { ret ref_shape_dep(self, x.ty) || ref_shape_dep(self, x.value); },
.VarDecl(x) => { ret ref_shape_dep(self, x.ty) || ref_shape_dep(self, x.init); },
.ConstDecl(x) => { ret ref_shape_dep(self, x.ty) || ref_shape_dep(self, x.init); },
.Field(x) => { ret ref_shape_dep(self, x.obj); },
.Index(x) => { ret ref_shape_dep(self, x.obj) || ref_shape_dep(self, x.idx); },
.Range(x) => { ret ref_shape_dep(self, x.begin) || ref_shape_dep(self, x.end); },
.SliceExpr(x) => { ret ref_shape_dep(self, x.obj) || ref_shape_dep(self, x.begin) ||
ref_shape_dep(self, x.end); },
.Cast(x) => { ret ref_shape_dep(self, x.value); },
.Addr(x) => { ret ref_shape_dep(self, x); },
.Deref(x) => { ret ref_shape_dep(self, x); },
.FieldLit(x) => { ret ref_shape_dep(self, x.value); },
.AggLit(x) => { ret any_shape_dep(self, x.fields); },
.ArrayLit(x) => { ret any_shape_dep(self, x.elems); },
.TupleLit(xs) => { ret any_shape_dep(self, xs); },
.CompoundAssign(x) => { ret ref_shape_dep(self, x.lval) || ref_shape_dep(self, x.rval); },
.Binary(x) => { ret ref_shape_dep(self, x.lval) || ref_shape_dep(self, x.rval); },
.Unary(x) => { ret ref_shape_dep(self, x.val); },
.Call(x) => { ret ref_shape_dep(self, x.callee) || any_shape_dep(self, x.args); },
.Comptime(x) => { ret ref_shape_dep(self, x); },
_ => {},
}
ret false;
}
// 依赖根只需要重解析到语句级;其他模板语句直接复用已分析结果。
fn collect_patch_roots(self: *Sema, body: Ref) {
self.shape_state.patch_roots.len = 0;
var n = Bld.node_ptr(&self.hir, body);
if n == null { ret; }
match n.kind {
.Block(x) => {
var i: usize = 0;
while i < x.stmts.len {
if ref_shape_dep(self, x.stmts[i]) {
var s = x.stmts[i];
match Vec.push(&self.shape_state.patch_roots, &s as *u8) { .Ok => {}, .Err(e) => {} }
}
i = i + 1;
}
if x.tail != 0 && ref_shape_dep(self, x.tail) {
var t = x.tail;
match Vec.push(&self.shape_state.patch_roots, &t as *u8) { .Ok => {}, .Err(e) => {} }
}
},
_ => {
if ref_shape_dep(self, body) {
match Vec.push(&self.shape_state.patch_roots, &body as *u8) { .Ok => {}, .Err(e) => {} }
}
},
}
}
// 只清掉依赖 shape 的节点;非依赖子树保留模板分析结果,sema 会在这些节点提前返回。
fn reset_patch_defs(self: *Sema, ref: Ref) {
if ref == 0 { ret; }
var n = Bld.node_ptr(&self.hir, ref);
if n == null { ret; }
if !ref_shape_dep(self, ref) { ret; }
var ri = SemaM.ref_info(self, ref);
if ri != null {
ri.tid = 0;
ri.def = 0;
ri.fn_sym = 0;
ri.builtin = 0;
ri.variant = 0;
ri.initref = 0;
ri.aggval = 0;
}
match n.kind {
.Block(x) => {
var i: usize = 0;
while i < x.stmts.len { reset_patch_defs(self, x.stmts[i]); i = i + 1; }
reset_patch_defs(self, x.tail);
},
.If(x) => { reset_patch_defs(self, x.cond); reset_patch_defs(self, x.then); reset_patch_defs(self, x.els); },
.IfVar(x) => { reset_patch_defs(self, x.pattern); reset_patch_defs(self, x.init); reset_patch_defs(self, x.then); reset_patch_defs(self, x.els); },
.Destructure(x) => { reset_patch_defs(self, x.init); },
.Loop(x) => { reset_patch_defs(self, x.body); },
.Iter(x) => { var i: usize = 0; while i < x.inputs.len { reset_patch_defs(self, x.inputs[i]); i = i + 1; }
reset_patch_defs(self, x.body); reset_patch_defs(self, x.else_body); },
.Break(x) => { reset_patch_defs(self, x.value); },
.Alloc(x) => { reset_patch_defs(self, x.ty); reset_patch_defs(self, x.value); },
.VarDecl(x) => { reset_patch_defs(self, x.ty); reset_patch_defs(self, x.init); },
.ConstDecl(x) => { reset_patch_defs(self, x.ty); reset_patch_defs(self, x.init); },
.Return(x) => { reset_patch_defs(self, x); },
.Defer(x) => { reset_patch_defs(self, x); },
.ErrDefer(x) => { reset_patch_defs(self, x); },
.Try(x) => { reset_patch_defs(self, x); },
.Catch(x) => { reset_patch_defs(self, x.value); reset_patch_defs(self, x.handler); },
.Match(x) => { reset_patch_defs(self, x.operand); var i: usize = 0; while i < x.arms.len { reset_patch_defs(self, x.arms[i]); i = i + 1; } },
.MatchArm(x) => { reset_patch_defs(self, x.pattern); reset_patch_defs(self, x.body); },
.PatLit(x) => { reset_patch_defs(self, x); },
.PatTag(x) => { reset_patch_defs(self, x.sub); },
.PatList(xs) => { var i: usize = 0; while i < xs.len { reset_patch_defs(self, xs[i]); i = i + 1; } },
.PatTuple(xs) => { var i: usize = 0; while i < xs.len { reset_patch_defs(self, xs[i]); i = i + 1; } },
.PatField(x) => { reset_patch_defs(self, x.sub); },
.Field(x) => { reset_patch_defs(self, x.obj); },
.Index(x) => { reset_patch_defs(self, x.obj); reset_patch_defs(self, x.idx); },
.SliceExpr(x) => { reset_patch_defs(self, x.obj); reset_patch_defs(self, x.begin); reset_patch_defs(self, x.end); },
.Cast(x) => { reset_patch_defs(self, x.value); },
.Addr(x) => { reset_patch_defs(self, x); },
.Deref(x) => { reset_patch_defs(self, x); },
.FieldLit(x) => { reset_patch_defs(self, x.value); },
.AggLit(x) => { var i: usize = 0; while i < x.fields.len { reset_patch_defs(self, x.fields[i]); i = i + 1; } },
.ArrayLit(x) => { var i: usize = 0; while i < x.elems.len { reset_patch_defs(self, x.elems[i]); i = i + 1; } },
.TupleLit(xs) => { var i: usize = 0; while i < xs.len { reset_patch_defs(self, xs[i]); i = i + 1; } },
.CompoundAssign(x) => { reset_patch_defs(self, x.lval); reset_patch_defs(self, x.rval); },
.Binary(x) => { reset_patch_defs(self, x.lval); reset_patch_defs(self, x.rval); },
.Unary(x) => { reset_patch_defs(self, x.val); },
.Call(x) => { reset_patch_defs(self, x.callee); var i: usize = 0; while i < x.args.len { reset_patch_defs(self, x.args[i]); i = i + 1; } },
.Comptime(x) => { reset_patch_defs(self, x); },
_ => {},
}
}
fn shape_instance_key_eq(self: *Sema, si: *ShapeInstance, fn_ref: Ref, args: []usize): bool {
if si.fn_ref != fn_ref || si.args.len != args.len { ret false; } if si.fn_ref != fn_ref || si.args.len != args.len { ret false; }
var i: usize = 0; var i: usize = 0;
while i < args.len { while i < args.len {
@@ -891,7 +1208,7 @@ fn shape_instance_for(self: *Sema, fn_ref: Ref, args: []usize): usize {
var i: usize = 0; var i: usize = 0;
while i < self.shape_state.instances.len { while i < self.shape_state.instances.len {
var si = (self.shape_state.instances.data as *ShapeInstance) + i; var si = (self.shape_state.instances.data as *ShapeInstance) + i;
if shape_instance_matches(self, si, fn_ref, args) { ret si.sym; } if shape_instance_key_eq(self, si, fn_ref, args) { ret si.sym; }
i = i + 1; i = i + 1;
} }
var orig = SemaM.fn_sym_for_ref(self, fn_ref); var orig = SemaM.fn_sym_for_ref(self, fn_ref);
@@ -906,8 +1223,9 @@ fn shape_instance_for(self: *Sema, fn_ref: Ref, args: []usize): usize {
SemaM.analyze_fn_body(self, od - 1); SemaM.analyze_fn_body(self, od - 1);
var clone_state = NodeClone.new(); var clone_state = NodeClone.new();
var clone = NodeClone.clone_ref(&self.hir, &clone_state, fn_ref); var clone = NodeClone.clone_ref(&self.hir, &clone_state, fn_ref);
NodeClone.drop(&clone_state);
SemaM.grow_tables(self); SemaM.grow_tables(self);
copy_clone_refinfo(self, &clone_state);
NodeClone.drop(&clone_state);
var nm = shape_instance_name(self); var nm = shape_instance_name(self);
var cn = Bld.node_ptr(&self.hir, clone); var cn = Bld.node_ptr(&self.hir, clone);
if cn != null { if cn != null {
@@ -957,7 +1275,23 @@ fn shape_instance_for(self: *Sema, fn_ref: Ref, args: []usize): usize {
var di = self.decls.len; var di = self.decls.len;
match Vec.push(&self.decls, &d as *u8) { .Ok => {}, .Err(e) => {} } match Vec.push(&self.decls, &d as *u8) { .Ok => {}, .Err(e) => {} }
SemaM.ensure_decl(self, di); SemaM.ensure_decl(self, di);
// 只重解析依赖 shape 形参的语句;其余模板节点复用克隆过来的分析结果。
var body_ref: Ref = 0;
var cbn = Bld.node_ptr(&self.hir, clone);
if cbn != null {
match cbn.kind { .FnDecl(f) => { body_ref = f.body; }, _ => {} }
}
collect_patch_roots(self, body_ref);
var ri: usize = 0;
while ri < self.shape_state.patch_roots.len {
reset_patch_defs(self, (self.shape_state.patch_roots.data as *Ref)[ri]);
ri = ri + 1;
}
self.shape_state.patching = true;
self.shape_state.patch_decl = di;
SemaM.analyze_fn_body(self, di); SemaM.analyze_fn_body(self, di);
self.shape_state.patching = false;
self.shape_state.patch_decl = 0;
var inst = SemaM.decl_at(self, di).sym; var inst = SemaM.decl_at(self, di).sym;
if m != saved { SemaM.switch_mod(self, saved); } if m != saved { SemaM.switch_mod(self, saved); }
if inst != 0 { if inst != 0 {
@@ -1021,8 +1355,33 @@ fn prepare_call(user: *any, callee_ref: Ref, callee: Ref, args: []usize,
if al == 0 { if al == 0 {
shape_ok = false; shape_ok = false;
need_report = true; need_report = true;
} else if !shape_conforms_use(self, sp.shape_ref, al) { } else if is_untyped_literal(self, a) {
SemaM.sema_error_code(self, ErrorCode.ShapeMismatch,
"shape argument literal requires `as`", "");
shape_ok = false; shape_ok = false;
} else if !sp.has_adapter {
// @[Shape]:没有默认 adapter;直接 conforming 允许。
if !shape_conforms_use(self, sp.shape_ref, al) {
shape_ok = false;
SemaM.sema_error_code(self, ErrorCode.ShapeMismatch,
"shape argument does not conform; add @adapter[Shape](...)",
"");
} else {
match Vec.push(&shape_args, &al as *u8) {
.Ok => {},
.Err(e) => { shape_ok = false; },
}
}
} else if SemaM.has_tag(self, a, "shape_applied") {
// 显式 @adapter[Shape](arg) 已经完成转换,不再套默认 adapter。
if !shape_conforms_use(self, sp.shape_ref, al) {
shape_ok = false;
} else {
match Vec.push(&shape_args, &al as *u8) {
.Ok => {},
.Err(e) => { shape_ok = false; },
}
}
} else { } else {
var sr = shape_adapter_result(self, pi + 1, al); var sr = shape_adapter_result(self, pi + 1, al);
if sr.lang == 0 || !shape_conforms_use(self, sp.shape_ref, sr.lang) { if sr.lang == 0 || !shape_conforms_use(self, sp.shape_ref, sr.lang) {
@@ -1059,6 +1418,107 @@ fn prepare_call(user: *any, callee_ref: Ref, callee: Ref, args: []usize,
} }
} }
// 裸数字字面量没有稳定类型;shape 参数必须先 `as` 出具体类型。
fn is_untyped_literal(self: *Sema, ref: Ref): bool {
var n = Bld.node_ptr(&self.hir, ref);
if n == null { ret false; }
match n.kind {
.LitInt(_), .LitFloat(_) => { ret true; },
_ => {},
}
ret false;
}
fn apply_expr_hook(user: *any, ref: Ref, adapter: []u8, shapes: []Ref, args: []Ref): usize {
ret shape_apply_expr(user as *Sema, ref, adapter, shapes, args);
}
// `@adapter[Shape](arg)`:解析 shape、执行 adapter、把 arg 替换成转换函数调用。
fn shape_apply_expr(self: *Sema, ref: Ref, adapter: []u8, shapes: []Ref, args: []Ref): usize {
if shapes.len == 0 {
SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape,
"shape application requires a shape", adapter);
ret 0;
}
var shape_lang = SemaM.resolve_type(self, shapes[0]);
if shape_lang == 0 { ret 0; }
if shapes.len > 1 {
var use_ref = Bld.construct(&self.hir, .{ .kind = .ShapeUse(.{
.adapter = "",
.shapes = shapes,
}) });
shape_lang = compose_shapes(self, use_ref);
if shape_lang == 0 { ret 0; }
}
if !is_shape_lang(self, shape_lang) {
SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape,
"shape application target is not a shape", adapter);
ret 0;
}
var adi = find_shape_adapter(self, adapter);
if adi == 0 { ret 0; }
if args.len != 1 {
SemaM.sema_error_code(self, ErrorCode.ShapeMismatch,
"shape application expects one argument", adapter);
ret 0;
}
var value = args[0];
SemaM.sema_expr(self, value, 0);
if is_untyped_literal(self, value) {
SemaM.sema_error_code(self, ErrorCode.ShapeMismatch,
"shape application literal requires `as`", adapter);
ret 0;
}
var arg_lang = SemaM.tid_of(self, value);
if arg_lang == 0 {
SemaM.sema_error_code(self, ErrorCode.ShapeMismatch,
"shape application argument has no type", adapter);
ret 0;
}
var ev = adapter_eval_for(self, adi - 1, arg_lang, shape_lang);
if ev.adapter_ref == 0 || ev.lang == 0 { ret 0; }
var binds = Vec.blank(@sizeof(ShapeBind), @alignof(ShapeBind));
defer { Vec.drop(&binds); }
if !shape_conforms_with(self, shape_lang, ev.lang, &binds) {
SemaM.sema_error_code(self, ErrorCode.ShapeMismatch,
"shape application result does not conform", adapter);
ret 0;
}
var amod = SemaM.decl_at(self, adi - 1).mod;
var sym = ensure_adapter_fn(self, ev.adapter_ref, amod);
if sym == 0 { ret 0; }
var ws = SemaM.sym_at(self, sym - 1);
var callee = Bld.construct(&self.hir, .{ .kind = .Global(ws.name) });
SemaM.set_node_fn(self, callee, sym);
SemaM.set_tid(self, callee, ws.fn_tid);
var av = Vec.blank(@sizeof(usize), @alignof(usize));
defer { Vec.drop(&av); }
match Vec.push(&av, &value as *u8) { .Ok => {}, .Err(e) => { ret 0; } }
var call = Bld.construct(&self.hir, .{ .kind = .Call(.{
.is_comptime = false,
.callee = callee,
.args = (av.data as *Ref)[0..av.len],
}) });
SemaM.sema_expr(self, call, 0);
var t = SemaM.tid_of(self, call);
if t == 0 { ret 0; }
var empty: [1]Ref = .[0];
var tag = Bld.construct(&self.hir, .{ .kind = .Tag(.{
.is_at = false,
.name = "shape_applied",
.args = empty[0..0],
}) });
var p = Bld.node_ptr(&self.hir, ref);
var rn = Bld.node_ptr(&self.hir, call);
if p != null && rn != null {
p.kind = rn.kind;
p.tags = rn.tags;
var tags: [1]Ref = .[tag];
p.tags = Bld.dup_refs(&self.hir, tags[0..1]);
}
ret t;
}
fn op_method(user: *any, value_lang: usize, shape_lang: usize, method: []u8): usize { fn op_method(user: *any, value_lang: usize, shape_lang: usize, method: []u8): usize {
var self = user as *Sema; var self = user as *Sema;
if !shape_marker_has(self, value_lang, shape_lang) { ret 0; } if !shape_marker_has(self, value_lang, shape_lang) { ret 0; }
@@ -1074,6 +1534,10 @@ fn marker_has_hook(user: *any, value_lang: usize, shape_lang: usize): bool {
ret shape_marker_has(user as *Sema, value_lang, shape_lang); ret shape_marker_has(user as *Sema, value_lang, shape_lang);
} }
fn shape_lang_hook(user: *any, lang: usize): bool {
ret is_shape_lang(user as *Sema, lang);
}
fn hooks(): ShapeHooks { fn hooks(): ShapeHooks {
ret ShapeHooks { ret ShapeHooks {
.bind_params = bind_params, .bind_params = bind_params,
@@ -1082,6 +1546,9 @@ fn hooks(): ShapeHooks {
.check_conforms = check_conforms, .check_conforms = check_conforms,
.op_method = op_method, .op_method = op_method,
.has_conformance = marker_has_hook, .has_conformance = marker_has_hook,
.is_shape_lang = shape_lang_hook,
.bind_type_arg = bind_type_arg,
.apply_expr = apply_expr_hook,
}; };
} }
+8
View File
@@ -106,6 +106,7 @@ fn kind_name(k: Node.Kind): []u8 {
.AggType(_) => { ret "agg_type"; }, .AggType(_) => { ret "agg_type"; },
.ShapeApply(_) => { ret "shape_apply"; }, .ShapeApply(_) => { ret "shape_apply"; },
.ShapeUse(_) => { ret "shape_use"; }, .ShapeUse(_) => { ret "shape_use"; },
.ShapeNoDefault(_) => { ret "shape_no_default"; },
.AssocBind(_) => { ret "assoc_bind"; }, .AssocBind(_) => { ret "assoc_bind"; },
.ArrayType(_) => { ret "array_type"; }, .ArrayType(_) => { ret "array_type"; },
.SliceType(_) => { ret "slice_type"; }, .SliceType(_) => { ret "slice_type"; },
@@ -140,6 +141,7 @@ fn kind_name(k: Node.Kind): []u8 {
.Binary(_) => { ret "binary"; }, .Binary(_) => { ret "binary"; },
.Unary(_) => { ret "unary"; }, .Unary(_) => { ret "unary"; },
.Call(_) => { ret "call"; }, .Call(_) => { ret "call"; },
.ShapeCall(_) => { ret "shape_call"; },
.Comptime(_) => { ret "comptime"; }, .Comptime(_) => { ret "comptime"; },
} }
ret "?"; ret "?";
@@ -248,6 +250,7 @@ fn construct(self: *HirNodeContainer, node: Node): Ref {
.ShapeUse(x) => { .ShapeUse(x) => {
k = .ShapeUse(.{ .adapter = dup_bytes(self, x.adapter), .shapes = dup_refs(self, x.shapes) }); k = .ShapeUse(.{ .adapter = dup_bytes(self, x.adapter), .shapes = dup_refs(self, x.shapes) });
}, },
.ShapeNoDefault(xs) => { k = .ShapeNoDefault(dup_refs(self, xs)); },
.AssocBind(x) => { k = .AssocBind(.{ .name = dup_bytes(self, x.name), .ty = x.ty }); }, .AssocBind(x) => { k = .AssocBind(.{ .name = dup_bytes(self, x.name), .ty = x.ty }); },
.FnType(x) => { k = .FnType(.{ .params = dup_refs(self, x.params), .ret_ty = x.ret_ty }); }, .FnType(x) => { k = .FnType(.{ .params = dup_refs(self, x.params), .ret_ty = x.ret_ty }); },
.TupleType(xs) => { k = .TupleType(dup_refs(self, xs)); }, .TupleType(xs) => { k = .TupleType(dup_refs(self, xs)); },
@@ -264,6 +267,11 @@ fn construct(self: *HirNodeContainer, node: Node): Ref {
k = .Call(.{ .is_comptime = x.is_comptime, .callee = x.callee, k = .Call(.{ .is_comptime = x.is_comptime, .callee = x.callee,
.args = dup_refs(self, x.args) }); .args = dup_refs(self, x.args) });
}, },
.ShapeCall(x) => {
k = .ShapeCall(.{ .adapter = dup_bytes(self, x.adapter),
.shapes = dup_refs(self, x.shapes),
.args = dup_refs(self, x.args) });
},
_ => {}, _ => {},
} }
var n = Node { .kind = k, .tags = dup_refs(self, node.tags), .loc = node.loc }; var n = Node { .kind = k, .tags = dup_refs(self, node.tags), .loc = node.loc };
+29
View File
@@ -1,6 +1,35 @@
// Expect retcode = 0 // Expect retcode = 0
type meta = @import("meta"); type meta = @import("meta");
type .{ .Ref } = meta;
#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(_) => { ret @meta.construct(.{ .kind = .Addr(implicit) }); },
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
type Pair = struct { type Pair = struct {
a: i32, a: i32,
+3 -2
View File
@@ -7,8 +7,9 @@ type .{ .Ref } = meta;
type .{ .Map } = @import("../support/generic_bind_fixture.spl"); type .{ .Map } = @import("../support/generic_bind_fixture.spl");
#hook(param) #hook(param)
macro fn Self(callee: Ref, value: Ref): Ref { macro fn Self(callee: Ref, value: Ref, implicit: Ref): Ref {
ret @meta.construct(.{ .kind = .Addr(value) }); if implicit == 0 { ret value; }
ret @meta.construct(.{ .kind = .Addr(implicit) });
} }
fn main() { fn main() {
+3 -2
View File
@@ -7,8 +7,9 @@ type .{ .Ref } = meta;
type .{ .Map } = @import("../support/generic_bind_fixture.spl"); type .{ .Map } = @import("../support/generic_bind_fixture.spl");
#hook(param) #hook(param)
macro fn Self(callee: Ref, value: Ref): Ref { macro fn Self(callee: Ref, value: Ref, implicit: Ref): Ref {
ret @meta.construct(.{ .kind = .Addr(value) }); if implicit == 0 { ret value; }
ret @meta.construct(.{ .kind = .Addr(implicit) });
} }
fn main() { fn main() {
+1 -1
View File
@@ -4,7 +4,7 @@ type meta = @import("meta");
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
#hook(param) #hook(param)
macro fn unused(callee: Ref, value: Ref): Ref { macro fn unused(callee: Ref, value: Ref, implicit: Ref): Ref {
ret @meta.construct(.{ .kind = .LitInt("9") }); ret @meta.construct(.{ .kind = .LitInt("9") });
} }
+29
View File
@@ -1,6 +1,35 @@
// Expect retcode = 0 // Expect retcode = 0
type meta = @import("meta"); type meta = @import("meta");
type .{ .Ref } = meta;
#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(_) => { ret @meta.construct(.{ .kind = .Addr(implicit) }); },
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
type Pair = struct { a: i32, b: u8 }; type Pair = struct { a: i32, b: u8 };
type Inner = struct { x: i16, y: bool }; type Inner = struct { x: i16, y: bool };
+29
View File
@@ -1,6 +1,35 @@
// Expect retcode = 0 // Expect retcode = 0
type meta = @import("meta"); type meta = @import("meta");
type .{ .Ref } = meta;
#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(_) => { ret @meta.construct(.{ .kind = .Addr(implicit) }); },
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
type Pair = struct { a: i32, b: u8 }; type Pair = struct { a: i32, b: u8 };
type Arr3 = [3]u16; type Arr3 = [3]u16;
+27
View File
@@ -1,6 +1,33 @@
// Expect retcode = 0 // Expect retcode = 0
type meta = @import("meta"); type meta = @import("meta");
#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(_) => { ret @meta.construct(.{ .kind = .Addr(implicit) }); },
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
type VoidT = void; type VoidT = void;
+27
View File
@@ -1,6 +1,33 @@
// Expect retcode = 0 // Expect retcode = 0
type meta = @import("meta"); type meta = @import("meta");
#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(_) => { ret @meta.construct(.{ .kind = .Addr(implicit) }); },
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
comptime fn tags_roundtrip(): usize { comptime fn tags_roundtrip(): usize {
@@ -1,6 +1,33 @@
// Expect retcode = 0 // Expect retcode = 0
type meta = @import("meta"); type meta = @import("meta");
#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(_) => { ret @meta.construct(.{ .kind = .Addr(implicit) }); },
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
comptime fn int_node(bits: usize, signed: bool): Ref { comptime fn int_node(bits: usize, signed: bool): Ref {
+27
View File
@@ -1,6 +1,33 @@
// Expect retcode = 0 // Expect retcode = 0
type meta = @import("meta"); type meta = @import("meta");
#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(_) => { ret @meta.construct(.{ .kind = .Addr(implicit) }); },
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
type .{ .method, .type_name } = @import("./meta_utils.spl"); type .{ .method, .type_name } = @import("./meta_utils.spl");
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
+27
View File
@@ -1,6 +1,33 @@
// Expect retcode = 0 // Expect retcode = 0
type meta = @import("meta"); type meta = @import("meta");
#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(_) => { ret @meta.construct(.{ .kind = .Addr(implicit) }); },
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
comptime fn int_ref(): Ref { comptime fn int_ref(): Ref {
+3 -6
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .identity } = @import("./support/shape_identity.spl");
type Cal = shape { type Cal = shape {
fn call(a: i32, b: i32): i32; fn call(a: i32, b: i32): i32;
} }
@@ -16,12 +18,7 @@ type Sub = struct {
} }
} }
#hook(adapter) fn Cal1(c: @identity[Cal], a: i32, b: i32): i32 {
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
fn Cal1(c: @static[Cal], a: i32, b: i32): i32 {
ret c.call(a, b); ret c.call(a, b);
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .static } = @import("./support/shape_identity.spl");
type Cal = shape { type Cal = shape {
fn call(a: i32, b: i32): i32; fn call(a: i32, b: i32): i32;
} }
@@ -16,11 +18,6 @@ type Sub = struct {
} }
} }
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
fn Both(a: @static[Cal], b: @static[Cal], x: i32, y: i32): i32 { fn Both(a: @static[Cal], b: @static[Cal], x: i32, y: i32): i32 {
ret a.call(x, y) + b.call(x, y); ret a.call(x, y) + b.call(x, y);
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .wrap } = @import("./support/shape_identity.spl");
type Cal = shape { type Cal = shape {
fn call(a: i32, b: i32): i32; fn call(a: i32, b: i32): i32;
} }
@@ -16,11 +18,6 @@ type Sub = struct {
} }
} }
#hook(adapter)
macro fn wrap(called_type: type, shape_type: type): Ref {
ret 0;
}
fn Use(c: @wrap[Cal], a: i32, b: i32): i32 { fn Use(c: @wrap[Cal], a: i32, b: i32): i32 {
ret c.call(a, b); ret c.call(a, b);
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .dyn } = @import("./support/shape_identity.spl");
type .{ .Ref } = @import("spl_ir"); type .{ .Ref } = @import("spl_ir");
type Cal = shape { type Cal = shape {
@@ -14,11 +16,6 @@ type Sub = struct {
fn call(a: i32, b: i32): i32 { ret a - b; } fn call(a: i32, b: i32): i32 { ret a - b; }
}; };
#hook(adapter)
macro fn dyn(called_type: type, shape_type: type): Ref {
ret 0;
}
fn Use(c: @dyn[Cal], a: i32, b: i32): i32 { fn Use(c: @dyn[Cal], a: i32, b: i32): i32 {
ret c.call(a, b); ret c.call(a, b);
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect compile_error E0305 // Expect compile_error E0305
type .{ .bad_adapter } = @import("./support/shape_identity.spl");
type Cal = shape { type Cal = shape {
fn call(a: i32, b: i32): i32; fn call(a: i32, b: i32): i32;
fn tag(): i32; fn tag(): i32;
@@ -14,11 +16,6 @@ type Wrong = struct {
fn tag(): i32 { ret 1; } fn tag(): i32 { ret 1; }
} }
#hook(adapter)
macro fn bad_adapter(called_type: type, shape_type: type): Ref {
ret 0;
}
fn UseMissing(c: @bad_adapter[Cal], a: i32, b: i32): i32 { fn UseMissing(c: @bad_adapter[Cal], a: i32, b: i32): i32 {
ret c.call(a, b) + c.tag(); ret c.call(a, b) + c.tag();
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .static } = @import("./support/shape_identity.spl");
type SelfShape = shape { type SelfShape = shape {
fn value(self: *@self): i32; fn value(self: *@self): i32;
fn same(self: *@self): *@self; fn same(self: *@self): *@self;
@@ -17,11 +19,6 @@ type Node = struct: SelfShape {
} }
} }
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
fn use_self(n: @static[SelfShape]): i32 { fn use_self(n: @static[SelfShape]): i32 {
var p = n.same(&n); var p = n.same(&n);
ret p.value(p); ret p.value(p);
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .static } = @import("./support/shape_identity.spl");
comptime fn Step(T: type): type { comptime fn Step(T: type): type {
ret enum { ret enum {
Item: T, Item: T,
@@ -26,11 +28,6 @@ type Counter = struct: Iter[Item = i32] {
} }
} }
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
fn first(it: @static[Iter[Item = i32]]): i32 { fn first(it: @static[Iter[Item = i32]]): i32 {
var s = it.next(&it); var s = it.next(&it);
match s { match s {
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .static } = @import("./support/shape_identity.spl");
comptime fn Step(T: type): type { comptime fn Step(T: type): type {
ret enum { ret enum {
Item: T, Item: T,
@@ -34,11 +36,6 @@ type CursorIter = struct: Iter[Item = i32] {
} }
} }
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
fn first(it: @static[Iter[Item = i32]]): i32 { fn first(it: @static[Iter[Item = i32]]): i32 {
var s = it.next(&it); var s = it.next(&it);
match s { match s {
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .static } = @import("./support/shape_identity.spl");
comptime fn Step(T: type): type { comptime fn Step(T: type): type {
ret enum { ret enum {
Item: T, Item: T,
@@ -34,11 +36,6 @@ type Counter = struct: Iter[Item = i32] + Tag {
} }
} }
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
fn use_both(it: @static[Iter[Item = i32] + Tag]): i32 { fn use_both(it: @static[Iter[Item = i32] + Tag]): i32 {
var s = it.next(&it); var s = it.next(&it);
match s { match s {
+2 -10
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .sa_adapter, .sb_adapter } = @import("./support/shape_identity.spl");
type .{ .Ref } = @import("spl_ir"); type .{ .Ref } = @import("spl_ir");
type SA = shape { type SA = shape {
@@ -18,16 +20,6 @@ type B = struct {
fn b(): i32 { ret 22; } fn b(): i32 { ret 22; }
}; };
#hook(adapter)
macro fn sa_adapter(called_type: type, shape_type: type): Ref {
ret 0;
}
#hook(adapter)
macro fn sb_adapter(called_type: type, shape_type: type): Ref {
ret 0;
}
fn use_a(x: @sa_adapter[SA]): i32 { fn use_a(x: @sa_adapter[SA]): i32 {
ret x.a(); ret x.a();
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect compile_error E0317 // Expect compile_error E0317
type .{ .alloc } = @import("./support/shape_identity.spl");
type .{ .Ref } = @import("spl_ir"); type .{ .Ref } = @import("spl_ir");
type SA = shape { type SA = shape {
@@ -10,11 +12,6 @@ type Bad = struct {
fn b(): i32 { ret 1; } fn b(): i32 { ret 1; }
}; };
#hook(adapter)
macro fn alloc(called_type: type, shape_type: type): Ref {
ret 0;
}
fn use_a(x: @alloc[SA]): i32 { fn use_a(x: @alloc[SA]): i32 {
ret x.a(); ret x.a();
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .static } = @import("./support/shape_identity.spl");
type ValueShape = shape { type ValueShape = shape {
fn value(self: *@self): i32; fn value(self: *@self): i32;
} }
@@ -12,11 +14,6 @@ type Node = struct {
} }
} }
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
fn read(n: @static[ValueShape]): i32 { fn read(n: @static[ValueShape]): i32 {
ret n.value(&n); ret n.value(&n);
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .static } = @import("./support/shape_identity.spl");
type Sink = shape { type Sink = shape {
type Item; type Item;
fn put(self: *@self, value: Item): Item; fn put(self: *@self, value: Item): Item;
@@ -14,11 +16,6 @@ type IntSink = struct: Sink[Item = i32] {
} }
} }
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
fn add(s: @static[Sink[Item = i32]], value: i32): i32 { fn add(s: @static[Sink[Item = i32]], value: i32): i32 {
ret s.put(&s, value); ret s.put(&s, value);
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .static } = @import("./support/shape_identity.spl");
type Base = shape { type Base = shape {
fn base(self: *@self): i32; fn base(self: *@self): i32;
} }
@@ -20,11 +22,6 @@ type Impl = struct: Derived {
} }
} }
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
fn use(d: @static[Derived]): i32 { fn use(d: @static[Derived]): i32 {
ret d.base(&d) + d.extra(&d); ret d.base(&d) + d.extra(&d);
} }
+1 -1
View File
@@ -22,5 +22,5 @@ fn main(): void {
@assert(c.value_copy() == 1, "self value"); @assert(c.value_copy() == 1, "self value");
c.set(7); c.set(7);
@assert(c.get() == 7, "self ref set"); @assert(c.get() == 7, "self ref set");
@assert(c.get(&c) == 7, "explicit receiver"); @assert(c.get() == 7, "implicit receiver");
} }
+1 -1
View File
@@ -7,7 +7,7 @@ comptime fn Pair(T: type): type {
a: T, a: T,
b: T, b: T,
fn add(lhs: @self, rhs: @self): @self { fn add(@Self lhs: @self, rhs: @self): @self {
ret .{ .a = lhs.a + rhs.a, .b = lhs.b + rhs.b }; ret .{ .a = lhs.a + rhs.a, .b = lhs.b + rhs.b };
} }
}; };
+1 -1
View File
@@ -6,7 +6,7 @@ comptime fn NumBox(T: type): type {
ret struct: Add[Rhs = T, Output = @self] { ret struct: Add[Rhs = T, Output = @self] {
v: T, v: T,
fn add(lhs: @self, rhs: T): @self { fn add(@Self lhs: @self, rhs: T): @self {
ret .{ .v = lhs.v + rhs }; ret .{ .v = lhs.v + rhs };
} }
}; };
+1 -1
View File
@@ -4,7 +4,7 @@ type meta = @import("meta");
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
#hook(param) #hook(param)
macro fn replace(callee: Ref, value: Ref): Ref { macro fn replace(callee: Ref, value: Ref, implicit: Ref): Ref {
ret @meta.construct(.{ .kind = .LitInt("7") }); ret @meta.construct(.{ .kind = .LitInt("7") });
} }
+2 -2
View File
@@ -4,12 +4,12 @@ type meta = @import("meta");
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
#hook(param) #hook(param)
macro fn seven(callee: Ref, value: Ref): Ref { macro fn seven(callee: Ref, value: Ref, implicit: Ref): Ref {
ret @meta.construct(.{ .kind = .LitInt("7") }); ret @meta.construct(.{ .kind = .LitInt("7") });
} }
#hook(param) #hook(param)
macro fn nine(callee: Ref, value: Ref): Ref { macro fn nine(callee: Ref, value: Ref, implicit: Ref): Ref {
ret @meta.construct(.{ .kind = .LitInt("9") }); ret @meta.construct(.{ .kind = .LitInt("9") });
} }
+2 -2
View File
@@ -4,7 +4,7 @@ type meta = @import("meta");
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
#hook(param) #hook(param)
macro fn plus_one(callee: Ref, value: Ref): Ref { macro fn plus_one(callee: Ref, value: Ref, implicit: Ref): Ref {
var one = @meta.construct(.{ .kind = .LitInt("1") }); var one = @meta.construct(.{ .kind = .LitInt("1") });
var sum = @meta.construct(.{ var sum = @meta.construct(.{
.kind = .Binary(.{ .op = .Add, .lval = value, .rval = one }), .kind = .Binary(.{ .op = .Add, .lval = value, .rval = one }),
@@ -13,7 +13,7 @@ macro fn plus_one(callee: Ref, value: Ref): Ref {
} }
#hook(param) #hook(param)
macro fn times_two(callee: Ref, value: Ref): Ref { macro fn times_two(callee: Ref, value: Ref, implicit: Ref): Ref {
var two = @meta.construct(.{ .kind = .LitInt("2") }); var two = @meta.construct(.{ .kind = .LitInt("2") });
var product = @meta.construct(.{ var product = @meta.construct(.{
.kind = .Binary(.{ .op = .Mul, .lval = value, .rval = two }), .kind = .Binary(.{ .op = .Mul, .lval = value, .rval = two }),
+1 -1
View File
@@ -4,7 +4,7 @@ type meta = @import("meta");
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
#hook(param) #hook(param)
macro fn check_callee(callee: Ref, value: Ref): Ref { macro fn check_callee(callee: Ref, value: Ref, implicit: Ref): Ref {
var n = @meta.inspect(callee); var n = @meta.inspect(callee);
match n.kind { match n.kind {
.FnDecl(f) => { .FnDecl(f) => {
+1 -1
View File
@@ -4,7 +4,7 @@ type meta = @import("meta");
type .{ .Node, .Ref } = @import("spl_ir"); type .{ .Node, .Ref } = @import("spl_ir");
#hook(param) #hook(param)
macro fn default_seven(callee: Ref, value: Ref): Ref { macro fn default_seven(callee: Ref, value: Ref, implicit: Ref): Ref {
if value != 0 { ret value; } if value != 0 { ret value; }
ret @meta.construct(.{ .kind = .LitInt("7") }); ret @meta.construct(.{ .kind = .LitInt("7") });
} }
+2 -5
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .identity } = @import("./support/shape_identity.spl");
type .{ .Ref } = @import("spl_ir"); type .{ .Ref } = @import("spl_ir");
type Cal = shape { type Cal = shape {
@@ -10,11 +12,6 @@ type A = struct {
fn call(): i32 { ret 5; } fn call(): i32 { ret 5; }
} }
#hook(adapter)
macro fn identity(called_type: type, shape_type: type): Ref {
ret 0;
}
fn use(c: @identity[Cal]): i32 { fn use(c: @identity[Cal]): i32 {
ret c.call(); ret c.call();
} }
+5 -3
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .identity } = @import("./support/shape_identity.spl");
type .{ .Ref } = @import("spl_ir"); type .{ .Ref } = @import("spl_ir");
type Cal = shape { type Cal = shape {
@@ -12,11 +14,11 @@ type A = struct {
// kind 只是声明信息;位置和签名才是 impl hook 的权威。 // kind 只是声明信息;位置和签名才是 impl hook 的权威。
#hook(param) #hook(param)
macro fn identity(called_type: type, shape_type: type): Ref { macro fn impl_identity(called_type: type, shape_type: type): Ref {
ret 0; ret @identity(called_type, shape_type);
} }
fn use(c: @identity[Cal]): i32 { fn use(c: @impl_identity[Cal]): i32 {
ret c.call(); ret c.call();
} }
+5 -3
View File
@@ -1,5 +1,7 @@
// Expect retcode = 0 // Expect retcode = 0
type .{ .identity } = @import("./support/shape_identity.spl");
type .{ .Ref } = @import("spl_ir"); type .{ .Ref } = @import("spl_ir");
type Cal = shape { type Cal = shape {
@@ -11,11 +13,11 @@ type A = struct {
} }
// 没有 #hook tag;位置和签名仍应决定它是 impl hook。 // 没有 #hook tag;位置和签名仍应决定它是 impl hook。
macro fn identity(called_type: type, shape_type: type): Ref { macro fn impl_identity(called_type: type, shape_type: type): Ref {
ret 0; ret @identity(called_type, shape_type);
} }
fn use(c: @identity[Cal]): i32 { fn use(c: @impl_identity[Cal]): i32 {
ret c.call(); ret c.call();
} }
@@ -0,0 +1,17 @@
// Expect compile_error E0106
// Expect location = 9:21
comptime fn Bad(T: type): type {
ret struct {
v: T,
fn broken(self: @self): T {
ret self.missing;
}
};
}
fn main() {
var b: @Bad(i32) = .{ .v = 1 };
var x = b.broken();
}
@@ -0,0 +1,17 @@
// Expect compile_error E0105 E0106
// Expect location = 9:26
comptime fn Bad(T: type): type {
ret struct {
v: T,
fn broken(self: @self): usize {
ret self.nope();
}
};
}
fn main() {
var b: @Bad(i32) = .{ .v = 1 };
var x = b.broken();
}
@@ -0,0 +1,57 @@
// Expect retcode = 0
#extern(vm) fn vm_alloc(sz: usize): *any;
type AllocError = enum {
OutOfMemory,
};
comptime fn Result(T: type, E: type): type {
ret enum {
#ok
Ok: T,
#error
Err: E,
};
}
type Alloc = struct {
fn alloc(@Self self: *@self, size: usize): @Result(*any, AllocError) {
var p = vm_alloc(size);
if p == null {
ret .(.Err(.OutOfMemory));
}
ret .(.Ok(p));
}
};
comptime fn Box(T: type): type {
ret struct {
data: *T,
len: usize,
cap: usize,
fn make(alloc: Alloc, n: usize): @self {
var v: @self = .{ .data = null, .len = 0, .cap = n };
var p: *any = null;
match alloc.alloc(@sizeof(T) * n) {
.Ok(raw) => { p = raw; },
.Err(e) => { panic("alloc failed"); },
}
v.data = p as *T;
ret v;
}
fn push(@Self self: *@self, v: T) {
self.data[self.len] = v;
self.len = self.len + 1;
}
};
}
fn main() {
var b = @Box(i32).make(Alloc{}, 4);
b.push(7);
@assert(b.data[0] == 7, "value");
}
@@ -0,0 +1,60 @@
// Expect retcode = 0
#extern(vm) fn vm_alloc(sz: usize): *any;
type AllocError = enum {
OutOfMemory,
};
comptime fn Result(T: type, E: type): type {
ret enum {
#ok
Ok: T,
#error
Err: E,
};
}
type Alloc = struct {
fn alloc(@Self self: *@self, size: usize): @Result(*any, AllocError) {
var p = vm_alloc(size);
if p == null {
ret .(.Err(.OutOfMemory));
}
ret .(.Ok(p));
}
};
fn take_alloc(r: @Result(*any, AllocError)): *any {
match r {
.Ok(p) => { ret p; },
.Err(e) => { panic("alloc failed"); ret null; },
}
}
comptime fn Box(T: type): type {
ret struct {
data: *T,
len: usize,
cap: usize,
fn make(alloc: Alloc, n: usize): @self {
var v: @self = .{ .data = null, .len = 0, .cap = n };
var p = take_alloc(alloc.alloc(@sizeof(T) * n));
v.data = p as *T;
ret v;
}
fn push(@Self self: *@self, v: T) {
self.data[self.len] = v;
self.len = self.len + 1;
}
};
}
fn main() {
var b = @Box(i32).make(Alloc{}, 4);
b.push(7);
@assert(b.data[0] == 7, "value");
}
+110
View File
@@ -0,0 +1,110 @@
// Expect retcode = 0
#extern(vm) fn vm_alloc(sz: usize): *any;
#extern(vm) fn vm_free(p: *any);
type AllocError = enum { OutOfMemory };
comptime fn Result(T: type, E: type): type {
ret enum {
#ok
Ok: T,
#error
Err: E,
};
}
type Alloc = struct {
fn alloc(@Self self: *@self, size: usize): @Result(*any, AllocError) {
var p = vm_alloc(size);
if p == null { ret .(.Err(.OutOfMemory)); }
ret .(.Ok(p));
}
fn dealloc(@Self self: *@self, ptr: *any): void {
vm_free(ptr);
}
};
comptime fn RawVec(T: type): type {
ret struct {
data: *T,
length: usize,
cap: usize,
fn empty(): @self {
ret .{ .data = null, .length = 0, .cap = 0 };
}
fn len(@Self self: *@self): usize {
ret self.length;
}
fn capacity(@Self self: *@self): usize {
ret self.cap;
}
fn push_unchecked(@Self self: *@self, v: T) {
self.data[self.length] = v;
self.length = self.length + 1;
}
};
}
fn grow_capacity(current: usize, min_cap: usize, need: usize): usize {
var cap = current;
if cap < min_cap { cap = min_cap; }
while cap < need { cap = cap * 2; }
ret cap;
}
comptime fn Grow(T: type, A: type): type {
ret struct {
fn reserve(base: *@RawVec(T), alloc: A, additional: usize) {
var need = base.len() + additional;
if need <= base.capacity() { ret; }
var new_cap = grow_capacity(base.capacity(), 8, need);
var p: *u8 = null;
match alloc.alloc(@sizeof(T) * new_cap) {
.Ok(raw) => { p = raw as *u8; },
.Err(e) => { panic("alloc failed"); },
}
base.data = p as *T;
base.cap = new_cap;
}
};
}
comptime fn VecOwned(T: type, A: type): type {
ret struct {
base: @RawVec(T),
alloc: A,
fn with_capacity(alloc: A, n: usize): @self {
var v: @self = .{ .base = @RawVec(T).empty(), .alloc = alloc };
if n == 0 { ret v; }
@Grow(T, A).reserve(&v.base, v.alloc, n);
ret v;
}
fn push(@Self self: *@self, v: T) {
if self.base.len() + 1 > self.base.cap {
@Grow(T, A).reserve(&self.base, self.alloc, 1);
}
@RawVec(T).push_unchecked(&self.base, v);
}
fn get(@Self self: *@self, i: usize): T {
ret self.base.data[i];
}
};
}
fn main() {
var v = @VecOwned([]u8, Alloc).with_capacity(Alloc{}, 3);
v.push("aa");
v.push("bb");
v.push("cc");
@assert(v.get(0).len() == 2, "aa");
@assert(v.get(2)[0] == 'c', "cc");
}
@@ -0,0 +1,47 @@
// Expect retcode = 0
#extern(vm) fn vm_alloc(sz: usize): *any;
#extern(vm) fn vm_free(p: *any);
type Allocator = shape {
fn alloc(@Self self: *@self, size: usize): *any;
fn dealloc(@Self self: *@self, ptr: *any);
};
type VmAlloc = struct: Allocator {
fn alloc(@Self self: *@self, size: usize): *any {
ret vm_alloc(size);
}
fn dealloc(@Self self: *@self, ptr: *any) {
vm_free(ptr);
}
};
comptime fn Box(T: type, A: Allocator): type {
ret struct {
p: *T,
alloc: A,
fn make(alloc: A): @self {
var b: @self = .{ .p = null, .alloc = alloc };
b.p = alloc.alloc(@sizeof(T)) as *T;
ret b;
}
fn set(@Self self: *@self, v: T) {
self.p[0] = v;
}
fn get(@Self self: *@self): T {
ret self.p[0];
}
};
}
fn main() {
@assert(@sizeof(@Box(i32, VmAlloc)) == @sizeof(*i32), "zst alloc field");
var b = @Box(i32, VmAlloc).make(VmAlloc{});
b.set(42);
@assert(b.get() == 42, "bound ok");
}
@@ -0,0 +1,44 @@
// Expect retcode = 0
type Sink = shape {
type Item;
fn put(@Self self: *@self, v: Item);
fn total(@Self self: *@self): i32;
};
type IntSink = struct: Sink[Item = i32] {
sum: i32,
fn put(@Self self: *@self, v: i32) {
self.sum = self.sum + v;
}
fn total(@Self self: *@self): i32 {
ret self.sum;
}
};
comptime fn Writer(S: Sink[Item = i32]): type {
ret struct {
sink: S,
fn make(sink: S): @self {
ret .{ .sink = sink };
}
fn add(@Self self: *@self, v: i32) {
self.sink.put(v);
}
fn total(@Self self: *@self): i32 {
ret self.sink.total();
}
};
}
fn main() {
var w = @Writer(IntSink).make(IntSink{ .sum = 0 });
w.add(3);
w.add(4);
@assert(w.total() == 7, "assoc bound");
}
@@ -0,0 +1,46 @@
// Expect retcode = 0
type Allocator = shape {
fn alloc(@Self self: *@self, size: usize): *any;
};
type Logger = shape {
fn log(@Self self: *@self, v: i32);
};
type Both = struct: Allocator + Logger {
mark: i32,
fn alloc(@Self self: *@self, size: usize): *any {
ret null;
}
fn log(@Self self: *@self, v: i32) {
self.mark = v;
}
};
comptime fn Use(A: Allocator + Logger): type {
ret struct {
a: A,
fn make(a: A): @self {
ret .{ .a = a };
}
fn run(@Self self: *@self, v: i32) {
self.a.log(v);
self.a.alloc(4);
}
fn mark(@Self self: *@self): i32 {
ret self.a.mark;
}
};
}
fn main() {
var u = @Use(Both).make(Both{ .mark = 0 });
u.run(9);
@assert(u.mark() == 9, "composed bound");
}
@@ -0,0 +1,38 @@
// Expect retcode = 0
type .{ .static } = @import("./support/shape_identity.spl");
type .{ .Ref } = @import("spl_ir");
type Allocator = shape {
fn alloc(@Self self: *@self, size: usize): *any;
};
type VmAlloc = struct: Allocator {
fn alloc(@Self self: *@self, size: usize): *any {
ret null;
}
};
comptime fn Box(T: type, A: @static[Allocator]): type {
ret struct {
p: *T,
alloc: A,
fn make(alloc: A): @self {
var b: @self = .{ .p = null, .alloc = alloc };
b.p = alloc.alloc(@sizeof(T)) as *T;
ret b;
}
fn ptr(@Self self: *@self): *T {
ret self.p;
}
};
}
fn main() {
var b = @Box(i32, VmAlloc).make(VmAlloc{});
@assert(@sizeof(@Box(i32, VmAlloc)) == @sizeof(*i32), "static hook zst");
@assert(b.ptr() == b.p, "static hook bound");
}
@@ -0,0 +1,19 @@
// Expect compile_error E0317
// Expect location = 18:31
type Allocator = shape {
fn alloc(@Self self: *@self, size: usize): *any;
};
type Bad = struct {};
comptime fn Box(T: type, A: Allocator): type {
ret struct {
p: *T,
alloc: A,
};
}
fn main() {
@assert(@sizeof(@Box(i32, Bad)) > 0, "size");
}
@@ -0,0 +1,23 @@
// Expect compile_error E0305
// Expect location = 22:31
type Allocator = shape {
fn alloc(@Self self: *@self, size: usize): *any;
};
type Bad = struct {
fn alloc(@Self self: *@self, wrong: i32): *any {
ret null;
}
};
comptime fn Box(T: type, A: Allocator): type {
ret struct {
p: *T,
alloc: A,
};
}
fn main() {
@assert(@sizeof(@Box(i32, Bad)) > 0, "size");
}
@@ -0,0 +1,57 @@
// Expect retcode = 0
type Allocator = shape {
fn alloc(@Self self: *@self, size: usize): *any;
};
type VmA = struct: Allocator {
pad: u8,
fn alloc(@Self self: *@self, size: usize): *any {
ret null;
}
};
type VmB = struct: Allocator {
pad: u32,
fn alloc(@Self self: *@self, size: usize): *any {
ret null;
}
};
comptime fn Inner(A: Allocator): type {
ret struct {
a: A,
fn make(a: A): @self {
ret .{ .a = a };
}
fn tag(@Self self: *@self): usize {
ret @sizeof(A);
}
};
}
comptime fn Outer(A: Allocator): type {
ret struct {
inner: @Inner(A),
fn make(a: A): @self {
ret .{ .inner = @Inner(A).make(a) };
}
fn tag(@Self self: *@self): usize {
ret self.inner.tag();
}
};
}
fn main() {
var a = @Outer(VmA).make(VmA{ .pad = 1 });
var b = @Outer(VmB).make(VmB{ .pad = 2 });
@assert(a.tag() == @sizeof(VmA), "instance a");
@assert(b.tag() == @sizeof(VmB), "instance b");
@assert(@sizeof(VmA) != @sizeof(VmB), "distinct instances");
}
@@ -0,0 +1,14 @@
// Expect compile_error E0308
// Expect location = 12:8
type Allocator = shape {
fn alloc(@Self self: *@self, size: usize): *any;
};
type Logger = shape {
fn log(@Self self: *@self, v: i32);
};
fn bad(x: Allocator + Logger) {}
fn main() {}
+78 -89
View File
@@ -9,64 +9,55 @@
type meta = @import("meta"); type meta = @import("meta");
type .{ .Ref } = meta; type .{ .Ref } = meta;
#hook(param) type .{ .Self } = @import("./support/self_hook.spl");
macro fn Self(callee: Ref, value: Ref): Ref {
if value == 0 {
ret 0;
}
var vn = @meta.inspect(value);
match vn.kind {
.Addr(_) => { ret value; },
_ => {},
}
ret @meta.construct(.{ .kind = .Addr(value) });
}
type Layout = struct { type Layout = struct {
size: usize, size: usize,
align: usize, align: usize,
}; };
type Allocator = shape { type AllocError = enum {
fn alloc(@Self self: *@self, layout: Layout): *u8; OutOfMemory,
fn dealloc(@Self self: *@self, ptr: *u8, layout: Layout): void; InvalidLayout,
fn realloc(@Self self: *@self, ptr: *u8, old: Layout, new: Layout): *u8;
}; };
fn vm_alloc_raw(layout: Layout): *u8 { comptime fn Result(T: type, E: type): type {
ret enum {
#ok
Ok: T,
#error
Err: E,
};
}
type Allocator = shape {
fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError);
fn dealloc(@Self self: *@self, ptr: *any, layout: Layout);
};
fn vm_alloc_raw(layout: Layout): @Result(*any, AllocError) {
var p = vm_alloc(layout.size); var p = vm_alloc(layout.size);
@assert(p != null, "alloc failed"); if p == null {
ret p as *u8; ret .(.Err(AllocError.OutOfMemory));
}
ret .(.Ok(p));
} }
fn vm_free_raw(ptr: *u8): void { fn alloc_value(r: @Result(*any, AllocError)): *any {
vm_free(ptr as *any); match r {
.Ok(p) => { ret p; },
.Err(e) => { panic("allocation failed"); ret null; },
} }
fn vm_realloc_raw(ptr: *u8, old: Layout, new: Layout): *u8 {
if ptr == null {
ret vm_alloc_raw(new);
}
if new.size == 0 {
vm_free_raw(ptr);
ret null;
}
var p = vm_realloc(ptr as *any, new.size);
@assert(p != null, "realloc failed");
ret p as *u8;
} }
type VmAlloc = struct: Allocator { type VmAlloc = struct: Allocator {
fn alloc(@Self self: *@self, layout: Layout): *u8 { fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError) {
ret vm_alloc_raw(layout); ret vm_alloc_raw(layout);
} }
fn dealloc(@Self self: *@self, ptr: *u8, layout: Layout): void { fn dealloc(@Self self: *@self, ptr: *any, layout: Layout): void {
vm_free_raw(ptr); vm_free(ptr);
}
fn realloc(@Self self: *@self, ptr: *u8, old: Layout, new: Layout): *u8 {
ret vm_realloc_raw(ptr, old, new);
} }
}; };
@@ -74,16 +65,12 @@ type VmAlloc = struct: Allocator {
type TaggedAlloc = struct: Allocator { type TaggedAlloc = struct: Allocator {
tag: u8, tag: u8,
fn alloc(@Self self: *@self, layout: Layout): *u8 { fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError) {
ret vm_alloc_raw(layout); ret vm_alloc_raw(layout);
} }
fn dealloc(@Self self: *@self, ptr: *u8, layout: Layout): void { fn dealloc(@Self self: *@self, ptr: *any, layout: Layout): void {
vm_free_raw(ptr); vm_free(ptr);
}
fn realloc(@Self self: *@self, ptr: *u8, old: Layout, new: Layout): *u8 {
ret vm_realloc_raw(ptr, old, new);
} }
}; };
@@ -121,49 +108,49 @@ comptime fn RawVec(T: type): type {
ret .{ ._ptr = null, ._len = 0, ._cap = 0 }; ret .{ ._ptr = null, ._len = 0, ._cap = 0 };
} }
fn len(self: @self): usize { fn len(@Self self: @self): usize {
ret self._len; ret self._len;
} }
fn capacity(self: @self): usize { fn capacity(@Self self: @self): usize {
ret self._cap; ret self._cap;
} }
fn as_ptr(self: @self): *T { fn as_ptr(@Self self: @self): *T {
ret self._ptr; ret self._ptr;
} }
fn as_slice(self: @self): []T { fn as_slice(@Self self: @self): []T {
ret @Slice(T).from_raw_parts(self._ptr, self._len); ret @Slice(T).from_raw_parts(self._ptr, self._len);
} }
fn get(self: @self, i: usize): T { fn get(@Self self: @self, i: usize): T {
@assert(i < self._len, "index out of range"); @assert(i < self._len, "index out of range");
ret self._ptr[i]; ret self._ptr[i];
} }
fn at(self: @self, i: usize): *T { fn at(@Self self: @self, i: usize): *T {
@assert(i < self._len, "index out of range"); @assert(i < self._len, "index out of range");
ret self._ptr + i; ret self._ptr + i;
} }
fn set(self: *@self, i: usize, v: T): void { fn set(@Self self: *@self, i: usize, v: T): void {
@assert(i < self._len, "index out of range"); @assert(i < self._len, "index out of range");
self._ptr[i] = v; self._ptr[i] = v;
} }
fn push_unchecked(self: *@self, v: T): void { fn push_unchecked(@Self self: *@self, v: T): void {
self._ptr[self._len] = v; self._ptr[self._len] = v;
self._len = self._len + 1; self._len = self._len + 1;
} }
fn pop_unchecked(self: *@self): T { fn pop_unchecked(@Self self: *@self): T {
@assert(self._len > 0, "pop from empty"); @assert(self._len > 0, "pop from empty");
self._len = self._len - 1; self._len = self._len - 1;
ret self._ptr[self._len]; ret self._ptr[self._len];
} }
fn insert_unchecked(self: *@self, i: usize, v: T): void { fn insert_unchecked(@Self self: *@self, i: usize, v: T): void {
var j = self._len; var j = self._len;
while j > i { while j > i {
self._ptr[j] = self._ptr[j - 1]; self._ptr[j] = self._ptr[j - 1];
@@ -173,7 +160,7 @@ comptime fn RawVec(T: type): type {
self._len = self._len + 1; self._len = self._len + 1;
} }
fn remove_unchecked(self: *@self, i: usize): T { fn remove_unchecked(@Self self: *@self, i: usize): T {
var v = self._ptr[i]; var v = self._ptr[i];
var j = i; var j = i;
while j + 1 < self._len { while j + 1 < self._len {
@@ -184,17 +171,17 @@ comptime fn RawVec(T: type): type {
ret v; ret v;
} }
fn clear(self: *@self): void { fn clear(@Self self: *@self): void {
self._len = 0; self._len = 0;
} }
fn truncate(self: *@self, n: usize): void { fn truncate(@Self self: *@self, n: usize): void {
if n < self._len { if n < self._len {
self._len = n; self._len = n;
} }
} }
fn reset(self: *@self): void { fn reset(@Self self: *@self): void {
self._ptr = null; self._ptr = null;
self._len = 0; self._len = 0;
self._cap = 0; self._cap = 0;
@@ -212,13 +199,15 @@ comptime fn Grow(T: type, A: type): type {
var new_cap = grow_capacity(base._cap, 8, need); var new_cap = grow_capacity(base._cap, 8, need);
var old_layout = layout_of(@sizeof(T), @alignof(T), base._cap); var old_layout = layout_of(@sizeof(T), @alignof(T), base._cap);
var new_layout = layout_of(@sizeof(T), @alignof(T), new_cap); var new_layout = layout_of(@sizeof(T), @alignof(T), new_cap);
var p: *u8 = null; var p = alloc_value(alloc.alloc(new_layout));
if base._cap == 0 { if base._cap != 0 {
p = alloc.alloc(new_layout); var i: usize = 0;
} else { while i < base._len * @sizeof(T) {
p = alloc.realloc(base._ptr as *u8, old_layout, new_layout); (p as *u8)[i] = (base._ptr as *u8)[i];
i = i + 1;
}
alloc.dealloc(base._ptr as *any, old_layout);
} }
@assert(p != null, "grow failed");
base._ptr = p as *T; base._ptr = p as *T;
base._cap = new_cap; base._cap = new_cap;
} }
@@ -241,33 +230,33 @@ comptime fn Vec(T: type): type {
} }
var g: VmAlloc = .{}; var g: VmAlloc = .{};
var lay = layout_of(@sizeof(T), @alignof(T), n); var lay = layout_of(@sizeof(T), @alignof(T), n);
var p = g.alloc(lay); var p = alloc_value(g.alloc(lay));
v.base._ptr = p as *T; v.base._ptr = p as *T;
v.base._cap = n; v.base._cap = n;
ret v; ret v;
} }
fn len(self: @self): usize { fn len(@Self self: @self): usize {
ret self.base.len(); ret self.base.len();
} }
fn capacity(self: @self): usize { fn capacity(@Self self: @self): usize {
ret self.base.capacity(); ret self.base.capacity();
} }
fn as_ptr(self: @self): *T { fn as_ptr(@Self self: @self): *T {
ret self.base.as_ptr(); ret self.base.as_ptr();
} }
fn as_slice(self: @self): []T { fn as_slice(@Self self: @self): []T {
ret self.base.as_slice(); ret self.base.as_slice();
} }
fn get(self: @self, i: usize): T { fn get(@Self self: @self, i: usize): T {
ret self.base.get(i); ret self.base.get(i);
} }
fn at(self: @self, i: usize): *T { fn at(@Self self: @self, i: usize): *T {
ret self.base.at(i); ret self.base.at(i);
} }
@@ -353,7 +342,7 @@ comptime fn Vec(T: type): type {
fn drop(@Self self: *@self): void { fn drop(@Self self: *@self): void {
if self.base._cap != 0 { if self.base._cap != 0 {
var g: VmAlloc = .{}; var g: VmAlloc = .{};
g.dealloc(self.base._ptr as *u8, layout_of(@sizeof(T), @alignof(T), self.base._cap)); g.dealloc(self.base._ptr as *any, layout_of(@sizeof(T), @alignof(T), self.base._cap));
} }
@RawVec(T).reset(&self.base); @RawVec(T).reset(&self.base);
} }
@@ -382,29 +371,29 @@ comptime fn VecOwned(T: type, A: type): type {
ret v; ret v;
} }
var lay = layout_of(@sizeof(T), @alignof(T), n); var lay = layout_of(@sizeof(T), @alignof(T), n);
var p = alloc.alloc(lay); var p = alloc_value(alloc.alloc(lay));
v.base._ptr = p as *T; v.base._ptr = p as *T;
v.base._cap = n; v.base._cap = n;
ret v; ret v;
} }
fn len(self: @self): usize { fn len(@Self self: @self): usize {
ret self.base.len(); ret self.base.len();
} }
fn capacity(self: @self): usize { fn capacity(@Self self: @self): usize {
ret self.base.capacity(); ret self.base.capacity();
} }
fn as_slice(self: @self): []T { fn as_slice(@Self self: @self): []T {
ret self.base.as_slice(); ret self.base.as_slice();
} }
fn get(self: @self, i: usize): T { fn get(@Self self: @self, i: usize): T {
ret self.base.get(i); ret self.base.get(i);
} }
fn at(self: @self, i: usize): *T { fn at(@Self self: @self, i: usize): *T {
ret self.base.at(i); ret self.base.at(i);
} }
@@ -485,7 +474,7 @@ comptime fn VecOwned(T: type, A: type): type {
fn drop(@Self self: *@self): void { fn drop(@Self self: *@self): void {
if self.base._cap != 0 { if self.base._cap != 0 {
self.alloc.dealloc(self.base._ptr as *u8, layout_of(@sizeof(T), @alignof(T), self.base._cap)); self.alloc.dealloc(self.base._ptr as *any, layout_of(@sizeof(T), @alignof(T), self.base._cap));
} }
@RawVec(T).reset(&self.base); @RawVec(T).reset(&self.base);
} }
@@ -513,29 +502,29 @@ comptime fn VecParam(T: type, A: type): type {
ret v; ret v;
} }
var lay = layout_of(@sizeof(T), @alignof(T), n); var lay = layout_of(@sizeof(T), @alignof(T), n);
var p = alloc.alloc(lay); var p = alloc_value(alloc.alloc(lay));
v.base._ptr = p as *T; v.base._ptr = p as *T;
v.base._cap = n; v.base._cap = n;
ret v; ret v;
} }
fn len(self: @self): usize { fn len(@Self self: @self): usize {
ret self.base.len(); ret self.base.len();
} }
fn capacity(self: @self): usize { fn capacity(@Self self: @self): usize {
ret self.base.capacity(); ret self.base.capacity();
} }
fn as_slice(self: @self): []T { fn as_slice(@Self self: @self): []T {
ret self.base.as_slice(); ret self.base.as_slice();
} }
fn get(self: @self, i: usize): T { fn get(@Self self: @self, i: usize): T {
ret self.base.get(i); ret self.base.get(i);
} }
fn at(self: @self, i: usize): *T { fn at(@Self self: @self, i: usize): *T {
ret self.base.at(i); ret self.base.at(i);
} }
@@ -616,7 +605,7 @@ comptime fn VecParam(T: type, A: type): type {
fn drop(@Self self: *@self, alloc: A): void { fn drop(@Self self: *@self, alloc: A): void {
if self.base._cap != 0 { if self.base._cap != 0 {
alloc.dealloc(self.base._ptr as *u8, layout_of(@sizeof(T), @alignof(T), self.base._cap)); alloc.dealloc(self.base._ptr as *any, layout_of(@sizeof(T), @alignof(T), self.base._cap));
} }
@RawVec(T).reset(&self.base); @RawVec(T).reset(&self.base);
} }
+3 -2
View File
@@ -4,8 +4,9 @@ type meta = @import("meta");
type .{ .Ref } = meta; type .{ .Ref } = meta;
#hook(param) #hook(param)
macro fn Self(callee: Ref, value: Ref): Ref { macro fn Self(callee: Ref, value: Ref, implicit: Ref): Ref {
ret @meta.construct(.{ .kind = .Addr(value) }); if implicit == 0 { ret value; }
ret @meta.construct(.{ .kind = .Addr(implicit) });
} }
type Counter = struct { type Counter = struct {
+1 -1
View File
@@ -4,7 +4,7 @@ type meta = @import("meta");
type .{ .Ref } = meta; type .{ .Ref } = meta;
#hook(param) #hook(param)
macro fn default(callee: Ref, value: Ref, fallback: i32): Ref { macro fn default(callee: Ref, value: Ref, implicit: Ref, fallback: i32): Ref {
if value != 0 { ret value; } if value != 0 { ret value; }
if fallback != 42 { @meta.error(.DefaultMismatch); ret 0; } if fallback != 42 { @meta.error(.DefaultMismatch); ret 0; }
ret @meta.construct(.{ .kind = .LitInt("42") }); ret @meta.construct(.{ .kind = .LitInt("42") });