Compare commits
3
Commits
126b979f72
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
032102f1d7 | ||
|
|
936a8d0e88 | ||
|
|
50ee126d44 |
No files matched your search
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
#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");
|
||||
type .{ .File, .FileMode, .Time, .Memory, .Process, .VM } = @import("./shape.spl");
|
||||
// type .{} = @import("");
|
||||
type ptr = @import("core/ptr.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 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(()));
|
||||
}
|
||||
|
||||
pub fn putchar(@Self _self: *@self, ch: u8): bool {
|
||||
vm_putchar(ch as i32);
|
||||
}
|
||||
}
|
||||
|
||||
// type VMFormat = struct: Formatter {
|
||||
|
||||
// }
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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(); }
|
||||
// }
|
||||
// }
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
type .{ .Result } = @import("./error.spl");
|
||||
|
||||
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 type Spec = struct {
|
||||
align: enum { Left, Center, Right },
|
||||
width: usize,
|
||||
fill: u8,
|
||||
// attrs: enum {
|
||||
// number: struct {},
|
||||
// }
|
||||
};
|
||||
|
||||
pub type Error = enum {
|
||||
WriteFailed,
|
||||
UnclosedLeftBrace,
|
||||
UnclosedRightBrace,
|
||||
UnknownSpec,
|
||||
MissingArg,
|
||||
TooManyArgs,
|
||||
};
|
||||
|
||||
// not have { and }
|
||||
pub fn parse_spec(pattern: []const u8): @Result(Spec, Error) {
|
||||
var res = Spec {
|
||||
.fill = ' ',
|
||||
.width = 0,
|
||||
.align = .Left,
|
||||
};
|
||||
ret .Ok(res);
|
||||
}
|
||||
|
||||
pub comptime fn Format(S: Sink): type {
|
||||
ret struct {
|
||||
out: S,
|
||||
|
||||
pub fn with_sink(out: S): @self {
|
||||
ret .{ .out = out };
|
||||
}
|
||||
|
||||
fn write(@Self self: *@self, str: []const u8): bool {
|
||||
var res = true;
|
||||
for i in str {
|
||||
res = self.out.write_byte(i);
|
||||
if (res == false) {
|
||||
ret false;
|
||||
}
|
||||
}
|
||||
ret res;
|
||||
}
|
||||
|
||||
pub fn format(@Self self: *@self, pattern: []const u8, args: []const DisplayArg): Error {
|
||||
var starti = 0;
|
||||
for i in 0..pattern.len() {
|
||||
var ch = pattern[i];
|
||||
match pattern[i] {
|
||||
'{' => {
|
||||
|
||||
},
|
||||
'}' => {
|
||||
|
||||
},
|
||||
_ => { continue; },
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
Whitespace-only changes.
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Whitespace-only changes.
@@ -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;
|
||||
}
|
||||
Whitespace-only changes.
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
type .{ .VMWriter, .VMFile, .strlen, .VMAllocator } = @import("compiler/vm.spl");
|
||||
type .{ .Vec } = @import("core/vec.spl");
|
||||
|
||||
type .{ .OptParse } = @import("compiler/optparse.spl");
|
||||
type .{ .Source, .SourceError } = @import("lexer/source.spl");
|
||||
|
||||
fn test() {
|
||||
var args: []const []const u8 = .["program", "-h"];
|
||||
var parser = OptParse.with_args(args);
|
||||
|
||||
@assert(parser.args.len() == 2, "args len != 2");
|
||||
@assert(parser.args.as_ptr() == args.as_ptr(), "args not assign");
|
||||
@assert(parser.current.handle_positional == false, "handle_position");
|
||||
@assert(parser.current.arg_pos == 1, "args pos need 1");
|
||||
@assert(parser.current.opt_pos == 0, "opts pos need 0");
|
||||
@assert(parser.current.opt == null, "current pot need null");
|
||||
@assert(parser.opts.as_ptr() == null, "opts need null");
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
test();
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
@@ -86,6 +86,7 @@ type Body = enum {
|
||||
},
|
||||
ExprAggregateLit: struct { name: ByteView, fields: Vec },
|
||||
ExprComptimeCall: struct { name: ByteView, args: Vec },
|
||||
ExprShapeApply: struct { adapter: ByteView, shapes: Vec, args: Vec },
|
||||
ExprTry: struct { value: usize }, // `try expr`
|
||||
ExprCatch: struct { value: usize, pattern: usize, handler: usize }, // `expr catch <pat> { }`
|
||||
ExprBlock: struct { stmts: Vec, tail_expr: usize },
|
||||
@@ -129,6 +130,7 @@ type Body = enum {
|
||||
TypeShapeApply: struct { base: ByteView, binds: Vec },
|
||||
TypeAssocBind: struct { name: ByteView, ty: usize },
|
||||
TypeShapeUse: struct { adapter: ByteView, shapes: Vec },
|
||||
TypeShapeNoDefault: struct { shapes: Vec },
|
||||
}
|
||||
|
||||
fn kind_name(body: Body): []u8 {
|
||||
@@ -180,6 +182,7 @@ fn kind_name(body: Body): []u8 {
|
||||
.ExprArrayLit(_) => { ret "array_literal"; },
|
||||
.ExprAggregateLit(_) => { ret "aggregate_literal"; },
|
||||
.ExprComptimeCall(_) => { ret "comptime_call"; },
|
||||
.ExprShapeApply(_) => { ret "shape_apply"; },
|
||||
.ExprTry(_) => { ret "try_expr"; },
|
||||
.ExprCatch(_) => { ret "catch_expr"; },
|
||||
.ExprComptimeInit(_) => { ret "comptime_init"; },
|
||||
@@ -201,6 +204,7 @@ fn kind_name(body: Body): []u8 {
|
||||
.TypeShapeApply(_) => { ret "type_shape_apply"; },
|
||||
.TypeAssocBind(_) => { ret "type_assoc_bind"; },
|
||||
.TypeShapeUse(_) => { ret "type_shape_use"; },
|
||||
.TypeShapeNoDefault(_) => { ret "type_shape_no_default"; },
|
||||
.TypeComptimeCall(_) => { ret "type_comptime_call"; },
|
||||
.PatternIdent(_) => { ret "pattern_ident"; },
|
||||
.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); },
|
||||
.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); },
|
||||
.ExprCatch(c2) => {
|
||||
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); },
|
||||
.TypeAssocBind(a) => { ok = dump_opt(ast, buf, stack, a.ty, true); },
|
||||
.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); },
|
||||
.PatternIdent(x) => {},
|
||||
.PatternUnderscore => {},
|
||||
|
||||
+138
-34
@@ -22,6 +22,7 @@ diag: *Diag, // 全程诊断;可为 null(自测)
|
||||
pos: usize,
|
||||
failed: bool,
|
||||
stop_agg: i32,
|
||||
array_elem: i32, // >0 表示正在解析 `[N]T[e...]` 的元素类型:`Name[` 不再按类型应用吞掉元素列表
|
||||
error_count: usize,
|
||||
file: usize, // 当前源文件在 Sources 中的下标
|
||||
comptime_depth: usize, // >0 表示处于 comptime 上下文(类型可作为表达式)
|
||||
@@ -33,6 +34,7 @@ fn new(ast: *Ast, toks: Vec, diag: *Diag): Parser {
|
||||
.pos = 0,
|
||||
.failed = false,
|
||||
.stop_agg = 0,
|
||||
.array_elem = 0,
|
||||
.error_count = 0,
|
||||
.file = 0,
|
||||
.comptime_depth = 0,
|
||||
@@ -311,19 +313,21 @@ fn can_start_expr(kind: TokenKind): bool {
|
||||
ret false;
|
||||
}
|
||||
|
||||
// comptime/type 调用实参可以是类型或表达式。`*` / `fn` / `const` 在表达式
|
||||
// 开头没有合法前缀形式(解引用写 `.*`),所以是唯一的语法分流点。
|
||||
fn type_arg_start(kind: TokenKind): bool {
|
||||
// comptime/type 调用实参可以是类型或表达式。`*` / `fn` / `const` 等纯类型起始
|
||||
// token 在表达式位置没有合法前缀形式(解引用写 `.*`),必须由同一张表判定,
|
||||
// 否则 `@F(bool)` 这类关键字类型会漏成“空实参”。
|
||||
fn kind_starts_type(kind: TokenKind): bool {
|
||||
match kind {
|
||||
.Ident => { ret true; },
|
||||
.Keyword(k) => {
|
||||
match k {
|
||||
.Fn, .Const => { ret true; },
|
||||
.Type, .Bool, .Any, .Fn, .Const, .Struct, .Union, .Enum, .Shape => { ret true; },
|
||||
_ => {},
|
||||
}
|
||||
},
|
||||
.Punct(p) => {
|
||||
match p {
|
||||
.Mul => { ret true; },
|
||||
.Mul, .LBracket, .At, .Sharp => { ret true; },
|
||||
_ => {},
|
||||
}
|
||||
},
|
||||
@@ -332,10 +336,30 @@ fn type_arg_start(kind: TokenKind): bool {
|
||||
ret false;
|
||||
}
|
||||
|
||||
fn type_arg_start(kind: TokenKind): bool {
|
||||
// 能起表达式的类别交给 parse_expr;只有纯类型起始才在这里分流。
|
||||
match kind {
|
||||
.Ident => { ret false; },
|
||||
.Punct(p) => {
|
||||
match p {
|
||||
.Mul => { ret true; },
|
||||
_ => { ret false; },
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
ret kind_starts_type(kind);
|
||||
}
|
||||
|
||||
fn parse_type_or_expr_arg(self: *Parser): usize {
|
||||
var t = peek(self);
|
||||
if t == null { ret 0; }
|
||||
if kind_is_keyword(t.kind, .Fn) && looks_like_lambda(self) { ret parse_expr(self); }
|
||||
// `comptime` 既能起表达式也能起类型;只有后面跟 `fn` 时才是类型实参。
|
||||
if kind_is_keyword(t.kind, .Comptime) {
|
||||
var nx = peek_next(self);
|
||||
if nx != null && kind_is_keyword(nx.kind, .Fn) { ret parse_type_expr(self); }
|
||||
}
|
||||
if type_arg_start(t.kind) { ret parse_type_expr(self); }
|
||||
ret parse_expr(self);
|
||||
}
|
||||
@@ -604,6 +628,9 @@ fn parse_pattern_atom(self: *Parser): usize {
|
||||
}
|
||||
}
|
||||
}
|
||||
if items.len == 1 {
|
||||
ret (items.data as *usize)[0];
|
||||
}
|
||||
var tn = Ast.node(self.ast, ref);
|
||||
match tn.body {
|
||||
.PatternTuple(_) => {
|
||||
@@ -773,6 +800,22 @@ fn parse_param_decl_impl(self: *Parser): usize {
|
||||
name);
|
||||
}
|
||||
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,
|
||||
.ParamDecl(.{ .attr_list = attrs, .is_comptime = is_comptime, .name = name.text, .type_expr = ty }),
|
||||
name);
|
||||
@@ -860,23 +903,7 @@ fn decorated_expr_follows(t: *Token): bool {
|
||||
|
||||
fn token_starts_type(t: *Token): bool {
|
||||
if t == null { ret false; }
|
||||
match t.kind {
|
||||
.Ident => { ret true; },
|
||||
.Keyword(k) => {
|
||||
match k {
|
||||
.Type, .Bool, .Any, .Fn, .Struct, .Union, .Enum, .Shape => { ret true; },
|
||||
_ => {},
|
||||
}
|
||||
},
|
||||
.Punct(p) => {
|
||||
match p {
|
||||
.Mul, .LBracket, .At, .Sharp => { ret true; },
|
||||
_ => {},
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
ret false;
|
||||
ret kind_starts_type(t.kind);
|
||||
}
|
||||
|
||||
fn parse_fn_decl(self: *Parser, tags: Vec, is_comptime: bool): usize {
|
||||
@@ -1043,10 +1070,12 @@ fn parse_member_decl(self: *Parser, tags: Vec): usize {
|
||||
te = parse_type_expr(self);
|
||||
t = peek(self);
|
||||
if t != null && kind_is_punct(t.kind, .Assign) {
|
||||
parse_error(self, t, "field declaration cannot have an initializer; use 'var'/'const' for namespace variables");
|
||||
advance(self);
|
||||
init = parse_expr(self);
|
||||
}
|
||||
} else if t != null && kind_is_punct(t.kind, .Assign) {
|
||||
parse_error(self, t, "field declaration cannot have an initializer; use 'var'/'const' for namespace variables");
|
||||
advance(self);
|
||||
init = parse_expr(self);
|
||||
}
|
||||
@@ -1204,6 +1233,13 @@ fn parse_type_comptime_call(self: *Parser): usize {
|
||||
var ok = kind_is_punct(start.kind, .At) || kind_is_punct(start.kind, .Sharp);
|
||||
if !ok { ret 0; }
|
||||
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);
|
||||
if name.len == 0 { ret 0; }
|
||||
var args = ref_vec();
|
||||
@@ -1223,6 +1259,18 @@ fn parse_type_comptime_call(self: *Parser): usize {
|
||||
.TypeComptimeCall(.{ .name = name, .args = args }), start);
|
||||
}
|
||||
|
||||
// `[N]T[e...]` 的元素类型解析:`T[` 后面不是 `Ident =` 时,`[` 属于元素列表。
|
||||
fn at_assoc_binds(self: *Parser): bool {
|
||||
var first = token_ptr(self, self.pos + 1);
|
||||
if first == null { ret false; }
|
||||
var is_ident = false;
|
||||
match first.kind { .Ident => { is_ident = true; }, _ => {} }
|
||||
if !is_ident { ret false; }
|
||||
var second = token_ptr(self, self.pos + 2);
|
||||
if second == null { ret false; }
|
||||
ret kind_is_punct(second.kind, .Assign);
|
||||
}
|
||||
|
||||
// `Name[...]` 只表达 shape 的关联类型绑定;类型构造必须写 `@Name(...)`。
|
||||
fn parse_type_apply(self: *Parser, bt: *Token): usize {
|
||||
expect_punct(self, .LBracket, "'[' in shape application");
|
||||
@@ -1271,19 +1319,14 @@ fn parse_type_apply(self: *Parser, bt: *Token): usize {
|
||||
}), bt);
|
||||
}
|
||||
|
||||
fn parse_type_base(self: *Parser): usize {
|
||||
var bt = peek(self);
|
||||
if bt == null { ret 0; }
|
||||
|
||||
if kind_is_keyword(bt.kind, .Fn) {
|
||||
advance(self);
|
||||
fn parse_fn_type(self: *Parser, at: *Token, is_comptime: bool): usize {
|
||||
if !expect_punct(self, .LParen, "'(' in function type") { ret 0; }
|
||||
// 先分配 TYPE_FN,再解析参数与返回类型。
|
||||
var ref = new_node(self, .TypeFn(.{
|
||||
.is_comptime = false,
|
||||
.is_comptime = is_comptime,
|
||||
.params = ref_vec(),
|
||||
.ret_type = 0,
|
||||
}), bt);
|
||||
}), at);
|
||||
var params = ref_vec();
|
||||
while !self.failed && !at_punct(self, .RParen) {
|
||||
var pt = parse_type_expr(self);
|
||||
@@ -1309,6 +1352,24 @@ fn parse_type_base(self: *Parser): usize {
|
||||
ret ref;
|
||||
}
|
||||
|
||||
fn parse_type_base(self: *Parser): usize {
|
||||
var bt = peek(self);
|
||||
if bt == null { ret 0; }
|
||||
|
||||
if kind_is_keyword(bt.kind, .Comptime) {
|
||||
var nx = peek_next(self);
|
||||
if nx != null && kind_is_keyword(nx.kind, .Fn) {
|
||||
advance(self);
|
||||
advance(self);
|
||||
ret parse_fn_type(self, bt, true);
|
||||
}
|
||||
}
|
||||
|
||||
if kind_is_keyword(bt.kind, .Fn) {
|
||||
advance(self);
|
||||
ret parse_fn_type(self, bt, false);
|
||||
}
|
||||
|
||||
match bt.kind {
|
||||
.Keyword(k) => {
|
||||
var kind_name: []u8 = "";
|
||||
@@ -1333,11 +1394,12 @@ fn parse_type_base(self: *Parser): usize {
|
||||
.conforms = conforms,
|
||||
.members = members,
|
||||
}), bt);
|
||||
var closed = false;
|
||||
while !self.failed {
|
||||
var t = peek(self);
|
||||
if t == null { break; }
|
||||
match t.kind { .Eof => { break; }, _ => {} }
|
||||
if kind_is_punct(t.kind, .RBrace) { advance(self); break; }
|
||||
if kind_is_punct(t.kind, .RBrace) { advance(self); closed = true; break; }
|
||||
var member = parse_container_declaration(self);
|
||||
if member != 0 {
|
||||
var node = Ast.node(self.ast, ref);
|
||||
@@ -1358,6 +1420,9 @@ fn parse_type_base(self: *Parser): usize {
|
||||
advance(self);
|
||||
}
|
||||
}
|
||||
if !closed && !self.failed {
|
||||
expect_punct(self, .RBrace, "'}' in aggregate type");
|
||||
}
|
||||
ret ref;
|
||||
}
|
||||
},
|
||||
@@ -1368,7 +1433,9 @@ fn parse_type_base(self: *Parser): usize {
|
||||
.Ident => {
|
||||
advance(self);
|
||||
// 类型应用:`Vec[i32]` / `Iter[Item = i32]`。
|
||||
if at_punct(self, .LBracket) {
|
||||
// 数组字面量元素类型(`[N]T[e...]`)里,`T[` 是元素列表,不是类型应用。
|
||||
if at_punct(self, .LBracket) &&
|
||||
(self.array_elem == 0 || at_assoc_binds(self)) {
|
||||
ret parse_type_apply(self, bt);
|
||||
}
|
||||
// 类型调用 `Name(T, ...)`(comptime 类型构造,如 `vec(i32)`)。
|
||||
@@ -1542,6 +1609,9 @@ fn parse_type_expr_core(self: *Parser): usize {
|
||||
t = peek(self);
|
||||
if t != null && kind_is_punct(t.kind, .RBracket) {
|
||||
expect_punct(self, .RBracket, "']' in array type");
|
||||
while skip_const_token(self) {
|
||||
// []const T
|
||||
}
|
||||
var slice_elem = parse_type_expr(self);
|
||||
ret new_node(self, .TypeSlice(.{ .elem_type = slice_elem }), t);
|
||||
}
|
||||
@@ -1937,7 +2007,9 @@ fn parse_primary(self: *Parser): usize {
|
||||
.Match => { ret parse_match_expr(self); },
|
||||
.Try => {
|
||||
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);
|
||||
},
|
||||
.Comptime => {
|
||||
@@ -2128,7 +2200,9 @@ fn parse_array_literal(self: *Parser): usize {
|
||||
}
|
||||
}
|
||||
if !expect_punct(self, .RBracket, "']' in array literal") { ret 0; }
|
||||
self.array_elem = self.array_elem + 1;
|
||||
var elem_type = parse_type_expr(self);
|
||||
self.array_elem = self.array_elem - 1;
|
||||
|
||||
// `[N]T` / `[]T` 本身也是类型表达式;没有第二组 `[elems]` 时按类型字面量返回。
|
||||
if !at_punct(self, .LBracket) {
|
||||
@@ -2176,8 +2250,29 @@ fn parse_comptime_call(self: *Parser): usize {
|
||||
var ok = kind_is_punct(start.kind, .At) || kind_is_punct(start.kind, .Sharp);
|
||||
if !ok { ret 0; }
|
||||
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);
|
||||
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();
|
||||
if at_punct(self, .LParen) {
|
||||
advance(self);
|
||||
@@ -2398,7 +2493,12 @@ fn parse_match_expr(self: *Parser): usize {
|
||||
var pat = parse_pattern(self);
|
||||
if pat == 0 { break; }
|
||||
if !expect_punct(self, .RightFatArrow, "'=>' in match arm") { break; }
|
||||
var body = parse_block(self);
|
||||
var body: usize = 0;
|
||||
if at_punct(self, .LBrace) {
|
||||
body = parse_block(self);
|
||||
} else {
|
||||
body = parse_expr(self);
|
||||
}
|
||||
match Vec.push(&patterns, &pat as *u8) { .Ok => {}, .Err(e) => { ret 0; } }
|
||||
match Vec.push(&bodies, &body as *u8) { .Ok => {}, .Err(e) => { ret 0; } }
|
||||
if at_punct(self, .Comma) { advance(self); }
|
||||
@@ -2520,6 +2620,10 @@ fn parse_comptime_stmt(self: *Parser): usize {
|
||||
var t = peek(self);
|
||||
if t != null && kind_is_punct(t.kind, .LBrace) { body = parse_block(self); }
|
||||
else { body = parse_expr(self); }
|
||||
var sep = peek(self);
|
||||
if sep != null && (kind_is_punct(sep.kind, .Semicolon) || kind_is_punct(sep.kind, .Comma)) {
|
||||
advance(self);
|
||||
}
|
||||
ret new_node(self, .StatementComptime(.{ .body = body }), kw);
|
||||
}
|
||||
|
||||
|
||||
+56
-9
@@ -201,6 +201,7 @@ fn op_of(op: Punct): Node.Kind.Op {
|
||||
.Lt => { ret .LessThan; },
|
||||
.Ge => { ret .GreaterEqual; },
|
||||
.Gt => { ret .GreaterThan; },
|
||||
.LeftArrow, .RightArrow, .ArrowBoth, .FatArrowBoth, .RightFatArrow => { ret .Reserved; },
|
||||
_ => { ret .Unknown; },
|
||||
}
|
||||
ret .Unknown;
|
||||
@@ -398,6 +399,16 @@ fn lower_type_inner(self: *Ast2Hir, ref: usize): Ref {
|
||||
.shapes = finish_list(self, &shapes),
|
||||
}), 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) => {
|
||||
if ByteView.eq(x.name, ByteView.from_slice("import")) {
|
||||
ret emit(self, .Import(comptime_str_arg(self, x.args)), n.span);
|
||||
@@ -590,7 +601,7 @@ fn lower_decl(self: *Ast2Hir, ref: usize): Ref {
|
||||
var init: Ref = 0;
|
||||
if x.init_expr != 0 { init = lower_expr(self, x.init_expr); }
|
||||
if self.in_fn {
|
||||
var r = emit(self, .Alloc(.{ .ty = ty, .value = init }), n.span);
|
||||
var r = emit(self, .Alloc(.{ .ty = ty, .value = init, .is_const = false }), n.span);
|
||||
scope_bind(&self.scopes, pattern_name(self, x.pattern), r);
|
||||
ret r;
|
||||
}
|
||||
@@ -604,7 +615,7 @@ fn lower_decl(self: *Ast2Hir, ref: usize): Ref {
|
||||
var init: Ref = 0;
|
||||
if x.init_expr != 0 { init = lower_expr(self, x.init_expr); }
|
||||
if self.in_fn {
|
||||
var r = emit(self, .Alloc(.{ .ty = ty, .value = init }), n.span);
|
||||
var r = emit(self, .Alloc(.{ .ty = ty, .value = init, .is_const = true }), n.span);
|
||||
scope_bind(&self.scopes, pattern_name(self, x.pattern), r);
|
||||
ret r;
|
||||
}
|
||||
@@ -896,20 +907,29 @@ fn lower_pattern(self: *Ast2Hir, ref: usize): Ref {
|
||||
.PatternList(x) => { ret lower_pattern_items(self, x.items, n.span, false); },
|
||||
.PatternTuple(x) => { ret lower_pattern_items(self, x.items, n.span, true); },
|
||||
.PatternAggregate(x) => {
|
||||
if x.items.len == 1 {
|
||||
var it = Ast.node(self.ast, (x.items.data as *usize)[0]);
|
||||
var out = new_vec();
|
||||
var i: usize = 0;
|
||||
while i < x.items.len {
|
||||
var it = Ast.node(self.ast, (x.items.data as *usize)[i]);
|
||||
if it != null {
|
||||
match it.body {
|
||||
.PatternField(pf) => {
|
||||
var sub: Ref = 0;
|
||||
if pf.pattern != 0 { sub = lower_pattern(self, pf.pattern); }
|
||||
ret emit(self, .PatTag(.{ .name = sl(pf.name), .sub = sub }), n.span);
|
||||
if pf.pattern != 0 {
|
||||
sub = lower_pattern(self, pf.pattern);
|
||||
} else {
|
||||
// `.{ .x }` 是 `.{ .x = x }` 的简写。
|
||||
sub = emit(self, .PatBind(sl(pf.name)), n.span);
|
||||
}
|
||||
var pfr = emit(self, .PatField(.{ .name = sl(pf.name), .sub = sub }), n.span);
|
||||
push_ref(&out, pfr);
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
i = i + 1;
|
||||
}
|
||||
ret lower_pattern_items(self, x.items, n.span, true);
|
||||
ret emit(self, .PatFields(finish_list(self, &out)), n.span);
|
||||
},
|
||||
.ExprIntLit(_), .ExprCharLit(_), .ExprBoolLit(_), .ExprStringLit(_), .ExprFloatLit(_) => {
|
||||
ret emit(self, .PatLit(lower_expr(self, ref)), n.span);
|
||||
@@ -947,6 +967,10 @@ fn bind_pattern_scope(self: *Ast2Hir, ref: usize) {
|
||||
var i: usize = 0;
|
||||
while i < xs.len { bind_pattern_scope(self, xs[i]); i = i + 1; }
|
||||
},
|
||||
.PatFields(xs) => {
|
||||
var i: usize = 0;
|
||||
while i < xs.len { bind_pattern_scope(self, xs[i]); i = i + 1; }
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
@@ -966,7 +990,8 @@ fn lower_expr(self: *Ast2Hir, ref: usize): Ref {
|
||||
// comptime 上下文里类型即表达式:类型 AST 节点交给 lower_type(它负责挂 attrs)。
|
||||
match n.body {
|
||||
.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);
|
||||
@@ -1176,7 +1201,11 @@ fn lower_expr_inner(self: *Ast2Hir, ref: usize): Ref {
|
||||
.ExprCatch(x) => {
|
||||
var v = lower_expr(self, x.value);
|
||||
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);
|
||||
scope_end(&self.scopes);
|
||||
ret emit(self, .Catch(.{ .value = v, .pattern = pat, .handler = handler }), n.span);
|
||||
},
|
||||
.ExprComptimeCall(x) => {
|
||||
@@ -1193,6 +1222,23 @@ fn lower_expr_inner(self: *Ast2Hir, ref: usize): Ref {
|
||||
ret emit(self, .Call(.{ .is_comptime = true, .callee = callee,
|
||||
.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) => {
|
||||
var operand = lower_expr(self, x.matched_expr);
|
||||
var arms = new_vec();
|
||||
@@ -1216,7 +1262,8 @@ fn lower_expr_inner(self: *Ast2Hir, ref: usize): Ref {
|
||||
}
|
||||
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 0;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#!builtin
|
||||
#!role(builtins)
|
||||
|
||||
type meta = @import("meta");
|
||||
|
||||
// splc3 的预置头:把编译器底层能力以 `#builtin` 声明暴露给用户/comptime 代码。
|
||||
// `#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;
|
||||
|
||||
// receiver hook:@Self 只挂在方法的第一个参数上。
|
||||
// 参数类型是 *T 时取地址,是 T 时按值传递;已显式传 &x 的调用不再二次取地址。
|
||||
// 参数类型是 *T 时取地址,是 T 时按值传递;implicit 本身已是指向接收者的指针时直接复用。
|
||||
#hook(param)
|
||||
macro fn Self(callee: Ref, value: Ref): Ref {
|
||||
if value == 0 { ret 0; }
|
||||
|
||||
var vn = @inspect(value);
|
||||
match vn.kind {
|
||||
.Addr(_) => { ret value; },
|
||||
_ => {},
|
||||
macro fn Self(callee: Ref, value: Ref, implicit: Ref): Ref {
|
||||
if implicit == 0 {
|
||||
if value != 0 { ret value; }
|
||||
ret 0;
|
||||
}
|
||||
|
||||
var cn = @inspect(callee);
|
||||
var cn = @meta.inspect(callee);
|
||||
match cn.kind {
|
||||
.FnDecl(f) => {
|
||||
var pn = @inspect(f.params[0]);
|
||||
var pn = @meta.inspect(f.params[0]);
|
||||
match pn.kind {
|
||||
.ParamDecl(p) => {
|
||||
var tn = @inspect(p.ty);
|
||||
var tn = @meta.inspect(p.ty);
|
||||
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;
|
||||
}
|
||||
@@ -16,7 +16,6 @@ type ErrorCode = enum {
|
||||
ShapeParamNotShape,
|
||||
MacroCode,
|
||||
FmtMissingArg,
|
||||
FmtNonliteral,
|
||||
FmtBadType,
|
||||
HookNotMacro,
|
||||
ParamHook,
|
||||
@@ -36,6 +35,14 @@ type ErrorCode = enum {
|
||||
DuplicateSuccess,
|
||||
TryNoError,
|
||||
LambdaCapture,
|
||||
// 值/声明/导入/控制流诊断;编号与 label() 固定在这里,增删只改本表。
|
||||
NotAssignable,
|
||||
AssignToConst,
|
||||
MissingDeclType,
|
||||
ImportFailed,
|
||||
BreakOutsideLoop,
|
||||
ContinueOutsideLoop,
|
||||
VarargsNotAllowed,
|
||||
};
|
||||
|
||||
fn number(code: ErrorCode): usize {
|
||||
@@ -56,7 +63,6 @@ fn number(code: ErrorCode): usize {
|
||||
.ShapeParamNotShape => { ret 308; },
|
||||
.MacroCode => { ret 309; },
|
||||
.FmtMissingArg => { ret 310; },
|
||||
.FmtNonliteral => { ret 311; },
|
||||
.FmtBadType => { ret 312; },
|
||||
.HookNotMacro => { ret 313; },
|
||||
.ParamHook => { ret 314; },
|
||||
@@ -76,6 +82,13 @@ fn number(code: ErrorCode): usize {
|
||||
.DuplicateSuccess => { ret 707; },
|
||||
.TryNoError => { ret 708; },
|
||||
.LambdaCapture => { ret 801; },
|
||||
.NotAssignable => { ret 108; },
|
||||
.AssignToConst => { ret 109; },
|
||||
.MissingDeclType => { ret 110; },
|
||||
.ImportFailed => { ret 111; },
|
||||
.BreakOutsideLoop => { ret 323; },
|
||||
.ContinueOutsideLoop => { ret 324; },
|
||||
.VarargsNotAllowed => { ret 325; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
@@ -98,7 +111,6 @@ fn label(code: ErrorCode): []u8 {
|
||||
.ShapeParamNotShape => { ret "E0308"; },
|
||||
.MacroCode => { ret "E0309"; },
|
||||
.FmtMissingArg => { ret "E0310"; },
|
||||
.FmtNonliteral => { ret "E0311"; },
|
||||
.FmtBadType => { ret "E0312"; },
|
||||
.HookNotMacro => { ret "E0313"; },
|
||||
.ParamHook => { ret "E0314"; },
|
||||
@@ -118,6 +130,13 @@ fn label(code: ErrorCode): []u8 {
|
||||
.DuplicateSuccess => { ret "E0707"; },
|
||||
.TryNoError => { ret "E0708"; },
|
||||
.LambdaCapture => { ret "E0801"; },
|
||||
.NotAssignable => { ret "E0108"; },
|
||||
.AssignToConst => { ret "E0109"; },
|
||||
.MissingDeclType => { ret "E0110"; },
|
||||
.ImportFailed => { ret "E0111"; },
|
||||
.BreakOutsideLoop => { ret "E0323"; },
|
||||
.ContinueOutsideLoop => { ret "E0324"; },
|
||||
.VarargsNotAllowed => { ret "E0325"; },
|
||||
}
|
||||
ret "";
|
||||
}
|
||||
|
||||
+32
-32
@@ -17,7 +17,7 @@ comptime fn Slice(T: type): type {
|
||||
_ptr: *T,
|
||||
_len: usize,
|
||||
|
||||
fn len(self: @self): usize {
|
||||
fn len(@Self self: @self): usize {
|
||||
ret self._len;
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ comptime fn Slice(T: type): type {
|
||||
comptime fn Array(T: type, N: usize): type {
|
||||
ret struct: IntoIter[Item = T, Iter = @Slice(T)] + Index[Output = T] {
|
||||
#builtin(array_len)
|
||||
fn len(self: @self): usize;
|
||||
fn len(@Self self: @self): usize;
|
||||
|
||||
#builtin(array_index)
|
||||
fn index(@Self self: *@self, i: usize): *T;
|
||||
@@ -83,46 +83,46 @@ comptime fn Int(bits: usize, signed: bool): type {
|
||||
+ Eq[Rhs = @self]
|
||||
+ Ord[Rhs = @self] {
|
||||
#op(add)
|
||||
fn add(lhs: @self, rhs: @self): @self;
|
||||
fn add(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(sub)
|
||||
fn sub(lhs: @self, rhs: @self): @self;
|
||||
fn sub(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(mul)
|
||||
fn mul(lhs: @self, rhs: @self): @self;
|
||||
fn mul(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(div)
|
||||
fn div(lhs: @self, rhs: @self): @self;
|
||||
fn div(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(mod)
|
||||
fn rem(lhs: @self, rhs: @self): @self;
|
||||
fn rem(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(neg)
|
||||
fn neg(value: @self): @self;
|
||||
fn neg(@Self value: @self): @self;
|
||||
|
||||
#op(bit_and)
|
||||
fn bit_and(lhs: @self, rhs: @self): @self;
|
||||
fn bit_and(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(bit_or)
|
||||
fn bit_or(lhs: @self, rhs: @self): @self;
|
||||
fn bit_or(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(bit_xor)
|
||||
fn bit_xor(lhs: @self, rhs: @self): @self;
|
||||
fn bit_xor(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(shl)
|
||||
fn shl(lhs: @self, rhs: @self): @self;
|
||||
fn shl(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(shr)
|
||||
fn shr(lhs: @self, rhs: @self): @self;
|
||||
fn shr(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(bit_not)
|
||||
fn bit_not(value: @self): @self;
|
||||
fn bit_not(@Self value: @self): @self;
|
||||
|
||||
#op(eq)
|
||||
fn eq(lhs: @self, rhs: @self): bool;
|
||||
fn eq(@Self lhs: @self, rhs: @self): bool;
|
||||
|
||||
#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]
|
||||
+ Ord[Rhs = @self] {
|
||||
#op(add)
|
||||
fn add(lhs: @self, rhs: @self): @self;
|
||||
fn add(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(sub)
|
||||
fn sub(lhs: @self, rhs: @self): @self;
|
||||
fn sub(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(mul)
|
||||
fn mul(lhs: @self, rhs: @self): @self;
|
||||
fn mul(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(div)
|
||||
fn div(lhs: @self, rhs: @self): @self;
|
||||
fn div(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(mod)
|
||||
fn rem(lhs: @self, rhs: @self): @self;
|
||||
fn rem(@Self lhs: @self, rhs: @self): @self;
|
||||
|
||||
#op(neg)
|
||||
fn neg(value: @self): @self;
|
||||
fn neg(@Self value: @self): @self;
|
||||
|
||||
#op(eq)
|
||||
fn eq(lhs: @self, rhs: @self): bool;
|
||||
fn eq(@Self lhs: @self, rhs: @self): bool;
|
||||
|
||||
#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 {
|
||||
ret struct: Eq[Rhs = @self] + Ord[Rhs = @self] {
|
||||
#op(eq)
|
||||
fn eq(lhs: @self, rhs: @self): bool;
|
||||
fn eq(@Self lhs: @self, rhs: @self): bool;
|
||||
|
||||
#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]
|
||||
+ Ord[Rhs = @self] {
|
||||
#op(add)
|
||||
fn add(lhs: @self, rhs: usize): @self;
|
||||
fn add(@Self lhs: @self, rhs: usize): @self;
|
||||
|
||||
#op(sub)
|
||||
fn sub(lhs: @self, rhs: usize): @self;
|
||||
fn sub(@Self lhs: @self, rhs: usize): @self;
|
||||
|
||||
#op(eq)
|
||||
fn eq(lhs: @self, rhs: @self): bool;
|
||||
fn eq(@Self lhs: @self, rhs: @self): bool;
|
||||
|
||||
#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 {
|
||||
ret struct: Eq[Rhs = @self] + Ord[Rhs = @self] {
|
||||
#op(eq)
|
||||
fn eq(lhs: @self, rhs: @self): bool;
|
||||
fn eq(@Self lhs: @self, rhs: @self): bool;
|
||||
|
||||
#op(ord)
|
||||
fn cmp(lhs: @self, rhs: @self): Ordering;
|
||||
fn cmp(@Self lhs: @self, rhs: @self): Ordering;
|
||||
};
|
||||
}
|
||||
+14
-14
@@ -14,94 +14,94 @@ type Ordering = enum {
|
||||
type Add = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn add(lhs: @self, rhs: Rhs): Output;
|
||||
fn add(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(sub)
|
||||
type Sub = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn sub(lhs: @self, rhs: Rhs): Output;
|
||||
fn sub(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(mul)
|
||||
type Mul = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn mul(lhs: @self, rhs: Rhs): Output;
|
||||
fn mul(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(div)
|
||||
type Div = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn div(lhs: @self, rhs: Rhs): Output;
|
||||
fn div(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(mod)
|
||||
type Mod = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn rem(lhs: @self, rhs: Rhs): Output;
|
||||
fn rem(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(neg)
|
||||
type Neg = shape {
|
||||
type Output;
|
||||
fn neg(value: @self): Output;
|
||||
fn neg(@Self value: @self): Output;
|
||||
};
|
||||
|
||||
#lang(bit_and)
|
||||
type BitAnd = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn bit_and(lhs: @self, rhs: Rhs): Output;
|
||||
fn bit_and(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(bit_or)
|
||||
type BitOr = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn bit_or(lhs: @self, rhs: Rhs): Output;
|
||||
fn bit_or(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(bit_xor)
|
||||
type BitXor = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn bit_xor(lhs: @self, rhs: Rhs): Output;
|
||||
fn bit_xor(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(shl)
|
||||
type Shl = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn shl(lhs: @self, rhs: Rhs): Output;
|
||||
fn shl(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(shr)
|
||||
type Shr = shape {
|
||||
type Rhs;
|
||||
type Output;
|
||||
fn shr(lhs: @self, rhs: Rhs): Output;
|
||||
fn shr(@Self lhs: @self, rhs: Rhs): Output;
|
||||
};
|
||||
|
||||
#lang(bit_not)
|
||||
type BitNot = shape {
|
||||
type Output;
|
||||
fn bit_not(value: @self): Output;
|
||||
fn bit_not(@Self value: @self): Output;
|
||||
};
|
||||
|
||||
#lang(eq)
|
||||
type Eq = shape {
|
||||
type Rhs;
|
||||
fn eq(lhs: @self, rhs: Rhs): bool;
|
||||
fn eq(@Self lhs: @self, rhs: Rhs): bool;
|
||||
};
|
||||
|
||||
#lang(ord)
|
||||
type Ord = shape {
|
||||
type Rhs;
|
||||
fn cmp(lhs: @self, rhs: Rhs): Ordering;
|
||||
fn cmp(@Self lhs: @self, rhs: Rhs): Ordering;
|
||||
};
|
||||
|
||||
#lang(index)
|
||||
|
||||
@@ -48,6 +48,7 @@ type Node = struct {
|
||||
LessEqual,
|
||||
GreaterThan,
|
||||
GreaterEqual,
|
||||
Reserved,
|
||||
}
|
||||
|
||||
type Agg = enum {
|
||||
@@ -79,7 +80,7 @@ type Node = struct {
|
||||
FieldDecl: struct { name: []u8, ty: Ref },
|
||||
VarDecl: struct { is_comptime: bool, name: []u8, ty: Ref, init: Ref },
|
||||
ConstDecl: struct { is_comptime: bool, name: []u8, ty: Ref, init: Ref },
|
||||
Alloc: struct { ty: Ref, value: Ref },
|
||||
Alloc: struct { ty: Ref, value: Ref, is_const: bool },
|
||||
|
||||
Block: struct { stmts: []Ref, tail: Ref },
|
||||
If: struct { cond: Ref, then: Ref, els: Ref, ret_ty: Ref },
|
||||
@@ -109,7 +110,7 @@ type Node = struct {
|
||||
PatList: []Ref,
|
||||
PatTuple: []Ref,
|
||||
PatField: struct { name: []u8, sub: Ref },
|
||||
|
||||
PatFields: []Ref,
|
||||
AggType: struct { kind: Agg, conforms: []Ref, fields: []Ref, decls: []Ref, injected: []Ref },
|
||||
ArrayType: struct { len: Ref, elem: Ref },
|
||||
SliceType: Ref,
|
||||
@@ -148,10 +149,12 @@ type Node = struct {
|
||||
Binary: struct { op: Op, lval: Ref, rval: Ref },
|
||||
Unary: struct { op: Op, val: Ref },
|
||||
Call: struct { is_comptime: bool, callee: Ref, args: []Ref },
|
||||
ShapeCall: struct { adapter: []u8, shapes: []Ref, args: []Ref },
|
||||
Comptime: Ref,
|
||||
AssocDecl: struct { name: []u8 },
|
||||
ShapeApply: struct { base: Ref, binds: []Ref },
|
||||
ShapeUse: struct { adapter: []u8, shapes: []Ref },
|
||||
ShapeNoDefault: []Ref,
|
||||
AssocBind: struct { name: []u8, ty: Ref },
|
||||
}
|
||||
}
|
||||
|
||||
+145
-15
@@ -54,6 +54,8 @@ type LoopCtx = struct {
|
||||
defer_base: usize,
|
||||
}
|
||||
|
||||
type GlobalInit = struct { mod: usize, gidx: usize, tid: usize, init: Ref };
|
||||
|
||||
type Hir2Ir = @self;
|
||||
|
||||
type OpEmitter = fn(*Hir2Ir, Ref, usize, []Ref): usize;
|
||||
@@ -71,6 +73,8 @@ loops: Vec, // LoopCtx
|
||||
defers: Vec, // 待执行的 defer / errdefer 体(HIR ref,LIFO)
|
||||
cur_defer_base: usize, // 当前函数的 defer 栈基址
|
||||
ct_mode: bool, // 正在编译 comptime chunk:局部常量初值可直接复现
|
||||
global_inits: Vec, // GlobalInit:非标量全局初值,在 main 入口执行
|
||||
global_inits_done: bool,
|
||||
|
||||
|
||||
fn new(hir: *Bld.HirNodeContainer, sema: *Sema, b: *IrBuilder, attr: *AttrM): Hir2Ir {
|
||||
@@ -87,6 +91,8 @@ fn new(hir: *Bld.HirNodeContainer, sema: *Sema, b: *IrBuilder, attr: *AttrM): Hi
|
||||
.defers = Vec.blank(@sizeof(usize), @alignof(usize)),
|
||||
.cur_defer_base = 0,
|
||||
.ct_mode = false,
|
||||
.global_inits = Vec.blank(@sizeof(GlobalInit), @alignof(GlobalInit)),
|
||||
.global_inits_done = false,
|
||||
};
|
||||
var i: usize = 0;
|
||||
while i < sema.defs.len {
|
||||
@@ -108,6 +114,7 @@ fn drop(self: *Hir2Ir) {
|
||||
Vec.drop(&self.fn_refs);
|
||||
Vec.drop(&self.loops);
|
||||
Vec.drop(&self.defers);
|
||||
Vec.drop(&self.global_inits);
|
||||
}
|
||||
|
||||
fn ignore_usize(v: usize) {}
|
||||
@@ -156,30 +163,38 @@ fn register_globals(self: *Hir2Ir) {
|
||||
var tid = SemaM.ir_of(self.sema, d.lang);
|
||||
var zero = true;
|
||||
var bytes = Vec.blank(1, 1);
|
||||
// 初值:仅支持零/未定义与整数字面量,其余暂零初始化(TODO)。
|
||||
var init_ref: usize = 0;
|
||||
var dn = Bld.node_ptr(self.hir, d.node);
|
||||
if dn != null {
|
||||
match dn.kind {
|
||||
.VarDecl(v) => { fill_global_bytes(self, v.init, d.lang, &bytes, &zero); },
|
||||
.ConstDecl(c) => { fill_global_bytes(self, c.init, d.lang, &bytes, &zero); },
|
||||
.VarDecl(v) => { init_ref = v.init; },
|
||||
.ConstDecl(c) => { init_ref = c.init; },
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
ignore_usize(IrBuilder.add_global(self.b, tid, zero, bytes));
|
||||
var needs_runtime = false;
|
||||
if init_ref != 0 {
|
||||
needs_runtime = !fill_global_bytes(self, init_ref, d.lang, &bytes, &zero);
|
||||
}
|
||||
var gidx = IrBuilder.add_global(self.b, tid, zero, bytes);
|
||||
if needs_runtime {
|
||||
var rec = GlobalInit { .mod = d.mod, .gidx = gidx, .tid = tid, .init = init_ref };
|
||||
match Vec.push(&self.global_inits, &rec as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
}
|
||||
}
|
||||
gi = gi + 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_global_bytes(self: *Hir2Ir, init_ref: usize, lang: usize, bytes: *Vec, zero: *bool) {
|
||||
if init_ref == 0 { zero.* = true; ret; }
|
||||
fn fill_global_bytes(self: *Hir2Ir, init_ref: usize, lang: usize, bytes: *Vec, zero: *bool): bool {
|
||||
if init_ref == 0 { zero.* = true; ret true; }
|
||||
var n = Bld.node_ptr(self.hir, init_ref);
|
||||
if n == null { zero.* = true; ret; }
|
||||
if n == null { zero.* = true; ret true; }
|
||||
match n.kind {
|
||||
.LitInt(v) => {
|
||||
var bits = LangType.int_bits(&self.sema.types, lang);
|
||||
var size = bits / 8;
|
||||
if size == 0 { zero.* = true; ret; }
|
||||
if size == 0 { zero.* = true; ret true; }
|
||||
zero.* = false;
|
||||
var i: usize = 0;
|
||||
while i < size {
|
||||
@@ -187,10 +202,39 @@ fn fill_global_bytes(self: *Hir2Ir, init_ref: usize, lang: usize, bytes: *Vec, z
|
||||
match Vec.push(bytes, &b as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
i = i + 1;
|
||||
}
|
||||
ret true;
|
||||
},
|
||||
.Undefined => { zero.* = true; },
|
||||
_ => { zero.* = true; }, // TODO: 其他初值
|
||||
.Undefined => { zero.* = true; ret true; },
|
||||
_ => { zero.* = true; ret false; }, // 聚合/字符串/函数指针等:main 入口运行时初始化
|
||||
}
|
||||
ret false;
|
||||
}
|
||||
|
||||
// 非标量全局初值在 main 入口执行;两个后端都只看到普通 IR。
|
||||
fn emit_global_inits(self: *Hir2Ir) {
|
||||
if self.global_inits_done { ret; }
|
||||
self.global_inits_done = true;
|
||||
var saved = self.sema.cur_mod;
|
||||
var i: usize = 0;
|
||||
while i < self.global_inits.len {
|
||||
var rec = (self.global_inits.data as *GlobalInit) + i;
|
||||
use_mod(self, rec.mod);
|
||||
var n = Bld.node_ptr(self.hir, rec.init);
|
||||
if n != null {
|
||||
match n.kind {
|
||||
.Undefined => { i = i + 1; continue; },
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
var v = emit_expr(self, rec.init);
|
||||
if v != 0 {
|
||||
var ptrir = TypeTable.make_ptr(&self.sema.types.ir, rec.tid);
|
||||
var gp = IrBuilder.type_const_global(self.b, ptrir, rec.gidx);
|
||||
ignore_usize(IrBuilder.mem_store(self.b, rec.tid, gp, v));
|
||||
}
|
||||
i = i + 1;
|
||||
}
|
||||
use_mod(self, saved);
|
||||
}
|
||||
|
||||
fn use_mod(self: *Hir2Ir, m: usize) {
|
||||
@@ -270,6 +314,7 @@ fn emit_fn(self: *Hir2Ir, i: usize) {
|
||||
}
|
||||
ignore_usize(IrBuilder.block_begin(self.b));
|
||||
emit_params(self, x.params, s.fn_tid);
|
||||
if s.mod == 0 && eqb(s.name, "main") { emit_global_inits(self); }
|
||||
emit_body(self, x.body);
|
||||
emit_deferred_until(self, self.cur_defer_base, false);
|
||||
if !self.b.terminated {
|
||||
@@ -1727,6 +1772,39 @@ fn emit_pattern_cond(self: *Hir2Ir, pat: usize, ol: usize, ov: usize): usize {
|
||||
IrBuilder.type_const_int(self.b, tir, idx as usize));
|
||||
},
|
||||
.PatTuple(_) => { ret 0; },
|
||||
.PatFields(xs) => {
|
||||
var sl = ol;
|
||||
if LangType.is_ptr(&self.sema.types, sl) { sl = LangType.elem_of(&self.sema.types, sl); }
|
||||
var sir = SemaM.ir_of(self.sema, sl);
|
||||
var acc: usize = 0;
|
||||
var i: usize = 0;
|
||||
while i < xs.len {
|
||||
var fnode = pat_expr(self, xs[i]);
|
||||
if fnode != null {
|
||||
match fnode.kind {
|
||||
.PatField(pf) => {
|
||||
var idx = LangType.member_idx(&self.sema.types, sl, pf.name);
|
||||
if idx >= 0 {
|
||||
var fl = LangType.member_lang(&self.sema.types, sl, idx as usize);
|
||||
var fv = field_value(self, sir, SemaM.ir_of(self.sema, fl), ov, idx as usize);
|
||||
var c = emit_pattern_cond(self, pf.sub, fl, fv);
|
||||
if c != 0 {
|
||||
if acc == 0 { acc = c; }
|
||||
else {
|
||||
acc = IrBuilder.arith_and(self.b,
|
||||
SemaM.ir_of(self.sema, LangType.make_bool(&self.sema.types)),
|
||||
acc, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
i = i + 1;
|
||||
}
|
||||
ret acc;
|
||||
},
|
||||
.PatList(x) => {
|
||||
if LangType.is_struct(&self.sema.types, ol) { ret 0; }
|
||||
var acc: usize = 0;
|
||||
@@ -1800,6 +1878,30 @@ fn emit_pattern_bind(self: *Hir2Ir, pat: usize, ol: usize, ov: usize) {
|
||||
var mv = field_value(self, SemaM.ir_of(self.sema, sl), SemaM.ir_of(self.sema, fl), ov, idx as usize);
|
||||
emit_pattern_bind(self, x.sub, fl, mv);
|
||||
},
|
||||
.PatFields(xs) => {
|
||||
var sl = ol;
|
||||
if LangType.is_ptr(&self.sema.types, sl) { sl = LangType.elem_of(&self.sema.types, sl); }
|
||||
var sir = SemaM.ir_of(self.sema, sl);
|
||||
var i: usize = 0;
|
||||
while i < xs.len {
|
||||
var fnode = pat_expr(self, xs[i]);
|
||||
if fnode != null {
|
||||
match fnode.kind {
|
||||
.PatField(pf) => {
|
||||
if pf.sub == 0 { i = i + 1; continue; }
|
||||
var idx = LangType.member_idx(&self.sema.types, sl, pf.name);
|
||||
if idx >= 0 {
|
||||
var fl = LangType.member_lang(&self.sema.types, sl, idx as usize);
|
||||
var mv = field_value(self, sir, SemaM.ir_of(self.sema, fl), ov, idx as usize);
|
||||
emit_pattern_bind(self, pf.sub, fl, mv);
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
i = i + 1;
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
@@ -1856,6 +1958,14 @@ fn emit_match(self: *Hir2Ir, ref: usize): usize {
|
||||
}
|
||||
var ov = emit_expr(self, 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 i: usize = 0;
|
||||
while i < x.arms.len {
|
||||
@@ -1965,6 +2075,16 @@ fn emit_const_agg(self: *Hir2Ir, ref: usize, sid: []u8): usize {
|
||||
ret IrBuilder.mem_load(self.b, tid, gp);
|
||||
}
|
||||
|
||||
fn is_undefined_expr(self: *Hir2Ir, ref: usize): bool {
|
||||
var n = Bld.node_ptr(self.hir, ref);
|
||||
if n == null { ret false; }
|
||||
match n.kind {
|
||||
.Undefined => { ret true; },
|
||||
_ => {},
|
||||
}
|
||||
ret false;
|
||||
}
|
||||
|
||||
fn emit_agg_lit(self: *Hir2Ir, ref: usize, fields: []Ref): usize {
|
||||
var sl = SemaM.tid_of(self.sema, ref);
|
||||
var sir = SemaM.ir_of(self.sema, sl);
|
||||
@@ -2031,6 +2151,8 @@ fn emit_agg_lit(self: *Hir2Ir, ref: usize, fields: []Ref): usize {
|
||||
var ml = LangType.member_lang(&self.sema.types, sl, i);
|
||||
var mir = SemaM.ir_of(self.sema, ml);
|
||||
var v: usize = 0;
|
||||
var has = false;
|
||||
var undef = false;
|
||||
var j: usize = 0;
|
||||
while j < fields.len {
|
||||
var fnode2 = Bld.node_ptr(self.hir, fields[j]);
|
||||
@@ -2038,18 +2160,26 @@ fn emit_agg_lit(self: *Hir2Ir, ref: usize, fields: []Ref): usize {
|
||||
match fnode2.kind {
|
||||
.FieldLit(y) => {
|
||||
var idx = LangType.member_idx(&self.sema.types, sl, y.name);
|
||||
if idx >= 0 && idx as usize == i { v = emit_expr(self, y.value); }
|
||||
if idx >= 0 && idx as usize == i {
|
||||
has = true;
|
||||
if is_undefined_expr(self, y.value) { undef = true; }
|
||||
else { v = emit_expr(self, y.value); }
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
j = j + 1;
|
||||
}
|
||||
if v == 0 {
|
||||
var faddr0 = IrBuilder.mem_field(self.b, sir, slot, i);
|
||||
emit_zero(self, mir, faddr0);
|
||||
} else {
|
||||
// 显式 undefined:不写该字段;缺省字段才零初始化。
|
||||
if undef {
|
||||
i = i + 1;
|
||||
continue;
|
||||
}
|
||||
var faddr = IrBuilder.mem_field(self.b, sir, slot, i);
|
||||
if !has || v == 0 {
|
||||
emit_zero(self, mir, faddr);
|
||||
} else {
|
||||
ignore_usize(IrBuilder.mem_store(self.b, mir, faddr, v));
|
||||
}
|
||||
i = i + 1;
|
||||
|
||||
+55
-11
@@ -83,9 +83,10 @@ fn check_hook(self: *Sema, hd: usize, kind: HookKind, at: Ref): bool {
|
||||
}
|
||||
},
|
||||
.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[1])) {
|
||||
!is_ref_type(self, param_type(self, f.params[1])) ||
|
||||
!is_ref_type(self, param_type(self, f.params[2])) {
|
||||
ok = false;
|
||||
}
|
||||
},
|
||||
@@ -128,7 +129,12 @@ fn run_hook(self: *Sema, hook_decl: usize, args: []Ref): Ref {
|
||||
var tags: [1]Ref = .[tag];
|
||||
var cn = Bld.node_ptr(&self.hir, call);
|
||||
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);
|
||||
self.ct.building = saved_building;
|
||||
var out: Ref = 0;
|
||||
var rn = Bld.node_ptr(&self.hir, call);
|
||||
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;
|
||||
out.args = args;
|
||||
out.changed = false;
|
||||
@@ -247,10 +254,25 @@ fn prepare_params(user: *any, callee_ref: Ref, args: []Ref, out: *HookParamResul
|
||||
}
|
||||
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));
|
||||
defer { Vec.drop(&buf); }
|
||||
var changed = false;
|
||||
var changed = has_implicit;
|
||||
var i: usize = 0;
|
||||
while i < f.params.len {
|
||||
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;
|
||||
}
|
||||
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;
|
||||
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;
|
||||
while hi > 0 {
|
||||
hi = hi - 1;
|
||||
@@ -285,8 +314,24 @@ fn prepare_params(user: *any, callee_ref: Ref, args: []Ref, out: *HookParamResul
|
||||
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)];
|
||||
var code = run_hook_tagged(self, hd - 1, hargs[0..2], x.args);
|
||||
SemaM.ensure_decl(self, hd - 1);
|
||||
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 {
|
||||
SemaM.sema_error_code_at(self, f.params[i], ErrorCode.ParamHook,
|
||||
"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,
|
||||
"missing param has no hook value", "");
|
||||
break;
|
||||
}
|
||||
if value == 0 { break; }
|
||||
match Vec.push(&buf, &value as *u8) {
|
||||
.Ok => {},
|
||||
.Err(error) => { ret; },
|
||||
|
||||
@@ -77,7 +77,7 @@ fn clone_ref(b: *Bld.HirNodeContainer, s: *CloneState, r: Ref): Ref {
|
||||
.FieldDecl(x) => { k = .FieldDecl(.{ .name = x.name, .ty = clone_ref(b, s, x.ty) }); },
|
||||
.VarDecl(x) => { k = .VarDecl(.{ .is_comptime = x.is_comptime, .name = x.name, .ty = clone_ref(b, s, x.ty), .init = clone_ref(b, s, x.init) }); },
|
||||
.ConstDecl(x) => { k = .ConstDecl(.{ .is_comptime = x.is_comptime, .name = x.name, .ty = clone_ref(b, s, x.ty), .init = clone_ref(b, s, x.init) }); },
|
||||
.Alloc(x) => { k = .Alloc(.{ .ty = clone_ref(b, s, x.ty), .value = clone_ref(b, s, x.value) }); },
|
||||
.Alloc(x) => { k = .Alloc(.{ .ty = clone_ref(b, s, x.ty), .value = clone_ref(b, s, x.value), .is_const = x.is_const }); },
|
||||
.Block(x) => { k = .Block(.{ .stmts = clone_refs(b, s, x.stmts), .tail = clone_ref(b, s, x.tail) }); },
|
||||
.If(x) => { k = .If(.{ .cond = clone_ref(b, s, x.cond), .then = clone_ref(b, s, x.then), .els = clone_ref(b, s, x.els), .ret_ty = clone_ref(b, s, x.ret_ty) }); },
|
||||
.IfVar(x) => { k = .IfVar(.{ .pattern = clone_ref(b, s, x.pattern), .init = clone_ref(b, s, x.init), .then = clone_ref(b, s, x.then), .els = clone_ref(b, s, x.els) }); },
|
||||
@@ -108,6 +108,7 @@ fn clone_ref(b: *Bld.HirNodeContainer, s: *CloneState, r: Ref): Ref {
|
||||
.PatList(xs) => { k = .PatList(clone_refs(b, s, xs)); },
|
||||
.PatTuple(xs) => { k = .PatTuple(clone_refs(b, s, xs)); },
|
||||
.PatField(x) => { k = .PatField(.{ .name = x.name, .sub = clone_ref(b, s, x.sub) }); },
|
||||
.PatFields(xs) => { k = .PatFields(clone_refs(b, s, xs)); },
|
||||
.AggType(x) => {
|
||||
k = .AggType(.{ .kind = x.kind, .conforms = clone_refs(b, s, x.conforms),
|
||||
.fields = clone_refs(b, s, x.fields),
|
||||
@@ -119,6 +120,10 @@ fn clone_ref(b: *Bld.HirNodeContainer, s: *CloneState, r: Ref): Ref {
|
||||
.ShapeUse(x) => {
|
||||
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) }); },
|
||||
.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)); },
|
||||
@@ -145,6 +150,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 on = Bld.node_ptr(b, out);
|
||||
if on != null { on.loc = n.loc; }
|
||||
record(s, r, out);
|
||||
ret out;
|
||||
}
|
||||
|
||||
@@ -84,6 +84,7 @@ fn read_node(sema: *Sema, vm: *any, off: u64, tmp: *Arena): Node {
|
||||
.PatList(xs) => { n = Node { .kind = .PatList(read_refs(sema, vm, xs, tmp)), .tags = tg }; },
|
||||
.PatTuple(xs) => { n = Node { .kind = .PatTuple(read_refs(sema, vm, xs, tmp)), .tags = tg }; },
|
||||
.PatField(x) => { n = Node { .kind = .PatField(.{ .name = read_bytes(sema, vm, x.name, tmp), .sub = x.sub }), .tags = tg }; },
|
||||
.PatFields(xs) => { n = Node { .kind = .PatFields(read_refs(sema, vm, xs, tmp)), .tags = tg }; },
|
||||
.AggType(x) => {
|
||||
n = Node { .kind = .AggType(.{ .kind = x.kind, .conforms = read_refs(sema, vm, x.conforms, tmp),
|
||||
.fields = read_refs(sema, vm, x.fields, tmp),
|
||||
@@ -95,6 +96,14 @@ fn read_node(sema: *Sema, vm: *any, off: u64, tmp: *Arena): Node {
|
||||
.ShapeUse(x) => {
|
||||
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 }; },
|
||||
.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 }; },
|
||||
@@ -172,6 +181,7 @@ fn write_node(sema: *Sema, vm: *any, off: u64, node: Node) {
|
||||
.PatList(xs) => { n = Node { .kind = .PatList(write_refs(sema, vm, xs)), .tags = tg }; },
|
||||
.PatTuple(xs) => { n = Node { .kind = .PatTuple(write_refs(sema, vm, xs)), .tags = tg }; },
|
||||
.PatField(x) => { n = Node { .kind = .PatField(.{ .name = write_bytes(sema, vm, x.name), .sub = x.sub }), .tags = tg }; },
|
||||
.PatFields(xs) => { n = Node { .kind = .PatFields(write_refs(sema, vm, xs)), .tags = tg }; },
|
||||
.AggType(x) => {
|
||||
n = Node { .kind = .AggType(.{ .kind = x.kind, .conforms = write_refs(sema, vm, x.conforms),
|
||||
.fields = write_refs(sema, vm, x.fields),
|
||||
@@ -183,6 +193,14 @@ fn write_node(sema: *Sema, vm: *any, off: u64, node: Node) {
|
||||
.ShapeUse(x) => {
|
||||
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 }; },
|
||||
.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 }; },
|
||||
|
||||
+42
-3
@@ -74,6 +74,33 @@ fn shape_method_hir(self: *Sema, shape_lang: usize, want_idx: usize): usize {
|
||||
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 {
|
||||
match LangType.kind_of(&self.types, l) {
|
||||
.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 => {
|
||||
// 互递归类型(如 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));
|
||||
defer { Vec.drop(&fields); }
|
||||
var i: usize = 0;
|
||||
while i < LangType.member_count(&self.types, l) {
|
||||
var fn2 = Bld.construct(&self.hir, .{ .kind = .FieldDecl(.{
|
||||
.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) => {} }
|
||||
i = i + 1;
|
||||
@@ -156,7 +194,7 @@ fn lang_to_reflect_hir_inner(self: *Sema, l: usize): usize {
|
||||
if pt == 0 { break; }
|
||||
var pr = Bld.construct(&self.hir, .{ .kind = .ParamDecl(.{
|
||||
.is_comptime = false, .by_ref = false, .name = "",
|
||||
.ty = lang_to_reflect_hir(self, pt),
|
||||
.ty = reflect_self_type(self, l, pt),
|
||||
}) });
|
||||
match Vec.push(¶ms, &pr as *u8) { .Ok => {}, .Err(e) => {} }
|
||||
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),
|
||||
.name = Bld.dup_bytes(&self.hir, name),
|
||||
.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,
|
||||
}) });
|
||||
SemaM.record_reflect_src(self, fd, mr);
|
||||
match Vec.push(&decls, &fd as *u8) { .Ok => {}, .Err(e) => {} }
|
||||
i = i + 1;
|
||||
}
|
||||
|
||||
+157
-23
@@ -26,6 +26,7 @@ type Def = struct {
|
||||
tid: usize,
|
||||
init: Ref, // 初值 HirRef(0 = 无);仅当 assigned=false 且初值为常量时可作常量复现
|
||||
assigned: bool, // 是否被重新赋值(赋值后不可当常量)
|
||||
mutable: bool, // var=true / const=false;赋值目标检查用
|
||||
}
|
||||
|
||||
// 每个 HIR Ref 的全部语义缓存集中到一项,避免多张 per-Ref 表长度漂移。
|
||||
@@ -75,6 +76,11 @@ type FnSym = struct {
|
||||
op: usize, // SemaOp 值;0 = 不是语言操作
|
||||
}
|
||||
|
||||
type ReflectSrc = struct {
|
||||
copy: Ref, // @meta.reflect 生成的方法签名副本
|
||||
src: Ref, // 原始 FnDecl 节点,用于反查 FnSym
|
||||
}
|
||||
|
||||
type TypeSym = struct {
|
||||
name: []u8,
|
||||
lang: usize,
|
||||
@@ -142,6 +148,7 @@ type GenInstance = struct { fn_ref: Ref, args: Vec, lang: usize };
|
||||
type ShapeParam = struct {
|
||||
fn_ref: Ref,
|
||||
param_index: usize,
|
||||
has_adapter: bool,
|
||||
adapter_decl: usize,
|
||||
shape_lang: usize,
|
||||
shape_ref: Ref, // ShapeApply / NamedType 使用点
|
||||
@@ -157,6 +164,7 @@ type ShapeInstance = struct {
|
||||
// shape 使用点的解析结果:`@adapter[Shape]` 里 adapter、shape 和绑定。
|
||||
type ShapeUse = struct {
|
||||
is_shape: bool,
|
||||
has_adapter: bool,
|
||||
adapter_decl: usize,
|
||||
shape_lang: usize,
|
||||
shape_ref: Ref,
|
||||
@@ -191,6 +199,12 @@ type ShapeAdapterResult = struct {
|
||||
adapter_mod: usize, // adapter FnDecl 所属模块
|
||||
};
|
||||
|
||||
// 类型生成器形参的 shape 约束求值结果:lang 是最终绑定进生成器的类型。
|
||||
type ShapeArgBind = struct {
|
||||
ok: bool,
|
||||
lang: usize,
|
||||
};
|
||||
|
||||
// comptime VM 内 IR 函数引用 -> Sema FnSym 的映射,用于把函数值还原为符号。
|
||||
type CtFnRef = struct { ref: Ref, sym: usize };
|
||||
|
||||
@@ -228,6 +242,9 @@ type ShapeState = struct {
|
||||
type_binds: Vec, // ShapeTypeBind,实例形参 ref -> lang
|
||||
assoc_types: Vec, // ShapeAssocType,shape 关联类型占位缓存
|
||||
composed: Vec, // ShapeComp,A + B 的临时组合
|
||||
patch_roots: Vec, // Ref,实例化时只需重解析的语句根
|
||||
patching: bool,
|
||||
patch_decl: usize, // 正在 patch 的 decl 下标;嵌套分析其他函数时必须走完整 sema
|
||||
};
|
||||
|
||||
// 一次 shape 调用点处理的结果;fn_tid/ret_tid 为实例化后的真实签名。
|
||||
@@ -245,6 +262,9 @@ type ShapeHooks = struct {
|
||||
check_conforms: fn(*any, Ref, usize): void,
|
||||
op_method: fn(*any, usize, usize, []u8): usize,
|
||||
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 只提供
|
||||
@@ -256,13 +276,14 @@ type HookParamResult = struct {
|
||||
|
||||
type HookHooks = struct {
|
||||
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,
|
||||
};
|
||||
|
||||
type ExprHooks = struct {
|
||||
sema_expr: fn(*any, Ref, usize): void,
|
||||
sema_body: fn(*any, usize, usize): void,
|
||||
patch_body: fn(*any, usize, usize): void,
|
||||
iter_capture_members: fn(*any, Ref): Vec,
|
||||
};
|
||||
|
||||
@@ -285,9 +306,11 @@ type LangHooks = struct {
|
||||
|
||||
type TypeHooks = struct {
|
||||
resolve_type: fn(*any, Ref): usize,
|
||||
resolve_decl_type: fn(*any, Ref, Ref): usize,
|
||||
resolve_param: fn(*any, Ref): usize,
|
||||
type_gen: fn(*any, Ref, Node.Kind.Call, 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_value_lang: fn(*any, Ref): usize,
|
||||
type_handle_arg: fn(*any, usize): usize,
|
||||
@@ -306,7 +329,6 @@ type BindingHooks = struct {
|
||||
builtin_tag_id: fn(*any, Ref): Builtin,
|
||||
has_tag: fn(*any, Ref, []u8): bool,
|
||||
has_builtin_tag: fn(*any, Ref): bool,
|
||||
insert_method_receiver: fn(*any, Ref, Ref, []Ref, *HookParamResult): void,
|
||||
collect_builtins: fn(*any): void,
|
||||
list_has_tag: fn(*any, []Ref, []u8): bool,
|
||||
raw_tag: fn(*any, Ref): []u8,
|
||||
@@ -328,6 +350,8 @@ hir: Bld.HirNodeContainer,
|
||||
mods: Vec, // Module
|
||||
cur_mod: usize,
|
||||
refs: Vec, // RefInfo,按 Ref 下标;0 号为哨兵
|
||||
reflect_stack: Vec, // 正在反射的 lang;互递归类型用名字截断
|
||||
reflect_srcs: Vec, // ReflectSrc:反射方法副本 -> 原始 FnDecl
|
||||
types: LangType,
|
||||
defs: Vec, // Def
|
||||
fn_syms: Vec, // FnSym(函数记录,惰性登记)
|
||||
@@ -338,6 +362,7 @@ def_global: Vec, // per def id -> gidx+1(0 = 非全局)
|
||||
loop_results: Vec, // 循环结果 lang 栈(供 break 值)
|
||||
current_agg: usize, // 当前所在聚合 lang(`@self`)
|
||||
self_lang: usize, // 非 0:当前实例化目标的 lang;`@self` 优先解析到它
|
||||
ret_override: usize, // 非 0:catch handler 内的 ret 使用外层函数返回类型
|
||||
lang_attach_depth: usize,
|
||||
|
||||
current_container: Ref, // 当前名称空间容器 ref(名字解析用)
|
||||
@@ -383,21 +408,32 @@ type_hooks: TypeHooks,
|
||||
binding_hooks: BindingHooks,
|
||||
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) {
|
||||
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 col: usize = 0;
|
||||
var has = false;
|
||||
if use != 0 {
|
||||
var n = Bld.node_ptr(&self.hir, use);
|
||||
if n != null && n.loc.line != 0 {
|
||||
line = n.loc.line;
|
||||
col = n.loc.col;
|
||||
has = true;
|
||||
var has = node_loc_of(self, use, &line, &col);
|
||||
// 生成/合成节点常常保留 ref 但 loc 为 0;继续向调用点/当前函数回退。
|
||||
if !has {
|
||||
use = self.macro_call_ref;
|
||||
has = node_loc_of(self, use, &line, &col);
|
||||
}
|
||||
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;
|
||||
if use != 0 {
|
||||
@@ -748,6 +784,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 {
|
||||
// 模块路径由 Sema 自己持有,driver 的临时 ModEntry 可以提前释放。
|
||||
var stable_path = ByteView.from_slice(Bld.dup_bytes(&hir, ByteView.as_slice(path)));
|
||||
@@ -760,6 +807,8 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
|
||||
.mods = Vec.blank(@sizeof(Module), @alignof(Module)),
|
||||
.cur_mod = 0,
|
||||
.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,
|
||||
.defs = Vec.blank(@sizeof(Def), @alignof(Def)),
|
||||
.fn_syms = Vec.blank(@sizeof(FnSym), @alignof(FnSym)),
|
||||
@@ -770,6 +819,7 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
|
||||
.loop_results = Vec.blank(@sizeof(usize), @alignof(usize)),
|
||||
.current_agg = 0,
|
||||
.self_lang = 0,
|
||||
.ret_override = 0,
|
||||
.lang_attach_depth = 0,
|
||||
.current_container = 0,
|
||||
.in_callee = false,
|
||||
@@ -800,11 +850,12 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
|
||||
.gen_method_binds = Vec.blank(@sizeof(GenBindRec), @alignof(GenBindRec)),
|
||||
.gen_instances = Vec.blank(@sizeof(GenInstance), @alignof(GenInstance)),
|
||||
.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 },
|
||||
.lang_hooks = LangHooks { .record_conforms = null, .copy_conforms = null, .conform_binds = null, .method_sym = null },
|
||||
.type_hooks = TypeHooks {
|
||||
.resolve_type = null, .resolve_param = null, .type_gen = null,
|
||||
.resolve_type = null, .resolve_decl_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_handle = null, .type_query_int = null,
|
||||
.type_builtin = null, .emit_intrinsic = null, .builtin_tid = null,
|
||||
@@ -812,7 +863,7 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
|
||||
},
|
||||
.binding_hooks = BindingHooks {
|
||||
.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,
|
||||
},
|
||||
.dump_hooks = DumpHooks { .dump = null },
|
||||
@@ -823,6 +874,9 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
|
||||
.type_binds = Vec.blank(@sizeof(ShapeTypeBind), @alignof(ShapeTypeBind)),
|
||||
.assoc_types = Vec.blank(@sizeof(ShapeAssocType), @alignof(ShapeAssocType)),
|
||||
.composed = Vec.blank(@sizeof(ShapeComp), @alignof(ShapeComp)),
|
||||
.patch_roots = Vec.blank(@sizeof(Ref), @alignof(Ref)),
|
||||
.patching = false,
|
||||
.patch_decl = 0,
|
||||
},
|
||||
.shape_hooks = ShapeHooks {
|
||||
.bind_params = null,
|
||||
@@ -831,6 +885,9 @@ fn new(hir: Bld.HirNodeContainer, path: ByteView, root: Ref, refs: []Ref): Sema
|
||||
.check_conforms = null,
|
||||
.op_method = null,
|
||||
.has_conformance = null,
|
||||
.is_shape_lang = null,
|
||||
.bind_type_arg = null,
|
||||
.apply_expr = null,
|
||||
},
|
||||
.shape_for_item = null,
|
||||
.hook_hooks = HookHooks {
|
||||
@@ -914,8 +971,11 @@ fn drop(self: *Sema) {
|
||||
ci = ci + 1;
|
||||
}
|
||||
Vec.drop(&self.shape_state.composed);
|
||||
Vec.drop(&self.shape_state.patch_roots);
|
||||
Vec.drop(&self.ct.fn_refs);
|
||||
Vec.drop(&self.refs);
|
||||
Vec.drop(&self.reflect_stack);
|
||||
Vec.drop(&self.reflect_srcs);
|
||||
var mi: usize = 0;
|
||||
while mi < self.mods.len {
|
||||
var mm = (self.mods.data as *Module) + mi;
|
||||
@@ -1085,6 +1145,11 @@ fn def_assigned(self: *Sema, d: usize): bool {
|
||||
ret (self.defs.data as *Def)[d - 1].assigned;
|
||||
}
|
||||
|
||||
fn def_mutable(self: *Sema, d: usize): bool {
|
||||
if d == 0 || d > self.defs.len { ret true; }
|
||||
ret (self.defs.data as *Def)[d - 1].mutable;
|
||||
}
|
||||
|
||||
fn set_def_init(self: *Sema, d: usize, init: Ref) {
|
||||
if d == 0 || d > self.defs.len { ret; }
|
||||
var e = (self.defs.data as *Def) + (d - 1);
|
||||
@@ -1099,18 +1164,18 @@ fn mark_assigned(self: *Sema, ref: Ref) {
|
||||
}
|
||||
|
||||
// 局部名已在 lowering 解析;sema 只为声明分配 def id。
|
||||
fn new_def(self: *Sema, tid: usize): usize {
|
||||
fn new_def(self: *Sema, tid: usize, mutable: bool): usize {
|
||||
var d = self.defs.len + 1;
|
||||
var e = Def { .tid = tid, .init = 0, .assigned = false };
|
||||
var e = Def { .tid = tid, .init = 0, .assigned = false, .mutable = mutable };
|
||||
match Vec.push(&self.defs, &e as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
var z: usize = 0;
|
||||
match Vec.push(&self.def_global, &z as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
ret d;
|
||||
}
|
||||
|
||||
fn new_global_def(self: *Sema, tid: usize, gidx: usize): usize {
|
||||
fn new_global_def(self: *Sema, tid: usize, gidx: usize, mutable: bool): usize {
|
||||
var d = self.defs.len + 1;
|
||||
var e = Def { .tid = tid, .init = 0, .assigned = false };
|
||||
var e = Def { .tid = tid, .init = 0, .assigned = false, .mutable = mutable };
|
||||
match Vec.push(&self.defs, &e as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
var gv = gidx + 1;
|
||||
match Vec.push(&self.def_global, &gv as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
@@ -1216,17 +1281,28 @@ fn scan_namespace_into(self: *Sema, ns_i: 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;
|
||||
while i < self.namespaces.len {
|
||||
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;
|
||||
}
|
||||
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)) };
|
||||
match Vec.push(&self.namespaces, &ns as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
var idx = self.namespaces.len - 1;
|
||||
scan_namespace_into(self, idx + 1);
|
||||
if ns_mod != saved { switch_mod(self, saved); }
|
||||
ret idx + 1;
|
||||
}
|
||||
|
||||
@@ -1302,7 +1378,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 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 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 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 {
|
||||
@@ -1337,8 +1412,15 @@ fn ct_lang(self: *Sema, h: tid): usize {
|
||||
|
||||
// 类型解析与生成器由 sema_type.spl 提供。
|
||||
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); }
|
||||
|
||||
// 声明位置的 `[_]T` 由类型层推断(sema_type),这里只做转发。
|
||||
fn resolve_decl_type(self: *Sema, ty_ref: Ref, init_ref: Ref): usize {
|
||||
if self.type_hooks.resolve_decl_type == null { ret 0; }
|
||||
ret self.type_hooks.resolve_decl_type(self as *any, ty_ref, init_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_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_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); }
|
||||
@@ -1454,6 +1536,25 @@ fn fn_sym_for_ref(self: *Sema, fn_ref: Ref): usize {
|
||||
if sym_at(self, i).ref == fn_ref { ret 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;
|
||||
}
|
||||
|
||||
@@ -1556,6 +1657,35 @@ fn resolve_unpack_member(self: *Sema, d: usize, name: []u8): usize {
|
||||
ret lookup_decl_in_mod(self, cmod, cont, name);
|
||||
}
|
||||
|
||||
// 点号 comptime 名按 `A.B` 命名空间路径解析;没有模块概念,
|
||||
// A 只是普通类型/值命名空间,逐段在容器命名空间里查。
|
||||
fn find_path_decl(self: *Sema, name: []u8): usize {
|
||||
var i: usize = 0;
|
||||
while i < name.len && name[i] != '.' { i = i + 1; }
|
||||
if i == name.len { ret 0; }
|
||||
var d = find_decl(self, name[0..i]);
|
||||
if d == 0 { ret 0; }
|
||||
var di = d - 1;
|
||||
ensure_decl(self, di);
|
||||
var lang = decl_at(self, di).lang;
|
||||
var pos = i + 1;
|
||||
while pos < name.len {
|
||||
var end = pos;
|
||||
while end < name.len && name[end] != '.' { end = end + 1; }
|
||||
if lang == 0 { ret 0; }
|
||||
var cmod = LangType.container_mod_of(&self.types, lang);
|
||||
var cont = LangType.container_of(&self.types, lang);
|
||||
var nd = lookup_decl_in_mod(self, cmod, cont, name[pos..end]);
|
||||
if nd == 0 { ret 0; }
|
||||
di = nd - 1;
|
||||
ensure_decl(self, di);
|
||||
lang = decl_at(self, di).lang;
|
||||
if end >= name.len { ret nd; }
|
||||
pos = end + 1;
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
// 按名查找有效声明(应用解包),返回 decl+1。
|
||||
fn find_decl(self: *Sema, name: []u8): usize {
|
||||
var d = lookup_decl(self, self.current_container, name);
|
||||
@@ -1615,7 +1745,7 @@ fn is_type_value_expr(self: *Sema, ref: Ref): bool {
|
||||
match n.kind {
|
||||
.IntType(_), .FloatType(_), .Bool, .Unit, .Any, .Type, .Never,
|
||||
.PtrType(_), .SliceType(_), .ArrayType(_), .FnType(_), .TupleType(_),
|
||||
.NamedType(_), .AggType(_), .ShapeApply(_), .ShapeUse(_) => { ret true; },
|
||||
.NamedType(_), .AggType(_), .ShapeApply(_), .ShapeUse(_), .ShapeNoDefault(_) => { ret true; },
|
||||
.Global(x) => {
|
||||
var d = find_decl(self, x);
|
||||
ret d != 0 && @enum2int(decl_at(self, d - 1).kind) == @enum2int(DeclKind.Type);
|
||||
@@ -1801,6 +1931,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); }
|
||||
}
|
||||
|
||||
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 {
|
||||
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);
|
||||
|
||||
@@ -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_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_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_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"); }
|
||||
@@ -44,7 +44,7 @@ fn hooks(): BindingHooks {
|
||||
.builtin_tag_id = hook_builtin_tag_id,
|
||||
.has_tag = hook_has_tag,
|
||||
.has_builtin_tag = hook_has_builtin_tag,
|
||||
.insert_method_receiver = hook_insert_method_receiver,
|
||||
|
||||
.collect_builtins = hook_collect_builtins,
|
||||
.list_has_tag = hook_list_has_tag,
|
||||
.raw_tag = hook_raw_tag,
|
||||
@@ -252,42 +252,7 @@ fn param_has_at(self: *Sema, param: Ref): bool {
|
||||
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 {
|
||||
var p = SemaM.module_at(self, m).path;
|
||||
|
||||
+45
-4
@@ -181,6 +181,14 @@ fn analyze_type_decl(self: *Sema, di: usize) {
|
||||
// 宏 varargs 的稳定类型标签;fmt 等库按标签选择生成代码。
|
||||
|
||||
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 container = SemaM.decl_at(self, di).container;
|
||||
var n = Bld.node_ptr(&self.hir, node);
|
||||
@@ -222,6 +230,11 @@ fn analyze_fn_decl(self: *Sema, di: usize) {
|
||||
is_va = true;
|
||||
} else {
|
||||
is_va = true;
|
||||
if !x.is_comptime {
|
||||
SemaM.sema_error_code_at(self, pref, ErrorCode.VarargsNotAllowed,
|
||||
"variadic parameter is only allowed in macro/comptime functions",
|
||||
"");
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -291,14 +304,33 @@ fn analyze_value_decl(self: *Sema, di: usize) {
|
||||
if n == null { ret; }
|
||||
var ty: usize = 0;
|
||||
var init: Ref = 0;
|
||||
var is_var = false;
|
||||
var has_ty = false;
|
||||
match n.kind {
|
||||
.VarDecl(x) => { ty = SemaM.resolve_type(self, x.ty); init = x.init; },
|
||||
.ConstDecl(x) => { ty = SemaM.resolve_type(self, x.ty); init = x.init; },
|
||||
.VarDecl(x) => {
|
||||
init = x.init;
|
||||
is_var = true;
|
||||
has_ty = x.ty != 0;
|
||||
if has_ty { ty = SemaM.resolve_decl_type(self, x.ty, init); }
|
||||
},
|
||||
.ConstDecl(x) => {
|
||||
init = x.init;
|
||||
has_ty = x.ty != 0;
|
||||
if has_ty { ty = SemaM.resolve_decl_type(self, x.ty, init); }
|
||||
},
|
||||
_ => { ret; },
|
||||
}
|
||||
if ty == 0 {
|
||||
if has_ty {
|
||||
// 声明类型存在但 `[_]T` 推断失败:错误已报,建 def 防止连锁。
|
||||
} else if init == 0 {
|
||||
SemaM.sema_error_code_at(self, node, ErrorCode.MissingDeclType,
|
||||
"declaration requires a type or an initializer", "");
|
||||
ret;
|
||||
} else {
|
||||
SemaM.sema_expr(self, init, 0);
|
||||
ty = SemaM.tid_of(self, init);
|
||||
}
|
||||
} else {
|
||||
SemaM.sema_expr(self, init, ty);
|
||||
}
|
||||
@@ -311,7 +343,7 @@ fn analyze_value_decl(self: *Sema, di: usize) {
|
||||
}
|
||||
var gidx = self.nglobals;
|
||||
self.nglobals = self.nglobals + 1;
|
||||
var def = SemaM.new_global_def(self, ty, gidx);
|
||||
var def = SemaM.new_global_def(self, ty, gidx, is_var);
|
||||
SemaM.set_def(self, node, def);
|
||||
SemaM.decl_at(self, di).gidx = gidx + 1;
|
||||
SemaM.decl_at(self, di).def = def;
|
||||
@@ -371,12 +403,21 @@ fn analyze_fn_body(self: *Sema, di: usize) {
|
||||
self.current_container = container;
|
||||
var ret_tid = SemaM.tid_of(self, x.ret_ty);
|
||||
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;
|
||||
while j < x.params.len {
|
||||
if patch_this { SemaM.set_def(self, x.params[j], 0); }
|
||||
bind_param(self, x.params[j]);
|
||||
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);
|
||||
}
|
||||
self.ret_override = saved_ret_override;
|
||||
self.cur_fn = saved_fn;
|
||||
self.cur_fn_ref = saved_ref;
|
||||
self.current_agg = saved_agg;
|
||||
@@ -396,7 +437,7 @@ fn bind_param(self: *Sema, ref: Ref) {
|
||||
match n.kind {
|
||||
.ParamDecl(x) => {
|
||||
var t = SemaM.resolve_param(self, ref);
|
||||
var d = SemaM.new_def(self, t);
|
||||
var d = SemaM.new_def(self, t, true);
|
||||
SemaM.set_def(self, ref, d);
|
||||
},
|
||||
_ => {},
|
||||
|
||||
+442
-79
@@ -11,6 +11,7 @@ type Bld = @import("./spl_ir_builder.spl");
|
||||
type .{ .Builtin } = @import("./intrinsic.spl");
|
||||
type B = @import("./intrinsic.spl");
|
||||
type SemaOpM = @import("./sema_op.spl");
|
||||
type ReflectType = @import("./reflect_type.spl");
|
||||
type .{ .SemaOp } = @import("./sema_op.spl");
|
||||
type .{ .LangKind, .ReprKind } = @import("./lang_type.spl");
|
||||
type .{ .StructMember } = @import("./lang_type.spl");
|
||||
@@ -26,6 +27,94 @@ type .{
|
||||
} = @import("./sema.spl");
|
||||
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_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); }
|
||||
@@ -34,6 +123,7 @@ fn hooks(): ExprHooks {
|
||||
ret ExprHooks {
|
||||
.sema_expr = hook_sema_expr,
|
||||
.sema_body = hook_sema_body,
|
||||
.patch_body = patch_body,
|
||||
.iter_capture_members = hook_iter_capture_members,
|
||||
};
|
||||
}
|
||||
@@ -49,8 +139,13 @@ fn bind_pattern(self: *Sema, ref: Ref, lang: usize) {
|
||||
match n.kind {
|
||||
.PatWild => { SemaM.set_tid(self, ref, 0); },
|
||||
.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, true);
|
||||
SemaM.set_def(self, ref, d);
|
||||
}
|
||||
SemaM.set_tid(self, ref, lang);
|
||||
},
|
||||
.PatLit(x) => { sema_expr(self, x, lang); SemaM.set_tid(self, ref, lang); },
|
||||
@@ -98,6 +193,27 @@ fn bind_pattern(self: *Sema, ref: Ref, lang: usize) {
|
||||
if x.sub != 0 { bind_pattern(self, x.sub, fl); }
|
||||
SemaM.set_tid(self, ref, sl);
|
||||
},
|
||||
.PatFields(xs) => {
|
||||
var sl = lang;
|
||||
if LangType.is_ptr(&self.types, sl) { sl = LangType.elem_of(&self.types, sl); }
|
||||
var i: usize = 0;
|
||||
while i < xs.len {
|
||||
var fnode = Bld.node_ptr(&self.hir, xs[i]);
|
||||
if fnode != null {
|
||||
match fnode.kind {
|
||||
.PatField(pf) => {
|
||||
var idx = LangType.member_idx(&self.types, sl, pf.name);
|
||||
var fl: usize = 0;
|
||||
if idx >= 0 { fl = LangType.member_lang(&self.types, sl, idx as usize); }
|
||||
if pf.sub != 0 { bind_pattern(self, pf.sub, fl); }
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
i = i + 1;
|
||||
}
|
||||
SemaM.set_tid(self, ref, sl);
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
@@ -176,7 +292,9 @@ fn dispatch_call_value(self: *Sema, ref: Ref, callee: Ref, args: []Ref, ct: usiz
|
||||
if self.shape_hooks.op_method == null { ret false; }
|
||||
var sym = self.shape_hooks.op_method(self as *any, ct, call_shape, "call");
|
||||
if sym == 0 { ret false; }
|
||||
// 参数 sema 可能追加 FnSym 并让 fn_syms 重分配,先保存返回类型。
|
||||
var s = SemaM.sym_at(self, sym - 1);
|
||||
var ret_tid = s.ret_tid;
|
||||
if LangType.fn_param_count(&self.types, s.fn_tid) < 2 { ret false; }
|
||||
var args_t = LangType.fn_param_of(&self.types, s.fn_tid, 1);
|
||||
if args_t == 0 { ret false; }
|
||||
@@ -201,7 +319,7 @@ fn dispatch_call_value(self: *Sema, ref: Ref, callee: Ref, args: []Ref, ct: usiz
|
||||
Vec.drop(&av);
|
||||
var cav: [2]Ref = .[callee, tuple_ref];
|
||||
var call_args = Bld.dup_refs(&self.hir, cav[0..2]);
|
||||
var call = build_op_call(self, sym, call_args, s.ret_tid);
|
||||
var call = build_op_call(self, sym, call_args, ret_tid);
|
||||
var cn = Bld.node_ptr(&self.hir, call);
|
||||
var np = Bld.node_ptr(&self.hir, ref);
|
||||
if cn != null && np != null {
|
||||
@@ -210,7 +328,7 @@ fn dispatch_call_value(self: *Sema, ref: Ref, callee: Ref, args: []Ref, ct: usiz
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
SemaM.set_tid(self, ref, s.ret_tid);
|
||||
SemaM.set_tid(self, ref, ret_tid);
|
||||
ret true;
|
||||
}
|
||||
|
||||
@@ -299,15 +417,18 @@ fn construct_variant_call(self: *Sema, ref: Ref, callee: Ref, args: []Ref): bool
|
||||
}
|
||||
|
||||
fn dispatch_user_binary(self: *Sema, ref: Ref, x: Node.Kind.Binary, lt: usize, sym: usize) {
|
||||
// FnSym 指针不能跨 sema_expr 保存:递归分析可能追加符号并让 fn_syms 重分配。
|
||||
var s = SemaM.sym_at(self, sym - 1);
|
||||
var fn_tid = s.fn_tid;
|
||||
var ret_tid = s.ret_tid;
|
||||
var rhs_want = lt;
|
||||
if LangType.fn_param_count(&self.types, s.fn_tid) > 1 {
|
||||
rhs_want = LangType.fn_param_of(&self.types, s.fn_tid, 1);
|
||||
if LangType.fn_param_count(&self.types, fn_tid) > 1 {
|
||||
rhs_want = LangType.fn_param_of(&self.types, fn_tid, 1);
|
||||
}
|
||||
sema_expr(self, x.rval, rhs_want);
|
||||
if rhs_want != 0 { SemaM.require_type(self, x.rval, rhs_want, "operand"); }
|
||||
|
||||
var out_tid = s.ret_tid;
|
||||
var out_tid = ret_tid;
|
||||
var av: [2]Ref = .[x.lval, x.rval];
|
||||
var args = Bld.dup_refs(&self.hir, av[0..2]);
|
||||
var call = build_op_call(self, sym, args, out_tid);
|
||||
@@ -372,9 +493,10 @@ fn dispatch_user_binary(self: *Sema, ref: Ref, x: Node.Kind.Binary, lt: usize, s
|
||||
|
||||
fn dispatch_user_unary(self: *Sema, ref: Ref, x: Node.Kind.Unary, vt: usize, sym: usize) {
|
||||
var s = SemaM.sym_at(self, sym - 1);
|
||||
var ret_tid = s.ret_tid;
|
||||
var av: [1]Ref = .[x.val];
|
||||
var args = Bld.dup_refs(&self.hir, av[0..1]);
|
||||
var call = build_op_call(self, sym, args, s.ret_tid);
|
||||
var call = build_op_call(self, sym, args, ret_tid);
|
||||
var cn = Bld.node_ptr(&self.hir, call);
|
||||
var np = Bld.node_ptr(&self.hir, ref);
|
||||
if cn != null && np != null {
|
||||
@@ -383,7 +505,7 @@ fn dispatch_user_unary(self: *Sema, ref: Ref, x: Node.Kind.Unary, vt: usize, sym
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
SemaM.set_tid(self, ref, s.ret_tid);
|
||||
SemaM.set_tid(self, ref, ret_tid);
|
||||
}
|
||||
|
||||
fn dispatch_user_index(self: *Sema, ref: Ref, x: Node.Kind.Index, ol: usize): bool {
|
||||
@@ -391,19 +513,21 @@ fn dispatch_user_index(self: *Sema, ref: Ref, x: Node.Kind.Index, ol: usize): bo
|
||||
if sl == 0 || self.shape_hooks.op_method == null { ret false; }
|
||||
var sym = self.shape_hooks.op_method(self as *any, ol, sl, "index");
|
||||
if sym == 0 { ret false; }
|
||||
// FnSym 指针不能跨 sema_expr 保存;先取出类型再递归分析下标。
|
||||
var s = SemaM.sym_at(self, sym - 1);
|
||||
var fn_tid = s.fn_tid;
|
||||
var ptr_ty = s.ret_tid;
|
||||
if !LangType.is_ptr(&self.types, ptr_ty) { ret false; }
|
||||
var item = LangType.elem_of(&self.types, ptr_ty);
|
||||
var idx_want = LangType.usize_lang(&self.types);
|
||||
if LangType.fn_param_count(&self.types, s.fn_tid) > 1 {
|
||||
idx_want = LangType.fn_param_of(&self.types, s.fn_tid, 1);
|
||||
if LangType.fn_param_count(&self.types, fn_tid) > 1 {
|
||||
idx_want = LangType.fn_param_of(&self.types, fn_tid, 1);
|
||||
}
|
||||
sema_expr(self, x.idx, idx_want);
|
||||
if idx_want != 0 { SemaM.require_type(self, x.idx, idx_want, "index"); }
|
||||
var recv_ty = ol;
|
||||
if LangType.fn_param_count(&self.types, s.fn_tid) > 0 {
|
||||
recv_ty = LangType.fn_param_of(&self.types, s.fn_tid, 0);
|
||||
if LangType.fn_param_count(&self.types, fn_tid) > 0 {
|
||||
recv_ty = LangType.fn_param_of(&self.types, fn_tid, 0);
|
||||
}
|
||||
var addr = Bld.construct(&self.hir, .{ .kind = .Addr(x.obj) });
|
||||
SemaM.grow_tables(self);
|
||||
@@ -466,7 +590,7 @@ fn bind_iter_captures(self: *Sema, captures: []Ref, members: []Ref, pattern_type
|
||||
}
|
||||
var d = SemaM.node_def(self, cap);
|
||||
if d == 0 {
|
||||
d = SemaM.new_def(self, ct);
|
||||
d = SemaM.new_def(self, ct, true);
|
||||
SemaM.set_def(self, cap, d);
|
||||
} else {
|
||||
SemaM.set_def_tid(self, d, ct);
|
||||
@@ -476,6 +600,74 @@ 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 "";
|
||||
}
|
||||
|
||||
// 把一个已解析的声明绑到表达式节点:`Global` 与 `Type.member` 共用。
|
||||
// Fn/Type/Var/Const 的绑定规则只在这里维护,避免两处漂移。
|
||||
fn bind_decl_ref(self: *Sema, ref: Ref, di: usize, want: usize) {
|
||||
var kind = SemaM.decl_at(self, di).kind;
|
||||
SemaM.ensure_decl(self, di);
|
||||
if @enum2int(kind) == @enum2int(DeclKind.Fn) {
|
||||
SemaM.set_node_fn(self, ref, SemaM.decl_at(self, di).sym);
|
||||
SemaM.set_tid(self, ref, SemaM.decl_at(self, di).lang);
|
||||
SemaM.record_call(self, SemaM.decl_at(self, di).sym);
|
||||
ret;
|
||||
}
|
||||
if @enum2int(kind) == @enum2int(DeclKind.Type) {
|
||||
if self.ct.building || (want != 0 && LangType.is_type(&self.types, want)) {
|
||||
// comptime 里类型名是类型值:物化为 ct_handle,供 == 和返回聚合使用。
|
||||
var tl = SemaM.decl_at(self, di).lang;
|
||||
var dn = Bld.node_ptr(&self.hir, SemaM.decl_at(self, di).node);
|
||||
if dn != null {
|
||||
match dn.kind {
|
||||
.TypeDecl(td) => {
|
||||
var rl = SemaM.resolve_type(self, td.ty);
|
||||
if rl != 0 { tl = rl; }
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
var h = SemaM.ct_handle(self, tl);
|
||||
Bld.node_ptr(&self.hir, ref).kind = .LitInt(SemaM.itext(self, h));
|
||||
SemaM.set_tid(self, ref, LangType.make_type(&self.types));
|
||||
} else {
|
||||
SemaM.set_tid(self, ref, SemaM.decl_at(self, di).lang);
|
||||
}
|
||||
ret;
|
||||
}
|
||||
if SemaM.decl_at(self, di).init != 0 {
|
||||
SemaM.set_node_initref(self, ref, SemaM.decl_at(self, di).init);
|
||||
} else {
|
||||
SemaM.set_def(self, ref, SemaM.decl_at(self, di).def);
|
||||
}
|
||||
SemaM.set_tid(self, ref, SemaM.decl_at(self, di).lang);
|
||||
}
|
||||
|
||||
fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
if ref == 0 { ret; }
|
||||
var n = Bld.node_ptr(&self.hir, ref);
|
||||
@@ -526,6 +718,7 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
},
|
||||
.Global(x) => {
|
||||
var d = SemaM.find_decl(self, x);
|
||||
if d == 0 { d = SemaM.find_path_decl(self, x); }
|
||||
if d == 0 {
|
||||
if SemaM.builtin_tid(self, x) == 0 && SemaM.lookup_type(self, x) == 0 {
|
||||
if SemaM.current_fn_is_lambda(self) {
|
||||
@@ -538,45 +731,15 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
SemaM.set_tid(self, ref, want);
|
||||
ret;
|
||||
}
|
||||
var di = d - 1;
|
||||
var kind = SemaM.decl_at(self, di).kind;
|
||||
SemaM.ensure_decl(self, di);
|
||||
if @enum2int(kind) == @enum2int(DeclKind.Fn) {
|
||||
SemaM.set_node_fn(self, ref, SemaM.decl_at(self, di).sym);
|
||||
SemaM.set_tid(self, ref, SemaM.decl_at(self, di).lang);
|
||||
SemaM.record_call(self, SemaM.decl_at(self, di).sym);
|
||||
} else if @enum2int(kind) == @enum2int(DeclKind.Type) {
|
||||
if self.ct.building || (want != 0 && LangType.is_type(&self.types, want)) {
|
||||
// comptime 里类型名是类型值:物化为 ct_handle,供 == 和返回聚合使用。
|
||||
var tl = SemaM.decl_at(self, di).lang;
|
||||
var dn = Bld.node_ptr(&self.hir, SemaM.decl_at(self, di).node);
|
||||
if dn != null {
|
||||
match dn.kind {
|
||||
.TypeDecl(td) => {
|
||||
var rl = SemaM.resolve_type(self, td.ty);
|
||||
if rl != 0 { tl = rl; }
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
var h = SemaM.ct_handle(self, tl);
|
||||
Bld.node_ptr(&self.hir, ref).kind = .LitInt(SemaM.itext(self, h));
|
||||
SemaM.set_tid(self, ref, LangType.make_type(&self.types));
|
||||
} else {
|
||||
SemaM.set_tid(self, ref, SemaM.decl_at(self, di).lang);
|
||||
}
|
||||
} else {
|
||||
if SemaM.decl_at(self, di).init != 0 {
|
||||
SemaM.set_node_initref(self, ref, SemaM.decl_at(self, di).init);
|
||||
} else {
|
||||
SemaM.set_def(self, ref, SemaM.decl_at(self, di).def);
|
||||
}
|
||||
SemaM.set_tid(self, ref, SemaM.decl_at(self, di).lang);
|
||||
}
|
||||
bind_decl_ref(self, ref, d - 1, want);
|
||||
},
|
||||
.Import(_) => {
|
||||
var tgt = SemaM.import_target(self, self.cur_mod, ref);
|
||||
if tgt == 0 { SemaM.set_tid(self, ref, 0); ret; }
|
||||
if tgt == 0 {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.ImportFailed, "cannot import module", "");
|
||||
SemaM.set_tid(self, ref, 0);
|
||||
ret;
|
||||
}
|
||||
var tm = tgt - 1;
|
||||
SemaM.ensure_module(self, tm);
|
||||
SemaM.set_tid(self, ref, SemaM.module_at(self, tm).root_lang);
|
||||
@@ -599,6 +762,13 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
}
|
||||
SemaM.set_tid(self, ref, want);
|
||||
},
|
||||
.LitChar(_) => {
|
||||
// 字符默认 u8;与整型上下文交互时沿用 LitInt 的重定型规则。
|
||||
if !LangType.is_int(&self.types, want) {
|
||||
want = LangType.make_int(&self.types, 8, false);
|
||||
}
|
||||
SemaM.set_tid(self, ref, want);
|
||||
},
|
||||
.LitFloat(_) => {
|
||||
if !LangType.is_float(&self.types, want) {
|
||||
want = LangType.make_float(&self.types, 64);
|
||||
@@ -677,6 +847,13 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// `Type.member`:容器命名空间里的 var/const/fn/type(Zig container-level)。
|
||||
if sl != 0 && (obj_is_type || SemaM.is_type_ref(self, x.obj)) {
|
||||
var cmod = LangType.container_mod_of(&self.types, sl);
|
||||
var cont = LangType.container_of(&self.types, sl);
|
||||
var d = SemaM.lookup_decl_in_mod(self, cmod, cont, x.name);
|
||||
if d != 0 { bind_decl_ref(self, ref, d - 1, want); ret; }
|
||||
}
|
||||
if ol != 0 && !LangType.is_type(&self.types, ol) &&
|
||||
!LangType.kind_eq(LangType.kind_of(&self.types, ol), .Any) {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.NoField, "no such field", x.name);
|
||||
@@ -685,7 +862,12 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
},
|
||||
.AggLit(x) => {
|
||||
var sl: usize = 0;
|
||||
if x.name.len != 0 { sl = SemaM.lookup_type(self, x.name); }
|
||||
// `@self { ... }`:以当前聚合匿名类型构造。
|
||||
if SemaM.eq(x.name, "self") {
|
||||
sl = self.self_lang;
|
||||
if sl == 0 { sl = self.current_agg; }
|
||||
}
|
||||
if sl == 0 && x.name.len != 0 { sl = SemaM.lookup_type(self, x.name); }
|
||||
if sl == 0 && want != 0 && LangType.is_agg(&self.types, want) { sl = want; }
|
||||
if sl == 0 && want != 0 && LangType.is_slice(&self.types, want) {
|
||||
// 切片字面量:字段名到表示槽位由 LangType 的表示层解析。
|
||||
@@ -872,6 +1054,14 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
var is_ct_builtin = false;
|
||||
var native_callee = false;
|
||||
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 cn = Bld.node_ptr(&self.hir, x.callee);
|
||||
if cn != null {
|
||||
@@ -883,6 +1073,7 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
var prefer_binding = x.is_comptime && bi != 0;
|
||||
var d: usize = 0;
|
||||
if !prefer_binding { d = SemaM.find_decl(self, vx); }
|
||||
if d == 0 && !prefer_binding { d = SemaM.find_path_decl(self, vx); }
|
||||
if d != 0 && @enum2int(SemaM.decl_at(self, d - 1).kind) == @enum2int(DeclKind.Fn) {
|
||||
SemaM.ensure_decl(self, d - 1);
|
||||
fn_tid = SemaM.decl_at(self, d - 1).lang;
|
||||
@@ -984,29 +1175,64 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
ret_tid = s2.ret_tid;
|
||||
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") &&
|
||||
!SemaM.has_tag(self, ref, "adapter_call") &&
|
||||
!SemaM.has_tag(self, ref, "hook_call");
|
||||
if is_macro && !x.is_comptime {
|
||||
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") {
|
||||
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 {
|
||||
var hr = HookParamResult { .args = x.args, .changed = false };
|
||||
self.hook_hooks.prepare_params(self as *any, callee_ref, x.args, &hr);
|
||||
// 实例化会改写形参类型,hook 注入结果必须按当前类型重算;
|
||||
// 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 {
|
||||
x.args = hr.args;
|
||||
} else if rerun {
|
||||
x.args = use_args;
|
||||
}
|
||||
if rerun || hr.changed {
|
||||
var call_node2 = Bld.node_ptr(&self.hir, ref);
|
||||
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") {
|
||||
@@ -1027,8 +1253,13 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
sema_expr(self, er, 0);
|
||||
var kind = SemaM.macro_arg_kind(self, er);
|
||||
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) => {} }
|
||||
ei = ei + 1;
|
||||
}
|
||||
@@ -1118,7 +1349,8 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
has_signature = true;
|
||||
}
|
||||
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 {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.ArgCount, "argument count mismatch", "");
|
||||
}
|
||||
@@ -1183,6 +1415,8 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
self.cur_fn_ref = saved_ref;
|
||||
self.cur_fn = sv;
|
||||
if is_macro {
|
||||
// 宏已通过 @meta.error 报过诊断:不要再叠加“返回值无效”错误。
|
||||
if self.had_error { ret; }
|
||||
var cn = Bld.node_ptr(&self.hir, ref);
|
||||
if cn == null { ret; }
|
||||
var code: Ref = 0;
|
||||
@@ -1214,8 +1448,18 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
SemaM.set_tid(self, ref, LangType.make_unit(&self.types));
|
||||
} 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) => {
|
||||
sema_expr(self, x.lval, want);
|
||||
check_assignable(self, x.lval);
|
||||
SemaM.mark_assigned(self, x.lval);
|
||||
var lt = SemaM.tid_of(self, x.lval);
|
||||
if lt == 0 { lt = want; }
|
||||
@@ -1256,15 +1500,17 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
},
|
||||
.User(sym) => {
|
||||
var s = SemaM.sym_at(self, sym - 1);
|
||||
var fn_tid = s.fn_tid;
|
||||
var ret_tid = s.ret_tid;
|
||||
var rhs_want = lt;
|
||||
if LangType.fn_param_count(&self.types, s.fn_tid) > 1 {
|
||||
rhs_want = LangType.fn_param_of(&self.types, s.fn_tid, 1);
|
||||
if LangType.fn_param_count(&self.types, fn_tid) > 1 {
|
||||
rhs_want = LangType.fn_param_of(&self.types, fn_tid, 1);
|
||||
}
|
||||
sema_expr(self, x.rval, rhs_want);
|
||||
if rhs_want != 0 { SemaM.require_type(self, x.rval, rhs_want, "compound assignment"); }
|
||||
var av: [2]Ref = .[x.lval, x.rval];
|
||||
var args = Bld.dup_refs(&self.hir, av[0..2]);
|
||||
var call = build_op_call(self, sym, args, s.ret_tid);
|
||||
var call = build_op_call(self, sym, args, ret_tid);
|
||||
SemaM.require_type(self, call, lt, "compound assignment");
|
||||
var np = Bld.node_ptr(&self.hir, ref);
|
||||
if np != null {
|
||||
@@ -1331,6 +1577,13 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
ret;
|
||||
}
|
||||
var op = SemaOpM.binary_op(x.op);
|
||||
if @enum2int(op) == @enum2int(SemaOp.Reserved) {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.OpNotImplemented,
|
||||
"reserved operator", "reserved operator");
|
||||
sema_expr(self, x.rval, lt);
|
||||
SemaM.set_tid(self, ref, lt);
|
||||
ret;
|
||||
}
|
||||
if @enum2int(op) == @enum2int(SemaOp.None) {
|
||||
sema_expr(self, x.rval, lt);
|
||||
if lt != 0 { SemaM.require_type(self, x.rval, lt, "operand"); }
|
||||
@@ -1369,8 +1622,20 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
},
|
||||
.Addr(x) => {
|
||||
sema_expr(self, x, 0);
|
||||
var t = want;
|
||||
if t == 0 { t = LangType.make_ptr(&self.types, SemaM.tid_of(self, x)); }
|
||||
var ot = 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);
|
||||
},
|
||||
.Deref(x) => {
|
||||
@@ -1587,15 +1852,72 @@ fn sema_expr(self: *Sema, ref: Ref, want: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
fn sema_let(self: *Sema, ref: Ref, ret_tid: usize) {
|
||||
// 赋值目标检查:只有 Local / Field / Index / Deref 可写,const 绑定不可写。
|
||||
fn check_assignable(self: *Sema, ref: Ref) {
|
||||
var n = Bld.node_ptr(&self.hir, ref);
|
||||
if n == null { ret; }
|
||||
match n.kind {
|
||||
.Local(x) => {
|
||||
var d = SemaM.node_def(self, x);
|
||||
if d != 0 && !SemaM.def_mutable(self, d) {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.AssignToConst,
|
||||
"cannot assign to const binding", "");
|
||||
}
|
||||
},
|
||||
.Field(x) => {
|
||||
// `S.c`:命名空间全局在 bind_decl_ref 里把 def 挂到 Field 节点上。
|
||||
var d = SemaM.node_def(self, ref);
|
||||
if d != 0 && !SemaM.def_mutable(self, d) {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.AssignToConst,
|
||||
"cannot assign to const binding", "");
|
||||
ret;
|
||||
}
|
||||
// 指针/切片的字段访问是写穿,不要求指针本身是 lvalue。
|
||||
var ot = SemaM.tid_of(self, x.obj);
|
||||
if LangType.is_ptr(&self.types, ot) || LangType.is_slice(&self.types, ot) { ret; }
|
||||
check_assignable(self, x.obj);
|
||||
},
|
||||
.Index(x) => {
|
||||
var ot = SemaM.tid_of(self, x.obj);
|
||||
if LangType.is_ptr(&self.types, ot) || LangType.is_slice(&self.types, ot) { ret; }
|
||||
check_assignable(self, x.obj);
|
||||
},
|
||||
.Deref(_) => {},
|
||||
.Global(x) => {
|
||||
var d = SemaM.node_def(self, ref);
|
||||
if d != 0 && !SemaM.def_mutable(self, d) {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.AssignToConst,
|
||||
"cannot assign to const binding", "");
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.NotAssignable,
|
||||
"assignment target is not assignable", "");
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn sema_let(self: *Sema, ref: Ref, ret_tid: usize) { var n = Bld.node_ptr(&self.hir, ref);
|
||||
if n == null { ret; }
|
||||
// 生成方法体可能被重复进入;重复 new_def 会让 Local 读取未初始化槽。
|
||||
if SemaM.node_def(self, ref) != 0 { ret; }
|
||||
match n.kind {
|
||||
.Alloc(x) => {
|
||||
var ty = SemaM.resolve_type(self, x.ty);
|
||||
if ty == 0 {
|
||||
var ty: usize = 0;
|
||||
if x.ty != 0 {
|
||||
ty = SemaM.resolve_decl_type(self, x.ty, x.value);
|
||||
if ty != 0 {
|
||||
sema_expr(self, x.value, ty);
|
||||
SemaM.require_type(self, x.value, ty, "initializer");
|
||||
}
|
||||
} else if x.value == 0 {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.MissingDeclType,
|
||||
"declaration requires a type or an initializer", "");
|
||||
var d0 = SemaM.new_def(self, 0, !x.is_const);
|
||||
SemaM.set_def(self, ref, d0);
|
||||
SemaM.set_tid(self, ref, 0);
|
||||
ret;
|
||||
} else {
|
||||
sema_expr(self, x.value, 0);
|
||||
ty = SemaM.tid_of(self, x.value);
|
||||
if ty == 0 { ty = ret_tid; }
|
||||
@@ -1604,12 +1926,9 @@ fn sema_let(self: *Sema, ref: Ref, ret_tid: usize) {
|
||||
var l = SemaM.ct_lang(self, SemaM.type_handle_arg(self, x.value));
|
||||
if l != 0 { ty = l; }
|
||||
}
|
||||
} else {
|
||||
sema_expr(self, x.value, ty);
|
||||
SemaM.require_type(self, x.value, ty, "initializer");
|
||||
}
|
||||
SemaM.set_tid(self, ref, ty);
|
||||
var d = SemaM.new_def(self, ty);
|
||||
var d = SemaM.new_def(self, ty, !x.is_const);
|
||||
SemaM.set_def(self, ref, d);
|
||||
SemaM.set_def_init(self, d, x.value);
|
||||
},
|
||||
@@ -1623,9 +1942,12 @@ fn sema_stmt(self: *Sema, ref: Ref, ret_tid: usize) {
|
||||
if n == null { ret; }
|
||||
match n.kind {
|
||||
.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) {
|
||||
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); },
|
||||
@@ -1651,11 +1973,20 @@ fn sema_stmt(self: *Sema, ref: Ref, ret_tid: usize) {
|
||||
var w: usize = 0;
|
||||
if self.loop_results.len != 0 {
|
||||
w = (self.loop_results.data as *usize)[self.loop_results.len - 1];
|
||||
} else {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.BreakOutsideLoop,
|
||||
"break outside loop", "");
|
||||
}
|
||||
if x.value != 0 { sema_expr(self, x.value, w); }
|
||||
SemaM.set_tid(self, ref, w);
|
||||
},
|
||||
.Continue(_) => { SemaM.set_tid(self, ref, 0); },
|
||||
.Continue(_) => {
|
||||
if self.loop_results.len == 0 {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.ContinueOutsideLoop,
|
||||
"continue outside loop", "");
|
||||
}
|
||||
SemaM.set_tid(self, ref, 0);
|
||||
},
|
||||
.Block(x) => {
|
||||
var i: usize = 0;
|
||||
while i < x.stmts.len {
|
||||
@@ -1664,7 +1995,7 @@ fn sema_stmt(self: *Sema, ref: Ref, ret_tid: usize) {
|
||||
}
|
||||
sema_expr(self, x.tail, ret_tid);
|
||||
},
|
||||
_ => { sema_expr(self, ref, ret_tid); },
|
||||
_ => { sema_expr(self, ref, 0); },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1675,3 +2006,35 @@ fn sema_body(self: *Sema, body: usize, ret_tid: usize) {
|
||||
if body == 0 { ret; }
|
||||
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); }
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ type SemaOp = enum {
|
||||
Invoke,
|
||||
Iter,
|
||||
IntoIter,
|
||||
Reserved,
|
||||
};
|
||||
|
||||
fn binary_op(op: Node.Kind.Op): SemaOp {
|
||||
@@ -47,6 +48,7 @@ fn binary_op(op: Node.Kind.Op): SemaOp {
|
||||
.RightShift => { ret .Shr; },
|
||||
.Equal, .NotEqual => { ret .Eq; },
|
||||
.LessThan, .LessEqual, .GreaterThan, .GreaterEqual => { ret .Ord; },
|
||||
.Reserved => { ret .Reserved; },
|
||||
_ => {},
|
||||
}
|
||||
ret .None;
|
||||
@@ -102,6 +104,7 @@ fn symbol_text(op: SemaOp): []u8 {
|
||||
.Ord => { ret "<"; },
|
||||
.Index => { ret "[]"; },
|
||||
.Invoke => { ret "()"; },
|
||||
.Reserved => { ret "reserved operator"; },
|
||||
_ => {},
|
||||
}
|
||||
ret "?";
|
||||
|
||||
+182
-10
@@ -22,14 +22,16 @@ type .{
|
||||
.TypeHooks, .GenBind, .GenBindRec, .GenInstance, .ShapeParam, .ShapeInstance,
|
||||
.ShapeUse, .ShapeAssocType, .ShapeComp, .IterInfo, .ShapeAdapterResult, .CtFnRef,
|
||||
.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
|
||||
} = @import("./sema.spl");
|
||||
type tid = usize;
|
||||
|
||||
fn hook_resolve_type(user: *any, ref: Ref): usize { ret resolve_type(user as *Sema, ref); }
|
||||
fn hook_resolve_decl_type(user: *any, ty: Ref, init: Ref): usize { ret resolve_decl_type(user as *Sema, ty, init); }
|
||||
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_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_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); }
|
||||
@@ -48,9 +50,11 @@ fn hook_instantiate_generator(user: *any, ref: Ref, x: Node.Kind.Call, di: usize
|
||||
fn hooks(): TypeHooks {
|
||||
ret TypeHooks {
|
||||
.resolve_type = hook_resolve_type,
|
||||
.resolve_decl_type = hook_resolve_decl_type,
|
||||
.resolve_param = hook_resolve_param,
|
||||
.type_gen = hook_type_gen,
|
||||
.instantiate_generator = hook_instantiate_generator,
|
||||
.type_is_generator = hook_type_is_generator,
|
||||
.type_arg_lang = hook_type_arg_lang,
|
||||
.type_value_lang = hook_type_value_lang,
|
||||
.type_handle_arg = hook_type_handle_arg,
|
||||
@@ -68,11 +72,13 @@ fn hooks(): TypeHooks {
|
||||
fn main() {}
|
||||
|
||||
fn gen_find(self: *Sema, name: []u8): usize {
|
||||
var i: usize = 0;
|
||||
while i < self.gen_binds.len {
|
||||
// gen_binds 是栈:外层生成器先入栈,内层后入栈。同名参数必须命中内层,
|
||||
// 否则 `@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;
|
||||
if SemaM.eq(b.name, name) { ret i + 1; }
|
||||
i = i + 1;
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
@@ -165,6 +171,23 @@ fn gen_instance_push(self: *Sema, fn_ref: Ref, args: []usize, lang: usize) {
|
||||
|
||||
// comptime fn `f(params...) type { ... }`:先查生成器声明的内建表示;
|
||||
// 命中 `#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 {
|
||||
var cn = Bld.node_ptr(&self.hir, x.callee);
|
||||
if cn == null { ret 0; }
|
||||
@@ -175,6 +198,8 @@ fn type_gen_lang(self: *Sema, ref: Ref, x: Node.Kind.Call, self_lang: usize): us
|
||||
}
|
||||
var d = SemaM.find_decl(self, name);
|
||||
if d == 0 { d = SemaM.find_lang_decl(self, name); }
|
||||
// 内置绑定(如 meta.build)优先于同名普通 FnDecl,否则会绕过 intrinsic。
|
||||
if d == 0 && SemaM.find_binding(self, name) == 0 { d = SemaM.find_path_decl(self, name); }
|
||||
if d == 0 { ret 0; }
|
||||
var di = d - 1;
|
||||
if @enum2int(SemaM.decl_at(self, di).kind) != @enum2int(DeclKind.Fn) { ret 0; }
|
||||
@@ -235,15 +260,17 @@ fn instantiate_generator(self: *Sema, ref: Ref, x: Node.Kind.Call, di: usize, se
|
||||
var base = self.gen_binds.len;
|
||||
var key = Vec.blank(@sizeof(usize), @alignof(usize));
|
||||
var key_ok = true;
|
||||
var bad_bound = false;
|
||||
var j: usize = 0;
|
||||
while j < params.len {
|
||||
var pn = Bld.node_ptr(&self.hir, params[j]);
|
||||
if pn == null { break; }
|
||||
var pname: []u8 = "";
|
||||
var pty: usize = 0;
|
||||
var pty_ref: Ref = 0;
|
||||
var got = false;
|
||||
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; }
|
||||
@@ -255,11 +282,68 @@ fn instantiate_generator(self: *Sema, ref: Ref, x: Node.Kind.Call, di: usize, se
|
||||
if al == 0 { key_ok = false; }
|
||||
match Vec.push(&key, &al as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
gen_push(self, pname, true, al, 0);
|
||||
} else {
|
||||
// 值实参可能是调用方的 const 表达式,同样在调用方模块求值。
|
||||
} else if self.shape_hooks.is_shape_lang != null &&
|
||||
self.shape_hooks.is_shape_lang(self as *any, pty) {
|
||||
// shape 约束的类型参数:实参在调用方模块解析,约束在生成器模块求值。
|
||||
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]);
|
||||
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;
|
||||
if an != null {
|
||||
match an.kind {
|
||||
@@ -272,12 +356,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 dmod != saved { SemaM.switch_mod(self, dmod); }
|
||||
match Vec.push(&key, &av as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
gen_push(self, pname, false, 0, av);
|
||||
}
|
||||
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 {
|
||||
var cached = gen_instance_find(self, SemaM.decl_at(self, di).node,
|
||||
(key.data as *usize)[0..key.len]);
|
||||
@@ -291,11 +382,13 @@ fn instantiate_generator(self: *Sema, ref: Ref, x: Node.Kind.Call, di: usize, se
|
||||
// 每次实例化克隆生成器体:方法 FnDecl 和 @self 必须按实例隔离,
|
||||
// 否则不同实参共用同一组方法节点和 gen_binds 记录。
|
||||
var inst_body = body;
|
||||
var clone_start = Bld.count(&self.hir);
|
||||
if body != 0 {
|
||||
var clone_state = NodeClone.new();
|
||||
inst_body = NodeClone.clone_ref(&self.hir, &clone_state, body);
|
||||
NodeClone.drop(&clone_state);
|
||||
}
|
||||
SemaM.record_new_ref_mods(self, dmod, clone_start);
|
||||
var saved_self = self.self_lang;
|
||||
if self_lang != 0 { self.self_lang = self_lang; }
|
||||
var lang = gen_eval_body(self, inst_body);
|
||||
@@ -599,6 +692,63 @@ fn type_ref_is_self(self: *Sema, ref: Ref): bool {
|
||||
ret false;
|
||||
}
|
||||
|
||||
// 声明位置的 `[_]T`:长度由初始化器推断,元素类型取声明里的,归一成 `[N]T`。
|
||||
fn resolve_decl_type(self: *Sema, ty_ref: Ref, init_ref: Ref): usize {
|
||||
if ty_ref == 0 { ret 0; }
|
||||
var is_infer = false;
|
||||
var elem_ref: Ref = 0;
|
||||
var n = Bld.node_ptr(&self.hir, ty_ref);
|
||||
if n != null {
|
||||
match n.kind {
|
||||
.ArrayType(x) => {
|
||||
if x.len == 0 {
|
||||
is_infer = true;
|
||||
elem_ref = x.elem;
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
if !is_infer { ret resolve_type(self, ty_ref); }
|
||||
if init_ref == 0 {
|
||||
SemaM.sema_error_code_at(self, ty_ref, ErrorCode.TypeMismatch,
|
||||
"cannot infer array length without an initializer", "");
|
||||
ret 0;
|
||||
}
|
||||
var e = resolve_type(self, elem_ref);
|
||||
// 字面量初始化器:长度可直接从元素个数得到,再按 `[N]e` 定型元素。
|
||||
var lit_len: usize = 0;
|
||||
var is_lit = false;
|
||||
var init_n = Bld.node_ptr(&self.hir, init_ref);
|
||||
if init_n != null {
|
||||
match init_n.kind {
|
||||
.ArrayLit(x) => { lit_len = x.elems.len; is_lit = true; },
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
if is_lit {
|
||||
var lt = SemaLang.array_type(self, e, lit_len, elem_ref, 0);
|
||||
SemaM.set_tid(self, ty_ref, lt);
|
||||
SemaM.sema_expr(self, init_ref, lt);
|
||||
ret lt;
|
||||
}
|
||||
SemaM.sema_expr(self, init_ref, 0);
|
||||
var it = SemaM.tid_of(self, init_ref);
|
||||
if !LangType.is_array(&self.types, it) {
|
||||
SemaM.sema_error_code_at(self, ty_ref, ErrorCode.TypeMismatch,
|
||||
"initializer is not an array; cannot infer array length", "");
|
||||
ret 0;
|
||||
}
|
||||
if LangType.elem_of(&self.types, it) != e {
|
||||
SemaM.sema_error_code_at(self, ty_ref, ErrorCode.TypeMismatch,
|
||||
"initializer element type does not match array element type", "");
|
||||
ret 0;
|
||||
}
|
||||
var t = SemaLang.array_type(self, e, LangType.array_len_of(&self.types, it), elem_ref, 0);
|
||||
SemaM.set_tid(self, ty_ref, t);
|
||||
ret t;
|
||||
}
|
||||
|
||||
fn resolve_type(self: *Sema, ref: Ref): usize {
|
||||
if ref == 0 { ret 0; }
|
||||
// 类型生成器实例化期间不使用缓存:泛型分析时缓存的是未代入参数的类型。
|
||||
@@ -657,7 +807,10 @@ fn resolve_type(self: *Sema, ref: Ref): usize {
|
||||
},
|
||||
.Import(_) => {
|
||||
var tgt = SemaM.import_target(self, self.cur_mod, ref);
|
||||
if tgt == 0 { ret 0; }
|
||||
if tgt == 0 {
|
||||
SemaM.sema_error_code_at(self, ref, ErrorCode.ImportFailed, "cannot import module", "");
|
||||
ret 0;
|
||||
}
|
||||
var tm = tgt - 1;
|
||||
SemaM.ensure_module(self, tm);
|
||||
var mt = SemaM.module_at(self, tm).root_lang;
|
||||
@@ -719,7 +872,20 @@ fn resolve_type(self: *Sema, ref: Ref): usize {
|
||||
SemaM.set_tid(self, ref, 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) => {
|
||||
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 i: usize = 0;
|
||||
while i < x.fields.len {
|
||||
@@ -749,7 +915,13 @@ fn resolve_type(self: *Sema, ref: Ref): usize {
|
||||
} else {
|
||||
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);
|
||||
// 实例化生成 struct:把参数绑定记到它的每个方法上,供分析方法体时重新激活。
|
||||
if self.gen_binds.len > 0 {
|
||||
|
||||
+495
-28
@@ -16,13 +16,15 @@ type ShapeInstance = SemaM.ShapeInstance;
|
||||
type ShapeUse = SemaM.ShapeUse;
|
||||
type ShapeAdapterResult = SemaM.ShapeAdapterResult;
|
||||
type ShapeAdapterEval = SemaM.ShapeAdapterEval;
|
||||
type ShapeArgBind = SemaM.ShapeArgBind;
|
||||
type ShapeTypeBind = SemaM.ShapeTypeBind;
|
||||
type CtFnRef = SemaM.CtFnRef;
|
||||
type Decl = SemaM.Decl;
|
||||
type ShapeCallResult = SemaM.ShapeCallResult;
|
||||
type ShapeHooks = SemaM.ShapeHooks;
|
||||
type ShapeComp = SemaM.ShapeComp;
|
||||
type ShapeBind = SemaM.ShapeBind;
|
||||
type ShapeComp = SemaM.ShapeComp;
|
||||
type RefInfo = SemaM.RefInfo;
|
||||
|
||||
fn shape_bind_find(binds: *Vec, name: []u8): usize {
|
||||
var i: usize = 0;
|
||||
@@ -55,6 +57,7 @@ fn shape_use_shape_count(self: *Sema, ref: Ref): usize {
|
||||
if n == null { ret 0; }
|
||||
match n.kind {
|
||||
.ShapeUse(x) => { ret x.shapes.len; },
|
||||
.ShapeNoDefault(xs) => { ret xs.len; },
|
||||
_ => {},
|
||||
}
|
||||
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]; }
|
||||
ret 0;
|
||||
},
|
||||
.ShapeNoDefault(xs) => {
|
||||
if i < xs.len { ret xs[i]; }
|
||||
ret 0;
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
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 {
|
||||
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; }
|
||||
var n = Bld.node_ptr(&self.hir, ty_ref);
|
||||
if n == null { ret out; }
|
||||
var adapter_name: []u8 = "";
|
||||
var no_default = false;
|
||||
match n.kind {
|
||||
.ShapeUse(x) => { adapter_name = x.adapter; },
|
||||
.ShapeNoDefault(_) => { no_default = true; },
|
||||
_ => {
|
||||
var old = at_tag_name(self, ty_ref);
|
||||
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; }
|
||||
// 空 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 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);
|
||||
ret out;
|
||||
}
|
||||
@@ -367,15 +383,35 @@ fn shape_use_of(self: *Sema, ty_ref: Ref): ShapeUse {
|
||||
if composed == 0 { ret out; }
|
||||
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);
|
||||
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 };
|
||||
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) {
|
||||
// 类型生成器的形参是类型/编译期值,不是运行期 shape 参数;
|
||||
// 其约束由 sema_type.instantiate_generator 统一处理。
|
||||
if SemaM.type_is_generator(self, fn_ref) { ret; }
|
||||
var j: usize = 0;
|
||||
while j < params.len {
|
||||
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);
|
||||
if shape_param_at(self, fn_ref, j) == 0 {
|
||||
var sp = ShapeParam { .fn_ref = fn_ref, .param_index = j,
|
||||
.has_adapter = su.has_adapter,
|
||||
.adapter_decl = su.adapter_decl,
|
||||
.shape_lang = su.shape_lang,
|
||||
.shape_ref = su.shape_ref };
|
||||
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 {
|
||||
// Ref 0 表示 identity:不生成 wrapper,装箱类型就是实参类型。
|
||||
out.lang = arg_lang;
|
||||
SemaM.sema_error_code(self, ErrorCode.ImplHookBadReturn, "shape adapter returned Ref 0", "");
|
||||
ret out;
|
||||
}
|
||||
// 非 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 调用,读取真实结果。
|
||||
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 {
|
||||
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; }
|
||||
var sp = (self.shape_state.params.data as *ShapeParam) + (sp_i - 1);
|
||||
var saved = self.cur_mod;
|
||||
var adi = sp.adapter_decl;
|
||||
var amod = SemaM.decl_at(self, adi).mod;
|
||||
if amod != saved { SemaM.switch_mod(self, amod); }
|
||||
SemaM.ensure_decl(self, adi);
|
||||
var ev = shape_adapter_eval_type(self, adi, arg_lang, sp.shape_lang);
|
||||
var ev = adapter_eval_for(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 };
|
||||
if amod != saved { SemaM.switch_mod(self, saved); }
|
||||
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 取,不做推断。
|
||||
fn shape_type_match(self: *Sema, a: usize, b: usize, shape_lang: usize, value_lang: usize,
|
||||
binds: *Vec, reported: *bool): bool {
|
||||
@@ -658,21 +727,45 @@ fn shape_conforms_use(self: *Sema, use_ref: Ref, value_lang: usize): bool {
|
||||
// 目标类型是否具备 shape 声明里的方法名与签名;方法体在实例化后继续分析。
|
||||
fn shape_conforms(self: *Sema, shape_ref: Ref, value_lang: usize): bool {
|
||||
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) {
|
||||
SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape,
|
||||
"shape parameter type is not a shape", "");
|
||||
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));
|
||||
defer { Vec.drop(&binds); }
|
||||
if !shape_apply_binds(self, shape_ref, &binds) { ret false; }
|
||||
if !shape_marker_binds(self, value_lang, shape_lang, &binds) { ret false; }
|
||||
var inner_ref = shape_ref;
|
||||
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; }
|
||||
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,
|
||||
binds: *Vec): bool {
|
||||
var vl = value_lang;
|
||||
var cont = LangType.container_of(&self.types, shape_lang);
|
||||
if cont == 0 { ret true; }
|
||||
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 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;
|
||||
if got != 0 { got_tid = SemaM.sym_at(self, got - 1).fn_tid; }
|
||||
var matched = false;
|
||||
if got != 0 {
|
||||
matched = shape_type_match(self, want_tid,
|
||||
SemaM.sym_at(self, got - 1).fn_tid,
|
||||
shape_lang, value_lang,
|
||||
shape_lang, vl,
|
||||
binds, &reported);
|
||||
} else {
|
||||
// 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 {
|
||||
SemaM.sema_error_code(self, ErrorCode.ShapeMethodMissing,
|
||||
"shape method is missing", f.name);
|
||||
@@ -714,15 +807,20 @@ fn shape_conforms_with(self: *Sema, shape_lang: usize, value_lang: usize,
|
||||
break;
|
||||
}
|
||||
matched = shape_type_match(self, want_tid,
|
||||
LangType.member_lang(&self.types, value_lang,
|
||||
LangType.member_lang(&self.types, vl,
|
||||
field_idx as usize),
|
||||
shape_lang, value_lang,
|
||||
shape_lang, vl,
|
||||
binds, &reported);
|
||||
}
|
||||
if !matched {
|
||||
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,
|
||||
"shape method signature mismatch", f.name);
|
||||
"shape method signature mismatch", ByteBuffer.as_slice(db));
|
||||
}
|
||||
ok = false;
|
||||
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 {
|
||||
.AggType(a) => {
|
||||
var pi: usize = 0;
|
||||
while pi < a.conforms.len {
|
||||
if !shape_conforms(self, a.conforms[pi], value_lang) {
|
||||
if !shape_conforms(self, a.conforms[pi], vl) {
|
||||
ok = false;
|
||||
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 {
|
||||
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.set_tid(self, r, lang);
|
||||
ret r;
|
||||
@@ -877,7 +983,218 @@ fn insert_shape_box(self: *Sema, arg: usize, ret_lang: usize, wrapper_sym: usize
|
||||
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; }
|
||||
var i: usize = 0;
|
||||
while i < args.len {
|
||||
@@ -891,7 +1208,7 @@ fn shape_instance_for(self: *Sema, fn_ref: Ref, args: []usize): usize {
|
||||
var i: usize = 0;
|
||||
while i < self.shape_state.instances.len {
|
||||
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;
|
||||
}
|
||||
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);
|
||||
var clone_state = NodeClone.new();
|
||||
var clone = NodeClone.clone_ref(&self.hir, &clone_state, fn_ref);
|
||||
NodeClone.drop(&clone_state);
|
||||
SemaM.grow_tables(self);
|
||||
copy_clone_refinfo(self, &clone_state);
|
||||
NodeClone.drop(&clone_state);
|
||||
var nm = shape_instance_name(self);
|
||||
var cn = Bld.node_ptr(&self.hir, clone);
|
||||
if cn != null {
|
||||
@@ -957,7 +1275,23 @@ fn shape_instance_for(self: *Sema, fn_ref: Ref, args: []usize): usize {
|
||||
var di = self.decls.len;
|
||||
match Vec.push(&self.decls, &d as *u8) { .Ok => {}, .Err(e) => {} }
|
||||
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);
|
||||
self.shape_state.patching = false;
|
||||
self.shape_state.patch_decl = 0;
|
||||
var inst = SemaM.decl_at(self, di).sym;
|
||||
if m != saved { SemaM.switch_mod(self, saved); }
|
||||
if inst != 0 {
|
||||
@@ -1021,8 +1355,33 @@ fn prepare_call(user: *any, callee_ref: Ref, callee: Ref, args: []usize,
|
||||
if al == 0 {
|
||||
shape_ok = false;
|
||||
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;
|
||||
} 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 {
|
||||
var sr = shape_adapter_result(self, pi + 1, al);
|
||||
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 {
|
||||
var self = user as *Sema;
|
||||
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);
|
||||
}
|
||||
|
||||
fn shape_lang_hook(user: *any, lang: usize): bool {
|
||||
ret is_shape_lang(user as *Sema, lang);
|
||||
}
|
||||
|
||||
fn hooks(): ShapeHooks {
|
||||
ret ShapeHooks {
|
||||
.bind_params = bind_params,
|
||||
@@ -1082,6 +1546,9 @@ fn hooks(): ShapeHooks {
|
||||
.check_conforms = check_conforms,
|
||||
.op_method = op_method,
|
||||
.has_conformance = marker_has_hook,
|
||||
.is_shape_lang = shape_lang_hook,
|
||||
.bind_type_arg = bind_type_arg,
|
||||
.apply_expr = apply_expr_hook,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -103,9 +103,11 @@ fn kind_name(k: Node.Kind): []u8 {
|
||||
.PatList(_) => { ret "pat_list"; },
|
||||
.PatTuple(_) => { ret "pat_tuple"; },
|
||||
.PatField(_) => { ret "pat_field"; },
|
||||
.PatFields(_) => { ret "pat_fields"; },
|
||||
.AggType(_) => { ret "agg_type"; },
|
||||
.ShapeApply(_) => { ret "shape_apply"; },
|
||||
.ShapeUse(_) => { ret "shape_use"; },
|
||||
.ShapeNoDefault(_) => { ret "shape_no_default"; },
|
||||
.AssocBind(_) => { ret "assoc_bind"; },
|
||||
.ArrayType(_) => { ret "array_type"; },
|
||||
.SliceType(_) => { ret "slice_type"; },
|
||||
@@ -140,6 +142,7 @@ fn kind_name(k: Node.Kind): []u8 {
|
||||
.Binary(_) => { ret "binary"; },
|
||||
.Unary(_) => { ret "unary"; },
|
||||
.Call(_) => { ret "call"; },
|
||||
.ShapeCall(_) => { ret "shape_call"; },
|
||||
.Comptime(_) => { ret "comptime"; },
|
||||
}
|
||||
ret "?";
|
||||
@@ -248,6 +251,7 @@ fn construct(self: *HirNodeContainer, node: Node): Ref {
|
||||
.ShapeUse(x) => {
|
||||
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 }); },
|
||||
.FnType(x) => { k = .FnType(.{ .params = dup_refs(self, x.params), .ret_ty = x.ret_ty }); },
|
||||
.TupleType(xs) => { k = .TupleType(dup_refs(self, xs)); },
|
||||
@@ -264,6 +268,11 @@ fn construct(self: *HirNodeContainer, node: Node): Ref {
|
||||
k = .Call(.{ .is_comptime = x.is_comptime, .callee = x.callee,
|
||||
.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 };
|
||||
|
||||
+21
-5
@@ -264,7 +264,8 @@ fn find_lib_import(libs: []ByteView, raw: ByteView): ByteBuffer {
|
||||
ret ByteBuffer.new();
|
||||
}
|
||||
|
||||
fn load_program(log: *Logger, path: ByteView, libs: []ByteView, mods: *Vec, edges: *Vec, hir: *Bld.HirNodeContainer): bool {
|
||||
fn load_program(log: *Logger, path: ByteView, libs: []ByteView, mods: *Vec, edges: *Vec, hir: *Bld.HirNodeContainer, load_errors: *usize): bool {
|
||||
load_errors.* = 0;
|
||||
var p0 = ByteBuffer.new();
|
||||
ignore_bool(push_s(&p0, ByteView.as_slice(path)));
|
||||
var start0 = Bld.count(hir);
|
||||
@@ -287,6 +288,7 @@ fn load_program(log: *Logger, path: ByteView, libs: []ByteView, mods: *Vec, edge
|
||||
match Vec.push(mods, &pe as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
} else {
|
||||
ByteBuffer.drop(&pp);
|
||||
ret false;
|
||||
}
|
||||
} else {
|
||||
ByteBuffer.drop(&pp);
|
||||
@@ -315,8 +317,15 @@ fn load_program(log: *Logger, path: ByteView, libs: []ByteView, mods: *Vec, edge
|
||||
ap = builtin_import_path(raw);
|
||||
}
|
||||
}
|
||||
var to: isize = -1;
|
||||
if ByteBuffer.as_slice(ap).len == 0 {
|
||||
var args: [1]Value = .[str(ByteView.as_slice(raw))];
|
||||
match Logger.errorf(log, "cannot resolve import: {}", args[0..1]) { .Ok => {}, .Err(error) => {} }
|
||||
load_errors.* = load_errors.* + 1;
|
||||
ByteBuffer.drop(&ap);
|
||||
} else {
|
||||
var apv = ByteView.from_slice(ByteBuffer.as_slice(ap));
|
||||
var to = find_mod(mods, apv);
|
||||
to = find_mod(mods, apv);
|
||||
if to < 0 {
|
||||
var mstart = Bld.count(hir);
|
||||
var mroot: Ref = 0;
|
||||
@@ -326,6 +335,7 @@ fn load_program(log: *Logger, path: ByteView, libs: []ByteView, mods: *Vec, edge
|
||||
to = (mods.len - 1) as isize;
|
||||
} else {
|
||||
ByteBuffer.drop(&ap);
|
||||
load_errors.* = load_errors.* + 1;
|
||||
}
|
||||
} else {
|
||||
ByteBuffer.drop(&ap);
|
||||
@@ -334,6 +344,7 @@ fn load_program(log: *Logger, path: ByteView, libs: []ByteView, mods: *Vec, edge
|
||||
var ed = Edge { .from = i, .ref = k, .to = to as usize };
|
||||
match Vec.push(edges, &ed as *u8) { .Ok => {}, .Err(error) => {} }
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
@@ -382,7 +393,8 @@ fn analyze_program(log: *Logger, path: ByteView, libs: []ByteView, out: *Sema):
|
||||
var mods = Vec.blank(@sizeof(ModEntry), @alignof(ModEntry));
|
||||
var edges = Vec.blank(@sizeof(Edge), @alignof(Edge));
|
||||
defer { drop_program(&mods, &edges); }
|
||||
if !load_program(log, path, libs, &mods, &edges, &hir) {
|
||||
var load_errors: usize = 0;
|
||||
if !load_program(log, path, libs, &mods, &edges, &hir, &load_errors) {
|
||||
Bld.drop(&hir);
|
||||
ret false;
|
||||
}
|
||||
@@ -403,7 +415,7 @@ fn analyze_program(log: *Logger, path: ByteView, libs: []ByteView, out: *Sema):
|
||||
sema.err = sema_fail;
|
||||
sema.err_user = log as *any;
|
||||
SemaM.run(&sema);
|
||||
if sema.had_error {
|
||||
if sema.had_error || load_errors != 0 {
|
||||
SemaM.drop(&sema);
|
||||
ret false;
|
||||
}
|
||||
@@ -689,7 +701,11 @@ fn lower_into(log: *Logger, path: ByteView, hir: *Bld.HirNodeContainer, root_out
|
||||
defer { ByteBuffer.drop(&content); }
|
||||
match read_all(path, &content) {
|
||||
.Ok => {},
|
||||
.Err(error) => { Logger.error(log, "cannot read input file"); ret false; },
|
||||
.Err(error) => {
|
||||
var args: [1]Value = .[str(ByteView.as_slice(path))];
|
||||
match Logger.errorf(log, "cannot read input file: {}", args[0..1]) { .Ok => {}, .Err(error2) => {} }
|
||||
ret false;
|
||||
},
|
||||
}
|
||||
var text = ByteView.from_slice(ByteBuffer.as_slice(content));
|
||||
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
comptime fn compute_size(seed: usize): usize {
|
||||
ret seed * 4;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
var arr: [@compute_size(5)]u8 = .[];
|
||||
@assert(arr.len() == 20);
|
||||
@assert(arr[19] == 0);
|
||||
@assert(arr[0] == 0);
|
||||
@assert(@compute_size(5) == 20);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
|
||||
comptime fn vec(elem: type): type {
|
||||
ret struct { fn add(a: i32, b: i32): i32 { ret a + b; } };
|
||||
}
|
||||
|
||||
fn main() {
|
||||
var v = @vec(u8);
|
||||
@assert(v.add(1, 2) == 3);
|
||||
@assert(v.add(1, 0) == 1);
|
||||
@assert(v.add(0, 1) == 1);
|
||||
@assert(v.add(0, 0) == 0);
|
||||
@assert(v.add(1, 1) == 2);
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
comptime fn gen_array(N: usize, T: type): type {
|
||||
ret [N]T;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
type A = @gen_array(4, u8);
|
||||
type B = @gen_array(4, u8);
|
||||
type C = @gen_array(5, u8);
|
||||
|
||||
var a: A = .[];
|
||||
var b: B = .[];
|
||||
var c: C = .[];
|
||||
|
||||
@assert(a.len() == 4);
|
||||
@assert(a[3] == 0);
|
||||
@assert(a[0] == 0);
|
||||
@assert(b.len() == 4);
|
||||
@assert(b[3] == 0);
|
||||
@assert(b[0] == 0);
|
||||
@assert(c.len() == 5);
|
||||
@assert(c[4] == 0);
|
||||
@assert(c[0] == 0);
|
||||
|
||||
@assert(A == B);
|
||||
@assert(A != C);
|
||||
@assert(@sizeof(A) == 4);
|
||||
@assert(A == [4]u8);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
comptime fn Box(t: type): type {
|
||||
ret struct { value: t };
|
||||
}
|
||||
|
||||
comptime fn Vec(t: type): type {
|
||||
ret struct { data: []t, len: usize };
|
||||
}
|
||||
|
||||
fn main(): void {
|
||||
type BI = @Box(i32);
|
||||
type VI = @Vec(i32);
|
||||
|
||||
@assert(@sizeof(BI) == 4, "box-size");
|
||||
@assert(@sizeof(VI) == 24, "vec-size");
|
||||
|
||||
var b: BI = .{ .value = 7 };
|
||||
@assert(b.value == 7, "box-field");
|
||||
|
||||
var v: VI = .{ .data = .[], .len = 1 };
|
||||
@assert(v.len == 1, "vec-field");
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type Pair = struct { a: usize, b: usize };
|
||||
|
||||
comptime fn make(): Pair {
|
||||
ret .{ .a = 20, .b = 22 };
|
||||
}
|
||||
|
||||
comptime fn use(p: Pair): usize {
|
||||
ret p.a + p.b;
|
||||
}
|
||||
|
||||
comptime fn chain(): usize {
|
||||
ret @use(@make());
|
||||
}
|
||||
|
||||
fn main(): void {
|
||||
var p: Pair = @make();
|
||||
@assert(p.a + p.b == 42, "make");
|
||||
@assert(@use(@make()) == 42, "depend");
|
||||
@assert(@chain() == 42, "chain");
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
|
||||
comptime fn Vec(t: type): type {
|
||||
ret struct {
|
||||
data: []t,
|
||||
len: usize,
|
||||
|
||||
fn assert(v: *@self): void {
|
||||
@assert(v.len == 1, "vec-field in assert");
|
||||
v.len += 1;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn main(): void {
|
||||
type VI = @Vec(i32);
|
||||
|
||||
var v: VI = .{ .data = .[], .len = 1 };
|
||||
@assert(v.len == 1, "vec-field before assert");
|
||||
v.assert(&v);
|
||||
@assert(v.len == 2, "vec-field after assert");
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
|
||||
comptime fn check(): usize {
|
||||
var r = @meta.reflect(i32);
|
||||
var n = @meta.inspect(r);
|
||||
match n.kind {
|
||||
.IntType(x) => { ret x.bits; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 1;
|
||||
}
|
||||
|
||||
fn main(): void {
|
||||
@assert(@check() == 32, "inspect int");
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
|
||||
type Pair = struct {
|
||||
a: i32,
|
||||
b: u8,
|
||||
}
|
||||
|
||||
type PtrI32 = *i32;
|
||||
type Arr4 = [4]u8;
|
||||
|
||||
type Cal = shape {
|
||||
fn call(a: i32, b: i32): i32;
|
||||
}
|
||||
|
||||
comptime fn check_int(): usize {
|
||||
var i = @meta.inspect(@meta.reflect(i32));
|
||||
match i.kind {
|
||||
.IntType(x) => { ret x.bits; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn check_float(): usize {
|
||||
var f = @meta.inspect(@meta.reflect(f64));
|
||||
match f.kind {
|
||||
.FloatType(x) => { ret x.bits; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn check_ptr(): usize {
|
||||
var p = @meta.inspect(@meta.reflect(PtrI32));
|
||||
match p.kind {
|
||||
.PtrType(_) => { ret @sizeof(@meta.build(@meta.reflect(PtrI32))); },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn check_array(): usize {
|
||||
var a = @meta.inspect(@meta.reflect(Arr4));
|
||||
match a.kind {
|
||||
.ArrayType(_) => { ret @sizeof(@meta.build(@meta.reflect(Arr4))); },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn check_agg(): usize {
|
||||
var a = @meta.inspect(@meta.reflect(Pair));
|
||||
match a.kind {
|
||||
.AggType(x) => { ret x.fields.len(); },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main(): void {
|
||||
@assert(@check_int() == 32, "int bits");
|
||||
@assert(@check_float() == 64, "float bits");
|
||||
@assert(@check_ptr() == 8, "ptr size");
|
||||
@assert(@check_array() == 4, "array size");
|
||||
@assert(@check_agg() == 2, "field count");
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
const TOP: i32 = 7;
|
||||
|
||||
fn sum(
|
||||
const a: i32,
|
||||
b: const i32,
|
||||
p: *const i32,
|
||||
q: const *i32,
|
||||
): i32 {
|
||||
var arr1: [2]const i32 = .[1, 2];
|
||||
var arr2: const [2]i32 = .[3, 4];
|
||||
var arr3: [const 2]i32 = .[5, 6];
|
||||
|
||||
ret a + b + p.* + q.* + arr1[0] + arr2[1] + arr3[0];
|
||||
}
|
||||
|
||||
fn main() {
|
||||
const LOCAL: i32 = 9;
|
||||
const INFER = 3;
|
||||
var v: i32 = 1;
|
||||
|
||||
@assert(TOP + LOCAL + INFER == 19, "const declarations");
|
||||
@assert(sum(1, 2, &v, &v) == 15, "const qualifiers");
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
pub fn add(a: i32, b: i32): i32 {
|
||||
ret a + b;
|
||||
}
|
||||
|
||||
pub type Pair = struct {
|
||||
pub a: i32;
|
||||
pub b: i32;
|
||||
};
|
||||
|
||||
pub const BASE: i32 = 10;
|
||||
pub var flag: i32 = 1;
|
||||
|
||||
fn main() {
|
||||
@assert(add(1, 2) == 3, "pub fn");
|
||||
@assert(BASE == 10, "pub const");
|
||||
|
||||
var p: Pair = .{ .a = 1, .b = 2 };
|
||||
@assert(p.a + p.b == 3, "pub struct members");
|
||||
|
||||
flag = 5;
|
||||
@assert(flag == 5, "pub var");
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
// 回归:泛型类型生成器的方法被复用后,参数/局部变量不能重复分配 def。
|
||||
// 这里只使用语言本身和一个最小 fixture,不依赖 src/libs。
|
||||
type meta = @import("meta");
|
||||
type .{ .Ref } = meta;
|
||||
type .{ .Map } = @import("../support/generic_bind_fixture.spl");
|
||||
|
||||
#hook(param)
|
||||
macro fn Self(callee: Ref, value: Ref): Ref {
|
||||
ret @meta.construct(.{ .kind = .Addr(value) });
|
||||
}
|
||||
|
||||
fn main() {
|
||||
type M = @Map(8);
|
||||
var map: M = M.init();
|
||||
|
||||
@assert(map.probe() == 8);
|
||||
@assert(map.table.probe() == 8);
|
||||
|
||||
map.put_first(42);
|
||||
@assert(map.first() == 42);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
// 回归:生成方法中的局部变量必须写入方法体实际读取的 slot。
|
||||
// 以前 put_first 的参数和局部变量会出现两个 def,写入 0 而不是调用值。
|
||||
type meta = @import("meta");
|
||||
type .{ .Ref } = meta;
|
||||
type .{ .Map } = @import("../support/generic_bind_fixture.spl");
|
||||
|
||||
#hook(param)
|
||||
macro fn Self(callee: Ref, value: Ref): Ref {
|
||||
ret @meta.construct(.{ .kind = .Addr(value) });
|
||||
}
|
||||
|
||||
fn main() {
|
||||
type M = @Map(8);
|
||||
var map: M = M.init();
|
||||
|
||||
map.put_first(7);
|
||||
@assert(map.first() == 7);
|
||||
|
||||
map.put_first(-9);
|
||||
@assert(map.first() == -9);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
fn main() {
|
||||
var a: [4]u8 = .[1, 2, 3, 4];
|
||||
var p: *u8 = &a[0];
|
||||
@assert(p[0] == 1, "array ptr");
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
// 只锁定 for 的新语法;迭代语义等 iterator shape 落地后再接 sema/lowering。
|
||||
comptime fn typed(values: [3]i32): void {
|
||||
for value: i32 in values {
|
||||
var copy = value;
|
||||
}
|
||||
}
|
||||
|
||||
comptime fn inferred(values: [3]i32): void {
|
||||
for value in values {
|
||||
var copy = value;
|
||||
}
|
||||
}
|
||||
|
||||
comptime fn with_else(values: [3]i32): void {
|
||||
for value: i32 in values {
|
||||
var copy = value;
|
||||
} else {
|
||||
var empty = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,9 +0,0 @@
|
||||
// Expect compile_error E0002
|
||||
|
||||
fn test(values: [3]i32) {
|
||||
for value: i32 values {
|
||||
var copy = value;
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,8 +0,0 @@
|
||||
// Expect compile_error E0104
|
||||
// Expect location = 7:6
|
||||
|
||||
fn f(a: i32, b: i32) {}
|
||||
|
||||
fn main() {
|
||||
f(1);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Expect compile_error E0104
|
||||
|
||||
fn f(a: i32, b: i32) {}
|
||||
|
||||
fn main() {
|
||||
f(1, 2, 3);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
fn f(a: i32, b: bool) {}
|
||||
|
||||
fn main() {
|
||||
f("x", true);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// Expect compile_error E0105
|
||||
|
||||
fn main() {
|
||||
var x: i32 = 1;
|
||||
x();
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Expect compile_error E0104
|
||||
|
||||
type M = @import("./call_lib.spl");
|
||||
|
||||
fn main() {
|
||||
M.add(1);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
type M = @import("./call_lib.spl");
|
||||
|
||||
fn main() {
|
||||
M.add("x", 1);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
fn f(): i32 {
|
||||
ret "x";
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
fn main() {
|
||||
var x: i32 = "x";
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
fn main() {
|
||||
var x: i32 = 0;
|
||||
x = "x";
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
fn main() {
|
||||
if 1 {}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
// Expect compile_error E0106
|
||||
|
||||
type S = struct {
|
||||
a: i32,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
var s = S{ .a = 1 };
|
||||
var x = s.b;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// Expect compile_error E0106
|
||||
|
||||
fn main() {
|
||||
var a: [4]u8 = .[];
|
||||
var p = a.ptr;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
fn main() {
|
||||
var x = 1 + true;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
fn main() {
|
||||
var x = !1;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Expect compile_error E0101 E0105
|
||||
|
||||
fn main() {
|
||||
nope();
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
// Expect compile_error E0105
|
||||
|
||||
type S = struct {
|
||||
a: i32,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
var s = S{ .a = 1 };
|
||||
s.a();
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Expect compile_error E0104
|
||||
|
||||
type .{ .Ref } = @import("spl_ir");
|
||||
|
||||
macro fn one(a: i32): Ref {
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@one(1, 2);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
type .{ .Ref } = @import("spl_ir");
|
||||
|
||||
macro fn one(a: i32): Ref {
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@one("x");
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// Expect compile_error E0104
|
||||
|
||||
type .{ .Ref } = @import("spl_ir");
|
||||
|
||||
type SA = shape {
|
||||
fn a(): i32;
|
||||
};
|
||||
|
||||
type A = struct {
|
||||
fn a(): i32 { ret 1; }
|
||||
};
|
||||
|
||||
#hook(adapter)
|
||||
macro fn sa(called_type: type, shape_type: type): Ref {
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn use_a(x: @sa[SA]): i32 {
|
||||
ret x.a();
|
||||
}
|
||||
|
||||
fn main() {
|
||||
var a: A = A{};
|
||||
use_a(a, 1);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type M = @import("./call_lib.spl");
|
||||
|
||||
fn main() {
|
||||
@assert(M.add(1, 2) == 3, "module call");
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
fn f(a: u8, b: i64) {}
|
||||
|
||||
fn main() {
|
||||
f(1, 2);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
// Expect compile_error E0106
|
||||
|
||||
type M = @import("./call_lib.spl");
|
||||
|
||||
fn main(): i32 {
|
||||
var buf: [128]u8 = .[];
|
||||
var read_size = M.read(&M.stdin(), buf.ptr, buf.len());
|
||||
M.write(&M.stderr(), buf.ptr, read_size);
|
||||
ret 0;
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// Expect compile_error E0310
|
||||
// Expect location = 34:5
|
||||
|
||||
type meta = @import("meta");
|
||||
type .{ .Node, .Ref } = @import("spl_ir");
|
||||
|
||||
// 只验证错误路径,不生成实际格式化代码。
|
||||
macro fn fmt(pattern: []u8, args: ...): Ref {
|
||||
var pairs: []Ref = .[];
|
||||
var an = @meta.inspect(args);
|
||||
match an.kind {
|
||||
.TupleLit(xs) => { pairs = xs; },
|
||||
_ => {},
|
||||
}
|
||||
|
||||
var count: usize = 0;
|
||||
var i: usize = 0;
|
||||
while i + 1 < pattern.len() {
|
||||
if pattern[i] == '{' && pattern[i + 1] == '}' {
|
||||
count = count + 1;
|
||||
i = i + 2;
|
||||
} else {
|
||||
i = i + 1;
|
||||
}
|
||||
}
|
||||
if count != pairs.len() {
|
||||
@meta.error(.FmtMissingArg);
|
||||
ret 0;
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@fmt("{} {}", 1);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
// Expect compile_error E0312
|
||||
|
||||
type meta = @import("meta");
|
||||
type .{ .Node, .Ref } = @import("spl_ir");
|
||||
|
||||
// 只验证错误路径,不生成实际格式化代码。
|
||||
macro fn fmt(pattern: []u8, args: ...): Ref {
|
||||
var pairs: []Ref = .[];
|
||||
var an = @meta.inspect(args);
|
||||
match an.kind {
|
||||
.TupleLit(xs) => { pairs = xs; },
|
||||
_ => {},
|
||||
}
|
||||
|
||||
var count: usize = 0;
|
||||
var i: usize = 0;
|
||||
while i + 1 < pattern.len() {
|
||||
if pattern[i] == '{' && pattern[i + 1] == '}' {
|
||||
count = count + 1;
|
||||
i = i + 2;
|
||||
} else {
|
||||
i = i + 1;
|
||||
}
|
||||
}
|
||||
if count != pairs.len() {
|
||||
@meta.error(.FmtMissingArg);
|
||||
ret 0;
|
||||
}
|
||||
|
||||
var j: usize = 0;
|
||||
while j < pairs.len() {
|
||||
var pn = @meta.inspect(pairs[j]);
|
||||
var pv: []Ref = .[];
|
||||
match pn.kind {
|
||||
.TupleLit(xs) => { pv = xs; },
|
||||
_ => {},
|
||||
}
|
||||
var kind: []u8 = "";
|
||||
if pv.len() > 1 {
|
||||
var kn = @meta.inspect(pv[1]);
|
||||
match kn.kind {
|
||||
.LitStr(s) => { kind = s; },
|
||||
_ => {},
|
||||
}
|
||||
}
|
||||
var ok = false;
|
||||
if kind.len() == 3 && kind[0] == 'i' && kind[1] == 'n' && kind[2] == 't' {
|
||||
ok = true;
|
||||
}
|
||||
if !ok {
|
||||
@meta.error(.FmtBadType);
|
||||
ret 0;
|
||||
}
|
||||
j = j + 1;
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
type P = struct {
|
||||
a: i32,
|
||||
};
|
||||
|
||||
fn main() {
|
||||
@fmt("{}", P{ .a = 1 });
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// Expect compile_error E0311
|
||||
|
||||
type meta = @import("meta");
|
||||
type .{ .Node, .Ref } = @import("spl_ir");
|
||||
|
||||
macro fn fmt(args: ...): Ref {
|
||||
var an = @meta.inspect(args);
|
||||
var pairs: []Ref = .[];
|
||||
match an.kind {
|
||||
.TupleLit(xs) => { pairs = xs; },
|
||||
_ => {},
|
||||
}
|
||||
if pairs.len() == 0 { @meta.error(.FmtNonliteral); ret 0; }
|
||||
var pn = @meta.inspect(pairs[0]);
|
||||
var pv: []Ref = .[];
|
||||
match pn.kind {
|
||||
.TupleLit(xs) => { pv = xs; },
|
||||
_ => {},
|
||||
}
|
||||
if pv.len() == 0 { @meta.error(.FmtNonliteral); ret 0; }
|
||||
var vn = @meta.inspect(pv[0]);
|
||||
match vn.kind {
|
||||
.LitStr(_) => {
|
||||
ret @meta.construct(.{ .kind = .LitInt("1") });
|
||||
},
|
||||
_ => {
|
||||
@meta.error(.FmtNonliteral);
|
||||
ret 0;
|
||||
},
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
var p = "{}";
|
||||
@fmt(p, 1);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Expect compile_error E0107
|
||||
|
||||
comptime fn same(): i32 {
|
||||
ret 1;
|
||||
}
|
||||
|
||||
macro fn same(): usize {
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,17 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
type .{ .Node, .Ref } = @import("spl_ir");
|
||||
|
||||
#hook(param)
|
||||
macro fn unused(callee: Ref, value: Ref): Ref {
|
||||
ret @meta.construct(.{ .kind = .LitInt("9") });
|
||||
}
|
||||
|
||||
fn f(x: i32): i32 {
|
||||
ret x;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(f(3) == 3, "no implicit hook scan");
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// Expect compile_error E0107
|
||||
|
||||
type Ref = @import("spl_ir").Ref;
|
||||
|
||||
#hook(decorator)
|
||||
macro fn same(node: Ref): Ref {
|
||||
ret node;
|
||||
}
|
||||
|
||||
fn same(): i32 {
|
||||
ret 1;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Expect compile_error E0107
|
||||
|
||||
fn same(): i32 {
|
||||
ret 1;
|
||||
}
|
||||
|
||||
fn same(): i32 {
|
||||
ret 2;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Expect compile_error E0107
|
||||
|
||||
type Same = struct {
|
||||
value: i32;
|
||||
}
|
||||
|
||||
fn Same(): i32 {
|
||||
ret 1;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,9 +0,0 @@
|
||||
// Expect compile_error E0107
|
||||
|
||||
const value: i32 = 1;
|
||||
|
||||
fn value(): i32 {
|
||||
ret 2;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Expect compile_error E0103
|
||||
|
||||
type meta = @import("meta");
|
||||
type Ref = @import("spl_ir").Ref;
|
||||
|
||||
macro fn fail(): Ref {
|
||||
@meta.error(311);
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@fail();
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// Expect compile_error E0002
|
||||
|
||||
fn bad() void {
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -1,55 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
// `[]` 只做 shape 的关联类型绑定;comptime 类型构造仍使用 `@Name(...)`。
|
||||
|
||||
comptime fn Vec(T: type): type {
|
||||
ret struct {
|
||||
data: []T,
|
||||
len: usize,
|
||||
};
|
||||
}
|
||||
|
||||
comptime fn PairBox(A: type, B: type): type {
|
||||
ret struct {
|
||||
a: A,
|
||||
b: B,
|
||||
};
|
||||
}
|
||||
|
||||
comptime fn Gen(N: usize, T: type): type {
|
||||
ret [N]T;
|
||||
}
|
||||
|
||||
type VecI = @Vec(i32);
|
||||
type Nested = @PairBox(@Vec(i32), @Vec(u8));
|
||||
type Arr = @Gen(4, u8);
|
||||
|
||||
type .{ .Iter, .Step } = @import("ops");
|
||||
|
||||
type Counter = struct: Iter[Item = i32] {
|
||||
i: i32,
|
||||
|
||||
fn next(@Self self: *@self): @Step(i32) {
|
||||
if self.i >= 3 {
|
||||
ret .Done;
|
||||
}
|
||||
var v = self.i;
|
||||
self.i = self.i + 1;
|
||||
ret .Item(v);
|
||||
}
|
||||
};
|
||||
|
||||
fn main() {
|
||||
@assert(@sizeof(VecI) == 24, "vec size");
|
||||
@assert(@sizeof(Nested) == 48, "nested comptime type");
|
||||
@assert(@sizeof(Arr) == 4, "const type argument");
|
||||
var v: VecI = .{ .data = .[], .len = 1 };
|
||||
@assert(v.len == 1, "vec field");
|
||||
|
||||
var c: Counter = .{ .i = 0 };
|
||||
var total: i32 = 0;
|
||||
for x in c {
|
||||
total = total + x;
|
||||
}
|
||||
@assert(total == 3, "for iter");
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Expect compile_error E0002
|
||||
|
||||
// 类型构造必须通过 comptime 调用;`Name[...]` 只用于 shape 关联类型绑定。
|
||||
|
||||
comptime fn Vec(T: type): type {
|
||||
ret struct {
|
||||
data: []T,
|
||||
};
|
||||
}
|
||||
|
||||
type V = Vec[i32];
|
||||
|
||||
fn main() {}
|
||||
@@ -1,79 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
|
||||
type BoolT = bool;
|
||||
type VoidT = void;
|
||||
type AnyT = any;
|
||||
type TypeT = type;
|
||||
|
||||
comptime fn int_bits(T: type): usize {
|
||||
var n = @meta.inspect(@meta.reflect(T));
|
||||
match n.kind {
|
||||
.IntType(x) => { ret x.bits; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn int_signed(T: type): usize {
|
||||
var n = @meta.inspect(@meta.reflect(T));
|
||||
match n.kind {
|
||||
.IntType(x) => { if x.signed { ret 1; } ret 0; },
|
||||
_ => { ret 2; },
|
||||
}
|
||||
ret 2;
|
||||
}
|
||||
|
||||
comptime fn float_bits(T: type): usize {
|
||||
var n = @meta.inspect(@meta.reflect(T));
|
||||
match n.kind {
|
||||
.FloatType(x) => { ret x.bits; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn kind_code(T: type): usize {
|
||||
var n = @meta.inspect(@meta.reflect(T));
|
||||
match n.kind {
|
||||
.Bool => { ret 1; },
|
||||
.Unit => { ret 2; },
|
||||
.Any => { ret 3; },
|
||||
.Type => { ret 4; },
|
||||
.Error => { ret 5; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(@int_bits(i8) == 8, "i8 bits");
|
||||
@assert(@int_bits(u8) == 8, "u8 bits");
|
||||
@assert(@int_bits(i16) == 16, "i16 bits");
|
||||
@assert(@int_bits(u16) == 16, "u16 bits");
|
||||
@assert(@int_bits(i32) == 32, "i32 bits");
|
||||
@assert(@int_bits(u32) == 32, "u32 bits");
|
||||
@assert(@int_bits(i64) == 64, "i64 bits");
|
||||
@assert(@int_bits(u64) == 64, "u64 bits");
|
||||
@assert(@int_bits(isize) == 64, "isize bits");
|
||||
@assert(@int_bits(usize) == 64, "usize bits");
|
||||
|
||||
@assert(@int_signed(i32) == 1, "i32 signed");
|
||||
@assert(@int_signed(u32) == 0, "u32 unsigned");
|
||||
@assert(@int_signed(isize) == 1, "isize signed");
|
||||
@assert(@int_signed(usize) == 0, "usize unsigned");
|
||||
|
||||
@assert(@float_bits(f32) == 32, "f32 bits");
|
||||
@assert(@float_bits(f64) == 64, "f64 bits");
|
||||
|
||||
@assert(@kind_code(BoolT) == 1, "bool kind");
|
||||
@assert(@kind_code(VoidT) == 2, "unit kind");
|
||||
@assert(@kind_code(AnyT) == 3, "any kind");
|
||||
@assert(@kind_code(TypeT) == 4, "type kind");
|
||||
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(i32))) == 4, "build i32");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(f64))) == 8, "build f64");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(BoolT))) == 1, "build bool");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(VoidT))) == 0, "build void");
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
|
||||
type PtrI32 = *i32;
|
||||
type SliceU16 = []u16;
|
||||
type Arr4 = [4]u8;
|
||||
type Call2 = fn(i32, u8): i64;
|
||||
type Tup2 = (i32, u8);
|
||||
|
||||
type Inner = struct {
|
||||
x: i16,
|
||||
y: bool,
|
||||
}
|
||||
|
||||
type PtrInner = *Inner;
|
||||
|
||||
type Outer = struct {
|
||||
id: u32,
|
||||
p: PtrInner,
|
||||
buf: [3]u8,
|
||||
data: []u8,
|
||||
}
|
||||
|
||||
type Color = enum {
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
|
||||
type Num = union {
|
||||
i: i32,
|
||||
f: f64,
|
||||
}
|
||||
|
||||
comptime fn has_ptr(T: type): usize {
|
||||
var n = @meta.inspect(@meta.reflect(T));
|
||||
match n.kind {
|
||||
.PtrType(e) => {
|
||||
var en = @meta.inspect(e);
|
||||
match en.kind {
|
||||
.IntType(x) => { ret x.bits; },
|
||||
.AggType(_) => { ret 100; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
},
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn field_count(T: type): usize {
|
||||
var n = @meta.inspect(@meta.reflect(T));
|
||||
match n.kind {
|
||||
.AggType(x) => { ret x.fields.len(); },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn field_code(T: type, idx: usize): usize {
|
||||
var n = @meta.inspect(@meta.reflect(T));
|
||||
match n.kind {
|
||||
.AggType(x) => {
|
||||
var f = @meta.inspect(x.fields[idx]);
|
||||
match f.kind {
|
||||
.FieldDecl(d) => {
|
||||
var t = @meta.inspect(d.ty);
|
||||
match t.kind {
|
||||
.IntType(i) => { ret i.bits; },
|
||||
.PtrType(_) => { ret 200; },
|
||||
.ArrayType(_) => { ret 300; },
|
||||
.SliceType(_) => { ret 400; },
|
||||
.Bool => { ret 1; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
},
|
||||
_ => { ret 2; },
|
||||
}
|
||||
},
|
||||
_ => { ret 3; },
|
||||
}
|
||||
ret 4;
|
||||
}
|
||||
|
||||
comptime fn agg_kind_code(T: type): usize {
|
||||
var n = @meta.inspect(@meta.reflect(T));
|
||||
match n.kind {
|
||||
.AggType(x) => {
|
||||
match x.kind {
|
||||
.Struct => { ret 1; },
|
||||
.Union => { ret 2; },
|
||||
.Enum => { ret 3; },
|
||||
.Shape => { ret 4; },
|
||||
}
|
||||
},
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(@has_ptr(PtrI32) == 32, "ptr elem bits");
|
||||
@assert(@has_ptr(PtrInner) == 100, "ptr elem agg");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(PtrI32))) == 8, "ptr size");
|
||||
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(SliceU16))) == 16, "slice size");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(Arr4))) == 4, "array size");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(Call2))) == 8, "fn size");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(Tup2))) == 8, "tuple size");
|
||||
|
||||
@assert(@field_count(Inner) == 2, "inner fields");
|
||||
@assert(@field_count(Outer) == 4, "outer fields");
|
||||
@assert(@field_code(Inner, 0) == 16, "inner.x");
|
||||
@assert(@field_code(Inner, 1) == 1, "inner.y");
|
||||
@assert(@field_code(Outer, 0) == 32, "outer.id");
|
||||
@assert(@field_code(Outer, 1) == 200, "outer.p");
|
||||
@assert(@field_code(Outer, 2) == 300, "outer.buf");
|
||||
@assert(@field_code(Outer, 3) == 400, "outer.data");
|
||||
|
||||
@assert(@agg_kind_code(Inner) == 1, "struct kind");
|
||||
@assert(@agg_kind_code(Num) == 2, "union kind");
|
||||
@assert(@agg_kind_code(Color) == 3, "enum kind");
|
||||
@assert(@field_count(Color) == 3, "enum variants");
|
||||
@assert(@field_count(Num) == 2, "union members");
|
||||
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(Inner))) == @sizeof(Inner), "inner size");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(Outer))) == @sizeof(Outer), "outer size");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(Color))) == @sizeof(Color), "enum size");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(Num))) == @sizeof(Num), "union size");
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
|
||||
type Pair = struct { a: i32, b: u8 };
|
||||
type Inner = struct { x: i16, y: bool };
|
||||
type Nested = struct { p: Pair, i: Inner, arr: [2]Pair };
|
||||
type Arr4 = [4]u8;
|
||||
type PtrPair = *Pair;
|
||||
type SlicePair = []Pair;
|
||||
type Callback = fn(Pair, u32): Pair;
|
||||
type Color = enum { Red, Green, Blue };
|
||||
|
||||
comptime fn roundtrip_size(T: type): usize {
|
||||
var r = @meta.reflect(T);
|
||||
var n = @meta.inspect(r);
|
||||
var r2 = @meta.construct(n);
|
||||
ret @sizeof(@meta.build(r2));
|
||||
}
|
||||
|
||||
comptime fn roundtrip_fields(T: type): usize {
|
||||
var r = @meta.reflect(T);
|
||||
var n = @meta.inspect(r);
|
||||
var r2 = @meta.construct(n);
|
||||
var n2 = @meta.inspect(r2);
|
||||
match n2.kind {
|
||||
.AggType(x) => { ret x.fields.len(); },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn same_fields(T: type): usize {
|
||||
var before = @meta.inspect(@meta.reflect(T));
|
||||
var after = @meta.inspect(@meta.construct(before));
|
||||
match before.kind {
|
||||
.AggType(a) => {
|
||||
match after.kind {
|
||||
.AggType(b) => {
|
||||
if a.fields.len() != b.fields.len() { ret 1; }
|
||||
if a.decls.len() != b.decls.len() { ret 2; }
|
||||
var i: usize = 0;
|
||||
while i < a.fields.len() {
|
||||
var fa = @meta.inspect(a.fields[i]);
|
||||
var fb = @meta.inspect(b.fields[i]);
|
||||
match fa.kind {
|
||||
.FieldDecl(x) => {
|
||||
match fb.kind {
|
||||
.FieldDecl(y) => {
|
||||
if x.name.len() != y.name.len() { ret 3; }
|
||||
var k: usize = 0;
|
||||
while k < x.name.len() {
|
||||
if x.name[k] != y.name[k] { ret 4; }
|
||||
k = k + 1;
|
||||
}
|
||||
},
|
||||
_ => { ret 5; },
|
||||
}
|
||||
},
|
||||
_ => { ret 6; },
|
||||
}
|
||||
i = i + 1;
|
||||
}
|
||||
ret 0;
|
||||
},
|
||||
_ => { ret 7; },
|
||||
}
|
||||
},
|
||||
_ => { ret 8; },
|
||||
}
|
||||
ret 9;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(@roundtrip_size(i32) == 4, "i32");
|
||||
@assert(@roundtrip_size(f64) == 8, "f64");
|
||||
@assert(@roundtrip_size(Arr4) == 4, "arr");
|
||||
@assert(@roundtrip_size(PtrPair) == 8, "ptr");
|
||||
@assert(@roundtrip_size(SlicePair) == 16, "slice");
|
||||
@assert(@roundtrip_size(Callback) == 8, "fn");
|
||||
|
||||
@assert(@roundtrip_size(Pair) == @sizeof(Pair), "pair");
|
||||
@assert(@roundtrip_size(Inner) == @sizeof(Inner), "inner");
|
||||
@assert(@roundtrip_size(Nested) == @sizeof(Nested), "nested");
|
||||
@assert(@roundtrip_size(Color) == @sizeof(Color), "enum");
|
||||
|
||||
@assert(@roundtrip_fields(Pair) == 2, "pair fields");
|
||||
@assert(@roundtrip_fields(Nested) == 3, "nested fields");
|
||||
@assert(@roundtrip_fields(Color) == 3, "enum fields");
|
||||
@assert(@same_fields(Pair) == 0, "pair names");
|
||||
@assert(@same_fields(Nested) == 0, "nested names");
|
||||
@assert(@same_fields(Color) == 0, "enum names");
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
|
||||
type Pair = struct { a: i32, b: u8 };
|
||||
type Arr3 = [3]u16;
|
||||
type SliceI32 = []i32;
|
||||
type PtrPair = *Pair;
|
||||
type Callback = fn(i32): i32;
|
||||
|
||||
comptime fn size_after_build(T: type): usize {
|
||||
var built = @meta.build(@meta.reflect(T));
|
||||
ret @sizeof(built);
|
||||
}
|
||||
|
||||
comptime fn size_after_rebuild(T: type): usize {
|
||||
var first = @meta.build(@meta.reflect(T));
|
||||
var second = @meta.build(@meta.reflect(first));
|
||||
ret @sizeof(second);
|
||||
}
|
||||
|
||||
comptime fn type_roundtrip_equal(T: type): usize {
|
||||
var a = @meta.build(@meta.reflect(T));
|
||||
var b = @meta.build(@meta.reflect(a));
|
||||
if a == b { ret 1; }
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn first_field_code(T: type): usize {
|
||||
var n = @meta.inspect(@meta.reflect(T));
|
||||
match n.kind {
|
||||
.AggType(x) => {
|
||||
var f = @meta.inspect(x.fields[0]);
|
||||
match f.kind {
|
||||
.FieldDecl(d) => {
|
||||
@assert(d.name.len() > 0, "empty field name");
|
||||
ret d.name[0] as usize;
|
||||
},
|
||||
_ => { ret 1; },
|
||||
}
|
||||
},
|
||||
_ => { ret 2; },
|
||||
}
|
||||
ret 3;
|
||||
}
|
||||
|
||||
comptime fn field_count_of(T: type): usize {
|
||||
ret @field_count(@meta.build(@meta.reflect(T)));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(@size_after_build(i32) == 4, "generic i32");
|
||||
@assert(@size_after_build(Pair) == @sizeof(Pair), "generic pair");
|
||||
@assert(@size_after_build(Arr3) == @sizeof(Arr3), "generic array");
|
||||
@assert(@size_after_build(SliceI32) == 16, "generic slice");
|
||||
@assert(@size_after_build(PtrPair) == 8, "generic ptr");
|
||||
@assert(@size_after_build(Callback) == 8, "generic fn");
|
||||
|
||||
@assert(@size_after_rebuild(i32) == 4, "rebuild i32");
|
||||
@assert(@size_after_rebuild(Pair) == @sizeof(Pair), "rebuild pair");
|
||||
@assert(@size_after_rebuild(Arr3) == @sizeof(Arr3), "rebuild array");
|
||||
|
||||
@assert(@type_roundtrip_equal(i32) == 1, "type equal i32");
|
||||
@assert(@type_roundtrip_equal(Pair) == 1, "type equal pair");
|
||||
@assert(@type_roundtrip_equal(Arr3) == 1, "type equal array");
|
||||
|
||||
@assert(@first_field_code(Pair) == 'a' as usize, "pair first");
|
||||
@assert(@field_count_of(Pair) == 2, "pair count");
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
type .{ .Node, .Ref } = @import("spl_ir");
|
||||
|
||||
type VoidT = void;
|
||||
|
||||
comptime fn ref_zero_kind(): usize {
|
||||
var n = @meta.inspect(0);
|
||||
match n.kind {
|
||||
.Error => { ret 1; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn ref_far_kind(): usize {
|
||||
var n = @meta.inspect(1073741824);
|
||||
match n.kind {
|
||||
.Error => { ret 1; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn build_zero_size(): usize {
|
||||
ret @sizeof(@meta.build(0));
|
||||
}
|
||||
|
||||
comptime fn build_lit_size(): usize {
|
||||
var lit: Node = .{ .kind = .LitInt("123") };
|
||||
var r = @meta.construct(lit);
|
||||
var n = @meta.inspect(r);
|
||||
match n.kind {
|
||||
.LitInt(s) => {
|
||||
@assert(s.len() == 3, "lit text roundtrip");
|
||||
ret @sizeof(@meta.build(r));
|
||||
},
|
||||
_ => { ret 99; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn construct_error_kind(): usize {
|
||||
var err: Node = .{ .kind = .Error };
|
||||
var r = @meta.construct(err);
|
||||
var n = @meta.inspect(r);
|
||||
match n.kind {
|
||||
.Error => { ret 1; },
|
||||
_ => { ret 0; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn empty_struct(T: type): usize {
|
||||
var one: [1]Ref = .[0];
|
||||
var none = one[0..0];
|
||||
var node: Node = .{ .kind = .AggType(.{
|
||||
.kind = .Struct,
|
||||
.conforms = none,
|
||||
.fields = none,
|
||||
.decls = none,
|
||||
.injected = none,
|
||||
}) };
|
||||
var r = @meta.construct(node);
|
||||
var t = @meta.build(r);
|
||||
@assert(@field_count(t) == 0, "empty field count");
|
||||
ret @sizeof(t);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(@ref_zero_kind() == 1, "ref 0");
|
||||
@assert(@ref_far_kind() == 1, "ref far");
|
||||
@assert(@build_zero_size() == 0, "build 0");
|
||||
@assert(@build_lit_size() == 0, "build literal");
|
||||
@assert(@construct_error_kind() == 1, "construct error");
|
||||
@assert(@empty_struct(VoidT) == 0, "empty struct");
|
||||
@assert(@sizeof(@meta.build(@meta.reflect(VoidT))) == 0, "void size");
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
type .{ .Node, .Ref } = @import("spl_ir");
|
||||
|
||||
comptime fn tags_roundtrip(): usize {
|
||||
var z: [1]Ref = .[0];
|
||||
var empty = z[0..0];
|
||||
var tag: Node = .{ .kind = .Tag(.{
|
||||
.is_at = false,
|
||||
.name = "marked",
|
||||
.args = empty,
|
||||
}) };
|
||||
var tr = @meta.construct(tag);
|
||||
var tags: [1]Ref = .[tr];
|
||||
var node: Node = .{ .kind = .LitInt("7"), .tags = tags[0..1] };
|
||||
var r = @meta.construct(node);
|
||||
var back = @meta.inspect(r);
|
||||
if back.tags.len() != 1 { ret 1; }
|
||||
var t = @meta.inspect(back.tags[0]);
|
||||
match t.kind {
|
||||
.Tag(x) => {
|
||||
if x.is_at { ret 2; }
|
||||
if x.name.len() != 6 { ret 3; }
|
||||
if x.name[0] != 'm' { ret 4; }
|
||||
if x.args.len() != 0 { ret 5; }
|
||||
},
|
||||
_ => { ret 6; },
|
||||
}
|
||||
match back.kind {
|
||||
.LitInt(s) => {
|
||||
if s.len() != 1 { ret 7; }
|
||||
if s[0] != '7' { ret 8; }
|
||||
},
|
||||
_ => { ret 9; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn binary_roundtrip(): usize {
|
||||
var l: Node = .{ .kind = .LitInt("1") };
|
||||
var rr: Node = .{ .kind = .LitInt("2") };
|
||||
var lr = @meta.construct(l);
|
||||
var rref = @meta.construct(rr);
|
||||
var bin: Node = .{ .kind = .Binary(.{ .op = .Add, .lval = lr, .rval = rref }) };
|
||||
var b = @meta.inspect(@meta.construct(bin));
|
||||
match b.kind {
|
||||
.Binary(x) => {
|
||||
match x.op {
|
||||
.Add => {},
|
||||
_ => { ret 1; },
|
||||
}
|
||||
var ln = @meta.inspect(x.lval);
|
||||
match ln.kind {
|
||||
.LitInt(s) => { if s.len() != 1 || s[0] != '1' { ret 2; } },
|
||||
_ => { ret 3; },
|
||||
}
|
||||
},
|
||||
_ => { ret 4; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn fn_decl_roundtrip(): usize {
|
||||
var z: [1]Ref = .[0];
|
||||
var empty = z[0..0];
|
||||
var p: Node = .{ .kind = .ParamDecl(.{
|
||||
.is_comptime = false,
|
||||
.by_ref = true,
|
||||
.name = "v",
|
||||
.ty = 0,
|
||||
}) };
|
||||
var pr = @meta.construct(p);
|
||||
var params: [1]Ref = .[pr];
|
||||
var fd: Node = .{ .kind = .FnDecl(.{
|
||||
.is_comptime = true,
|
||||
.injected = empty,
|
||||
.name = "demo",
|
||||
.params = params[0..1],
|
||||
.ret_ty = 0,
|
||||
.body = 0,
|
||||
}) };
|
||||
var f = @meta.inspect(@meta.construct(fd));
|
||||
match f.kind {
|
||||
.FnDecl(x) => {
|
||||
if !x.is_comptime { ret 1; }
|
||||
if x.name.len() != 4 { ret 2; }
|
||||
if x.name[0] != 'd' { ret 3; }
|
||||
if x.params.len() != 1 { ret 4; }
|
||||
var pn = @meta.inspect(x.params[0]);
|
||||
match pn.kind {
|
||||
.ParamDecl(y) => {
|
||||
if !y.by_ref { ret 5; }
|
||||
if y.name[0] != 'v' { ret 6; }
|
||||
},
|
||||
_ => { ret 7; },
|
||||
}
|
||||
},
|
||||
_ => { ret 8; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn literal_nodes(): usize {
|
||||
var f: Node = .{ .kind = .FieldLit(.{ .name = "f", .value = 3 }) };
|
||||
var fr = @meta.construct(f);
|
||||
var fields: [1]Ref = .[fr];
|
||||
var agg: Node = .{ .kind = .AggLit(.{ .name = "T", .fields = fields[0..1] }) };
|
||||
var a = @meta.inspect(@meta.construct(agg));
|
||||
match a.kind {
|
||||
.AggLit(x) => {
|
||||
if x.name[0] != 'T' { ret 1; }
|
||||
if x.fields.len() != 1 { ret 2; }
|
||||
var fl = @meta.inspect(x.fields[0]);
|
||||
match fl.kind {
|
||||
.FieldLit(y) => {
|
||||
if y.name[0] != 'f' { ret 3; }
|
||||
if y.value != 3 { ret 4; }
|
||||
},
|
||||
_ => { ret 5; },
|
||||
}
|
||||
},
|
||||
_ => { ret 6; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(@tags_roundtrip() == 0, "tags");
|
||||
@assert(@binary_roundtrip() == 0, "binary");
|
||||
@assert(@fn_decl_roundtrip() == 0, "fn decl");
|
||||
@assert(@literal_nodes() == 0, "literals");
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
type .{ .Node, .Ref } = @import("spl_ir");
|
||||
|
||||
comptime fn int_node(bits: usize, signed: bool): Ref {
|
||||
var n: Node = .{ .kind = .IntType(.{ .bits = bits, .signed = signed }) };
|
||||
ret @meta.construct(n);
|
||||
}
|
||||
|
||||
comptime fn field_node(name: []u8, ty: Ref): Ref {
|
||||
var n: Node = .{ .kind = .FieldDecl(.{ .name = name, .ty = ty }) };
|
||||
ret @meta.construct(n);
|
||||
}
|
||||
|
||||
comptime fn lit_node(text: []u8): Ref {
|
||||
var n: Node = .{ .kind = .LitInt(text) };
|
||||
ret @meta.construct(n);
|
||||
}
|
||||
|
||||
comptime fn scalar_types(): usize {
|
||||
var i32r = @int_node(32, true);
|
||||
var u8r = @int_node(8, false);
|
||||
if @sizeof(@meta.build(i32r)) != 4 { ret 1; }
|
||||
if @sizeof(@meta.build(u8r)) != 1 { ret 2; }
|
||||
|
||||
var pnode: Node = .{ .kind = .PtrType(i32r) };
|
||||
var pr = @meta.construct(pnode);
|
||||
if @sizeof(@meta.build(pr)) != 8 { ret 3; }
|
||||
|
||||
var snode: Node = .{ .kind = .SliceType(i32r) };
|
||||
var sr = @meta.construct(snode);
|
||||
if @sizeof(@meta.build(sr)) != 16 { ret 4; }
|
||||
|
||||
var len = @lit_node("4");
|
||||
var anode: Node = .{ .kind = .ArrayType(.{ .len = len, .elem = u8r }) };
|
||||
var ar = @meta.construct(anode);
|
||||
if @sizeof(@meta.build(ar)) != 4 { ret 5; }
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn fn_type(): usize {
|
||||
var i32r = @int_node(32, true);
|
||||
var u8r = @int_node(8, false);
|
||||
var params: [2]Ref = .[i32r, u8r];
|
||||
var ft: Node = .{ .kind = .FnType(.{ .params = params[0..2], .ret_ty = i32r }) };
|
||||
var r = @meta.construct(ft);
|
||||
var n = @meta.inspect(r);
|
||||
match n.kind {
|
||||
.FnType(x) => {
|
||||
if x.params.len() != 2 { ret 1; }
|
||||
var p = @meta.inspect(x.params[1]);
|
||||
match p.kind {
|
||||
.IntType(y) => { if y.bits != 8 { ret 2; } },
|
||||
_ => { ret 3; },
|
||||
}
|
||||
},
|
||||
_ => { ret 4; },
|
||||
}
|
||||
if @sizeof(@meta.build(r)) != 8 { ret 5; }
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn struct_type(): usize {
|
||||
var i32r = @int_node(32, true);
|
||||
var u8r = @int_node(8, false);
|
||||
var f0 = @field_node("a", i32r);
|
||||
var f1 = @field_node("b", u8r);
|
||||
var fields: [2]Ref = .[f0, f1];
|
||||
var z: [1]Ref = .[0];
|
||||
var agg: Node = .{ .kind = .AggType(.{
|
||||
.kind = .Struct,
|
||||
.conforms = z[0..0],
|
||||
.fields = fields[0..2],
|
||||
.decls = z[0..0],
|
||||
.injected = z[0..0],
|
||||
}) };
|
||||
var r = @meta.construct(agg);
|
||||
var t = @meta.build(r);
|
||||
if @sizeof(t) != 8 { ret 1; }
|
||||
if @field_count(t) != 2 { ret 2; }
|
||||
|
||||
var tn = @meta.inspect(@meta.reflect(t));
|
||||
match tn.kind {
|
||||
.AggType(x) => {
|
||||
if x.fields.len() != 2 { ret 3; }
|
||||
var fa = @meta.inspect(x.fields[0]);
|
||||
match fa.kind {
|
||||
.FieldDecl(d) => {
|
||||
if d.name.len() != 1 || d.name[0] != 'a' { ret 4; }
|
||||
},
|
||||
_ => { ret 5; },
|
||||
}
|
||||
},
|
||||
_ => { ret 6; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn nested_struct(): usize {
|
||||
var i16r = @int_node(16, true);
|
||||
var u8r = @int_node(8, false);
|
||||
var inner_fields: [2]Ref = .[
|
||||
@field_node("x", i16r),
|
||||
@field_node("y", u8r),
|
||||
];
|
||||
var z: [1]Ref = .[0];
|
||||
var inner: Node = .{ .kind = .AggType(.{
|
||||
.kind = .Struct,
|
||||
.conforms = z[0..0],
|
||||
.fields = inner_fields[0..2],
|
||||
.decls = z[0..0],
|
||||
.injected = z[0..0],
|
||||
}) };
|
||||
var ir = @meta.construct(inner);
|
||||
var outer_fields: [2]Ref = .[
|
||||
@field_node("id", u8r),
|
||||
@field_node("in", ir),
|
||||
];
|
||||
var outer: Node = .{ .kind = .AggType(.{
|
||||
.kind = .Struct,
|
||||
.conforms = z[0..0],
|
||||
.fields = outer_fields[0..2],
|
||||
.decls = z[0..0],
|
||||
.injected = z[0..0],
|
||||
}) };
|
||||
var t = @meta.build(@meta.construct(outer));
|
||||
if @field_count(t) != 2 { ret 1; }
|
||||
if @sizeof(t) != 6 { ret 2; }
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn union_and_enum(): usize {
|
||||
var i32r = @int_node(32, true);
|
||||
var f32r = @int_node(32, false);
|
||||
var uf: [2]Ref = .[ @field_node("i", i32r), @field_node("f", f32r) ];
|
||||
var z: [1]Ref = .[0];
|
||||
var un: Node = .{ .kind = .AggType(.{
|
||||
.kind = .Union,
|
||||
.conforms = z[0..0],
|
||||
.fields = uf[0..2],
|
||||
.decls = z[0..0],
|
||||
.injected = z[0..0],
|
||||
}) };
|
||||
var ur = @meta.construct(un);
|
||||
var uin = @meta.inspect(ur);
|
||||
match uin.kind {
|
||||
.AggType(x) => {
|
||||
match x.kind {
|
||||
.Union => {},
|
||||
_ => { ret 1; },
|
||||
}
|
||||
if x.fields.len() != 2 { ret 2; }
|
||||
},
|
||||
_ => { ret 3; },
|
||||
}
|
||||
|
||||
var efields: [3]Ref = .[
|
||||
@field_node("Red", 0),
|
||||
@field_node("Green", 0),
|
||||
@field_node("Blue", 0),
|
||||
];
|
||||
var en: Node = .{ .kind = .AggType(.{
|
||||
.kind = .Enum,
|
||||
.conforms = z[0..0],
|
||||
.fields = efields[0..3],
|
||||
.decls = z[0..0],
|
||||
.injected = z[0..0],
|
||||
}) };
|
||||
var er = @meta.construct(en);
|
||||
var et = @meta.build(er);
|
||||
if @field_count(et) != 3 { ret 4; }
|
||||
if @sizeof(et) != 4 { ret 5; }
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(@scalar_types() == 0, "scalar types");
|
||||
@assert(@fn_type() == 0, "fn type");
|
||||
@assert(@struct_type() == 0, "struct type");
|
||||
@assert(@nested_struct() == 0, "nested struct");
|
||||
@assert(@union_and_enum() == 0, "union/enum");
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
type .{ .method, .type_name } = @import("./meta_utils.spl");
|
||||
type .{ .Node, .Ref } = @import("spl_ir");
|
||||
|
||||
type Pair = struct { a: i32, b: u8 };
|
||||
type PairAlias = Pair;
|
||||
|
||||
type Color = enum { Red, Green };
|
||||
|
||||
type Num = union { i: i32, f: f64 };
|
||||
|
||||
type WithFn = struct {
|
||||
fn inc(x: i32): i32 { ret x + 1; }
|
||||
}
|
||||
|
||||
comptime fn method_ref_ok(T: type): usize {
|
||||
if @method(T, "inc") != 0 { ret 1; }
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn method_ref_missing(T: type): usize {
|
||||
if @method(T, "nope") == 0 { ret 1; }
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn first_byte(T: type): usize {
|
||||
var s = @type_name(T);
|
||||
if s.len() == 0 { ret 0; }
|
||||
ret s[0] as usize;
|
||||
}
|
||||
|
||||
comptime fn name_len(T: type): usize {
|
||||
ret @type_name(T).len();
|
||||
}
|
||||
|
||||
comptime fn generated_name_len(): usize {
|
||||
var f: Node = .{ .kind = .FieldDecl(.{
|
||||
.name = "x",
|
||||
.ty = @meta.construct(.{ .kind = .IntType(.{ .bits = 32, .signed = true }) }),
|
||||
}) };
|
||||
var fields: [1]Ref = .[ @meta.construct(f) ];
|
||||
var z: [1]Ref = .[0];
|
||||
var agg: Node = .{ .kind = .AggType(.{
|
||||
.kind = .Struct,
|
||||
.conforms = z[0..0],
|
||||
.fields = fields[0..1],
|
||||
.decls = z[0..0],
|
||||
.injected = z[0..0],
|
||||
}) };
|
||||
var t = @meta.build(@meta.construct(agg));
|
||||
ret @type_name(t).len();
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(@name_len(Pair) == 4, "pair name");
|
||||
@assert(@first_byte(Pair) == 'P' as usize, "pair first");
|
||||
@assert(@name_len(PairAlias) == 4, "alias keeps name");
|
||||
@assert(@first_byte(PairAlias) == 'P' as usize, "alias first");
|
||||
@assert(@name_len(Color) == 5, "enum name");
|
||||
@assert(@first_byte(Color) == 'C' as usize, "enum first");
|
||||
@assert(@name_len(Num) == 3, "union name");
|
||||
@assert(@first_byte(Num) == 'N' as usize, "union first");
|
||||
@assert(@name_len(i32) == 0, "builtin no name");
|
||||
@assert(@generated_name_len() == 0, "generated no name");
|
||||
@assert(@method_ref_ok(WithFn) == 1, "method ref");
|
||||
@assert(@method_ref_missing(WithFn) == 1, "missing method");
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type meta = @import("meta");
|
||||
type .{ .Node, .Ref } = @import("spl_ir");
|
||||
|
||||
comptime fn int_ref(): Ref {
|
||||
var n: Node = .{ .kind = .IntType(.{ .bits = 32, .signed = true }) };
|
||||
ret @meta.construct(n);
|
||||
}
|
||||
|
||||
comptime fn codec_decls(): usize {
|
||||
var ir = @int_ref();
|
||||
|
||||
var p: Node = .{ .kind = .ParamDecl(.{
|
||||
.is_comptime = false,
|
||||
.by_ref = true,
|
||||
.name = "p",
|
||||
.ty = ir,
|
||||
}) };
|
||||
var pr = @meta.construct(p);
|
||||
var params: [1]Ref = .[pr];
|
||||
var z: [1]Ref = .[0];
|
||||
var empty = z[0..0];
|
||||
|
||||
var fn_node: Node = .{ .kind = .FnDecl(.{
|
||||
.is_comptime = false,
|
||||
.injected = empty,
|
||||
.name = "f",
|
||||
.params = params[0..1],
|
||||
.ret_ty = ir,
|
||||
.body = 0,
|
||||
}) };
|
||||
var fn_ref = @meta.construct(fn_node);
|
||||
|
||||
var tag: Node = .{ .kind = .Tag(.{
|
||||
.is_at = false,
|
||||
.name = "mark",
|
||||
.args = params[0..1],
|
||||
}) };
|
||||
var tag_ref = @meta.construct(tag);
|
||||
|
||||
var field: Node = .{ .kind = .FieldDecl(.{ .name = "a", .ty = ir }) };
|
||||
var field_ref = @meta.construct(field);
|
||||
var fields: [1]Ref = .[field_ref];
|
||||
var decls: [1]Ref = .[fn_ref];
|
||||
var injected: [1]Ref = .[tag_ref];
|
||||
|
||||
var agg: Node = .{ .kind = .AggType(.{
|
||||
.kind = .Struct,
|
||||
.conforms = injected[0..0],
|
||||
.fields = fields[0..1],
|
||||
.decls = decls[0..1],
|
||||
.injected = injected[0..1],
|
||||
}) };
|
||||
var an = @meta.inspect(@meta.construct(agg));
|
||||
match an.kind {
|
||||
.AggType(x) => {
|
||||
if x.fields.len() != 1 { ret 1; }
|
||||
if x.decls.len() != 1 { ret 2; }
|
||||
if x.injected.len() != 1 { ret 3; }
|
||||
var fd = @meta.inspect(x.fields[0]);
|
||||
match fd.kind {
|
||||
.FieldDecl(y) => { if y.name[0] != 'a' { ret 4; } },
|
||||
_ => { ret 5; },
|
||||
}
|
||||
var fdn = @meta.inspect(x.decls[0]);
|
||||
match fdn.kind {
|
||||
.FnDecl(y) => {
|
||||
if y.name[0] != 'f' { ret 6; }
|
||||
if y.params.len() != 1 { ret 7; }
|
||||
var pn = @meta.inspect(y.params[0]);
|
||||
match pn.kind {
|
||||
.ParamDecl(q) => { if !q.by_ref || q.name[0] != 'p' { ret 8; } },
|
||||
_ => { ret 9; },
|
||||
}
|
||||
},
|
||||
_ => { ret 10; },
|
||||
}
|
||||
var tn = @meta.inspect(x.injected[0]);
|
||||
match tn.kind {
|
||||
.Tag(y) => {
|
||||
if y.name.len() != 4 || y.name[0] != 'm' { ret 11; }
|
||||
if y.args.len() != 1 { ret 12; }
|
||||
},
|
||||
_ => { ret 13; },
|
||||
}
|
||||
},
|
||||
_ => { ret 14; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn codec_exprs(): usize {
|
||||
var ir = @int_ref();
|
||||
var l1: Node = .{ .kind = .LitInt("1") };
|
||||
var l2: Node = .{ .kind = .LitInt("2") };
|
||||
var r1 = @meta.construct(l1);
|
||||
var r2 = @meta.construct(l2);
|
||||
var args: [2]Ref = .[r1, r2];
|
||||
|
||||
var g: Node = .{ .kind = .Global("g") };
|
||||
var gr = @meta.construct(g);
|
||||
var call: Node = .{ .kind = .Call(.{
|
||||
.is_comptime = false,
|
||||
.callee = gr,
|
||||
.args = args[0..2],
|
||||
}) };
|
||||
var cn = @meta.inspect(@meta.construct(call));
|
||||
match cn.kind {
|
||||
.Call(x) => {
|
||||
if x.args.len() != 2 { ret 1; }
|
||||
var c = @meta.inspect(x.callee);
|
||||
match c.kind {
|
||||
.Global(s) => { if s.len() != 1 || s[0] != 'g' { ret 2; } },
|
||||
_ => { ret 3; },
|
||||
}
|
||||
},
|
||||
_ => { ret 4; },
|
||||
}
|
||||
|
||||
var lab: Node = .{ .kind = .Label("L") };
|
||||
var lr = @meta.construct(lab);
|
||||
var block: Node = .{ .kind = .Block(.{ .stmts = args[0..1], .tail = r1 }) };
|
||||
var br = @meta.construct(block);
|
||||
var it: Node = .{ .kind = .Iter(.{
|
||||
.label = lr,
|
||||
.inputs = args[0..2],
|
||||
.captures = args[0..1],
|
||||
.pattern_type = 0,
|
||||
.body = br,
|
||||
.else_body = 0,
|
||||
}) };
|
||||
var inode = @meta.inspect(@meta.construct(it));
|
||||
match inode.kind {
|
||||
.Iter(x) => {
|
||||
if x.inputs.len() != 2 { ret 5; }
|
||||
if x.captures.len() != 1 { ret 6; }
|
||||
var bn = @meta.inspect(x.body);
|
||||
match bn.kind {
|
||||
.Block(y) => {
|
||||
if y.stmts.len() != 1 { ret 7; }
|
||||
if y.tail == 0 { ret 8; }
|
||||
},
|
||||
_ => { ret 9; },
|
||||
}
|
||||
var ln = @meta.inspect(x.label);
|
||||
match ln.kind {
|
||||
.Label(s) => { if s.len() != 1 || s[0] != 'L' { ret 10; } },
|
||||
_ => { ret 11; },
|
||||
}
|
||||
},
|
||||
_ => { ret 12; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
comptime fn codec_pats(): usize {
|
||||
var l1: Node = .{ .kind = .LitInt("7") };
|
||||
var r1 = @meta.construct(l1);
|
||||
var b: Node = .{ .kind = .PatBind("v") };
|
||||
var br = @meta.construct(b);
|
||||
var pt: Node = .{ .kind = .PatTag(.{ .name = "Some", .sub = br }) };
|
||||
var ptn = @meta.inspect(@meta.construct(pt));
|
||||
match ptn.kind {
|
||||
.PatTag(x) => {
|
||||
if x.name[0] != 'S' { ret 1; }
|
||||
var sn = @meta.inspect(x.sub);
|
||||
match sn.kind {
|
||||
.PatBind(s) => { if s.len() != 1 || s[0] != 'v' { ret 2; } },
|
||||
_ => { ret 3; },
|
||||
}
|
||||
},
|
||||
_ => { ret 4; },
|
||||
}
|
||||
|
||||
var one: [1]Ref = .[r1];
|
||||
var arr: Node = .{ .kind = .ArrayLit(.{ .elem_ty = 0, .elems = one[0..1] }) };
|
||||
var an = @meta.inspect(@meta.construct(arr));
|
||||
match an.kind {
|
||||
.ArrayLit(x) => {
|
||||
if x.elems.len() != 1 { ret 5; }
|
||||
},
|
||||
_ => { ret 6; },
|
||||
}
|
||||
|
||||
var fl: Node = .{ .kind = .FieldLit(.{ .name = "x", .value = r1 }) };
|
||||
var flr = @meta.construct(fl);
|
||||
var fs: [1]Ref = .[flr];
|
||||
var ag: Node = .{ .kind = .AggLit(.{ .name = "T", .fields = fs[0..1] }) };
|
||||
var agn = @meta.inspect(@meta.construct(ag));
|
||||
match agn.kind {
|
||||
.AggLit(x) => {
|
||||
if x.name[0] != 'T' { ret 7; }
|
||||
if x.fields.len() != 1 { ret 8; }
|
||||
},
|
||||
_ => { ret 9; },
|
||||
}
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@assert(@codec_decls() == 0, "decls codec");
|
||||
@assert(@codec_exprs() == 0, "exprs codec");
|
||||
@assert(@codec_pats() == 0, "pats codec");
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type Cal = shape {
|
||||
fn call(a: i32, b: i32): i32;
|
||||
}
|
||||
|
||||
type Add = struct {
|
||||
fn call(a: i32, b: i32): i32 {
|
||||
ret a + b;
|
||||
}
|
||||
}
|
||||
|
||||
type Sub = struct {
|
||||
fn call(a: i32, b: i32): i32 {
|
||||
ret a - b;
|
||||
}
|
||||
}
|
||||
|
||||
#hook(adapter)
|
||||
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);
|
||||
}
|
||||
|
||||
fn main(): void {
|
||||
var add: Add = Add{};
|
||||
var sub: Sub = Sub{};
|
||||
@assert(Cal1(add, 2, 3) == 5, "add");
|
||||
@assert(Cal1(sub, 5, 3) == 2, "sub");
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type Cal = shape {
|
||||
fn call(a: i32, b: i32): i32;
|
||||
}
|
||||
|
||||
type Add = struct {
|
||||
fn call(a: i32, b: i32): i32 {
|
||||
ret a + b;
|
||||
}
|
||||
}
|
||||
|
||||
type Sub = struct {
|
||||
fn call(a: i32, b: i32): i32 {
|
||||
ret a - b;
|
||||
}
|
||||
}
|
||||
|
||||
#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 {
|
||||
ret a.call(x, y) + b.call(x, y);
|
||||
}
|
||||
|
||||
fn main(): void {
|
||||
var add: Add = Add{};
|
||||
var sub: Sub = Sub{};
|
||||
|
||||
@assert(Both(add, sub, 7, 2) == 14, "add-sub");
|
||||
@assert(Both(sub, add, 7, 2) == 14, "sub-add");
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
// Expect retcode = 0
|
||||
|
||||
type Cal = shape {
|
||||
fn call(a: i32, b: i32): i32;
|
||||
}
|
||||
|
||||
type Add = struct {
|
||||
fn call(a: i32, b: i32): i32 {
|
||||
ret a + b;
|
||||
}
|
||||
}
|
||||
|
||||
type Sub = struct {
|
||||
fn call(a: i32, b: i32): i32 {
|
||||
ret a - b;
|
||||
}
|
||||
}
|
||||
|
||||
#hook(adapter)
|
||||
macro fn wrap(called_type: type, shape_type: type): Ref {
|
||||
ret 0;
|
||||
}
|
||||
|
||||
fn Use(c: @wrap[Cal], a: i32, b: i32): i32 {
|
||||
ret c.call(a, b);
|
||||
}
|
||||
|
||||
fn main(): void {
|
||||
var add: Add = Add{};
|
||||
var sub: Sub = Sub{};
|
||||
|
||||
@assert(Use(add, 4, 6) == 10, "add");
|
||||
@assert(Use(sub, 9, 4) == 5, "sub");
|
||||
}
|
||||
Loaded 100 of 402 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user