Compare commits

..
9 Commits
Author SHA1 Message Date
zzy 6c764bb8a0 refactor(stage1 ai): 抽离 IR 类型系统并让 exec 基于 IR 运行
- IR 类型表并入 spl_ir_t,lang_type 改为借用
- 抽出 spl_ir_type / spl_ir_layout,移除前端专用 IR 类型
- lang 聚合改为 nominal 身份,字段与方法回收到 lang_type
- 新增 spl_ir_link,建立 def/lang_type <-> ir_func/ir_type 双向绑定
- exec 去除 CFG 依赖,plan 由 IR 调用图生成
- meta 不再构建 AST CFG,按 IR 函数按需编译
- host ABI 改为 typed value,支持聚合返回
- @sap.view 改为普通 host op,支持动态 handle
- 新增 nominal 聚合与动态 sap.view 回归测试
2026-12-03 12:31:34 +08:00
zzy 480945a92f ai: stage1 unify IR values and globals
- add spl_ir_value_t (INST/CONST/GLOBAL) and global table
- remove mem.global_alloc and global.ref instructions
- dedup byte constants in a program-level pool
- zero-init aggregate literals in ast2ir; honor undefined
- C backend: fix zero-arg main return, extern prototypes/varargs
- fix dangling inline-module method names (0018 flake)
2026-12-02 22:41:20 +08:00
zzy 663adf6cae ai: 实现mod语法 提供namespace框架 2026-12-02 13:02:58 +08:00
zzy e531aab2d3 ai: 重新设计stage1的spl 让ai重构代码 2026-12-02 12:40:36 +08:00
zzy 032102f1d7 ai: 生成代码准备重构前的一次提交 2026-11-30 12:58:19 +08:00
zzy 936a8d0e88 fix ai修复出现的stage2和stage3问题 2026-11-13 22:15:07 +08:00
zzy 50ee126d44 spl 编写编译器基础框架 ai修复出现的stage2和stage3问题并提供新语法 2026-11-07 21:52:02 +08:00
zzy 126b979f72 stage3 ai编写新语法语义 同时提供fflush 2026-11-05 09:48:43 +08:00
zzy bb8761d392 nob 实现最后一步编译框架 移动测试用例 准备for的新语法 2026-11-02 21:41:19 +08:00
387 changed files with 22543 additions and 9772 deletions

No files matched your search

+71 -7
View File
@@ -1,6 +1,6 @@
#define COMMON_CFLAGS "-Wall", "-Wextra", "-D_CRT_SECURE_NO_WARNINGS"
#define SPL_CFLAGS COMMON_CFLAGS, "-O0", "-g"
#define COMMON_CFLAGS "-Wall", "-Wextra", "-D_CRT_SECURE_NO_WARNINGS", "-D_CRT_NONSTDC_NO_DEPRECATE"
#define SPL_CFLAGS COMMON_CFLAGS, "-I.", "-Istage1/include", "-O0", "-g"
#define SPL_OPTIMIZATION_FLAG COMMON_CFLAGS, "-O2"
#define nob_cc_flags(cmd) nob_cmd_append(cmd, SPL_CFLAGS)
#undef UNICODE
@@ -19,7 +19,7 @@
#define BUILD_FOLDER "build/"
// Content of the .cflags stamp file; must match SPL_CFLAGS above.
#define CFLAGS_STR "-Wall -Wextra -O0 -g"
#define CFLAGS_STR "-Wall -Wextra -I. -Istage1/include -O0 -g"
// Stamp file whose mtime is refreshed whenever the flags change so that all
// object files get rebuilt.
static const char *CFLAGS_STAMP = BUILD_FOLDER ".cflags";
@@ -288,6 +288,7 @@ defer:
const char *build_target(const char *name) {
if (!prepare_build())
return NULL;
const char *splc_libs = "./src/libs";
for (size_t i = 0; i < NOB_ARRAY_LEN(targets); ++i) {
if (name != NULL && strcmp(targets[i].name, name) != 0) {
continue;
@@ -298,6 +299,7 @@ const char *build_target(const char *name) {
case BUILD_EXE: {
return build_exe(target);
}
case BUILD_SPLC_SIR:
case BUILD_SIR: {
const char *target_sir = sir_path(name);
// 编译器先建好:它的产物也要算进依赖,编译器变了就得重编 .sir。
@@ -321,6 +323,9 @@ const char *build_target(const char *name) {
return target_sir;
Nob_Cmd cmd = {0};
if (target->kind == BUILD_SPLC_SIR) {
nob_cmd_append(&cmd, "-I", splc_libs);
}
nob_cmd_append(&cmd, target->sir.src, target_sir);
if (!run_target(target->sir.compiler, &cmd)) {
nob_log(NOB_ERROR, "failed to build `%s`", name);
@@ -330,6 +335,7 @@ const char *build_target(const char *name) {
nob_cmd_free(cmd);
return target_sir;
}
case BUILD_SPLC_NATIVE:
case BUILD_NATIVE: {
Nob_Cmd cmd = {0};
const char *target_exe = exe_path(name);
@@ -353,6 +359,9 @@ const char *build_target(const char *name) {
return NULL;
}
if (needs != 0) {
if (target->kind == BUILD_SPLC_NATIVE) {
nob_cmd_append(&cmd, "-I", splc_libs);
}
nob_cmd_append(&cmd, "--dump", "c", target->native.src, target_c);
if (!run_target(target->native.compiler, &cmd)) {
nob_log(NOB_ERROR, "failed to build `%s`", name);
@@ -449,6 +458,7 @@ typedef struct {
bool has_location;
int line;
int col;
bool pending;
} test_expect_t;
static bool test_parse_error_code(Nob_String_View value, int *out) {
@@ -530,6 +540,10 @@ static bool test_parse_expect(const char *fname, test_expect_t *expect) {
break;
continue;
}
if (nob_sv_eq(key, nob_sv_from_cstr("pending"))) {
expect->pending = true;
continue;
}
if (nob_sv_eq(key, nob_sv_from_cstr("location"))) {
if (expect->has_location) {
malformed = true;
@@ -575,6 +589,7 @@ typedef struct {
static const test_suite_t TEST_SUITES[] = {
{"stage1", "./tests/stage1/"},
{"spl_core", "./tests/spl_core/"},
{"stage2", "./tests/stage2/"},
{"stage3", "./tests/stage3/"},
};
@@ -613,6 +628,7 @@ typedef struct {
const scc_argparse_list_t *filters; // 按文件名子串过滤,空则全跑
int passed;
int failed;
int pending; // `// Expect pending` 的预期失败数
int no_expect; // 没写 Expect 注解、按 0 期望的文件数
} test_ctx_t;
@@ -622,6 +638,48 @@ static bool test_has_error_code(const Nob_Cmd_Result *result, int code) {
return result->out.items != NULL && strstr(result->out.items, needle) != NULL;
}
static void test_pending_compile_and_run(const char *fname, test_ctx_t *ctx) {
Nob_Cmd compile = {0};
nob_cmd_extend(&compile, &ctx->compiler);
nob_cmd_append(&compile, fname, ctx->out_sir);
Nob_Cmd_Result compile_result = {0};
if (!run_capture(&compile, &compile_result)) {
nob_log(NOB_ERROR, "%s: failed to launch compiler", fname);
nob_cmd_free(compile);
ctx->failed += 1;
return;
}
nob_cmd_free(compile);
if (compile_result.exit_code != 0) {
nob_log(NOB_INFO, "%s: pending (compile failed as expected)", fname);
nob_cmd_result_free(compile_result);
ctx->pending += 1;
return;
}
nob_cmd_result_free(compile_result);
Nob_Cmd run = {0};
nob_cmd_extend(&run, &ctx->vm);
nob_cmd_append(&run, ctx->out_sir);
Nob_Cmd_Result result = {0};
if (!run_capture(&run, &result)) {
nob_log(NOB_ERROR, "%s: failed to run", fname);
nob_cmd_free(run);
ctx->failed += 1;
return;
}
nob_cmd_free(run);
if (result.exit_code != 0) {
nob_log(NOB_INFO, "%s: pending (run failed as expected)", fname);
ctx->pending += 1;
} else {
nob_log(NOB_ERROR, "%s: pending test passed unexpectedly; remove `// Expect pending`",
fname);
ctx->failed += 1;
}
nob_cmd_result_free(result);
}
static void test_compile_and_run(const char *fname, test_ctx_t *ctx) {
test_expect_t expect = {0};
if (!test_parse_expect(fname, &expect)) {
@@ -629,6 +687,10 @@ static void test_compile_and_run(const char *fname, test_ctx_t *ctx) {
ctx->failed += 1;
return;
}
if (expect.pending) {
test_pending_compile_and_run(fname, ctx);
return;
}
Nob_Cmd compile = {0};
nob_cmd_extend(&compile, &ctx->compiler);
@@ -967,11 +1029,11 @@ static int cli_test(nob_cli_t *cli) {
bool walked = walk_spl_files(suite->dir, &cli->test_filters, test_run_file, &ctx);
if (ctx.no_expect > 0)
nob_log(NOB_INFO, "%s (`%s`): %d passed, %d failed (%d without `// Expect`)", suite->name,
target, ctx.passed, ctx.failed, ctx.no_expect);
nob_log(NOB_INFO, "%s (`%s`): %d passed, %d failed, %d pending (%d without `// Expect`)",
suite->name, target, ctx.passed, ctx.failed, ctx.pending, ctx.no_expect);
else
nob_log(NOB_INFO, "%s (`%s`): %d passed, %d failed", suite->name, target, ctx.passed,
ctx.failed);
nob_log(NOB_INFO, "%s (`%s`): %d passed, %d failed, %d pending", suite->name, target,
ctx.passed, ctx.failed, ctx.pending);
nob_cmd_free(ctx.compiler);
nob_cmd_free(ctx.vm);
@@ -1057,10 +1119,12 @@ static int cli_list(void) {
count_files(t->exe.srcs, t->exe.srcs_count),
count_files(t->exe.headers, t->exe.headers_count));
break;
case BUILD_SPLC_SIR:
case BUILD_SIR:
printf(" %-12s %-9s %s <- %s deps=%zu\n", t->name, kind, t->sir.src, t->sir.compiler,
count_files(t->sir.deps, t->sir.deps_count));
break;
case BUILD_SPLC_NATIVE:
case BUILD_NATIVE:
printf(" %-12s %-9s %s <- %s deps=%zu crt=%zu\n", t->name, kind, t->native.src,
t->native.compiler, count_files(t->native.deps, t->native.deps_count),
+6 -4
View File
@@ -10,12 +10,12 @@
// 不含 '*' 的条目按字面路径处理;某个模式一条都没匹配到会直接报错。
static const char *stage0_headers[] = {"stage0/*.h"};
static const char *splc1_headers[] = {"stage0/*.h", "stage1/*.h"};
static const char *splc1_headers[] = {"stage0/*.h", "stage1/**/*.h"};
static const char *spl_cli_srcs[] = {"stage0/spl_cli.c", VM_SRCS};
static const char *vm_test_srcs[] = {"stage0/test_spl_vm.c", VM_SRCS};
static const char *splc1_srcs[] = {"stage1/*.c", "stage0/spl_mcode.c"};
static const char *splc1_srcs[] = {"stage1/**/*.c", "stage0/spl_mcode.c"};
#define CRT_DEPS \
"stage0/spl_rt.h", "stage0/spl_rt_core.h", "stage0/spl_asp.h", \
@@ -50,6 +50,8 @@ typedef struct build {
BUILD_EXE_WITH_OPTIMIZATION,
BUILD_SIR,
BUILD_NATIVE,
BUILD_SPLC_SIR,
BUILD_SPLC_NATIVE,
} kind;
union {
struct {
@@ -173,7 +175,7 @@ static build_t targets[] = {
},
{
"splc4",
BUILD_SIR,
BUILD_SPLC_SIR,
.sir =
{
.src = "src/main.spl",
@@ -184,7 +186,7 @@ static build_t targets[] = {
},
{
"splc4n",
BUILD_NATIVE,
BUILD_SPLC_NATIVE,
.native =
{
.src = "src/main.spl",
+79
View File
@@ -0,0 +1,79 @@
type .{ .Vec } = @import("core/vec.spl");
type .{ .Allocator } = @import("core/alloc.spl");
type .{ .String } = @import("core/str.spl");
type .{ .Result } = @import("core/error.spl");
type ptr = @import("core/ptr.spl");
type .{ .File } = @import("compiler/shape.spl");
type SourceId = u32;
pub comptime fn SourceFile(A: Allocator): type {
ret struct {
id: SourceId,
name: @Vec(u8, A),
content: @Vec(u8, A),
line_offsets: @Vec(usize, A),
}
}
type SourceError = enum {
UnknownError,
FileOpenError,
FileAttributeError,
FileReadError,
OutOfMemory,
}
pub comptime fn Source(A: Allocator, F: File): type {
ret struct {
// TODO HashSet 进行去重
files: @Vec(@SourceFile(A), A),
fshape: F,
alloc: A,
pub fn new(alloc: A, fshape: F): @self {
ret .{ .files = @Vec(@SourceFile(A), A).empty(alloc), .alloc = alloc, .fshape = fshape };
}
pub fn add_file(@Self self: *@self, name: []const u8): @Result(SourceId, SourceError) {
var fp = self.fshape.open(name, .Read) catch .Err(_) {
ret .(.Err(.FileOpenError));
};
errdefer { fp.close(); }
var size = fp.size() catch .Err(_) {
ret .(.Err(.FileAttributeError));
};
var content = @Vec(u8, A).with_capacity(self.alloc, size) catch .Err(_) {
ret .(.Err(.OutOfMemory));
};
content._set_len(size);
var read_size = fp.read(content.as_slice()) catch .Err(_) {
ret .(.Err(.FileReadError));
};
if read_size != size {
ret .(.Err(.FileReadError));
}
var owned_name = @Vec(u8, A).with_capacity(self.alloc, name.len()) catch .Err(_) {
ret .(.Err(.OutOfMemory));
};
owned_name._set_len(name.len());
ptr.copy(owned_name.as_slice().as_ptr(), name.as_ptr(), name.len());
ret self.add_virtual(owned_name, content);
}
pub fn add_virtual(@Self self: *@self, name: @Vec(u8, A), content: @Vec(u8, A)): @Result(SourceId, SourceError) {
var id = self.files.len();
var file: @SourceFile(A) = .{
.id = id as u32,
.name = name,
.content = content,
.line_offsets = @Vec(usize, A).empty(self.alloc),
};
self.files.push(file) catch .Err(e) {
ret .(.Err(.OutOfMemory));
};
ret .(.Ok(id as SourceId));
}
}
}
+30
View File
@@ -0,0 +1,30 @@
type .{ .Writer, .Reader, .IOError } = @import("core/io.spl");
type .{ .Result, .Option } = @import("core/error.spl");
pub type FileMode = enum {
Read,
Write,
Append,
}
pub type File = shape: Writer + Reader {
fn open(path: []const u8, mode: FileMode): @Result(@self, IOError);
fn close(@Self self: *@self): @Result((), IOError);
fn size(@Self self: *@self): @Result(usize, IOError);
}
pub type Time = shape {
}
pub type Memory = shape {
}
pub type Process = shape {
}
pub type VM = shape {
}
+205
View File
@@ -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 {
// }
+16
View File
@@ -0,0 +1,16 @@
type .{ .Result } = @import("./error.spl");
pub type Layout = struct {
size: usize;
align: usize;
}
pub type AllocError = enum {
OutOfMemory,
InvalidLayout,
}
pub type Allocator = shape {
fn alloc(@Self self: *@self, layout: Layout): @Result(*any, AllocError);
fn dealloc(@Self self: *@self, ptr: *any, layout: Layout);
}
+59
View File
@@ -0,0 +1,59 @@
pub comptime fn Option(T: type): type {
ret enum {
pub Some: T,
pub None: void,
// pub fn unwrap(@Self self: *@self): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { panic("called unwrap on None"); ret undefined; }
// }
// }
// pub fn expect(@Self self: *@self, msg: []u8): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { panic(msg); ret undefined; }
// }
// }
// pub fn unwrap_or_else(@Self self: *@self, f: fn(): T): T {
// match self.* {
// .Some(v) => { ret v; }
// .None => { ret f(); }
// }
// }
};
}
pub comptime fn Result(T: type, E: type): type {
ret enum {
#ok
pub Ok: T,
#error
pub Err: E,
// pub fn unwrap(@Self self: *@self): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { panic("called unwrap on Err"); ret undefined; }
// }
// }
// pub fn expect(@Self self: *@self, msg: []u8): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { panic(msg); ret undefined; }
// }
// }
// pub fn unwrap_or_else(@Self self: *@self, f: fn(): T): T {
// match self.* {
// .Ok(v) => { ret v; }
// .Err(e) => { ret f(); }
// }
// }
};
}
+80
View File
@@ -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; },
}
}
}
};
}
View File
Whitespace-only changes.
+19
View File
@@ -0,0 +1,19 @@
type .{ .Allocator } = @import("./alloc.spl");
type .{ .Result } = @import("./error.spl");
type .{ .static } = @import("./macro.spl");
type IOError = enum {
UnknownError,
OutOfMemory,
BufferTooSmall,
}
pub type Reader = shape {
fn read(@Self self: *@self, buf: []u8): @Result(usize, IOError);
}
pub type Writer = shape {
fn write(@Self self: *@self, buf: []const u8): @Result(usize, IOError);
fn flush(@Self self: *@self): @Result((), IOError);
}
+22
View File
@@ -0,0 +1,22 @@
type meta = @import("meta");
type .{ .Ref } = meta;
#hook(param)
macro fn default(callee: Ref, value: Ref, fallback: Ref): Ref {
if value != 0 { ret value; }
if fallback != 0 { @meta.error(704); ret 0; }
// TODO check the same type
ret Ref;
}
#hook(param)
macro fn Self(callee: Ref, value: Ref): Ref {
// TODO value direct not supported
// @meta.
ret @meta.construct(.{ .kind = .Addr(value) });
}
#hook(adapter)
macro fn static(called_type: type, shape_type: type): Ref {
ret 0;
}
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
pub fn bytes_eq(a: []const u8, b: []const u8): bool {
if a.len() != b.len() { ret false; }
var i: usize = 0;
while i < a.len() {
if a[i] != b[i] { ret false; }
i = i + 1;
}
ret true;
}
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
fn copy(dst: *any, src: *const any, count: usize) {
var _dst = dst as *u8;
var _src = src as *const u8;
var i: usize = 0;
while (i < count) {
_dst[i] = _src[i];
i = i + 1;
}
}
+120
View File
@@ -0,0 +1,120 @@
type .{ .Vec } = @import("./vec.spl");
type .{ .Allocator, .AllocError } = @import("./alloc.spl");
type .{ .Result, .Option } = @import("./error.spl");
type .{ .Format } = @import("./fmt.spl");
type .{ .static } = @import("./macro.spl");
type FromStr = shape {
type Err;
fn from_str(s: []const u8): @Result(@self, Err);
}
pub fn eq(a: []const u8, b: []const u8): bool {
if a.len() != b.len() { ret false; }
var i: usize = 0;
while i < a.len() {
if a[i] != b[i] { ret false; }
i = i + 1;
}
ret true;
}
pub fn starts_with(s: []const u8, prefix: []const u8): bool {
if prefix.len() > s.len() { ret false; }
ret eq(s[0..prefix.len()], prefix);
}
pub fn index_byte(s: []const u8, b: u8, from: usize): @Option(usize) {
var i = from;
while i < s.len() {
if s[i] == b { ret .Some(i); }
i = i + 1;
}
ret .None;
}
pub fn is_space(b: u8): bool {
ret b == ' ' || b == '\t' || b == '\r' || b == '\n';
}
pub fn is_digit(b: u8): bool {
ret b >= '0' && b <= '9';
}
pub fn is_hex_digit(b: u8): bool {
ret is_digit(b) || (b >= 'a' && b <= 'f') || (b >= 'A' && b <= 'F');
}
pub fn is_alpha(b: u8): bool {
ret (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z');
}
pub fn is_ident_start(b: u8): bool {
ret is_alpha(b) || b == '_';
}
pub fn is_ident_continue(b: u8): bool {
ret is_ident_start(b) || is_digit(b);
}
pub fn trim_ascii(s: []const u8): []const u8 {
var a: usize = 0;
var b: usize = s.len();
while a < b && is_space(s[a]) { a = a + 1; }
while b > a && is_space(s[b - 1]) { b = b - 1; }
ret s[a..b];
}
pub comptime fn String(A: Allocator): type {
ret struct {
data: @Vec(u8, A),
pub fn new(alloc: A): @self {
ret .{ .data = @Vec(u8, A).empty(alloc) };
}
pub fn from_slice(alloc: A, s: []const u8): @Result(@self, AllocError) {
var out: @self = .{ .data = @Vec(u8, A).empty(alloc) };
try out.push_str(s);
ret .(.Ok(out));
}
pub fn push_str(@Self self: *@self, s: []const u8): @Result((), AllocError) {
var i: usize = 0;
while i < s.len() {
try self.data.push(s[i]);
i = i + 1;
}
}
pub fn from_cstr(alloc: A, s: *const u8): @Result(@self, AllocError) {
var res: @self = .{ .data = @Vec(u8, A).empty(alloc) };
try res.push_cstr(s);
ret .(.Ok(res));
}
pub fn push_cstr(@Self self: *@self, s: *const u8): @Result((), AllocError) {
var i: usize = 0;
while s[i] != 0 {
try self.data.push(s[i]);
i = i + 1;
}
}
pub fn as_slice(@Self self: *@self): []const u8 {
ret self.data.as_slice();
}
pub fn len(@Self self: *@self): usize {
ret self.data.len();
}
pub fn clear(@Self self: *@self) {
self.data.clear();
}
pub fn drop(@Self self: *@self) {
self.data.drop();
}
};
}
+279
View File
@@ -0,0 +1,279 @@
type .{ .Option, .Result } = @import("./error.spl");
type .{ .Layout, .AllocError, .Allocator } = @import("./alloc.spl");
type ptr = @import("ptr.spl");
comptime fn RawVec(t: type): type {
ret struct {
data: *t,
length: usize,
cap: usize,
pub fn empty(): @self {
ret .{ .data = null, .length = 0, .cap = 0 };
}
pub fn len(@Self self: *@self): usize {
ret self.length;
}
pub fn capacity(@Self self: *@self): usize {
ret self.cap;
}
pub fn as_raw_ptr(@Self self: *@self): *t {
ret self.data;
}
pub fn as_slice(@Self self: *@self): []t {
ret @Slice(t).from_raw_parts(self.data, self.length);
}
pub fn get(@Self self: *@self, i: usize): @Option(t) {
if i >= self.length { ret .None }
ret .Some(self.data[i]);
}
pub fn at(@Self self: *@self, i: usize): @Option(*t) {
if i >= self.length { ret .None }
ret .Some(self.data + i);
}
pub fn set(@Self self: *@self, i: usize, v: t): bool {
if (i >= self.length) { ret false }
self.data[i] = v;
ret true;
}
pub fn clear(@Self self: *@self): () {
self.length = 0;
}
pub fn truncate(@Self self: *@self, n: usize): () {
if n < self.length {
self.length = n;
}
}
pub fn reset(@Self self: *@self): () {
self.data = null;
self.length = 0;
self.cap = 0;
}
pub fn set_unchecked(@Self self: *@self, i: usize, v: t) {
self.data[i] = v;
}
pub fn push_unchecked(@Self self: *@self, v: t): () {
self.data[self.length] = v;
self.length = self.length + 1;
}
pub fn pop_unchecked(@Self self: *@self): t {
self.length = self.length - 1;
ret self.data[self.length];
}
pub fn insert_unchecked(@Self self: *@self, i: usize, v: t): () {
var j = self.length;
while j > i {
self.data[j] = self.data[j - 1];
j = j - 1;
}
self.data[i] = v;
self.length += 1;
}
pub fn remove_unchecked(@Self self: *@self, i: usize): t {
var v = self.data[i];
var j = i;
while j + 1 < self.length {
self.data[j] = self.data[j + 1];
j = j + 1;
}
self.length -= 1;
ret v;
}
};
}
fn layout_of(size: usize, align: usize, n: usize): Layout {
var limit: usize = ~(0 as usize);
@assert(n == 0 || size <= limit / n, "layout overflow");
ret .{ .size = size * n, .align = align };
}
fn grow_capacity(current: usize, min_cap: usize, need: usize): usize {
var cap = current;
if cap < min_cap {
cap = min_cap;
}
while cap < need {
cap = cap * 2;
}
ret cap;
}
comptime fn Grow(T: type, A: Allocator): type {
ret struct {
fn reserve(base: *@RawVec(T), alloc: A, additional: usize): @Result((), AllocError) {
var need = base.len() + additional;
if need <= base.capacity() {
ret;
}
var new_cap = grow_capacity(base.capacity(), 8, need);
var old_layout = layout_of(@sizeof(T), @alignof(T), base.capacity());
var new_layout = layout_of(@sizeof(T), @alignof(T), new_cap);
var p: *u8 = try alloc.alloc(new_layout) as *u8;
if base.capacity() != 0 {
// TODO : Use copy_nonoverlapping to copy the data from the old allocation to the new one
// This is a placeholder for the actual memory copy operation
ptr.copy(p, base.data as *u8, base.len() * @sizeof(T));
alloc.dealloc(base.data as *any, old_layout);
}
base.data = p as *T;
base.cap = new_cap;
}
};
}
pub comptime fn Vec(T: type, A: Allocator): type {
ret struct {
base: @RawVec(T),
alloc: A,
pub fn empty(alloc: A): @self {
ret .{ .base = @RawVec(T).empty(), .alloc = alloc };
}
pub fn with_capacity(alloc: A, n: usize): @Result(@self, AllocError) {
@assert(@sizeof(T) > 0, "zero-size element unsupported");
var v: @self = .{ .base = @RawVec(T).empty(), .alloc = alloc };
if n == 0 {
ret .Ok(v);
}
try @Grow(T, A).reserve(&v.base, v.alloc, n);
ret .Ok(v);
}
pub fn len(@Self self: *@self): usize {
ret self.base.len();
}
pub fn capacity(@Self self: *@self): usize {
ret self.base.capacity();
}
pub fn as_slice(@Self self: *@self): []T {
ret self.base.as_slice();
}
pub fn get(@Self self: *@self, i: usize): @Option(T) {
ret self.base.get(i);
}
pub fn at(@Self self: *@self, i: usize): @Option(*T) {
ret self.base.at(i);
}
pub fn set(@Self self: *@self, i: usize, v: T): bool {
ret @RawVec(T).set(&self.base, i, v);
}
pub fn reserve(@Self self: *@self, additional: usize): @Result((), AllocError){
try @Grow(T, A).reserve(&self.base, self.alloc, additional);
}
pub fn push(@Self self: *@self, v: T): @Result((), AllocError) {
if self.base.len() + 1 > self.base.cap {
try @Grow(T, A).reserve(&self.base, self.alloc, 1);
}
@RawVec(T).push_unchecked(&self.base, v);
ret .Ok(());
}
pub fn pop(@Self self: *@self): @Option(T) {
if self.base.len() == 0 {
ret .None;
}
ret .Some(@RawVec(T).pop_unchecked(&self.base));
}
pub fn append(@Self self: *@self, items: []T): @Result((), AllocError) {
var count = items.len();
if count == 0 {
ret .Ok(());
}
var offset: usize = 0;
var inside = false;
if self.base.len() != 0 {
var base_addr = self.base.data as usize;
var src_addr = items.as_ptr() as usize;
if src_addr >= base_addr && src_addr - base_addr < self.base.len() * @sizeof(T) {
offset = src_addr - base_addr;
inside = true;
}
}
if self.base.len() + count > self.base.capacity() {
try @Grow(T, A).reserve(&self.base, self.alloc, count);
}
var src = items.as_ptr();
if inside {
src = ((self.base.data as *u8) + offset) as *T;
}
var i: usize = 0;
while i < count {
@RawVec(T).push_unchecked(&self.base, src[i]);
i = i + 1;
}
ret .Ok(());
}
pub fn insert(@Self self: *@self, i: usize, v: T): @Result((), AllocError) {
@assert(i <= self.base.len(), "insert out of range");
if self.base.len() + 1 > self.base.capacity() {
try @Grow(T, A).reserve(&self.base, self.alloc, 1);
}
@RawVec(T).insert_unchecked(&self.base, i, v);
ret .Ok(());
}
pub fn remove(@Self self: *@self, i: usize): @Option(T) {
if (i < self.base.len()) {
ret .None;
}
var res = @RawVec(T).remove_unchecked(&self.base, i);
ret .Some(res);
}
pub fn clear(@Self self: *@self): void {
@RawVec(T).clear(&self.base);
}
pub fn truncate(@Self self: *@self, n: usize): bool {
if (n >= self.base.len()) { ret false }
@RawVec(T).truncate(&self.base, n);
ret true;
}
pub fn _set_len(@Self self: *@self, n: usize): bool {
if (n >= self.base.capacity()) { ret false; }
self.base.length = n;
ret true;
}
pub fn drop(@Self self: *@self) {
if self.base.capacity() != 0 {
self.alloc.dealloc(self.base.data as *u8,
layout_of(@sizeof(T), @alignof(T), self.base.capacity()));
}
@RawVec(T).reset(&self.base);
}
pub fn take(@Self self: *@self): @self {
var r = self.*;
@RawVec(T).reset(&self.base);
ret r;
}
};
}
+84
View File
@@ -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());
}
+116 -86
View File
@@ -5,8 +5,12 @@
* -g, --debug-cli interactive debugger (REPL)
* --entry <name> entry function (default: main)
* --trace print every instruction
* --profile native sampling profiler
* --profile-interval <N> profile sampling interval (default: 10000)
* -h, --help show help
*
* 选项可以出现在 <file.sir> 之前或之间;`--` 之后全部作为 spl 程序参数。
*
* spl 程序 argv:argv[0]=file.sir,argv[1..]=args。
* REPL 配合 splc0 -g(.sir 尾部内嵌 debug 段:IR 行 + VAR 行)可显示
* 当前 IR 节点/源行/局部变量。
@@ -21,103 +25,121 @@
#include <stdlib.h>
#include <string.h>
#define SCC_ARGPARSE_IMPLEMENTATION
#define SCC_OPTPARSER_IMPLEMENTATION
#include "../nob/argparse.h"
/* ================================================================
* 命令行解析
* ================================================================ */
typedef struct {
int debug;
int debug_cli;
int trace;
int disasm;
int profile;
cbool debug;
cbool debug_cli;
cbool trace;
cbool disasm;
cbool profile;
int profile_interval;
const char *profile_out;
int stats;
cbool stats;
const char *entry;
const char *path; /* file.sir */
const char **args; /* spl 程序参数(file.sir 之后) */
int nargs;
const char *path; /* file.sir */
scc_argparse_list_t args; /* spl 程序参数(file.sir 之后) */
} cli_opts_t;
static void usage(void) {
fprintf(stderr, "Usage: spl_cli [options] <file.sir> [args...]\n"
" -d, --debug stack-canary checks\n"
" -g, --debug-cli interactive debugger (REPL)\n"
" --disasm disasm dump sir\n"
" --entry <name> entry function (default: main)\n"
" --trace print every instruction\n"
" --profile[=N] native sampling profiler (every N insns, default 10000)\n"
" --profile-out <p> profile output prefix (default build/profile)\n"
" --stats print executed instructions / call count at exit\n"
" -h, --help show help\n");
static void add_bool_opt(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
cbool *store) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
scc_argparse_spec_setup_bool(&opt.spec, store);
scc_argparse_cmd_add_opt(cmd, &opt);
}
/* options 可穿插;`--` 终止 option 解析(本身不作为 file/args)。
* 第一个非 option 为 file.sir,其后为 spl args。 */
static int parse_args(int argc, const char **argv, cli_opts_t *o) {
memset(o, 0, sizeof *o);
o->entry = "main";
int i = 1;
for (; i < argc; i++) {
const char *a = argv[i];
if (a[0] == '-' && a[1]) {
if (strcmp(a, "--") == 0) {
i++;
break;
}
if (strcmp(a, "-d") == 0 || strcmp(a, "--debug") == 0) {
o->debug = 1;
} else if (strcmp(a, "-g") == 0 || strcmp(a, "--debug-cli") == 0) {
o->debug_cli = 1;
} else if (strcmp(a, "--trace") == 0) {
o->trace = 1;
} else if (strcmp(a, "--disasm") == 0) {
o->disasm = 1;
} else if (strcmp(a, "--stats") == 0) {
o->stats = 1;
} else if (strcmp(a, "--profile") == 0) {
o->profile = 1;
} else if (strncmp(a, "--profile=", 10) == 0) {
o->profile = 1;
o->profile_interval = (int)strtol(a + 10, NULL, 10);
} else if (strcmp(a, "--profile-out") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "spl_cli: --profile-out needs a prefix\n");
return -1;
}
o->profile_out = argv[++i];
} else if (strcmp(a, "--entry") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "spl_cli: --entry needs a name\n");
return -1;
}
o->entry = argv[++i];
} else if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) {
usage();
return -1;
} else {
fprintf(stderr, "spl_cli: unknown option '%s'\n", a);
usage();
return -1;
}
} else {
static void add_string_opt(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
const char **store) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
scc_argparse_spec_setup_string(&opt.spec, store);
scc_argparse_cmd_add_opt(cmd, &opt);
}
static void add_int_opt(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
int *store) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
scc_argparse_spec_setup_int(&opt.spec, store);
scc_argparse_cmd_add_opt(cmd, &opt);
}
static void add_arg_string(scc_argparse_cmd_t *cmd, const char *name, const char *desc,
const char **store, cbool required) {
scc_argparse_arg_t arg;
scc_argparse_arg_init(&arg, name, desc);
scc_argparse_spec_setup_string(&arg.spec, store);
arg.spec.flag_required = required;
scc_argparse_cmd_add_arg(cmd, &arg);
}
static void add_arg_list(scc_argparse_cmd_t *cmd, const char *name, const char *desc,
scc_argparse_list_t *store) {
scc_argparse_arg_t arg;
scc_argparse_arg_init(&arg, name, desc);
scc_argparse_spec_setup_list(&arg.spec, store);
scc_argparse_cmd_add_arg(cmd, &arg);
}
/* argparse 的 BOOL 会忽略 `--profile=500` 的尾部值;显式拦掉,避免间隔被悄悄丢掉。 */
static int reject_inline_profile(int argc, const char **argv) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--") == 0)
break;
if (strncmp(argv[i], "--profile=", 10) == 0) {
fprintf(stderr,
"spl_cli: `%s` is not supported, use `--profile --profile-interval N`\n",
argv[i]);
return -1;
}
}
/* 跳过前导 `--`(pipeline 调用会带 `--` 分隔 file 与 args) */
while (i < argc && strcmp(argv[i], "--") == 0)
i++;
if (i >= argc) {
fprintf(stderr, "spl_cli: missing <file.sir>\n");
usage();
return 0;
}
/* `--` 之后 optparse 不再识别选项,剩余 token 全部落进 args。 */
static int parse_cli(int argc, const char **argv, cli_opts_t *o) {
memset(o, 0, sizeof *o);
o->entry = "main";
if (reject_inline_profile(argc, argv) != 0)
return -1;
scc_argparse_t parser;
scc_argparse_init(&parser, "spl_cli", "SIR VM launcher + gdb-style debugger");
scc_argparse_cmd_t *root = scc_argparse_get_root(&parser);
add_bool_opt(root, 'd', "debug", "stack-canary checks", &o->debug);
add_bool_opt(root, 'g', "debug-cli", "interactive debugger (REPL)", &o->debug_cli);
add_bool_opt(root, 0, "disasm", "disasm dump sir", &o->disasm);
add_string_opt(root, 0, "entry", "entry function (default: main)", &o->entry);
add_bool_opt(root, 0, "trace", "print every instruction", &o->trace);
add_bool_opt(root, 0, "profile", "native sampling profiler", &o->profile);
add_int_opt(root, 0, "profile-interval", "profile sampling interval in insns (default: 10000)",
&o->profile_interval);
add_string_opt(root, 0, "profile-out", "profile output prefix (default: build/profile)",
&o->profile_out);
add_bool_opt(root, 0, "stats", "print executed instructions / call count at exit",
&o->stats);
add_arg_string(root, "file", "SIR bytecode file", &o->path, true);
add_arg_list(root, "args", "arguments passed to the spl program", &o->args);
int rc = scc_argparse_parse(&parser, argc, argv);
if (parser.out.count > 0)
fwrite(parser.out.items, 1, parser.out.count, stdout);
scc_argparse_drop(&parser);
if (rc != SCC_ARGPARSE_ERR_NONE) {
scc_vec_free(o->args);
/* 1 表示 -h/--version 已处理,按成功退出。 */
return rc == SCC_ARGPARSE_ERR_PNT_DEFAULT ? 1 : -1;
}
o->path = argv[i++];
while (i < argc && strcmp(argv[i], "--") == 0)
i++;
o->args = argv + i;
o->nargs = argc - i;
return 0;
}
@@ -640,17 +662,20 @@ static void repl_loop(dbg_t *d) {
int main(int argc, const char **argv) {
cli_opts_t o;
if (parse_args(argc, argv, &o) != 0)
return 1;
int cli_rc = parse_cli(argc, argv, &o);
if (cli_rc != 0)
return cli_rc > 0 ? 0 : 1;
spl_prog_t prog;
if (spl_prog_load_from_file(o.path, &prog) != 0) {
fprintf(stderr, "spl_cli: cannot load '%s'\n", o.path);
scc_vec_free(o.args);
return 1;
}
if (o.disasm) {
spl_prog_dump(&prog);
scc_vec_free(o.args);
return 0;
}
spl_syscall_register(&prog);
@@ -671,6 +696,7 @@ int main(int argc, const char **argv) {
fprintf(stderr, "spl_cli: failed to load prog\n");
spl_vm_drop(&vm);
spl_prog_drop(&prog);
scc_vec_free(o.args);
return 1;
}
if (o.profile) {
@@ -680,21 +706,24 @@ int main(int argc, const char **argv) {
}
/* spl 程序 argv:argv[0]=file.sir(程序名),argv[1..]=args */
const char **spl_argv = (const char **)malloc(sizeof(char *) * (size_t)(o.nargs + 1));
int nargs = (int)o.args.count;
const char **spl_argv = (const char **)malloc(sizeof(char *) * (size_t)(nargs + 1));
if (!spl_argv) {
spl_vm_drop(&vm);
spl_prog_drop(&prog);
scc_vec_free(o.args);
return 1;
}
spl_argv[0] = o.path;
for (int i = 0; i < o.nargs; i++)
spl_argv[i + 1] = o.args[i];
for (int i = 0; i < nargs; i++)
spl_argv[i + 1] = o.args.items[i];
if (spl_vm_prepare(&vm, o.entry, o.nargs + 1, spl_argv, NULL) != 0) {
if (spl_vm_prepare(&vm, o.entry, nargs + 1, spl_argv, NULL) != 0) {
fprintf(stderr, "spl_cli: entry point '%s' not found\n", o.entry);
free(spl_argv);
spl_vm_drop(&vm);
spl_prog_drop(&prog);
scc_vec_free(o.args);
return 1;
}
@@ -735,6 +764,7 @@ int main(int argc, const char **argv) {
free(spl_argv);
spl_vm_drop(&vm);
spl_prog_drop(&prog);
scc_vec_free(o.args);
if (ret < 0)
return 1;
+1
View File
@@ -69,6 +69,7 @@ SPL_FN u64 vm_fsize(void *f) {
SPL_FN void *vm_stdin(void) { return (void *)stdin; }
SPL_FN void *vm_stdout(void) { return (void *)stdout; }
SPL_FN void *vm_stderr(void) { return (void *)stderr; }
SPL_FN i32 vm_fflush(void *f) { return f ? fflush((FILE *)f) : 0; }
SPL_FN i32 vm_putchar(i32 c) { return fputc(c, stdout); }
SPL_FN i32 vm_getchar(void) { return fgetc(stdin); }
+32 -2
View File
@@ -182,6 +182,26 @@ static spl_vm_val_t vm_putstr(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
return 0;
}
static spl_vm_val_t spl_sys_panic(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
spl_vm_val_t *slice;
const char *msg;
usize len;
CHECK_NARGS("panic", 1);
slice = (spl_vm_val_t *)VM_X(_vm, args[0]);
if (!slice) {
fputs("panic\n", stderr);
exit(1);
}
msg = (const char *)VM_X(_vm, slice[0]);
len = (usize)slice[1];
fputs("panic: ", stderr);
if (msg && len)
fwrite(msg, 1, len, stderr);
fputc('\n', stderr);
exit(1);
return 0;
}
static spl_vm_val_t vm_fopen(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
const char *path, *mode;
CHECK_NARGS("vm_fopen", 2);
@@ -233,6 +253,15 @@ static spl_vm_val_t vm_fsize(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
return (spl_vm_val_t)(uintptr_t)(sz < 0 ? 0 : sz);
}
static spl_vm_val_t vm_fflush(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
FILE *f;
CHECK_NARGS("vm_fflush", 1);
f = vm_file_get(_vm, args[0]);
if (!f)
return 0;
return (spl_vm_val_t)fflush(f);
}
static spl_vm_val_t vm_std_handle(spl_vm_t *_vm, int which) {
if (_vm->stdio_off[which] == 0) {
FILE *f = which == 0 ? stdin : (which == 1 ? stdout : stderr);
@@ -536,8 +565,7 @@ static spl_vm_val_t spl_bridge_forward(spl_vm_t *nested, const spl_vm_call_t *ca
}
/* SIR 后端按名字调用宿主 VM 函数,不需要额外的函数指针登记。 */
static spl_vm_val_t sc_vm_bind_foreign(spl_vm_t *_vm, int nargs,
spl_vm_val_t *args) {
static spl_vm_val_t sc_vm_bind_foreign(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
(void)args;
CHECK_NARGS("vm_bind_foreign", 2);
@@ -764,11 +792,13 @@ void spl_syscall_register(spl_prog_t *prog) {
{"vm_getchar", 0, vm_getchar},
{"vm_putint", 0, vm_putint},
{"vm_putstr", 0, vm_putstr},
{"panic", 0, spl_sys_panic},
{"vm_fopen", 0, vm_fopen},
{"vm_fclose", 0, vm_fclose},
{"vm_fread", 0, vm_fread},
{"vm_fwrite", 0, vm_fwrite},
{"vm_fsize", 0, vm_fsize},
{"vm_fflush", 0, vm_fflush},
{"vm_stdin", 0, vm_stdin},
{"vm_stdout", 0, vm_stdout},
{"vm_stderr", 0, vm_stderr},
+22 -12
View File
@@ -105,6 +105,8 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
case SPL_AST_CONTAINER_MEMBERS:
dump_vec(ast, node->container_members.external_tags, stack);
if (node->container_members.module)
dump_node(ast, node->container_members.module, stack, false);
dump_vec(ast, node->container_members.declarations, stack);
break;
@@ -113,8 +115,18 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
dump_vec(ast, node->tag_item.args, stack);
break;
case SPL_AST_MOD_DECL:
dump_vec(ast, node->mod_decl.decorator_list, stack);
dump_vec(ast, node->mod_decl.decls, stack);
break;
case SPL_AST_IMPORT_DECL:
dump_vec(ast, node->import_decl.decorator_list, stack);
break;
case SPL_AST_FN_DECL:
dump_vec(ast, node->fn_decl.tag_list, stack);
dump_vec(ast, node->fn_decl.decorator_list, stack);
dump_vec(ast, node->fn_decl.attr_list, stack);
dump_vec(ast, node->fn_decl.params, stack);
if (node->fn_decl.ret_type)
dump_node(ast, node->fn_decl.ret_type, stack, false);
@@ -124,6 +136,7 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
case SPL_AST_VAR_DECL:
case SPL_AST_CONST_DECL:
dump_vec(ast, node->var_const_decl.decorator_list, stack);
dump_vec(ast, node->var_const_decl.attr_list, stack);
if (node->var_const_decl.pattern)
dump_node(ast, node->var_const_decl.pattern, stack, false);
@@ -134,6 +147,7 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
break;
case SPL_AST_TYPE_DECL:
dump_vec(ast, node->type_decl.decorator_list, stack);
dump_vec(ast, node->type_decl.attr_list, stack);
if (node->type_decl.pattern)
dump_node(ast, node->type_decl.pattern, stack, false);
@@ -142,6 +156,7 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
break;
case SPL_AST_MEMBER_DECL:
dump_vec(ast, node->member_decl.decorator_list, stack);
dump_vec(ast, node->member_decl.attr_list, stack);
if (node->member_decl.type_expr)
dump_node(ast, node->member_decl.type_expr, stack, false);
@@ -155,13 +170,9 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
dump_node(ast, node->param_decl.type_expr, stack, true);
break;
case SPL_AST_COMPTIME_DECL:
if (node->comptime_decl.body)
dump_node(ast, node->comptime_decl.body, stack, true);
break;
case SPL_AST_TOP_LEVEL_BLOCK:
dump_vec(ast, node->top_level_block.tag_list, stack);
dump_vec(ast, node->top_level_block.decorator_list, stack);
dump_vec(ast, node->top_level_block.attr_list, stack);
if (node->top_level_block.block)
dump_node(ast, node->top_level_block.block, stack, true);
break;
@@ -184,7 +195,6 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
break;
case SPL_AST_STATEMENT_DEFER:
case SPL_AST_STATEMENT_COMPTIME:
if (node->statement_defer.body)
dump_node(ast, node->statement_defer.body, stack, true);
break;
@@ -292,8 +302,8 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
dump_vec(ast, node->aggregate_literal.fields, stack);
break;
case SPL_AST_EXPR_COMPTIME_CALL:
dump_vec(ast, node->comptime_call.args, stack);
case SPL_AST_EXPR_COMPILE_CALL:
dump_vec(ast, node->compile_call.args, stack);
break;
case SPL_AST_EXPR_BLOCK:
@@ -394,8 +404,8 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
dump_vec(ast, node->type_aggregate.members, stack);
break;
case SPL_AST_TYPE_COMPTIME_CALL:
dump_vec(ast, node->type_comptime_call.args, stack);
case SPL_AST_TYPE_COMPILE_CALL:
dump_vec(ast, node->type_compile_call.args, stack);
break;
case SPL_AST_PATTERN_IDENT:
File renamed without changes.
+1 -1
View File
@@ -1,5 +1,5 @@
#include "spl_diag.h"
#include "../stage0/include/color.h"
#include "stage0/include/color.h"
#include <stdarg.h>
+311 -255
View File
@@ -8,16 +8,27 @@
聚合值统一表示为「指向存储的指针」:u64 sN[..]; void* vN。
类型/布局全部走 layout,生成期不做运行时分发。非 extern 函数名 f<fid>。 */
typedef struct {
spl_ir_value_kind_t kind;
spl_ir_type_id_t tid;
uint64_t bits;
usize slot;
} cconst_t;
typedef VEC(cconst_t) cconst_vec_t;
typedef struct {
const spl_ir_t *ir;
const spl_type_t *type;
const spl_ir_type_table_t *type;
spl_layout_t *layout;
const spl_attr_t *attr;
spl_ir2c_buf_t *out;
usize gdata_n; /* 每个 mem.global_alloc 生成一块静态数据,从 1 开始编号 */
cconst_vec_t cconsts; /* 当前函数的 CONST 操作数槽 */
bool failed;
} ir2c_t;
/* 常量操作数占用 v 的高位编号,避免与指令结果 v1..vN 冲突。 */
#define SPL_IR2C_CONST_BASE ((usize)1 << 30)
static void buf_append(spl_ir2c_buf_t *b, const char *s, usize n) {
if (n == 0)
return;
@@ -34,12 +45,24 @@ static void buf_append(spl_ir2c_buf_t *b, const char *s, usize n) {
static void put(ir2c_t *c, const char *s) { buf_append(c->out, s, strlen(s)); }
static void put_n(ir2c_t *c, const char *s, usize n) { buf_append(c->out, s, n); }
static void put_byte(ir2c_t *c, char b) { buf_append(c->out, &b, 1); }
static void put_u(ir2c_t *c, usize v) {
static void put_u_raw(ir2c_t *c, usize v) {
char buf[32];
int n = snprintf(buf, sizeof buf, "%llu", (unsigned long long)v);
if (n > 0)
buf_append(c->out, buf, (usize)n);
}
static usize const_slot_lookup(ir2c_t *c, spl_ir_value_t v);
static void put_value_id(ir2c_t *c, spl_ir_value_t v) {
if (v.kind == SPL_IR_VALUE_INST) {
put_u_raw(c, v.inst);
return;
}
put_u_raw(c, SPL_IR2C_CONST_BASE + const_slot_lookup(c, v));
}
/* usize 走原路径;Value 常量走 v<base+slot>。 */
#define put_u(c_, x_) _Generic((x_), spl_ir_value_t: put_value_id, default: put_u_raw)((c_), (x_))
static void put_i(ir2c_t *c, long long v) {
char buf[32];
int n = snprintf(buf, sizeof buf, "%lld", v);
@@ -54,18 +77,18 @@ static void put_unsupported(ir2c_t *c, const char *what) {
put(c, " */\n");
}
static const spl_layout_info_t *info_of(ir2c_t *c, spl_type_id_t tid) {
static const spl_layout_info_t *info_of(ir2c_t *c, spl_ir_type_id_t tid) {
return spl_layout_info_of(c->layout, tid);
}
static usize type_size(ir2c_t *c, spl_type_id_t tid) {
static usize type_size(ir2c_t *c, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = info_of(c, tid);
if (!info)
return 0;
return (info->size_bits + 7) / 8;
}
static usize type_align(ir2c_t *c, spl_type_id_t tid) {
static usize type_align(ir2c_t *c, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = info_of(c, tid);
if (!info)
return 1;
@@ -73,68 +96,64 @@ static usize type_align(ir2c_t *c, spl_type_id_t tid) {
return a ? a : 1;
}
static bool is_aggregate(ir2c_t *c, spl_type_id_t tid) {
spl_type_node_t *te = spl_type_node(c->type, tid);
static bool is_aggregate(ir2c_t *c, spl_ir_type_id_t tid) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return false;
switch (te->kind) {
case SPL_TYPE_ARRAY:
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_ARRAY:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
return true;
default:
return false;
}
}
static bool tid_is_bool(ir2c_t *c, spl_type_id_t tid) {
spl_type_node_t *te = spl_type_node(c->type, tid);
return te && te->kind == SPL_TYPE_BOOL;
static bool tid_is_bool(ir2c_t *c, spl_ir_type_id_t tid) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
return te && te->kind == SPL_IR_TYPE_BOOL;
}
static bool tid_is_unit(ir2c_t *c, spl_type_id_t tid) {
static bool tid_is_unit(ir2c_t *c, spl_ir_type_id_t tid) {
if (tid == 0)
return true;
spl_type_node_t *te = spl_type_node(c->type, tid);
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return true;
return te->kind == SPL_TYPE_UNIT;
return te->kind == SPL_IR_TYPE_UNIT;
}
static spl_type_id_t fn_ret_type(ir2c_t *c, spl_type_id_t fn_tid) {
spl_type_node_t *te = spl_type_node(c->type, fn_tid);
if (!te || te->kind != SPL_TYPE_FN)
static spl_ir_type_id_t fn_ret_type(ir2c_t *c, spl_ir_type_id_t fn_tid) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, fn_tid);
if (!te || te->kind != SPL_IR_TYPE_FN)
return 0;
return te->fn_type.ret;
}
static spl_type_id_t make_ptr(ir2c_t *c, spl_type_id_t pointee) {
return spl_type_builder_ptr((spl_type_t *)c->type, pointee);
static spl_ir_type_id_t make_ptr(ir2c_t *c, spl_ir_type_id_t pointee) {
return spl_ir_type_builder_ptr((spl_ir_type_table_t *)c->type, pointee);
}
static spl_type_id_t make_bool(ir2c_t *c) {
return spl_type_builder_simple((spl_type_t *)c->type, SPL_TYPE_BOOL);
static spl_ir_type_id_t make_bool(ir2c_t *c) {
return spl_ir_type_builder_simple((spl_ir_type_table_t *)c->type, SPL_IR_TYPE_BOOL);
}
static spl_type_id_t make_usize(ir2c_t *c) {
return spl_type_builder_int((spl_type_t *)c->type, 64, 0);
static spl_ir_type_id_t make_usize(ir2c_t *c) {
return spl_ir_type_builder_int((spl_ir_type_table_t *)c->type, 64, 0);
}
static bool put_type(ir2c_t *c, spl_type_id_t tid) {
spl_type_node_t *te = spl_type_node(c->type, tid);
static bool put_type(ir2c_t *c, spl_ir_type_id_t tid) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return false;
switch (te->kind) {
case SPL_TYPE_UNIT:
case SPL_IR_TYPE_UNIT:
put(c, "void");
return true;
case SPL_TYPE_NEVER:
put(c, "void");
return true;
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_BOOL:
put(c, "u8");
return true;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
if (te->int_type.bits == 8)
put(c, te->int_type.is_signed ? "i8" : "u8");
else if (te->int_type.bits == 16)
@@ -144,21 +163,20 @@ static bool put_type(ir2c_t *c, spl_type_id_t tid) {
else
put(c, te->int_type.is_signed ? "i64" : "u64");
return true;
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
put(c, te->float_type.bits == 32 ? "float" : "double");
return true;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
put(c, "void*");
return true;
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
put(c, "void*");
return true;
/* 聚合值统一以「指向存储的指针」表示 */
case SPL_TYPE_ARRAY:
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_ARRAY:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
put(c, "void*");
return true;
default:
@@ -167,7 +185,7 @@ static bool put_type(ir2c_t *c, spl_type_id_t tid) {
}
static bool fn_is_extern(ir2c_t *c, const spl_ir_func_t *f) {
return spl_ir_fn_extern_attr(c->attr, f) != NULL;
return f->extern_fn || spl_ir_fn_extern_attr(c->attr, f) != NULL;
}
static void c_fn_name(ir2c_t *c, spl_ir_func_ref_t fid) {
@@ -181,71 +199,60 @@ static void c_fn_name(ir2c_t *c, spl_ir_func_ref_t fid) {
put_u(c, fid);
}
/* 读取 type.const 的整数值;按 tid 决定落在哪个 union 成员(同 ir2vm 约定)。 */
static usize const_node(ir2c_t *c, const spl_ir_func_t *f, spl_ir_node_ref_t ref) {
if (ref == 0 || ref >= vec_size(f->nodes))
return 0;
const spl_ir_node_t *n = &vec_at(f->nodes, ref);
if (n->kind != SPL_IR_TYPE_CONST)
return 0;
spl_type_node_t *te = spl_type_node(c->type, n->type_const.tid);
if (!te)
return 0;
switch (te->kind) {
case SPL_TYPE_BOOL:
return n->type_const.bool_lit ? 1 : 0;
case SPL_TYPE_INT:
if (te->int_type.bits == 8)
return (usize)(unsigned char)n->type_const.ch_lit;
return n->type_const.int_lit;
case SPL_TYPE_PTR:
return (usize)n->type_const.ptr_lit;
default:
return 0;
/* 常量操作数按 (tid, 位模式) 共享一个 v<slot> 变量。 */
static uint64_t value_bits(spl_ir_value_t v) {
uint64_t bits = 0;
memcpy(&bits, &v.int_bits, sizeof bits);
return bits;
}
static usize const_slot_lookup(ir2c_t *c, spl_ir_value_t v) {
uint64_t bits = value_bits(v);
for (usize i = 0; i < vec_size(c->cconsts); ++i) {
cconst_t *e = &vec_at(c->cconsts, i);
if (e->kind == v.kind && e->tid == v.tid && e->bits == bits)
return e->slot;
}
cconst_t e = {.kind = v.kind, .tid = v.tid, .bits = bits, .slot = vec_size(c->cconsts)};
vec_push(c->cconsts, e);
return e.slot;
}
/* 函数常量节点(Fn lit)持有的函数 ref;非函数常量返回 0。 */
static spl_ir_func_ref_t const_fn_ref(ir2c_t *c, const spl_ir_func_t *f, spl_ir_node_ref_t ref) {
if (ref == 0 || ref >= vec_size(f->nodes))
return 0;
const spl_ir_node_t *n = &vec_at(f->nodes, ref);
if (n->kind != SPL_IR_TYPE_CONST)
return 0;
spl_type_node_t *te = spl_type_node(c->type, n->type_const.tid);
if (!te || te->kind != SPL_TYPE_FN)
return 0;
return n->type_const.fn;
static usize value_int(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_CONST ? (usize)v.int_bits : 0;
}
static spl_type_id_t field_tid(ir2c_t *c, spl_type_id_t tid, usize idx) {
spl_type_node_t *te = spl_type_node(c->type, tid);
static spl_ir_func_ref_t value_fn(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_CONST ? v.fn : 0;
}
static spl_ir_type_id_t field_tid(ir2c_t *c, spl_ir_type_id_t tid, usize idx) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return 0;
switch (te->kind) {
case SPL_TYPE_ENUM:
case SPL_IR_TYPE_ENUM:
if (idx == SPL_ENUM_TAG_FIELD_IDX)
return te->agg_type.tag_type;
idx -= 1;
/* fallthrough */
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
if (idx < vec_size(te->agg_type.variants))
return vec_at(te->agg_type.variants, idx).type_id;
return 0;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
return te->array_type.element;
default:
return 0;
}
}
static usize field_off(ir2c_t *c, spl_type_id_t tid, usize idx) {
spl_type_node_t *te = spl_type_node(c->type, tid);
static usize field_off(ir2c_t *c, spl_ir_type_id_t tid, usize idx) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, tid);
if (!te)
return 0;
if (te->kind == SPL_TYPE_ARRAY)
if (te->kind == SPL_IR_TYPE_ARRAY)
return idx * type_size(c, te->array_type.element);
const spl_layout_info_t *info = info_of(c, tid);
if (!info || idx >= vec_size(info->field_bit_offsets))
@@ -254,7 +261,7 @@ static usize field_off(ir2c_t *c, spl_type_id_t tid, usize idx) {
}
/* 节点的「值类型」;0 表示无结果。 */
static spl_type_id_t result_tid(ir2c_t *c, const spl_ir_node_t *n) {
static spl_ir_type_id_t result_tid(ir2c_t *c, const spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
@@ -291,16 +298,12 @@ static spl_type_id_t result_tid(ir2c_t *c, const spl_ir_node_t *n) {
return n->cast.to_tid;
case SPL_IR_MEM_ALLOCA:
return make_ptr(c, n->mem_alloc.tid);
case SPL_IR_MEM_GLOBAL_ALLOC:
return n->mem_global_alloc.tid; /* 已是 *u8 */
case SPL_IR_MEM_LOAD:
return n->mem_load.tid;
case SPL_IR_MEM_OFFSET:
return make_ptr(c, n->mem_offset.tid);
case SPL_IR_MEM_FIELD_PTR:
return make_ptr(c, field_tid(c, n->mem_field_ptr.tid, n->mem_field_ptr.field_idx));
case SPL_IR_TYPE_CONST:
return n->type_const.tid;
case SPL_IR_TYPE_BITSIZEOF:
case SPL_IR_TYPE_SIZEOF:
case SPL_IR_TYPE_ALIGNOF:
@@ -324,6 +327,14 @@ static spl_type_id_t result_tid(ir2c_t *c, const spl_ir_node_t *n) {
}
}
static spl_ir_type_id_t value_type(ir2c_t *c, const spl_ir_func_t *f, spl_ir_value_t v) {
if (v.kind != SPL_IR_VALUE_INST)
return v.tid;
if (v.inst == 0 || v.inst >= vec_size(f->nodes))
return 0;
return result_tid(c, &vec_at(f->nodes, v.inst));
}
static void bind_agg(ir2c_t *c, usize ref) {
put(c, "v");
put_u(c, ref);
@@ -332,7 +343,7 @@ static void bind_agg(ir2c_t *c, usize ref) {
put(c, ";\n");
}
static void declare_ref(ir2c_t *c, usize ref, spl_type_id_t tid) {
static void declare_ref(ir2c_t *c, usize ref, spl_ir_type_id_t tid) {
if (is_aggregate(c, tid)) {
usize size = type_size(c, tid);
usize words = (size + 7) / 8;
@@ -360,10 +371,12 @@ static void emit_agg_construct(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
return;
}
bind_agg(c, ref);
spl_type_id_t agg_t = n->agg_construct.tid;
spl_ir_type_id_t agg_t = n->agg_construct.tid;
for (usize i = 0; i < vec_size(n->agg_construct.fields); ++i) {
spl_ir_node_ref_t fref = vec_at(n->agg_construct.fields, i);
spl_type_id_t ftid = field_tid(c, agg_t, i);
spl_ir_value_t fref = vec_at(n->agg_construct.fields, i);
if (spl_ir_value_is_none(fref))
continue;
spl_ir_type_id_t ftid = field_tid(c, agg_t, i);
if (!ftid)
continue;
usize foff = field_off(c, agg_t, i);
@@ -421,7 +434,7 @@ static void emit_agg_extract(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
static void emit_agg_insert(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
bind_agg(c, ref);
spl_type_id_t agg_t = n->agg_insert.tid;
spl_ir_type_id_t agg_t = n->agg_insert.tid;
usize sz = type_size(c, agg_t);
put(c, "memcpy(v");
put_u(c, ref);
@@ -430,7 +443,7 @@ static void emit_agg_insert(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
put(c, ", ");
put_u(c, sz);
put(c, ");\n");
spl_type_id_t ftid = field_tid(c, agg_t, n->agg_insert.field_idx);
spl_ir_type_id_t ftid = field_tid(c, agg_t, n->agg_insert.field_idx);
usize foff = field_off(c, agg_t, n->agg_insert.field_idx);
if (!ftid)
return;
@@ -598,14 +611,14 @@ static void emit_cast(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
bool from_is_ptr = false;
bool from_is_bool = false;
bool to_is_ptr = false;
spl_type_node_t *te = spl_type_node(c->type, n->cast.from_tid);
spl_ir_type_node_t *te = spl_ir_type_node(c->type, n->cast.from_tid);
if (te) {
from_is_ptr = te->kind == SPL_TYPE_PTR;
from_is_bool = te->kind == SPL_TYPE_BOOL;
from_is_ptr = te->kind == SPL_IR_TYPE_PTR;
from_is_bool = te->kind == SPL_IR_TYPE_BOOL;
}
spl_type_node_t *tte = spl_type_node(c->type, n->cast.to_tid);
spl_ir_type_node_t *tte = spl_ir_type_node(c->type, n->cast.to_tid);
if (tte)
to_is_ptr = tte->kind == SPL_TYPE_PTR;
to_is_ptr = tte->kind == SPL_IR_TYPE_PTR;
if (to_is_ptr) {
put(c, "(void*)(usize)v");
put_u(c, n->cast.val);
@@ -623,68 +636,8 @@ static void emit_cast(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
put(c, ";\n");
}
static void emit_const(ir2c_t *c, usize ref, const spl_ir_node_t *n) {
spl_type_id_t tid = n->type_const.tid;
spl_type_node_t *te = spl_type_node(c->type, tid);
if (!te)
return;
if (te->kind == SPL_TYPE_UNIT)
return;
put(c, "v");
put_u(c, ref);
put(c, " = ");
switch (te->kind) {
case SPL_TYPE_BOOL:
put(c, n->type_const.bool_lit ? "1" : "0");
break;
case SPL_TYPE_INT: {
usize raw = (te->int_type.bits == 8) ? (usize)(unsigned char)n->type_const.ch_lit
: n->type_const.int_lit;
if (te->int_type.is_signed) {
long long sv = (long long)raw;
if (sv == (-9223372036854775807LL - 1))
put(c, "(-9223372036854775807 - 1)");
else
put_i(c, sv);
} else {
put_u(c, raw);
if (te->int_type.bits >= 64)
put(c, "ull");
}
break;
}
case SPL_TYPE_PTR:
put(c, "(void*)");
put_u(c, (usize)n->type_const.ptr_lit);
break;
/* 字节常量(字符串/文件名):只被 mem.global_alloc 通过字段引用,vN 是死值。
若输出宿主指针会导致生成物随编译进程地址而变,这里固定为 0。 */
case SPL_TYPE_ARRAY:
put(c, "(void*)0");
break;
case SPL_TYPE_FN:
put(c, "(void*)&");
c_fn_name(c, n->type_const.fn);
break;
case SPL_TYPE_FLOAT: {
double d = n->type_const.float_lit;
if (isfinite(d)) {
char buf[64];
snprintf(buf, sizeof buf, "%.17g", d);
put(c, buf);
} else {
put(c, "0.0");
}
break;
}
default:
put(c, "0");
break;
}
put(c, ";\n");
}
static void emit_mem(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n) {
(void)f;
switch (n->kind) {
case SPL_IR_MEM_ALLOCA:
@@ -766,62 +719,13 @@ static void emit_mem(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_
break;
}
case SPL_IR_MEM_GLOBAL_ALLOC: {
spl_type_id_t ctid = 0;
const void *pv = NULL;
if (n->mem_global_alloc.const_node > 0 &&
n->mem_global_alloc.const_node < vec_size(f->nodes)) {
const spl_ir_node_t *cn = &vec_at(f->nodes, n->mem_global_alloc.const_node);
if (cn->kind == SPL_IR_TYPE_CONST) {
ctid = cn->type_const.tid;
pv = cn->type_const.ptr_lit;
}
}
if (!pv) {
put(c, "v");
put_u(c, ref);
put(c, " = (void*)0;\n");
break;
}
/* size 为 0(空数组)时只生成一个零词,避免越界读取宿主内存导致生成物不确定。 */
usize size = type_size(c, ctid);
usize gid = c->gdata_n++;
usize words = (size + 7) / 8;
if (words == 0)
words = 1;
put(c, "static const u64 g");
put_u(c, gid);
put(c, "[");
put_u(c, words);
put(c, "] = {");
for (usize j = 0; j < words; ++j) {
if (j > 0)
put(c, ", ");
uint64_t w = 0;
for (usize k = 0; k < 8; ++k) {
usize idx = j * 8 + k;
uint64_t b = 0;
if (idx < size)
b = (uint64_t)((const unsigned char *)pv)[idx];
w |= b << (k * 8);
}
put_u(c, (usize)w);
put(c, "ull");
}
put(c, "};\nv");
put_u(c, ref);
put(c, " = (void*)g");
put_u(c, gid);
put(c, ";\n");
break;
}
default:
break;
}
}
static void emit_typeop(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n) {
(void)f;
usize v = 0;
switch (n->kind) {
case SPL_IR_TYPE_SIZEOF:
@@ -838,21 +742,20 @@ static void emit_typeop(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_
break;
case SPL_IR_TYPE_OFFSETOF: {
/* field_idx 是一个常量节点 ref */
usize idx = const_node(c, f, n->ir_offsetof.field_idx);
usize idx = value_int(n->ir_offsetof.field_idx);
v = field_off(c, n->ir_offsetof.tid, idx);
break;
}
case SPL_IR_TYPE_FIELD_COUNT: {
spl_type_node_t *te = spl_type_node(c->type, n->field_count.tid);
spl_ir_type_node_t *te = spl_ir_type_node(c->type, n->field_count.tid);
if (te) {
switch (te->kind) {
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
v = vec_size(te->agg_type.variants);
break;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
v = te->array_type.len;
break;
default:
@@ -872,7 +775,7 @@ static void emit_typeop(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_
}
static void emit_call(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n) {
spl_ir_func_ref_t callee = const_fn_ref(c, f, n->control_call.func);
spl_ir_func_ref_t callee = value_fn(n->control_call.func);
bool ret_agg = is_aggregate(c, n->control_call.tid);
if (callee != 0) {
if (ret_agg) {
@@ -899,11 +802,9 @@ static void emit_call(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
}
/* 间接调用:从 func 值的类型构造函数指针类型 */
spl_type_id_t func_tid = 0;
if (n->control_call.func < vec_size(f->nodes))
func_tid = result_tid(c, &vec_at(f->nodes, n->control_call.func));
spl_type_node_t *ftnode = spl_type_node(c->type, func_tid);
if (!ftnode || ftnode->kind != SPL_TYPE_FN) {
spl_ir_type_id_t func_tid = value_type(c, f, n->control_call.func);
spl_ir_type_node_t *ftnode = spl_ir_type_node(c->type, func_tid);
if (!ftnode || ftnode->kind != SPL_IR_TYPE_FN) {
put_unsupported(c, "indirect call type");
return;
}
@@ -930,7 +831,7 @@ static void emit_call(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
for (usize kp = 0; kp < np; ++kp) {
if (need_comma)
put(c, ", ");
spl_type_id_t pt = vec_at(ftnode->fn_type.params, kp);
spl_ir_type_id_t pt = vec_at(ftnode->fn_type.params, kp);
if (is_aggregate(c, pt))
put(c, "void*");
else if (!put_type(c, pt))
@@ -956,10 +857,10 @@ static void emit_call(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
}
static void emit_control(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n,
spl_type_id_t ret_tid) {
spl_ir_type_id_t ret_tid) {
switch (n->kind) {
case SPL_IR_CONTROL_PARAM: {
usize idx = const_node(c, f, n->control_param.idx);
usize idx = value_int(n->control_param.idx);
if (is_aggregate(c, n->control_param.tid)) {
put(c, "v");
put_u(c, ref);
@@ -980,7 +881,7 @@ static void emit_control(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl
case SPL_IR_CONTROL_RET:
if (is_aggregate(c, ret_tid)) {
if (n->control_ret.val) {
if (!spl_ir_value_is_none(n->control_ret.val)) {
usize sz = type_size(c, ret_tid);
put(c, "memcpy(ret__, v");
put_u(c, n->control_ret.val);
@@ -1024,12 +925,8 @@ static void emit_control(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl
}
static void emit_node(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir_node_t *n,
spl_type_id_t ret_tid) {
spl_ir_type_id_t ret_tid) {
switch (n->kind) {
case SPL_IR_TYPE_CONST:
emit_const(c, ref, n);
break;
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
case SPL_IR_ARITH_MUL:
@@ -1074,7 +971,6 @@ static void emit_node(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
case SPL_IR_MEM_STORE:
case SPL_IR_MEM_OFFSET:
case SPL_IR_MEM_FIELD_PTR:
case SPL_IR_MEM_GLOBAL_ALLOC:
emit_mem(c, f, ref, n);
break;
@@ -1160,14 +1056,109 @@ static void emit_node(ir2c_t *c, const spl_ir_func_t *f, usize ref, const spl_ir
}
}
static void emit_const_literal(ir2c_t *c, spl_ir_value_t v) {
if (v.kind == SPL_IR_VALUE_GLOBAL) {
put(c, "(void*)gg");
put_u_raw(c, v.global_id);
return;
}
spl_ir_type_node_t *te = spl_ir_type_node(c->type, v.tid);
if (!te) {
put(c, "0");
return;
}
switch (te->kind) {
case SPL_IR_TYPE_BOOL:
put(c, v.int_bits ? "1" : "0");
break;
case SPL_IR_TYPE_INT: {
uint64_t raw = v.int_bits;
if (te->int_type.bits == 8)
raw = (unsigned char)raw;
if (te->int_type.is_signed) {
long long sv = (long long)raw;
if (sv == (-9223372036854775807LL - 1))
put(c, "(-9223372036854775807LL - 1)");
else {
put(c, "(");
put_i(c, sv);
put(c, ")");
}
} else {
put(c, "(");
put_u_raw(c, (usize)raw);
if (te->int_type.bits >= 64)
put(c, "ull");
put(c, ")");
}
break;
}
case SPL_IR_TYPE_PTR:
if (v.global_id) {
put(c, "(void*)gg");
put_u_raw(c, v.global_id);
} else {
put(c, "(void*)0");
}
break;
case SPL_IR_TYPE_FN:
if (v.fn == 0) {
put(c, "(void*)0");
} else {
put(c, "(void*)&");
c_fn_name(c, v.fn);
}
break;
case SPL_IR_TYPE_FLOAT: {
char buf[64];
if (isfinite(v.float_bits))
snprintf(buf, sizeof buf, "%.17g", v.float_bits);
else
snprintf(buf, sizeof buf, "0.0");
put(c, buf);
break;
}
default:
put(c, "0");
break;
}
}
static void collect_const_cb(void *ud, spl_ir_value_t v) {
ir2c_t *c = ud;
if (v.kind != SPL_IR_VALUE_INST)
(void)const_slot_lookup(c, v);
}
static void declare_consts(ir2c_t *c) {
for (usize i = 0; i < vec_size(c->cconsts); ++i) {
cconst_t *e = &vec_at(c->cconsts, i);
if (!put_type(c, e->tid))
put(c, "void*");
put(c, " v");
put_u_raw(c, SPL_IR2C_CONST_BASE + e->slot);
put(c, " = ");
spl_ir_value_t v = {0};
v.kind = e->kind;
v.tid = e->tid;
memcpy(&v.int_bits, &e->bits, sizeof e->bits);
emit_const_literal(c, v);
put(c, ";\n");
}
}
static void declare_all(ir2c_t *c, const spl_ir_func_t *f) {
c->cconsts.size = 0;
for (usize i = 1; i < vec_size(f->nodes); ++i)
spl_ir_node_visit_values(&vec_at(f->nodes, i), collect_const_cb, c);
for (usize i = 1; i < vec_size(f->nodes); ++i) {
const spl_ir_node_t *n = &vec_at(f->nodes, i);
if (n->kind == SPL_IR_MEM_ALLOCA) {
usize count = const_node(c, f, n->mem_alloc.count);
usize count = value_int(n->mem_alloc.count);
if (count == 0)
count = 1;
spl_type_id_t pointee = n->mem_alloc.tid;
spl_ir_type_id_t pointee = n->mem_alloc.tid;
if (is_aggregate(c, pointee)) {
usize esz = type_size(c, pointee);
usize words = (esz * count + 7) / 8;
@@ -1193,15 +1184,16 @@ static void declare_all(ir2c_t *c, const spl_ir_func_t *f) {
}
continue;
}
spl_type_id_t tid = result_tid(c, n);
spl_ir_type_id_t tid = result_tid(c, n);
if (tid != 0 && !tid_is_unit(c, tid))
declare_ref(c, i, tid);
}
declare_consts(c);
}
static void emit_fn_sig(ir2c_t *c, spl_ir_func_ref_t fid, bool with_names) {
const spl_ir_func_t *f = spl_ir_func((spl_ir_t *)c->ir, fid);
spl_type_id_t ret_tid = fn_ret_type(c, f->fn_tid);
spl_ir_type_id_t ret_tid = fn_ret_type(c, f->fn_tid);
bool ret_agg = is_aggregate(c, ret_tid);
if (ret_agg)
put(c, "void");
@@ -1215,13 +1207,20 @@ static void emit_fn_sig(ir2c_t *c, spl_ir_func_ref_t fid, bool with_names) {
put(c, "void* ret__");
need = true;
}
spl_type_node_t *te = spl_type_node(c->type, f->fn_tid);
if (te && te->kind == SPL_TYPE_FN) {
spl_ir_type_node_t *te = spl_ir_type_node(c->type, f->fn_tid);
if (te && te->kind == SPL_IR_TYPE_FN) {
usize nargs = vec_size(te->fn_type.params);
for (usize k = 0; k < nargs; ++k) {
if (need)
put(c, ", ");
spl_type_id_t pt = vec_at(te->fn_type.params, k);
spl_ir_type_id_t pt = vec_at(te->fn_type.params, k);
spl_ir_type_node_t *ptn = spl_ir_type_node(c->type, pt);
if (ptn && ptn->kind == SPL_IR_TYPE_UNIT) {
/* varargs 标记在 IR 里落成 unit 类型。 */
put(c, "...");
need = true;
continue;
}
if (is_aggregate(c, pt))
put(c, "void*");
else if (!put_type(c, pt))
@@ -1245,7 +1244,7 @@ static void emit_proto(ir2c_t *c, spl_ir_func_ref_t fid) {
static void emit_def(ir2c_t *c, spl_ir_func_ref_t fid) {
const spl_ir_func_t *f = spl_ir_func((spl_ir_t *)c->ir, fid);
spl_type_id_t ret_tid = fn_ret_type(c, f->fn_tid);
spl_ir_type_id_t ret_tid = fn_ret_type(c, f->fn_tid);
emit_fn_sig(c, fid, true);
put(c, " {\n");
declare_all(c, f);
@@ -1267,14 +1266,63 @@ static spl_ir_func_ref_t find_main(ir2c_t *c) {
return 0;
}
static void emit_globals(ir2c_t *c) {
for (usize i = 1; i < vec_size(c->ir->globals); ++i) {
const spl_ir_global_t *g = &vec_at(c->ir->globals, i);
usize size = type_size(c, g->tid);
usize words = (size + 7) / 8;
if (words == 0)
words = 1;
put(c, "static ");
if (g->readonly)
put(c, "const ");
put(c, "u64 gg");
put_u_raw(c, i);
put(c, "[");
put_u_raw(c, words);
put(c, "] = {");
for (usize w = 0; w < words; ++w) {
if (w > 0)
put(c, ", ");
uint64_t word = 0;
if (g->init.kind == SPL_IR_VALUE_CONST) {
spl_ir_type_node_t *it = spl_ir_type_node(c->type, g->init.tid);
if (it && it->kind == SPL_IR_TYPE_ARRAY) {
spl_ir_const_t *k =
spl_ir_const((spl_ir_t *)c->ir, g->init.const_id);
if (k) {
for (usize b = 0; b < 8; ++b) {
usize idx = w * 8 + b;
if (idx < k->bytes.len)
word |= (uint64_t)k->bytes.data[idx] << (b * 8);
}
}
} else if (w == 0) {
memcpy(&word, &g->init.int_bits, sizeof word);
}
}
put_u_raw(c, (usize)word);
put(c, "ull");
}
put(c, "};");
if (g->name) {
put(c, " /* ");
put(c, g->name);
put(c, " */");
}
put(c, "\n");
}
}
static void run(ir2c_t *c) {
put(c, "// AUTO-GENERATED\n");
put(c, "#include \"spl_rt.h\"\n");
emit_globals(c);
usize nf = vec_size(c->ir->funcs);
for (spl_ir_func_ref_t i = 1; i < nf; ++i) {
const spl_ir_func_t *f = spl_ir_func((spl_ir_t *)c->ir, i);
if (f && !fn_is_extern(c, f))
if (f)
emit_proto(c, i);
}
for (spl_ir_func_ref_t i = 1; i < nf; ++i) {
@@ -1287,13 +1335,20 @@ static void run(ir2c_t *c) {
if (m != 0) {
const spl_ir_func_t *f = spl_ir_func((spl_ir_t *)c->ir, m);
usize nargs = 0;
spl_type_node_t *te = spl_type_node(c->type, f->fn_tid);
if (te && te->kind == SPL_TYPE_FN)
spl_ir_type_node_t *te = spl_ir_type_node(c->type, f->fn_tid);
if (te && te->kind == SPL_IR_TYPE_FN)
nargs = vec_size(te->fn_type.params);
if (nargs == 0) {
put(c, "int main(void) { f");
put_u(c, m);
put(c, "(); return 0; }\n");
put(c, "int main(void) { ");
if (!tid_is_unit(c, fn_ret_type(c, f->fn_tid))) {
put(c, "return (int)f");
put_u(c, m);
put(c, "(); }\n");
} else {
put(c, "f");
put_u(c, m);
put(c, "(); return 0; }\n");
}
} else {
put(c, "int main(int argc, char** argv) { ");
if (!tid_is_unit(c, fn_ret_type(c, f->fn_tid))) {
@@ -1309,17 +1364,18 @@ static void run(ir2c_t *c) {
}
}
bool spl_ir2c_run(const spl_ir_t *ir, const spl_type_t *type, spl_layout_t *layout,
const spl_attr_t *attr, spl_ir2c_buf_t *out) {
bool spl_ir2c_run(const spl_ir_t *ir, spl_layout_t *layout, const spl_attr_t *attr,
spl_ir2c_buf_t *out) {
ir2c_t c = {
.ir = ir,
.type = type,
.type = ir->types,
.layout = layout,
.attr = attr,
.out = out,
.gdata_n = 1,
.failed = false,
};
vec_init(c.cconsts);
run(&c);
vec_free(c.cconsts);
return !c.failed;
}
@@ -4,18 +4,18 @@
static usize align_up(usize x, usize a);
/* size/align/offset 统一取自 layout(spl_layout 是唯一准确来源)。 */
static const spl_layout_info_t *ir_layout(spl_ir2vm_t *ctx, spl_type_id_t tid) {
static const spl_layout_info_t *ir_layout(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
return spl_layout_info_of(ctx->layout, tid);
}
static usize ir_type_size(spl_ir2vm_t *ctx, spl_type_id_t tid) {
static usize ir_type_size(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = ir_layout(ctx, tid);
if (!info)
return 0;
return (info->size_bits + 7) / 8;
}
static usize ir_type_align(spl_ir2vm_t *ctx, spl_type_id_t tid) {
static usize ir_type_align(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = ir_layout(ctx, tid);
if (!info)
return 1;
@@ -23,34 +23,34 @@ static usize ir_type_align(spl_ir2vm_t *ctx, spl_type_id_t tid) {
return a ? a : 1;
}
static bool ir_is_aggregate(spl_ir2vm_t *ctx, spl_type_id_t tid) {
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
static bool ir_is_aggregate(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, tid);
if (!tn)
return false;
return tn->kind == SPL_TYPE_ARRAY || tn->kind == SPL_TYPE_STRUCT ||
tn->kind == SPL_TYPE_UNION || tn->kind == SPL_TYPE_ENUM || tn->kind == SPL_TYPE_SHAPE;
return tn->kind == SPL_IR_TYPE_ARRAY || tn->kind == SPL_IR_TYPE_STRUCT ||
tn->kind == SPL_IR_TYPE_UNION || tn->kind == SPL_IR_TYPE_ENUM;
}
/* 从 fn_tid 取返回类型;非 fn 类型返回 0。 */
static spl_type_id_t fn_ret_type(spl_ir2vm_t *ctx, spl_type_id_t fn_tid) {
spl_type_node_t *ftn = spl_type_node(ctx->type, fn_tid);
if (!ftn || ftn->kind != SPL_TYPE_FN)
static spl_ir_type_id_t fn_ret_type(spl_ir2vm_t *ctx, spl_ir_type_id_t fn_tid) {
spl_ir_type_node_t *ftn = spl_ir_type_node(ctx->type, fn_tid);
if (!ftn || ftn->kind != SPL_IR_TYPE_FN)
return 0;
return ftn->fn_type.ret;
}
static usize fn_nargs(spl_ir2vm_t *ctx, spl_type_id_t fn_tid) {
spl_type_node_t *ftn = spl_type_node(ctx->type, fn_tid);
if (!ftn || ftn->kind != SPL_TYPE_FN)
static usize fn_nargs(spl_ir2vm_t *ctx, spl_ir_type_id_t fn_tid) {
spl_ir_type_node_t *ftn = spl_ir_type_node(ctx->type, fn_tid);
if (!ftn || ftn->kind != SPL_IR_TYPE_FN)
return 0;
return vec_size(ftn->fn_type.params);
}
static spl_type_id_t ir_agg_field_tid(spl_ir2vm_t *ctx, spl_type_id_t tid, usize idx) {
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
static spl_ir_type_id_t ir_agg_field_tid(spl_ir2vm_t *ctx, spl_ir_type_id_t tid, usize idx) {
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, tid);
if (!tn)
return 0;
if (tn->kind == SPL_TYPE_ENUM) {
if (tn->kind == SPL_IR_TYPE_ENUM) {
if (idx == SPL_ENUM_TAG_FIELD_IDX)
return tn->agg_type.tag_type;
usize vidx = idx - 1;
@@ -58,20 +58,20 @@ static spl_type_id_t ir_agg_field_tid(spl_ir2vm_t *ctx, spl_type_id_t tid, usize
return vec_at(tn->agg_type.variants, vidx).type_id;
return 0;
}
if (tn->kind == SPL_TYPE_STRUCT || tn->kind == SPL_TYPE_UNION) {
if (tn->kind == SPL_IR_TYPE_STRUCT || tn->kind == SPL_IR_TYPE_UNION) {
if (idx < vec_size(tn->agg_type.variants))
return vec_at(tn->agg_type.variants, idx).type_id;
} else if (tn->kind == SPL_TYPE_ARRAY) {
} else if (tn->kind == SPL_IR_TYPE_ARRAY) {
return tn->array_type.element;
}
return 0;
}
static usize ir_agg_field_off(spl_ir2vm_t *ctx, spl_type_id_t tid, usize idx) {
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
static usize ir_agg_field_off(spl_ir2vm_t *ctx, spl_ir_type_id_t tid, usize idx) {
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, tid);
if (!tn)
return 0;
if (tn->kind == SPL_TYPE_ARRAY)
if (tn->kind == SPL_IR_TYPE_ARRAY)
return idx * ir_type_size(ctx, tn->array_type.element);
const spl_layout_info_t *info = ir_layout(ctx, tid);
@@ -96,16 +96,16 @@ static int get_or_add_native(spl_ir2vm_t *ctx, const char *name) {
return (int)(vec_size(ctx->prog.natives) - 1);
}
static uint8_t vm_kind_of(spl_ir2vm_t *ctx, spl_type_id_t tid) {
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
static uint8_t vm_kind_of(spl_ir2vm_t *ctx, spl_ir_type_id_t tid) {
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, tid);
if (!tn)
return SPL_VOID;
switch (tn->kind) {
case SPL_TYPE_UNIT:
case SPL_IR_TYPE_UNIT:
return SPL_VOID;
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_BOOL:
return SPL_BOOL;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
if (tn->int_type.bits == 0)
return SPL_I32;
switch (tn->int_type.bits) {
@@ -118,20 +118,20 @@ static uint8_t vm_kind_of(spl_ir2vm_t *ctx, spl_type_id_t tid) {
default:
return tn->int_type.is_signed ? SPL_I64 : SPL_U64;
}
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
return tn->float_type.bits == 32 ? SPL_F32 : SPL_F64;
default:
return SPL_PTR;
}
}
/* 计算 IR 节点的"值类型",两处用途:
/* 计算 IR 节点的值类型,两处用途:
* 1) frame_build 判断该节点是否占用结果槽(只看是否非 0);
* 2) CALL 推导实参的 LOAD/STORE kind。
* mem.offset/mem.field 的 .tid 存的是 pointee/aggregate,须转成指针类型。
* cmp/type.* 这里刻意返回操作数/被测量类型的 tid 而非 bool/usize:
* cmp/type.* 这里刻意返回操作数被测量类型的 tid 而非 bool/usize;
* CALL 实参 kind 依赖此点,改动会改变生成字节码,diff 测试据此守门。 */
static spl_type_id_t ir_result_tid(spl_ir2vm_t *ctx, const spl_ir_node_t *n) {
static spl_ir_type_id_t ir_result_tid(spl_ir2vm_t *ctx, const spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
@@ -167,20 +167,16 @@ static spl_type_id_t ir_result_tid(spl_ir2vm_t *ctx, const spl_ir_node_t *n) {
case SPL_IR_CASE_FLOAT2INT:
return n->cast.to_tid;
case SPL_IR_MEM_ALLOCA:
return spl_type_builder_ptr((spl_type_t *)ctx->type, n->mem_alloc.tid);
case SPL_IR_MEM_GLOBAL_ALLOC:
return n->mem_global_alloc.tid;
return spl_ir_type_builder_ptr((spl_ir_type_table_t *)ctx->type, n->mem_alloc.tid);
case SPL_IR_MEM_LOAD:
return n->mem_load.tid;
case SPL_IR_MEM_OFFSET:
return spl_type_builder_ptr((spl_type_t *)ctx->type, n->mem_offset.tid);
return spl_ir_type_builder_ptr((spl_ir_type_table_t *)ctx->type, n->mem_offset.tid);
case SPL_IR_MEM_FIELD_PTR: {
spl_type_id_t field =
spl_ir_type_id_t field =
ir_agg_field_tid(ctx, n->mem_field_ptr.tid, n->mem_field_ptr.field_idx);
return spl_type_builder_ptr((spl_type_t *)ctx->type, field);
return spl_ir_type_builder_ptr((spl_ir_type_table_t *)ctx->type, field);
}
case SPL_IR_TYPE_CONST:
return n->type_const.tid;
case SPL_IR_TYPE_BITSIZEOF:
return n->bitsizeof.tid;
case SPL_IR_TYPE_SIZEOF:
@@ -226,16 +222,28 @@ typedef struct {
/* panic 数据区:fmt slice + msg slice,各 2 words(ptr + len)。 */
enum { IR2VM_PANIC_WORDS = 4 };
static spl_ir_type_id_t value_tid(spl_ir2vm_t *ctx, const spl_ir_func_t *f, spl_ir_value_t v) {
if (v.kind != SPL_IR_VALUE_INST)
return v.tid;
if (v.inst == 0 || v.inst >= vec_size(f->nodes))
return 0;
return ir_result_tid(ctx, &vec_at(f->nodes, v.inst));
}
static usize value_int(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_CONST ? (usize)v.int_bits : 0;
}
static spl_ir_func_ref_t value_fn(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_CONST ? v.fn : 0;
}
/* 结果槽存标量;聚合/大对象额外分配一块数据区(data_off)。 */
static usize node_data_size(spl_ir2vm_t *ctx, const spl_ir_func_t *f, const spl_ir_node_t *node) {
(void)f;
switch (node->kind) {
case SPL_IR_MEM_ALLOCA: {
usize count = 1;
if (node->mem_alloc.count < vec_size(f->nodes)) {
const spl_ir_node_t *cn = &vec_at(f->nodes, node->mem_alloc.count);
if (cn->kind == SPL_IR_TYPE_CONST)
count = (usize)cn->type_const.int_lit;
}
usize count = value_int(node->mem_alloc.count);
if (count == 0)
count = 1;
usize sz = ir_type_size(ctx, node->mem_alloc.tid);
@@ -280,7 +288,7 @@ static void frame_build(frame_layout_t *fl, spl_ir2vm_t *ctx, spl_ir_func_ref_t
for (usize i = 0; i < n; ++i)
vec_push(fl->slots, (slot_t){0});
/* 聚合返回时 fp+0 是 caller 传入的 sret 指针,占用一个隐藏参数槽 */
/* 聚合返回时 fp+0 是 caller 传入的 sret 指针,占用一个隐藏参数槽。 */
usize nargs = fn_nargs(ctx, f->fn_tid);
usize hidden_sret = ir_is_aggregate(ctx, fn_ret_type(ctx, f->fn_tid)) ? 1 : 0;
fl->args_bytes = (nargs + hidden_sret) * sizeof(spl_vm_val_t);
@@ -343,8 +351,14 @@ static void CG_OP(cgen_t *cg, uint8_t op, uint8_t k) { emit(cg, op, k, 0); }
static void CG_SWAP(cgen_t *cg) { emit(cg, SPL_SWAP, SPL_VOID, 0); }
static void CG_GADDR(cgen_t *cg, spl_vm_val_t idx) { emit(cg, SPL_GADDR, SPL_VOID, idx); }
static void cg_load_slot(cgen_t *cg, usize ref, uint8_t k) {
CG_LADDR(cg, vec_at(cg->frame.slots, ref).result_off);
static void cg_push_const(cgen_t *cg, spl_ir_value_t v, uint8_t k);
static void cg_load_slot(cgen_t *cg, spl_ir_value_t v, uint8_t k) {
if (v.kind != SPL_IR_VALUE_INST) {
cg_push_const(cg, v, k);
return;
}
CG_LADDR(cg, vec_at(cg->frame.slots, v.inst).result_off);
CG_LOAD(cg, k);
}
@@ -364,6 +378,7 @@ typedef struct {
bool indirect;
usize off;
usize base;
int gdata; /* >0:全局数据区索引,直接 GADDR */
} data_loc_t;
static data_loc_t direct_data(usize off) {
@@ -372,16 +387,19 @@ static data_loc_t direct_data(usize off) {
static data_loc_t direct_data_base(usize off, usize base) {
return (data_loc_t){.indirect = false, .off = off, .base = base};
}
static data_loc_t ptr_slot(usize slot_off) {
return (data_loc_t){.indirect = true, .off = slot_off, .base = 0};
}
static data_loc_t ptr_slot_base(usize slot_off, usize base) {
return (data_loc_t){.indirect = true, .off = slot_off, .base = base};
}
static void cg_push_addr(cgen_t *cg, data_loc_t loc, usize extra) {
usize delta = loc.base + extra;
if (loc.indirect) {
if (loc.gdata > 0) {
emit(cg, SPL_GADDR, SPL_VOID, (spl_vm_val_t)loc.gdata);
if (delta) {
CG_PUSH(cg, SPL_U64, delta);
CG_OP(cg, SPL_ADD, SPL_PTR);
}
} else if (loc.indirect) {
CG_LADDR(cg, loc.off);
CG_LOAD(cg, SPL_PTR);
if (delta) {
@@ -393,7 +411,19 @@ static void cg_push_addr(cgen_t *cg, data_loc_t loc, usize extra) {
}
}
static void cg_copy_agg(cgen_t *cg, data_loc_t src, data_loc_t dst, spl_type_id_t tid) {
/* 聚合值的存储位置:指令槽指针,或全局数据区地址。 */
static data_loc_t value_ptr_loc(cgen_t *cg, spl_ir_value_t v, usize base) {
if (v.kind == SPL_IR_VALUE_GLOBAL) {
usize gid = v.global_id;
int idx = 0;
if (gid > 0 && gid < vec_size(cg->ctx->global_data_idx))
idx = (int)vec_at(cg->ctx->global_data_idx, gid);
return (data_loc_t){.gdata = idx, .base = base};
}
return ptr_slot_base(vec_at(cg->frame.slots, v.inst).result_off, base);
}
static void cg_copy_agg(cgen_t *cg, data_loc_t src, data_loc_t dst, spl_ir_type_id_t tid) {
usize sz = ir_type_size(cg->ctx, tid);
usize done = 0;
while (sz - done >= 8) {
@@ -442,60 +472,63 @@ static void cg_cmp(cgen_t *cg, usize ref, const spl_ir_node_t *n, uint8_t op) {
cg_store_slot(cg, ref, SPL_BOOL);
}
static void cg_const(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
static void cg_push_const(cgen_t *cg, spl_ir_value_t v, uint8_t k) {
spl_ir2vm_t *ctx = cg->ctx;
spl_type_id_t tid = n->type_const.tid;
spl_type_node_t *tn = spl_type_node(ctx->type, tid);
if (v.kind == SPL_IR_VALUE_GLOBAL) {
int gi = (v.global_id > 0 && v.global_id < vec_size(ctx->global_data_idx))
? (int)vec_at(ctx->global_data_idx, v.global_id)
: 0;
if (gi > 0)
emit(cg, SPL_GADDR, SPL_VOID, (spl_vm_val_t)gi);
else
CG_PUSH(cg, SPL_PTR, 0);
return;
}
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, v.tid);
if (!tn)
return;
if (tn->kind == SPL_TYPE_FN) {
if (tn->kind == SPL_IR_TYPE_FN) {
isize nat_idx = -1;
if (n->type_const.fn > 0)
map_get(ctx->extern_native, n->type_const.fn, &nat_idx);
if (v.fn > 0)
map_get(ctx->extern_native, v.fn, &nat_idx);
if (nat_idx >= 0) {
CG_PUSH(cg, SPL_U64, (spl_vm_val_t)nat_idx);
} else {
usize idx = ip_of(cg);
CG_PUSH(cg, SPL_PTR, 0);
cg_add_fix(cg, idx, FIX_FNADDR, 0, n->type_const.fn);
cg_add_fix(cg, idx, FIX_FNADDR, 0, v.fn);
}
cg_store_slot(cg, ref, SPL_PTR);
return;
}
uint8_t k = vm_kind_of(ctx, tid);
spl_vm_val_t imm = 0;
switch (tn->kind) {
case SPL_TYPE_BOOL:
imm = n->type_const.bool_lit ? 1 : 0;
case SPL_IR_TYPE_BOOL:
imm = v.int_bits ? 1 : 0;
break;
case SPL_TYPE_INT:
if (tn->int_type.bits == 8)
imm = (spl_vm_val_t)(unsigned char)n->type_const.ch_lit;
else
imm = (spl_vm_val_t)n->type_const.int_lit;
case SPL_IR_TYPE_INT:
imm = (spl_vm_val_t)v.int_bits;
break;
case SPL_TYPE_FLOAT:
memcpy(&imm, &n->type_const.float_lit, sizeof(double));
case SPL_IR_TYPE_FLOAT:
memcpy(&imm, &v.float_bits, sizeof(double));
break;
case SPL_TYPE_PTR:
imm = (spl_vm_val_t)(usize)n->type_const.ptr_lit;
case SPL_IR_TYPE_PTR:
imm = 0;
break;
case SPL_TYPE_UNIT:
return;
default:
break;
}
CG_PUSH(cg, k, imm);
cg_store_slot(cg, ref, k);
}
static void cg_cast(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
spl_ir2vm_t *ctx = cg->ctx;
spl_type_node_t *ft = spl_type_node(ctx->type, n->cast.from_tid);
spl_type_node_t *tt = spl_type_node(ctx->type, n->cast.to_tid);
spl_ir_type_node_t *ft = spl_ir_type_node(ctx->type, n->cast.from_tid);
spl_ir_type_node_t *tt = spl_ir_type_node(ctx->type, n->cast.to_tid);
if (!ft || !tt)
return;
@@ -504,14 +537,14 @@ static void cg_cast(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_load_slot(cg, n->cast.val, fk);
if (ft->kind == SPL_TYPE_INT && tt->kind == SPL_TYPE_INT) {
if (ft->kind == SPL_IR_TYPE_INT && tt->kind == SPL_IR_TYPE_INT) {
usize fb = ft->int_type.bits;
usize tb = tt->int_type.bits;
if (fb > tb)
emit(cg, SPL_TRUNC, SPL_VOID, tb);
else if (fb < tb)
emit(cg, ft->int_type.is_signed ? SPL_SEXT : SPL_ZEXT, SPL_VOID, fb);
} else if (ft->kind == SPL_TYPE_BOOL && tt->kind == SPL_TYPE_INT) {
} else if (ft->kind == SPL_IR_TYPE_BOOL && tt->kind == SPL_IR_TYPE_INT) {
emit(cg, SPL_ZEXT, SPL_VOID, 1);
}
@@ -528,26 +561,11 @@ static void cg_mem(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
break;
}
case SPL_IR_MEM_GLOBAL_ALLOC: {
const spl_ir_node_t *cn = &vec_at(cg->irf->nodes, n->mem_global_alloc.const_node);
int idx = 0;
if (cn->kind == SPL_IR_TYPE_CONST && cn->type_const.ptr_lit) {
usize size = ir_type_size(ctx, cn->type_const.tid);
idx = spl_prog_add_data(&ctx->prog, cn->type_const.ptr_lit, size);
}
if (idx > 0)
emit(cg, SPL_GADDR, SPL_VOID, (spl_vm_val_t)idx);
else
CG_PUSH(cg, SPL_PTR, 0);
cg_store_slot(cg, ref, SPL_PTR);
break;
}
case SPL_IR_MEM_LOAD: {
spl_type_id_t tid = n->mem_load.tid;
spl_ir_type_id_t tid = n->mem_load.tid;
if (ir_is_aggregate(ctx, tid)) {
usize data = vec_at(cg->frame.slots, ref).data_off;
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, n->mem_load.ptr).result_off),
cg_copy_agg(cg, value_ptr_loc(cg, n->mem_load.ptr, 0),
direct_data(data), tid);
CG_LADDR(cg, data);
cg_store_slot(cg, ref, SPL_PTR);
@@ -561,10 +579,10 @@ static void cg_mem(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_MEM_STORE: {
spl_type_id_t tid = n->mem_store.tid;
spl_ir_type_id_t tid = n->mem_store.tid;
if (ir_is_aggregate(ctx, tid)) {
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, n->mem_store.val).result_off),
ptr_slot(vec_at(cg->frame.slots, n->mem_store.ptr).result_off), tid);
cg_copy_agg(cg, value_ptr_loc(cg, n->mem_store.val, 0),
value_ptr_loc(cg, n->mem_store.ptr, 0), tid);
} else {
uint8_t k = vm_kind_of(ctx, tid);
cg_load_slot(cg, n->mem_store.ptr, SPL_PTR);
@@ -588,7 +606,7 @@ static void cg_mem(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_MEM_FIELD_PTR: {
spl_type_id_t agg_tid = n->mem_field_ptr.tid;
spl_ir_type_id_t agg_tid = n->mem_field_ptr.tid;
usize off = ir_agg_field_off(ctx, agg_tid, n->mem_field_ptr.field_idx);
cg_load_slot(cg, n->mem_field_ptr.agg, SPL_PTR);
if (off) {
@@ -610,17 +628,19 @@ static void cg_agg(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
case SPL_IR_AGG_CONSTRUCT: {
usize base = vec_at(cg->frame.slots, ref).data_off;
spl_type_id_t agg_t = n->agg_construct.tid;
spl_ir_type_id_t agg_t = n->agg_construct.tid;
for (usize i = 0; i < vec_size(n->agg_construct.fields); ++i) {
spl_ir_node_ref_t fref = vec_at(n->agg_construct.fields, i);
spl_type_id_t ftid = ir_agg_field_tid(ctx, agg_t, i);
spl_ir_value_t fref = vec_at(n->agg_construct.fields, i);
if (spl_ir_value_is_none(fref))
continue;
spl_ir_type_id_t ftid = ir_agg_field_tid(ctx, agg_t, i);
if (!ftid)
continue;
usize foff = ir_agg_field_off(ctx, agg_t, i);
if (ir_is_aggregate(ctx, ftid)) {
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, fref).result_off),
cg_copy_agg(cg, value_ptr_loc(cg, fref, 0),
direct_data_base(base, foff), ftid);
} else {
uint8_t fk = vm_kind_of(ctx, ftid);
@@ -634,14 +654,14 @@ static void cg_agg(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_AGG_EXTRACT: {
spl_type_id_t agg_t = n->agg_extract.tid;
spl_type_id_t ftid = n->agg_extract.field_tid;
spl_ir_type_id_t agg_t = n->agg_extract.tid;
spl_ir_type_id_t ftid = n->agg_extract.field_tid;
usize foff = ir_agg_field_off(ctx, agg_t, n->agg_extract.field_idx);
if (ir_is_aggregate(ctx, ftid)) {
usize data = vec_at(cg->frame.slots, ref).data_off;
cg_copy_agg(cg,
ptr_slot_base(vec_at(cg->frame.slots, n->agg_extract.val).result_off, foff),
value_ptr_loc(cg, n->agg_extract.val, foff),
direct_data(data), ftid);
CG_LADDR(cg, data);
cg_store_slot(cg, ref, SPL_PTR);
@@ -660,16 +680,16 @@ static void cg_agg(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
case SPL_IR_AGG_INSERT: {
usize base = vec_at(cg->frame.slots, ref).data_off;
spl_type_id_t agg_t = n->agg_insert.tid;
spl_ir_type_id_t agg_t = n->agg_insert.tid;
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, n->agg_insert.agg).result_off),
cg_copy_agg(cg, value_ptr_loc(cg, n->agg_insert.agg, 0),
direct_data(base), agg_t);
usize foff = ir_agg_field_off(ctx, agg_t, n->agg_insert.field_idx);
spl_type_id_t ftid = ir_agg_field_tid(ctx, agg_t, n->agg_insert.field_idx);
spl_ir_type_id_t ftid = ir_agg_field_tid(ctx, agg_t, n->agg_insert.field_idx);
if (ftid) {
if (ir_is_aggregate(ctx, ftid)) {
cg_copy_agg(cg, ptr_slot(vec_at(cg->frame.slots, n->agg_insert.field).result_off),
cg_copy_agg(cg, value_ptr_loc(cg, n->agg_insert.field, 0),
direct_data_base(base, foff), ftid);
} else {
uint8_t fk = vm_kind_of(ctx, ftid);
@@ -704,19 +724,14 @@ static void cg_typeop(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
v = ir_type_align(ctx, n->ir_alignof.tid);
break;
case SPL_IR_TYPE_OFFSETOF: {
usize idx = 0;
if (n->ir_offsetof.field_idx < vec_size(cg->irf->nodes)) {
const spl_ir_node_t *idx_node = &vec_at(cg->irf->nodes, n->ir_offsetof.field_idx);
if (idx_node->kind == SPL_IR_TYPE_CONST)
idx = (usize)idx_node->type_const.int_lit;
}
usize idx = value_int(n->ir_offsetof.field_idx);
v = ir_agg_field_off(ctx, n->ir_offsetof.tid, idx);
break;
}
case SPL_IR_TYPE_FIELD_COUNT: {
spl_type_node_t *tn = spl_type_node(ctx->type, n->field_count.tid);
if (tn && (tn->kind == SPL_TYPE_STRUCT || tn->kind == SPL_TYPE_UNION ||
tn->kind == SPL_TYPE_ENUM || tn->kind == SPL_TYPE_SHAPE))
spl_ir_type_node_t *tn = spl_ir_type_node(ctx->type, n->field_count.tid);
if (tn && (tn->kind == SPL_IR_TYPE_STRUCT || tn->kind == SPL_IR_TYPE_UNION ||
tn->kind == SPL_IR_TYPE_ENUM))
v = vec_size(tn->agg_type.variants);
break;
}
@@ -733,13 +748,8 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
case SPL_IR_CONTROL_PARAM: {
uint8_t k = vm_kind_of(ctx, n->control_param.tid);
usize idx = 0;
if (n->control_param.idx < vec_size(cg->irf->nodes)) {
const spl_ir_node_t *idx_node = &vec_at(cg->irf->nodes, n->control_param.idx);
if (idx_node->kind == SPL_IR_TYPE_CONST)
idx = (usize)idx_node->type_const.int_lit;
}
/* 聚合返回时 fp+0 是 sret 指针,实参从 fp+8 起 */
usize idx = value_int(n->control_param.idx);
/* 聚合返回时 fp+0 是 sret 指针,实参从 fp+8 起。 */
usize shift = ir_is_aggregate(ctx, fn_ret_type(ctx, cg->irf->fn_tid)) ? 1 : 0;
CG_LADDR(cg, (idx + shift) * sizeof(spl_vm_val_t));
CG_LOAD(cg, k);
@@ -748,10 +758,10 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_CONTROL_RET: {
spl_type_id_t ret_tid = n->control_ret.tid;
spl_ir_type_id_t ret_tid = n->control_ret.tid;
if (ir_is_aggregate(ctx, ret_tid)) {
/* sret:把返回值写入 *(fp+0),然后以 void 返回 */
if (n->control_ret.val) {
/* sret:把返回值写入 *(fp+0),然后以 void 返回。 */
if (!spl_ir_value_is_none(n->control_ret.val)) {
usize sz = ir_type_size(ctx, ret_tid);
CG_LADDR(cg, 0);
CG_LOAD(cg, SPL_PTR);
@@ -763,7 +773,7 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
break;
}
uint8_t k = vm_kind_of(ctx, ret_tid);
if (k != SPL_VOID && n->control_ret.val)
if (k != SPL_VOID && !spl_ir_value_is_none(n->control_ret.val))
cg_load_slot(cg, n->control_ret.val, k);
emit(cg, SPL_RET, k, 0);
break;
@@ -788,13 +798,7 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
}
case SPL_IR_CONTROL_CALL: {
spl_ir_func_ref_t callee_ref = 0;
spl_ir_node_ref_t fref = n->control_call.func;
if (fref < vec_size(cg->irf->nodes)) {
const spl_ir_node_t *fn_node = &vec_at(cg->irf->nodes, fref);
if (fn_node->kind == SPL_IR_TYPE_CONST)
callee_ref = fn_node->type_const.fn;
}
spl_ir_func_ref_t callee_ref = value_fn(n->control_call.func);
isize nat_idx = -1;
if (callee_ref > 0)
@@ -804,21 +808,34 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
if (nat_idx >= 0) {
for (usize i = 0; i < nargs; ++i) {
spl_ir_node_ref_t pref = vec_at(n->control_call.params, i);
const spl_ir_node_t *pn = &vec_at(cg->irf->nodes, pref);
uint8_t pk = vm_kind_of(ctx, ir_result_tid(ctx, pn));
spl_ir_value_t pref = vec_at(n->control_call.params, i);
uint8_t pk = vm_kind_of(ctx, value_tid(ctx, cg->irf, pref));
cg_load_slot(cg, pref, pk);
}
CG_PUSH(cg, SPL_U64, (spl_vm_val_t)nat_idx);
emit(cg, SPL_NCALL, SPL_VOID, (spl_vm_val_t)nargs);
uint8_t rk = vm_kind_of(ctx, n->control_call.tid);
if (rk == SPL_VOID)
emit(cg, SPL_DROP, SPL_VOID, 0); /* NCALL always push result */
else
cg_store_slot(cg, ref, rk);
if (ir_is_aggregate(ctx, n->control_call.tid)) {
usize sz = ir_type_size(ctx, n->control_call.tid);
usize result_off = vec_at(cg->frame.slots, ref).result_off;
usize data_off = vec_at(cg->frame.slots, ref).data_off;
cg_store_slot(cg, ref, SPL_PTR);
CG_LADDR(cg, data_off);
CG_LADDR(cg, result_off);
CG_LOAD(cg, SPL_PTR);
CG_PUSH(cg, SPL_U64, (spl_vm_val_t)sz);
emit(cg, SPL_MEMCPY, SPL_VOID, 0);
CG_LADDR(cg, data_off);
cg_store_slot(cg, ref, SPL_PTR);
} else {
uint8_t rk = vm_kind_of(ctx, n->control_call.tid);
if (rk == SPL_VOID)
emit(cg, SPL_DROP, SPL_VOID, 0); /* NCALL always push result */
else
cg_store_slot(cg, ref, rk);
}
} else {
spl_type_id_t ret_t = n->control_call.tid;
spl_ir_type_id_t ret_t = n->control_call.tid;
bool ret_is_sret = ir_is_aggregate(ctx, ret_t);
usize sret_off = 0;
@@ -831,17 +848,16 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
CG_LADDR(cg, sret_off);
}
for (usize i = 0; i < nargs; ++i) {
spl_ir_node_ref_t pref = vec_at(n->control_call.params, i);
const spl_ir_node_t *pn = &vec_at(cg->irf->nodes, pref);
uint8_t pk = vm_kind_of(ctx, ir_result_tid(ctx, pn));
spl_ir_value_t pref = vec_at(n->control_call.params, i);
uint8_t pk = vm_kind_of(ctx, value_tid(ctx, cg->irf, pref));
cg_load_slot(cg, pref, pk);
}
cg_load_slot(cg, fref, SPL_PTR);
cg_load_slot(cg, n->control_call.func, SPL_PTR);
spl_vm_val_t actual_nargs = nargs + (ret_is_sret ? 1 : 0);
emit(cg, SPL_CALL, SPL_VOID, actual_nargs);
if (ret_is_sret) {
/* result slot 保存 sret 指针 */
/* result slot 保存 sret 指针。 */
CG_LADDR(cg, sret_off);
cg_store_slot(cg, ref, SPL_PTR);
} else {
@@ -865,10 +881,6 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_TYPE_CONST:
cg_const(cg, ref, n);
break;
case SPL_IR_ARITH_ADD:
cg_binop(cg, ref, n, SPL_ADD);
break;
@@ -879,14 +891,14 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_binop(cg, ref, n, SPL_MUL);
break;
case SPL_IR_ARITH_DIV: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_binop(cg, ref, n, sgn ? SPL_DIV_S : SPL_DIV_U);
break;
}
case SPL_IR_ARITH_REM: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_binop(cg, ref, n, sgn ? SPL_REM_S : SPL_REM_U);
break;
}
@@ -903,8 +915,8 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_binop(cg, ref, n, SPL_SHL);
break;
case SPL_IR_ARITH_SHR: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->arith.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_binop(cg, ref, n, sgn ? SPL_SHR_S : SPL_SHR_U);
break;
}
@@ -912,8 +924,8 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_unop(cg, ref, n, SPL_NEG);
break;
case SPL_IR_ARITH_NOT: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->arith.tid);
if (tn && tn->kind == SPL_TYPE_BOOL) {
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->arith.tid);
if (tn && tn->kind == SPL_IR_TYPE_BOOL) {
cg_load_slot(cg, n->arith.left, SPL_BOOL);
CG_PUSH(cg, SPL_BOOL, 0);
CG_OP(cg, SPL_EQ, SPL_BOOL);
@@ -931,26 +943,26 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
cg_cmp(cg, ref, n, SPL_NE);
break;
case SPL_IR_CMP_LT: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_cmp(cg, ref, n, sgn ? SPL_SLT : SPL_ULT);
break;
}
case SPL_IR_CMP_LE: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_cmp(cg, ref, n, sgn ? SPL_SLE : SPL_ULE);
break;
}
case SPL_IR_CMP_GT: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_cmp(cg, ref, n, sgn ? SPL_SGT : SPL_UGT);
break;
}
case SPL_IR_CMP_GE: {
spl_type_node_t *tn = spl_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_TYPE_INT && tn->int_type.is_signed;
spl_ir_type_node_t *tn = spl_ir_type_node(cg->ctx->type, n->cmp.tid);
bool sgn = tn && tn->kind == SPL_IR_TYPE_INT && tn->int_type.is_signed;
cg_cmp(cg, ref, n, sgn ? SPL_SGE : SPL_UGE);
break;
}
@@ -970,7 +982,6 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
break;
case SPL_IR_MEM_ALLOCA:
case SPL_IR_MEM_GLOBAL_ALLOC:
case SPL_IR_MEM_LOAD:
case SPL_IR_MEM_STORE:
case SPL_IR_MEM_OFFSET:
@@ -1011,19 +1022,19 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
if (msg_idx <= 0 || fmt_idx <= 0)
break;
/* fmt slice = {ptr, len=2} 写到 data+0 */
/* fmt slice = {ptr, len=2} 写到 data+0。 */
CG_GADDR(cg, (spl_vm_val_t)fmt_idx);
cg_store_at(cg, data + 0, SPL_PTR);
CG_PUSH(cg, SPL_U64, 2);
cg_store_at(cg, data + 8, SPL_U64);
/* msg slice = {ptr, len} 写到 data+16 */
/* msg slice = {ptr, len} 写到 data+16。 */
CG_GADDR(cg, (spl_vm_val_t)msg_idx);
cg_store_at(cg, data + 16, SPL_PTR);
CG_PUSH(cg, SPL_U64, n->dbg_panic.len);
cg_store_at(cg, data + 24, SPL_U64);
/* push fmt slice 指针,push msg slice 指针 */
/* push fmt slice 指针,push msg slice 指针。 */
CG_LADDR(cg, data + 0);
CG_LADDR(cg, data + 16);
@@ -1040,7 +1051,7 @@ static void cg_node(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
break;
default:
/* 前端不发射 select/mem.copy/mem.set/abs;出现即后端缺口,直接报错。 */
/* 前端不发射 select/mem.copy/mem.set/abs;出现即后端缺口,直接报错。 */
Panic("ir2vm: unsupported IR node kind %d", (int)n->kind);
break;
}
@@ -1110,8 +1121,9 @@ static void register_externs(spl_ir2vm_t *ctx) {
if (!irf)
continue;
spl_attr_node_t *ext = spl_ir_fn_extern_attr(ctx->attr, irf);
if (ext) {
ext->consumed_mask |= (1u << SPL_ATTR_STAGE_IR);
if (ext || irf->extern_fn) {
if (ext)
ext->consumed_mask |= (1u << SPL_ATTR_STAGE_IR);
int nat_idx = get_or_add_native(ctx, irf->name);
map_put(ctx->extern_native, i, (isize)nat_idx);
}
@@ -1121,14 +1133,49 @@ static void register_externs(spl_ir2vm_t *ctx) {
static usize spl_map_hash(usize k) { return MAP_HASH_INT(k); }
static int spl_map_cmp(usize a, usize b) { return MAP_CMP_INT(a, b); }
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, const spl_type_t *type,
spl_layout_t *layout, const spl_attr_t *attr) {
Assert(ir != NULL && type != NULL && attr != NULL);
static void prepare_globals(spl_ir2vm_t *ctx) {
vec_push(ctx->global_data_idx, 0);
for (usize i = 1; i < vec_size(ctx->ir->globals); ++i) {
const spl_ir_global_t *g = &vec_at(ctx->ir->globals, i);
usize size = ir_type_size(ctx, g->tid);
if (size == 0)
size = 1;
unsigned char *buf = calloc(1, size);
if (!buf) {
vec_push(ctx->global_data_idx, 0);
continue;
}
if (g->init.kind == SPL_IR_VALUE_CONST) {
spl_ir_type_node_t *it = spl_ir_type_node(ctx->type, g->init.tid);
if (it && it->kind == SPL_IR_TYPE_ARRAY) {
spl_ir_const_t *k = spl_ir_const((spl_ir_t *)ctx->ir, g->init.const_id);
if (k) {
usize n = size < k->bytes.len ? size : k->bytes.len;
memcpy(buf, k->bytes.data, n);
}
} else {
uint64_t bits = 0;
memcpy(&bits, &g->init.int_bits, sizeof bits);
usize n = size < sizeof(bits) ? size : sizeof(bits);
for (usize j = 0; j < n; ++j)
buf[j] = (unsigned char)(bits >> (j * 8));
}
}
int idx = spl_prog_add_data(&ctx->prog, buf, size);
vec_push(ctx->global_data_idx, idx);
free(buf);
}
}
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, spl_layout_t *layout,
const spl_attr_t *attr) {
Assert(ir != NULL && attr != NULL);
ctx->ir = ir;
ctx->type = type;
ctx->type = ir->types;
ctx->attr = attr;
ctx->layout = layout;
map_init(ctx->extern_native, spl_map_hash, spl_map_cmp);
vec_init(ctx->global_data_idx);
spl_prog_init(&ctx->prog);
ctx->diag = NULL;
@@ -1136,6 +1183,7 @@ void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, const spl_type_t *type
void spl_ir2vm_drop(spl_ir2vm_t *ctx) {
spl_prog_drop(&ctx->prog);
vec_free(ctx->global_data_idx);
map_free(ctx->extern_native);
}
@@ -1145,12 +1193,13 @@ int spl_ir2vm_run(spl_ir2vm_t *ctx) {
return 0;
register_externs(ctx);
prepare_globals(ctx);
/* 保留 insn 0 作为哨兵:确保真实函数入口地址非零,
从而 0 可唯一表示 null 函数指针(函数指针与 null 比较)。 */
/* 保留 insn 0 作为哨兵:确认真实函数入口地址非零,
从而使 0 唯一表示 null 函数指针(函数指针与 null 比较)。 */
spl_prog_add_instr(&ctx->prog, SPL_HALT, SPL_VOID, 0);
/* Pass 2:翻译非 extern 的函数 */
/* Pass 2:翻译非 extern 的函数。 */
/* Pass 2锛氱炕璇戦潪 extern 鐨勫嚱鏁?*/
usize *fid_ip = calloc(n, sizeof(usize));
fix_vec_t all_fixups;
vec_init(all_fixups);
@@ -1161,8 +1210,8 @@ int spl_ir2vm_run(spl_ir2vm_t *ctx) {
continue;
fid_ip[i] = translate_function(ctx, i, &all_fixups);
}
/* FNADDR 回填 */
/* FNADDR 回填。 */
/* FNADDR 鍥炲~ */
for (usize i = 0; i < vec_size(all_fixups); ++i) {
fix_t *fx = &vec_at(all_fixups, i);
if (fx->kind != FIX_FNADDR)
@@ -2,7 +2,7 @@
#include "vm_opt.h"
#include "../stage0/include/core_map.h"
#include "stage0/include/core_map.h"
#include <stdlib.h>
+422
View File
@@ -0,0 +1,422 @@
#include "spl_cfg_ast.h"
#include <stdlib.h>
#include <string.h>
typedef struct {
spl_ast_t *ast;
spl_ast_node_ref_t ref;
spl_cfg_node_t node;
} ast_fn_ref_t;
typedef VEC(ast_fn_ref_t) ast_fn_ref_vec_t;
typedef struct {
spl_cfg_t *cfg;
spl_sema_t *sema;
spl_ast_t *ast;
spl_cfg_node_t fn_node;
spl_cfg_node_t *def_node;
usize def_count;
MAP(const char *, spl_cfg_node_t) hosts;
} ast_ctx_t;
static void walk_node(ast_ctx_t *c, spl_ast_node_ref_t ref);
static void walk_vec(ast_ctx_t *c, spl_ast_node_ref_vec_t vec);
static void collect_decls(ast_ctx_t *c, spl_ast_node_ref_t ref, ast_fn_ref_vec_t *out);
static void walk_opt(ast_ctx_t *c, spl_ast_node_ref_t ref) {
if (ref)
walk_node(c, ref);
}
static void walk_vec(ast_ctx_t *c, spl_ast_node_ref_vec_t vec) {
for (usize i = 0; i < vec_size(vec); ++i)
walk_opt(c, vec_at(vec, i));
}
static spl_def_node_t *ctx_def(ast_ctx_t *c, usize def_id) {
if (!def_id || def_id >= c->def_count)
return NULL;
return spl_def_node(c->sema->type, def_id);
}
static void add_fn_edge(ast_ctx_t *c, usize def_id, spl_cfg_edge_kind_t kind) {
spl_def_node_t *def = ctx_def(c, def_id);
if (!def || def->kind != SPL_DEF_FN || def_id >= c->def_count)
return;
spl_cfg_node_t target = c->def_node[def_id];
if (!target || (target == c->fn_node && kind == SPL_CFG_EDGE_FUNC_REF))
return;
spl_cfg_add_edge(c->cfg, c->fn_node, target, kind);
}
static spl_cfg_node_t add_host(ast_ctx_t *c, const char *name) {
if (!name)
return 0;
spl_cfg_node_t node = 0;
if (map_get(c->hosts, name, &node))
return node;
spl_cfg_node_info_t info = {0};
info.kind = SPL_CFG_NODE_HOST;
info.name = name;
node = spl_cfg_add_node(c->cfg, info);
map_put(c->hosts, name, node);
return node;
}
static void add_host_edge(ast_ctx_t *c, const char *name) {
spl_cfg_node_t host = add_host(c, name);
if (host)
spl_cfg_add_edge(c->cfg, c->fn_node, host, SPL_CFG_EDGE_HOST);
}
static void walk_compile_call(ast_ctx_t *c, const char *name, spl_ast_node_ref_vec_t args) {
if (name && strncmp(name, "sap.", 4) == 0) {
add_host_edge(c, name);
} else if (name) {
spl_symbol_t sym;
if (c->sema->ns && spl_ns_lookup(c->sema->ns, name, &sym) &&
sym.kind == SPL_SYMBOL_KIND_FN)
add_fn_edge(c, sym.node, SPL_CFG_EDGE_CALL);
}
walk_vec(c, args);
}
static void walk_call(ast_ctx_t *c, spl_ast_node_t *n) {
spl_ast_node_t *callee = spl_ast_node(c->ast, n->call.callee);
if (callee && callee->kind == SPL_AST_EXPR_IDENT) {
add_fn_edge(c, callee->resolved_def_id, SPL_CFG_EDGE_CALL);
} else if (callee && callee->kind == SPL_AST_EXPR_FIELD) {
add_fn_edge(c, callee->resolved_def_id, SPL_CFG_EDGE_CALL);
walk_opt(c, callee->field.obj);
} else {
walk_opt(c, n->call.callee);
}
walk_vec(c, n->call.args);
}
static void walk_node(ast_ctx_t *c, spl_ast_node_ref_t ref) {
spl_ast_node_t *n = spl_ast_node(c->ast, ref);
if (!n)
return;
switch (n->kind) {
case SPL_AST_ROOT:
walk_opt(c, n->root.members);
break;
case SPL_AST_CONTAINER_MEMBERS:
walk_vec(c, n->container_members.external_tags);
walk_opt(c, n->container_members.module);
walk_vec(c, n->container_members.declarations);
break;
case SPL_AST_EXTERNAL_TAG_ITEM:
case SPL_AST_TAG_ITEM:
walk_vec(c, n->tag_item.args);
break;
case SPL_AST_MOD_DECL:
walk_vec(c, n->mod_decl.decorator_list);
walk_vec(c, n->mod_decl.decls);
break;
case SPL_AST_IMPORT_DECL:
walk_vec(c, n->import_decl.decorator_list);
break;
case SPL_AST_TOP_LEVEL_BLOCK:
walk_vec(c, n->top_level_block.decorator_list);
walk_vec(c, n->top_level_block.attr_list);
walk_opt(c, n->top_level_block.block);
break;
case SPL_AST_FN_DECL:
/* 嵌套函数由 collect_decls 单独处理,避免把它的引用算到外层。 */
break;
case SPL_AST_VAR_DECL:
case SPL_AST_CONST_DECL:
walk_vec(c, n->var_const_decl.decorator_list);
walk_vec(c, n->var_const_decl.attr_list);
walk_opt(c, n->var_const_decl.pattern);
walk_opt(c, n->var_const_decl.type);
walk_opt(c, n->var_const_decl.init_expr);
break;
case SPL_AST_TYPE_DECL:
walk_vec(c, n->type_decl.decorator_list);
walk_vec(c, n->type_decl.attr_list);
walk_opt(c, n->type_decl.pattern);
walk_opt(c, n->type_decl.type_expr);
break;
case SPL_AST_MEMBER_DECL:
walk_vec(c, n->member_decl.decorator_list);
walk_vec(c, n->member_decl.attr_list);
walk_opt(c, n->member_decl.type_expr);
walk_opt(c, n->member_decl.init_expr);
break;
case SPL_AST_PARAM_DECL:
walk_vec(c, n->param_decl.attr_list);
walk_opt(c, n->param_decl.type_expr);
break;
case SPL_AST_AGGREGATE_MEMBER:
walk_vec(c, n->aggregate_member.attr_list);
walk_opt(c, n->aggregate_member.type_expr);
walk_opt(c, n->aggregate_member.init_expr);
break;
case SPL_AST_STRUCT_INIT_ITEM:
walk_opt(c, n->struct_init_item.expr);
break;
case SPL_AST_MATCH_ARM:
walk_opt(c, n->match_arm.pattern);
walk_opt(c, n->match_arm.body);
break;
case SPL_AST_STATEMENT_RET:
walk_opt(c, n->statement_ret.expr);
break;
case SPL_AST_STATEMENT_BREAK:
walk_opt(c, n->statement_break.label);
walk_opt(c, n->statement_break.expr);
break;
case SPL_AST_STATEMENT_CONTINUE:
walk_opt(c, n->statement_continue.label);
break;
case SPL_AST_STATEMENT_DEFER:
walk_opt(c, n->statement_defer.body);
break;
case SPL_AST_STATEMENT_DECL:
walk_opt(c, n->statement_decl.decl);
break;
case SPL_AST_STATEMENT_EXPR:
walk_opt(c, n->statement_expr.expr);
break;
case SPL_AST_EXPR_IDENT:
add_fn_edge(c, n->resolved_def_id, SPL_CFG_EDGE_FUNC_REF);
break;
case SPL_AST_EXPR_UNARY:
walk_opt(c, n->unary.operand);
break;
case SPL_AST_EXPR_BINARY:
walk_opt(c, n->binary.left);
walk_opt(c, n->binary.right);
break;
case SPL_AST_EXPR_CALL:
walk_call(c, n);
break;
case SPL_AST_EXPR_FIELD:
add_fn_edge(c, n->resolved_def_id, SPL_CFG_EDGE_FUNC_REF);
walk_opt(c, n->field.obj);
break;
case SPL_AST_EXPR_INDEX:
walk_opt(c, n->index.obj);
walk_opt(c, n->index.index);
break;
case SPL_AST_EXPR_SLICE:
walk_opt(c, n->slice.obj);
walk_opt(c, n->slice.begin);
walk_opt(c, n->slice.end);
break;
case SPL_AST_EXPR_CAST:
walk_opt(c, n->cast.expr);
walk_opt(c, n->cast.type);
break;
case SPL_AST_EXPR_TUPLE:
walk_vec(c, n->tuple.elems);
break;
case SPL_AST_EXPR_ARRAY_LIT:
walk_opt(c, n->array_literal.elem_type);
walk_vec(c, n->array_literal.elems);
break;
case SPL_AST_EXPR_AGGREGATE_LIT:
walk_vec(c, n->aggregate_literal.fields);
break;
case SPL_AST_EXPR_COMPILE_CALL:
walk_compile_call(c, n->compile_call.name, n->compile_call.args);
break;
case SPL_AST_EXPR_BLOCK:
walk_vec(c, n->block.stmts);
walk_opt(c, n->block.tail_expr);
break;
case SPL_AST_EXPR_IF:
walk_opt(c, n->if_expr.cond);
walk_opt(c, n->if_expr.then_block);
walk_opt(c, n->if_expr.else_branch);
break;
case SPL_AST_EXPR_IFVAR:
walk_opt(c, n->ifvar_expr.var_decl);
walk_opt(c, n->ifvar_expr.then_block);
walk_opt(c, n->ifvar_expr.else_branch);
break;
case SPL_AST_EXPR_WHILE:
walk_opt(c, n->while_expr.label);
walk_opt(c, n->while_expr.cond);
walk_opt(c, n->while_expr.body);
walk_opt(c, n->while_expr.else_branch);
break;
case SPL_AST_EXPR_LOOP:
walk_opt(c, n->loop_expr.label);
walk_opt(c, n->loop_expr.body);
break;
case SPL_AST_EXPR_FOR:
walk_opt(c, n->for_expr.label);
walk_vec(c, n->for_expr.iter_exprs);
walk_opt(c, n->for_expr.pattern);
walk_opt(c, n->for_expr.body);
walk_opt(c, n->for_expr.else_branch);
break;
case SPL_AST_EXPR_MATCH:
walk_opt(c, n->match_expr.matched_expr);
walk_vec(c, n->match_expr.arms);
break;
case SPL_AST_EXPR_FN_TYPE:
walk_vec(c, n->fn_type.params);
walk_opt(c, n->fn_type.ret_type);
break;
case SPL_AST_TYPE_PATH:
walk_vec(c, n->type_path.generic_args);
break;
case SPL_AST_TYPE_POINTER:
walk_opt(c, n->type_pointer.pointee);
break;
case SPL_AST_TYPE_ARRAY:
walk_opt(c, n->type_array.elem_type);
break;
case SPL_AST_TYPE_SLICE:
walk_opt(c, n->type_slice.elem_type);
break;
case SPL_AST_TYPE_FN:
walk_vec(c, n->type_fn.params);
walk_opt(c, n->type_fn.ret_type);
break;
case SPL_AST_TYPE_PAREN:
walk_vec(c, n->type_paren.types);
break;
case SPL_AST_TYPE_AGGREGATE:
walk_vec(c, n->type_aggregate.members);
break;
case SPL_AST_TYPE_COMPILE_CALL:
walk_compile_call(c, n->type_compile_call.name, n->type_compile_call.args);
break;
case SPL_AST_PATTERN_DOT:
walk_opt(c, n->pattern_dot.sub_pattern);
break;
case SPL_AST_PATTERN_TUPLE:
walk_vec(c, n->pattern_tuple.patterns);
break;
case SPL_AST_PATTERN_LIST:
walk_vec(c, n->pattern_list.patterns);
break;
case SPL_AST_PATTERN_AGGREGATE:
walk_vec(c, n->pattern_aggregate.fields);
break;
case SPL_AST_PATTERN_FIELD:
walk_opt(c, n->pattern_field.pattern);
break;
case SPL_AST_PATTERN_REF:
walk_opt(c, n->pattern_ref.pat);
break;
default:
break;
}
}
static void collect_decls(ast_ctx_t *c, spl_ast_node_ref_t ref, ast_fn_ref_vec_t *out) {
spl_ast_node_t *n = spl_ast_node(c->ast, ref);
if (!n)
return;
switch (n->kind) {
case SPL_AST_ROOT:
collect_decls(c, n->root.members, out);
break;
case SPL_AST_CONTAINER_MEMBERS:
for (usize i = 0; i < vec_size(n->container_members.declarations); ++i)
collect_decls(c, vec_at(n->container_members.declarations, i), out);
break;
case SPL_AST_MOD_DECL:
for (usize i = 0; i < vec_size(n->mod_decl.decls); ++i)
collect_decls(c, vec_at(n->mod_decl.decls, i), out);
break;
case SPL_AST_TOP_LEVEL_BLOCK:
collect_decls(c, n->top_level_block.block, out);
break;
case SPL_AST_EXPR_BLOCK:
for (usize i = 0; i < vec_size(n->block.stmts); ++i)
collect_decls(c, vec_at(n->block.stmts, i), out);
break;
case SPL_AST_STATEMENT_DECL:
collect_decls(c, n->statement_decl.decl, out);
break;
case SPL_AST_TYPE_DECL: {
spl_ast_node_t *te = spl_ast_node(c->ast, n->type_decl.type_expr);
if (te && te->kind == SPL_AST_TYPE_AGGREGATE)
collect_decls(c, n->type_decl.type_expr, out);
break;
}
case SPL_AST_TYPE_AGGREGATE:
for (usize i = 0; i < vec_size(n->type_aggregate.members); ++i)
collect_decls(c, vec_at(n->type_aggregate.members, i), out);
break;
case SPL_AST_FN_DECL: {
usize def_id = n->resolved_def_id;
if (!def_id || def_id >= c->def_count || c->def_node[def_id])
break;
spl_cfg_node_info_t info = {0};
info.kind = SPL_CFG_NODE_FN;
info.name = n->fn_decl.name;
info.user = def_id;
spl_cfg_node_t node = spl_cfg_add_node(c->cfg, info);
c->def_node[def_id] = node;
ast_fn_ref_t entry = {.ast = c->ast, .ref = ref, .node = node};
vec_push(*out, entry);
break;
}
default:
break;
}
}
bool spl_cfg_ast_build(spl_cfg_t *cfg, spl_sema_t *sema, const spl_ast_ptr_vec_t *asts) {
if (!cfg || !sema || !asts)
return false;
usize def_count = vec_size(sema->type->def_table);
spl_cfg_node_t *def_node = calloc(def_count ? def_count : 1, sizeof(*def_node));
if (!def_node)
return false;
ast_ctx_t c = {0};
c.cfg = cfg;
c.sema = sema;
c.def_node = def_node;
c.def_count = def_count;
map_init(c.hosts, MAP_HASH_STR, MAP_CMP_STR);
ast_fn_ref_vec_t fns;
vec_init(fns);
for (usize i = 0; i < vec_size(*asts); ++i) {
spl_ast_t *ast = vec_at(*asts, i);
if (!ast || !ast->root)
continue;
c.ast = ast;
collect_decls(&c, ast->root, &fns);
}
for (usize i = 0; i < vec_size(fns); ++i) {
ast_fn_ref_t *fn = &vec_at(fns, i);
spl_ast_node_t *n = spl_ast_node(fn->ast, fn->ref);
if (!n || n->kind != SPL_AST_FN_DECL)
continue;
c.ast = fn->ast;
c.fn_node = fn->node;
spl_ns_id_t saved_scope = sema->ns ? sema->ns->current : 0;
if (n->resolved_ns_id && sema->ns)
sema->ns->current = n->resolved_ns_id;
walk_vec(&c, n->fn_decl.decorator_list);
walk_vec(&c, n->fn_decl.attr_list);
walk_vec(&c, n->fn_decl.params);
walk_opt(&c, n->fn_decl.ret_type);
walk_opt(&c, n->fn_decl.body);
if (sema->ns)
sema->ns->current = saved_scope;
}
vec_free(fns);
map_free(c.hosts);
free(def_node);
return spl_cfg_finalize(cfg);
}
+432
View File
@@ -0,0 +1,432 @@
#include "spl_cfg.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char *spl_cfg_node_kind_name(spl_cfg_node_kind_t kind) {
switch (kind) {
case SPL_CFG_NODE_FN:
return "fn";
case SPL_CFG_NODE_BLOCK:
return "block";
case SPL_CFG_NODE_HOST:
return "host";
case SPL_CFG_NODE_EXIT:
return "exit";
default:
return "?";
}
}
const char *spl_cfg_edge_kind_name(spl_cfg_edge_kind_t kind) {
switch (kind) {
case SPL_CFG_EDGE_CALL:
return "call";
case SPL_CFG_EDGE_FUNC_REF:
return "func_ref";
case SPL_CFG_EDGE_BR_TRUE:
return "br_true";
case SPL_CFG_EDGE_BR_FALSE:
return "br_false";
case SPL_CFG_EDGE_JMP:
return "jmp";
case SPL_CFG_EDGE_HOST:
return "host";
default:
return "?";
}
}
void spl_cfg_init(spl_cfg_t *cfg) {
memset(cfg, 0, sizeof(*cfg));
vec_init(cfg->nodes);
vec_init(cfg->edges);
vec_init(cfg->out_start);
vec_init(cfg->out_edges);
vec_init(cfg->in_start);
vec_init(cfg->in_edges);
vec_init(cfg->scc);
vec_init(cfg->topo);
/* 哨兵节点。 */
spl_cfg_node_info_t none = {0};
vec_push(cfg->nodes, none);
}
void spl_cfg_drop(spl_cfg_t *cfg) {
if (!cfg)
return;
vec_free(cfg->nodes);
vec_free(cfg->edges);
vec_free(cfg->out_start);
vec_free(cfg->out_edges);
vec_free(cfg->in_start);
vec_free(cfg->in_edges);
vec_free(cfg->scc);
vec_free(cfg->topo);
memset(cfg, 0, sizeof(*cfg));
}
static void cfg_invalidate(spl_cfg_t *cfg) {
cfg->finalized = false;
cfg->scc_done = false;
cfg->topo_done = false;
}
spl_cfg_node_t spl_cfg_add_node(spl_cfg_t *cfg, spl_cfg_node_info_t info) {
vec_push(cfg->nodes, info);
cfg_invalidate(cfg);
return vec_size(cfg->nodes) - 1;
}
void spl_cfg_add_edge(spl_cfg_t *cfg, spl_cfg_node_t from, spl_cfg_node_t to,
spl_cfg_edge_kind_t kind) {
if (!from || !to || from >= vec_size(cfg->nodes) || to >= vec_size(cfg->nodes))
return;
spl_cfg_edge_t edge = {.from = from, .to = to, .kind = kind};
vec_push(cfg->edges, edge);
cfg_invalidate(cfg);
}
const spl_cfg_node_info_t *spl_cfg_node_info(const spl_cfg_t *cfg, spl_cfg_node_t node) {
if (!cfg || !node || node >= vec_size(cfg->nodes))
return NULL;
return &vec_at(cfg->nodes, node);
}
usize spl_cfg_node_count(const spl_cfg_t *cfg) { return cfg ? vec_size(cfg->nodes) : 0; }
bool spl_cfg_finalize(spl_cfg_t *cfg) {
if (!cfg)
return false;
if (cfg->finalized)
return true;
usize n = vec_size(cfg->nodes);
usize ne = vec_size(cfg->edges);
cfg->out_start.size = 0;
cfg->out_edges.size = 0;
cfg->in_start.size = 0;
cfg->in_edges.size = 0;
for (usize i = 0; i <= n; ++i)
vec_push(cfg->out_start, 0);
for (usize i = 0; i <= n; ++i)
vec_push(cfg->in_start, 0);
for (usize i = 0; i < ne; ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
vec_at(cfg->out_start, e->from + 1) += 1;
vec_at(cfg->in_start, e->to + 1) += 1;
}
for (usize i = 1; i <= n; ++i) {
vec_at(cfg->out_start, i) += vec_at(cfg->out_start, i - 1);
vec_at(cfg->in_start, i) += vec_at(cfg->in_start, i - 1);
}
for (usize i = 0; i < ne; ++i)
vec_push(cfg->out_edges, 0);
for (usize i = 0; i < ne; ++i)
vec_push(cfg->in_edges, 0);
spl_cfg_index_vec_t out_cursor;
spl_cfg_index_vec_t in_cursor;
vec_init(out_cursor);
vec_init(in_cursor);
for (usize i = 0; i < n; ++i) {
vec_push(out_cursor, vec_at(cfg->out_start, i));
vec_push(in_cursor, vec_at(cfg->in_start, i));
}
for (usize i = 0; i < ne; ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
vec_at(cfg->out_edges, vec_at(out_cursor, e->from)++) = i;
vec_at(cfg->in_edges, vec_at(in_cursor, e->to)++) = i;
}
vec_free(out_cursor);
vec_free(in_cursor);
cfg->finalized = true;
return true;
}
static bool cfg_scc_impl(spl_cfg_t *cfg) {
if (!spl_cfg_finalize(cfg))
return false;
if (cfg->scc_done)
return true;
usize n = vec_size(cfg->nodes);
spl_cfg_index_vec_t visited;
spl_cfg_index_vec_t cursor;
spl_cfg_index_vec_t stack;
spl_cfg_index_vec_t post;
vec_init(visited);
vec_init(cursor);
vec_init(stack);
vec_init(post);
for (usize i = 0; i < n; ++i) {
vec_push(visited, 0);
vec_push(cursor, 0);
}
for (usize start = 1; start < n; ++start) {
if (vec_at(visited, start))
continue;
vec_at(visited, start) = 1;
vec_at(cursor, start) = vec_at(cfg->out_start, start);
vec_push(stack, start);
while (vec_size(stack) > 0) {
usize u = vec_at(stack, vec_size(stack) - 1);
usize cur = vec_at(cursor, u);
usize end = vec_at(cfg->out_start, u + 1);
if (cur < end) {
usize ei = vec_at(cfg->out_edges, cur);
vec_at(cursor, u) = cur + 1;
usize w = vec_at(cfg->edges, ei).to;
if (!vec_at(visited, w)) {
vec_at(visited, w) = 1;
vec_at(cursor, w) = vec_at(cfg->out_start, w);
vec_push(stack, w);
}
} else {
(void)vec_pop(stack);
vec_push(post, u);
}
}
}
cfg->scc.size = 0;
for (usize i = 0; i < n; ++i)
vec_push(cfg->scc, 0);
usize nscc = 0;
for (usize i = vec_size(post); i > 0; --i) {
usize start = vec_at(post, i - 1);
if (vec_at(cfg->scc, start))
continue;
nscc += 1;
vec_at(cfg->scc, start) = nscc;
vec_push(stack, start);
while (vec_size(stack) > 0) {
usize u = vec_pop(stack);
usize begin = vec_at(cfg->in_start, u);
usize end = vec_at(cfg->in_start, u + 1);
for (usize k = begin; k < end; ++k) {
usize ei = vec_at(cfg->in_edges, k);
usize w = vec_at(cfg->edges, ei).from;
if (!vec_at(cfg->scc, w)) {
vec_at(cfg->scc, w) = nscc;
vec_push(stack, w);
}
}
}
}
vec_free(visited);
vec_free(cursor);
vec_free(stack);
vec_free(post);
cfg->scc_done = true;
return true;
}
bool spl_cfg_scc(spl_cfg_t *cfg) { return cfg_scc_impl(cfg); }
static bool cfg_topo_impl(spl_cfg_t *cfg) {
if (!cfg_scc_impl(cfg))
return false;
if (cfg->topo_done)
return true;
usize n = vec_size(cfg->nodes);
usize nscc = 0;
for (usize i = 1; i < n; ++i) {
if (vec_at(cfg->scc, i) > nscc)
nscc = vec_at(cfg->scc, i);
}
spl_cfg_index_vec_t cond_start;
spl_cfg_index_vec_t cond_edges;
spl_cfg_index_vec_t indeg;
vec_init(cond_start);
vec_init(cond_edges);
vec_init(indeg);
for (usize i = 0; i < nscc + 2; ++i)
vec_push(cond_start, 0);
for (usize i = 0; i < nscc + 1; ++i)
vec_push(indeg, 0);
for (usize i = 0; i < vec_size(cfg->edges); ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
usize su = vec_at(cfg->scc, e->from);
usize sv = vec_at(cfg->scc, e->to);
if (su == sv)
continue;
vec_at(cond_start, su + 1) += 1;
}
for (usize i = 1; i <= nscc + 1; ++i)
vec_at(cond_start, i) += vec_at(cond_start, i - 1);
for (usize i = 0; i < vec_at(cond_start, nscc + 1); ++i)
vec_push(cond_edges, 0);
spl_cfg_index_vec_t cursor;
vec_init(cursor);
for (usize i = 0; i < nscc + 1; ++i)
vec_push(cursor, vec_at(cond_start, i));
for (usize i = 0; i < vec_size(cfg->edges); ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
usize su = vec_at(cfg->scc, e->from);
usize sv = vec_at(cfg->scc, e->to);
if (su == sv)
continue;
vec_at(cond_edges, vec_at(cursor, su)++) = sv;
vec_at(indeg, sv) += 1;
}
vec_free(cursor);
spl_cfg_index_vec_t queue;
spl_cfg_index_vec_t order;
vec_init(queue);
vec_init(order);
for (usize s = 1; s <= nscc; ++s) {
if (vec_at(indeg, s) == 0)
vec_push(queue, s);
}
usize head = 0;
while (head < vec_size(queue)) {
usize s = vec_at(queue, head++);
vec_push(order, s);
usize begin = vec_at(cond_start, s);
usize end = vec_at(cond_start, s + 1);
for (usize i = begin; i < end; ++i) {
usize t = vec_at(cond_edges, i);
if (vec_at(indeg, t) == 0)
continue;
vec_at(indeg, t) -= 1;
if (vec_at(indeg, t) == 0)
vec_push(queue, t);
}
}
if (vec_size(order) != nscc) {
vec_free(cond_start);
vec_free(cond_edges);
vec_free(indeg);
vec_free(queue);
vec_free(order);
return false;
}
/* 按 SCC 顺序展开节点;SCC 内按节点 id 升序。 */
spl_cfg_index_vec_t scc_start;
spl_cfg_index_vec_t scc_nodes;
vec_init(scc_start);
vec_init(scc_nodes);
for (usize i = 0; i < nscc + 2; ++i)
vec_push(scc_start, 0);
for (usize v = 1; v < n; ++v)
vec_at(scc_start, vec_at(cfg->scc, v) + 1) += 1;
for (usize i = 1; i <= nscc + 1; ++i)
vec_at(scc_start, i) += vec_at(scc_start, i - 1);
for (usize i = 0; i < n; ++i)
vec_push(scc_nodes, 0);
spl_cfg_index_vec_t fill;
vec_init(fill);
for (usize i = 0; i < nscc + 1; ++i)
vec_push(fill, vec_at(scc_start, i));
for (usize v = 1; v < n; ++v) {
usize s = vec_at(cfg->scc, v);
vec_at(scc_nodes, vec_at(fill, s)++) = v;
}
vec_free(fill);
cfg->topo.size = 0;
for (usize i = 0; i < vec_size(order); ++i) {
usize s = vec_at(order, i);
usize begin = vec_at(scc_start, s);
usize end = vec_at(scc_start, s + 1);
for (usize k = begin; k < end; ++k)
vec_push(cfg->topo, vec_at(scc_nodes, k));
}
vec_free(scc_start);
vec_free(scc_nodes);
vec_free(cond_start);
vec_free(cond_edges);
vec_free(indeg);
vec_free(queue);
vec_free(order);
cfg->topo_done = true;
return true;
}
bool spl_cfg_topo(spl_cfg_t *cfg) { return cfg_topo_impl(cfg); }
bool spl_cfg_closure(spl_cfg_t *cfg, spl_cfg_node_t root, spl_cfg_node_vec_t *out) {
if (!cfg || !out || !spl_cfg_finalize(cfg))
return false;
usize n = vec_size(cfg->nodes);
if (!root || root >= n)
return false;
spl_cfg_index_vec_t visited;
spl_cfg_index_vec_t stack;
vec_init(visited);
vec_init(stack);
for (usize i = 0; i < n; ++i)
vec_push(visited, 0);
vec_at(visited, root) = 1;
vec_push(stack, root);
while (vec_size(stack) > 0) {
usize u = vec_pop(stack);
vec_push(*out, u);
usize begin = vec_at(cfg->out_start, u);
usize end = vec_at(cfg->out_start, u + 1);
for (usize i = begin; i < end; ++i) {
usize ei = vec_at(cfg->out_edges, i);
usize w = vec_at(cfg->edges, ei).to;
if (!vec_at(visited, w)) {
vec_at(visited, w) = 1;
vec_push(stack, w);
}
}
}
vec_free(visited);
vec_free(stack);
return true;
}
void spl_cfg_dump(const spl_cfg_t *cfg, FILE *out) {
if (!cfg || !out)
return;
fprintf(out, "cfg nodes=%zu edges=%zu\n", vec_size(cfg->nodes) - 1, vec_size(cfg->edges));
for (usize i = 1; i < vec_size(cfg->nodes); ++i) {
const spl_cfg_node_info_t *info = &vec_at(cfg->nodes, i);
fprintf(out, " node %zu %s", i, spl_cfg_node_kind_name(info->kind));
if (info->name)
fprintf(out, " %s", info->name);
if (info->user)
fprintf(out, " user=%zu", info->user);
if (vec_size(cfg->scc) > i)
fprintf(out, " scc=%zu", vec_at(cfg->scc, i));
fprintf(out, "\n");
}
for (usize i = 0; i < vec_size(cfg->edges); ++i) {
const spl_cfg_edge_t *e = &vec_at(cfg->edges, i);
fprintf(out, " edge %zu -> %zu %s\n", e->from, e->to, spl_cfg_edge_kind_name(e->kind));
}
if (vec_size(cfg->topo) > 0) {
fprintf(out, " topo:");
for (usize i = 0; i < vec_size(cfg->topo); ++i)
fprintf(out, " %zu", vec_at(cfg->topo, i));
fprintf(out, "\n");
}
}
+104
View File
@@ -0,0 +1,104 @@
#include "spl_cfg_ir.h"
#include <stdlib.h>
#include <string.h>
bool spl_cfg_ir_build(spl_cfg_t *cfg, const spl_ir_t *ir, spl_ir_func_ref_t fid,
spl_cfg_node_t *entry) {
if (!cfg || !ir || !fid || !entry)
return false;
spl_ir_func_t *f = spl_ir_func((spl_ir_t *)ir, fid);
if (!f)
return false;
usize n = vec_size(f->nodes);
if (n <= 1)
return false;
unsigned char *starts = calloc(n, 1);
spl_cfg_node_t *block_of = calloc(n, sizeof(*block_of));
spl_cfg_node_t *block_nodes = calloc(n, sizeof(*block_nodes));
if (!starts || !block_of || !block_nodes) {
free(starts);
free(block_of);
free(block_nodes);
return false;
}
starts[1] = 1;
for (usize i = 1; i < n; ++i) {
spl_ir_node_t *node = &vec_at(f->nodes, i);
if (node->kind == SPL_IR_CONTROL_BR) {
if (node->control_br.true_label > 0 && node->control_br.true_label < n)
starts[node->control_br.true_label] = 1;
if (node->control_br.false_label > 0 && node->control_br.false_label < n)
starts[node->control_br.false_label] = 1;
} else if (node->kind == SPL_IR_CONTROL_JMP) {
if (node->control_jmp.label > 0 && node->control_jmp.label < n)
starts[node->control_jmp.label] = 1;
}
}
usize nblocks = 0;
for (usize i = 1; i < n; ++i) {
if (!starts[i])
continue;
spl_cfg_node_info_t info = {0};
info.kind = SPL_CFG_NODE_BLOCK;
info.name = f->name;
info.user = i;
spl_cfg_node_t b = spl_cfg_add_node(cfg, info);
block_of[i] = b;
block_nodes[nblocks++] = b;
if (nblocks == 1)
*entry = b;
}
/* 每个节点归属到最近的、以某个 start 开始的 block。 */
usize bi = 0;
for (usize i = 1; i < n; ++i) {
if (i != 1 && starts[i])
bi += 1;
block_of[i] = block_nodes[bi];
}
spl_cfg_node_info_t exit_info = {0};
exit_info.kind = SPL_CFG_NODE_EXIT;
exit_info.name = f->name;
spl_cfg_node_t exit_node = spl_cfg_add_node(cfg, exit_info);
for (usize k = 0; k < nblocks; ++k) {
usize end = (k + 1 < nblocks)
? (usize)spl_cfg_node_info(cfg, block_nodes[k + 1])->user
: n;
usize last = end - 1;
spl_ir_node_t *term = &vec_at(f->nodes, last);
if (term->kind == SPL_IR_CONTROL_BR) {
usize tl = term->control_br.true_label;
usize fl = term->control_br.false_label;
if (tl > 0 && tl < n && block_of[tl])
spl_cfg_add_edge(cfg, block_nodes[k], block_of[tl], SPL_CFG_EDGE_BR_TRUE);
if (fl > 0 && fl < n && block_of[fl])
spl_cfg_add_edge(cfg, block_nodes[k], block_of[fl], SPL_CFG_EDGE_BR_FALSE);
} else if (term->kind == SPL_IR_CONTROL_JMP) {
usize tl = term->control_jmp.label;
if (tl > 0 && tl < n && block_of[tl])
spl_cfg_add_edge(cfg, block_nodes[k], block_of[tl], SPL_CFG_EDGE_JMP);
} else if (term->kind == SPL_IR_CONTROL_RET || term->kind == SPL_IR_CONTROL_TRAP ||
term->kind == SPL_IR_CONTROL_UNREACHABLE) {
spl_cfg_add_edge(cfg, block_nodes[k], exit_node, SPL_CFG_EDGE_JMP);
} else {
if (k + 1 < nblocks)
spl_cfg_add_edge(cfg, block_nodes[k], block_nodes[k + 1], SPL_CFG_EDGE_JMP);
else
spl_cfg_add_edge(cfg, block_nodes[k], exit_node, SPL_CFG_EDGE_JMP);
}
}
free(starts);
free(block_of);
free(block_nodes);
return spl_cfg_finalize(cfg);
}
+110 -88
View File
@@ -1,13 +1,15 @@
/* splc0.c - SPL compiler CLI (stage 1, 引导用)
/* splc1.c - SPL compiler CLI (stage 1, 引导用)
*
* splc0 --dump tokens|ast|sema|ir|vm <file> dump 前端产物
* splc0 <in> <out> 编译
* splc1 [--dump <none|lex|ast|sema|ir|vm|c>] [-g] [--opt] <in> <out>
*/
#define __SCC_LOG_IMPL_IMPORT_SRC__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#define SCC_ARGPARSE_IMPLEMENTATION
#define SCC_OPTPARSER_IMPLEMENTATION
#include "nob/argparse.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ir_opt.h"
@@ -18,7 +20,10 @@
#include "spl_diag.h"
#include "spl_ir2c.h"
#include "spl_ir2vm.h"
#include "spl_ir_link.h"
#include "spl_lexer.h"
#include "spl_meta.h"
#include "spl_module.h"
#include "spl_parser.h"
#include "spl_sema.h"
#include "spl_tok.h"
@@ -47,10 +52,17 @@ typedef struct {
spl_driver_module_vec_t modules;
MAP(const char *, usize) path_to_idx;
spl_module_registry_t module_registry;
spl_diag_t *diag;
} spl_driver_t;
static spl_module_id_t driver_register_module(spl_driver_t *d, spl_ast_t *ast, const char *path,
spl_diag_t *diag) {
return spl_module_register(&d->module_registry, ast, path, spl_module_declared_name(ast),
diag);
}
static char *read_file(const char *path, long *out_len) {
FILE *f = fopen(path, "rb");
if (!f) {
@@ -217,6 +229,8 @@ static spl_ast_t *driver_load(void *user, const char *from_fname, const char *pa
vec_at(d->modules, idx).ast = ast;
vec_at(d->modules, idx).src = src;
if (!driver_register_module(d, ast, key, diag))
return NULL;
return ast;
}
@@ -234,6 +248,7 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_ast_init(&drv.main_ast, &drv.main_toks);
map_init(drv.path_to_idx, MAP_HASH_STR, MAP_CMP_STR);
vec_init(drv.modules);
spl_module_registry_init(&drv.module_registry);
int rc = 0;
@@ -243,6 +258,7 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
dump_tokens(drv.main_toks);
free(drv.main_path);
map_free(drv.path_to_idx);
spl_module_registry_drop(&drv.module_registry);
spl_diag_drop(&diag);
return 0;
}
@@ -251,8 +267,10 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_lang_type_t lang_type;
spl_layout_target_t layout_target;
spl_layout_t layout;
spl_scope_t scope;
spl_namespace_t ns;
spl_sema_t sema;
spl_meta_t *meta = NULL;
spl_ir_link_t *ir_link = NULL;
spl_ast2ir_t a2ir;
spl_ir_builder_t ir_builder;
spl_ir2vm_t ir2vm;
@@ -277,9 +295,17 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
goto cleanup;
}
if (!driver_register_module(&drv, &drv.main_ast, drv.main_path, &diag)) {
spl_diag_summary(&diag);
rc = 1;
goto cleanup;
}
spl_attr_init(&attr);
attr_ok = 1;
spl_lang_type_init(&lang_type);
spl_ir_builder_init(&ir_builder);
irb_ok = 1;
spl_lang_type_init(&lang_type, ir_builder.ir.types);
lang_type_ok = 1;
/* 目标描述符:剥离目标机器细节,layout 是 size/align/offset 的唯一来源。 */
@@ -290,10 +316,16 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_layout_init(&layout, &layout_target);
layout_ok = 1;
spl_scope_init(&scope);
spl_ns_init(&ns);
scope_ok = 1;
spl_sema_init(&sema, &drv.main_ast, &lang_type, &layout, &scope, &attr);
spl_sema_init(&sema, &drv.main_ast, &lang_type, &layout, &ns, &attr);
sema.modules = &drv.module_registry;
sema.ir = &ir_builder.ir;
ir_link = spl_ir_link_create(&ir_builder.ir, &sema);
sema.ir_link = ir_link;
meta = spl_meta_create(&sema);
sema.meta = meta;
sema_ok = 1;
spl_module_loader_t loader = {.load = driver_load, .user = &drv};
sema.loader = &loader;
@@ -318,8 +350,6 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
for (usize i = 0; i < vec_size(drv.modules); ++i)
vec_push(all_asts, vec_at(drv.modules, i).ast);
spl_ir_builder_init(&ir_builder);
irb_ok = 1;
spl_ast2ir_init(&a2ir, &ir_builder, &layout, &sema);
a2ir_ok = 1;
spl_diag_set_stage(&diag, SPL_STAGE_AST2IR);
@@ -335,18 +365,18 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
spl_ir_opt(&ir_builder.ir, &attr);
if (dump == DUMP_IR) {
spl_ir_dump(&ir_builder.ir, &lang_type.ir, &attr);
spl_ir_dump(&ir_builder.ir, &attr);
goto cleanup;
}
/* 类型已全部就绪:解析 layout,供 ir2vm/ir2c 的 size/align/offset 使用。 */
spl_layout_resolve(&layout, &lang_type.ir);
spl_layout_resolve(&layout, ir_builder.ir.types);
/* C 后端:IR -> C99 写入缓冲,再落盘,不经 VM。 */
if (dump == DUMP_C) {
spl_ir2c_buf_t cbuf;
vec_init(cbuf);
bool cok = spl_ir2c_run(&a2ir.ir->ir, &lang_type.ir, &layout, &attr, &cbuf);
bool cok = spl_ir2c_run(&a2ir.ir->ir, &layout, &attr, &cbuf);
FILE *cf = fopen(outpath, "wb");
if (!cf) {
LOG_FATAL("cannot open C output file `%s`", outpath);
@@ -363,7 +393,7 @@ static int compile_spl(const char *src, const char *fname, const char *outpath,
goto cleanup;
}
spl_ir2vm_init(&ir2vm, &a2ir.ir->ir, &lang_type.ir, &layout, &attr);
spl_ir2vm_init(&ir2vm, &a2ir.ir->ir, &layout, &attr);
ir2vm_ok = 1;
spl_diag_set_stage(&diag, SPL_STAGE_IR2VM);
ir2vm.diag = &diag;
@@ -390,16 +420,18 @@ cleanup:
spl_ir2vm_drop(&ir2vm);
if (a2ir_ok)
spl_ast2ir_drop(&a2ir);
if (irb_ok)
spl_ir_builder_drop(&ir_builder);
spl_meta_destroy(meta);
if (sema_ok)
spl_sema_drop(&sema);
if (scope_ok)
spl_scope_drop(&scope);
if (layout_ok)
spl_layout_drop(&layout);
spl_ir_link_destroy(ir_link);
if (lang_type_ok)
spl_lang_type_drop(&lang_type);
if (layout_ok)
spl_layout_drop(&layout);
if (irb_ok)
spl_ir_builder_drop(&ir_builder);
if (scope_ok)
spl_ns_drop(&ns);
if (attr_ok)
spl_attr_drop(&attr);
@@ -416,86 +448,76 @@ cleanup:
vec_free(drv.modules);
/* map 的 key 是 module 里 strdup 出的 abs_path,已随 module 释放 */
map_free(drv.path_to_idx);
spl_module_registry_drop(&drv.module_registry);
free(drv.main_path);
spl_diag_drop(&diag);
return rc;
}
typedef struct {
const char *in;
const char *out;
int dump_choice;
cbool gen_debug;
cbool opt;
} splc1_cli_t;
/* 顺序必须与 dump_t 一致:choices 存的是下标,这里直接当下标用。 */
static const char *DUMP_MODE_NAMES[] = {"none", "lex", "ast", "sema", "ir", "vm", "c"};
static void add_bool_opt(scc_argparse_cmd_t *cmd, char sn, const char *ln, const char *desc,
cbool *store) {
scc_argparse_opt_t opt;
scc_argparse_opt_init(&opt, sn, ln, desc);
scc_argparse_spec_setup_bool(&opt.spec, store);
scc_argparse_cmd_add_opt(cmd, &opt);
}
static void add_arg_string(scc_argparse_cmd_t *cmd, const char *name, const char *desc,
const char **store, cbool required) {
scc_argparse_arg_t arg;
scc_argparse_arg_init(&arg, name, desc);
scc_argparse_spec_setup_string(&arg.spec, store);
arg.spec.flag_required = required;
scc_argparse_cmd_add_arg(cmd, &arg);
}
int main(int argc, char **argv) {
if (argc < 2) {
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
return 1;
}
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) {
LOG_INFO("splc0 <in> <out> compile (.spl -> .sir, stage B)");
LOG_INFO("splc0 --dump <flags> <file> dump: lex,ast,sema,ir,vm,none");
return 0;
}
int opt = 0;
for (int ai = 1; ai < argc; ai++)
if (strcmp(argv[ai], "--opt") == 0)
opt = 1;
splc1_cli_t cli = {0};
cli.dump_choice = DUMP_NONE;
int argi = 1;
if (argi >= argc) {
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
return 1;
}
scc_argparse_t parser;
scc_argparse_init(&parser, "splc1", "The first spl compiler.");
scc_argparse_cmd_t *root = scc_argparse_get_root(&parser);
dump_t dump = DUMP_NONE;
if (strcmp(argv[argi], "--dump") == 0) {
if (argc < argi + 3) {
LOG_INFO("splc0: --dump need <flags> <file>");
return 1;
}
scc_argparse_opt_t dump_opt;
scc_argparse_opt_init(&dump_opt, 0, "dump", "dump a front-end product");
scc_argparse_spec_setup_choices(&dump_opt.spec, DUMP_MODE_NAMES,
(int)(sizeof DUMP_MODE_NAMES / sizeof DUMP_MODE_NAMES[0]),
&cli.dump_choice);
scc_argparse_opt_set_group(&dump_opt, "Dump");
scc_argparse_cmd_add_opt(root, &dump_opt);
const char *flags = argv[argi + 1];
if (strcmp(flags, "lex") == 0) {
dump = DUMP_TOKEN;
} else if (strcmp(flags, "ast") == 0) {
dump = DUMP_AST;
} else if (strcmp(flags, "sema") == 0) {
dump = DUMP_SEMA;
} else if (strcmp(flags, "ir") == 0) {
dump = DUMP_IR;
} else if (strcmp(flags, "vm") == 0) {
dump = DUMP_VM;
} else if (strcmp(flags, "c") == 0) {
dump = DUMP_C;
} else if (strcmp(flags, "none") == 0) {
dump = DUMP_NONE;
} else {
LOG_FATAL("splc0: --dump takes one of lex|ast|sema|ir|vm|c|none, got `%s`", flags);
return 1;
}
argi += 2;
}
/* splc0 [-g] <in> <out> */
if (argc < argi + 2) {
LOG_FATAL("Usage: splc0 <in> <out> [-g] or splc0 --dump <flags> <file>\n");
return 1;
}
int gen_debug = 0;
while (argi < argc - 1) {
if (strcmp(argv[argi], "-g") == 0) {
gen_debug = 1;
argi++;
} else if (strcmp(argv[argi], "--opt") == 0) {
opt = 1;
argi++;
} else {
break;
}
}
if (argc < argi + 2) {
LOG_FATAL("Usage: splc0 <in> <out> [-g] [--opt] or splc0 --dump <flags> <file>\n");
return 1;
add_bool_opt(root, 'g', NULL, "emit debug info", &cli.gen_debug);
add_bool_opt(root, 0, "opt", "enable IR/bytecode optimizations", &cli.opt);
add_arg_string(root, "in", "source file", &cli.in, true);
add_arg_string(root, "out", "output file", &cli.out, true);
int rc = scc_argparse_parse(&parser, argc, (const char **)argv);
if (parser.out.count > 0)
fwrite(parser.out.items, 1, parser.out.count, stdout);
if (rc != SCC_ARGPARSE_ERR_NONE) {
scc_argparse_drop(&parser);
return rc == SCC_ARGPARSE_ERR_PNT_DEFAULT ? 0 : 1;
}
scc_argparse_drop(&parser);
long len;
char *src = read_file(argv[argi], &len);
char *src = read_file(cli.in, &len);
if (!src)
return 1;
int rc = compile_spl(src, argv[argi], argv[argi + 1], gen_debug, dump, opt);
rc = compile_spl(src, cli.in, cli.out, cli.gen_debug, (dump_t)cli.dump_choice, cli.opt);
free(src);
return rc;
}
+407
View File
@@ -0,0 +1,407 @@
#include "spl_exec.h"
#include <stdlib.h>
#include <string.h>
typedef struct {
spl_exec_unit_key_t key;
spl_exec_unit_t *unit;
bool loaded;
} spl_exec_unit_entry_t;
typedef VEC(spl_exec_unit_entry_t) spl_exec_unit_entry_vec_t;
typedef struct {
spl_ir_func_ref_t root;
spl_exec_phase_t phase;
usize viewpoint;
usize generation;
spl_exec_plan_t plan;
} spl_exec_plan_entry_t;
typedef VEC(spl_exec_plan_entry_t) spl_exec_plan_entry_vec_t;
typedef struct {
spl_exec_unit_key_t key;
usize generation;
usize nargs;
usize *args;
usize result;
} spl_exec_result_entry_t;
typedef VEC(spl_exec_result_entry_t) spl_exec_result_entry_vec_t;
struct spl_exec {
spl_ir_t *ir;
spl_layout_t *layout;
const spl_exec_frontend_t *frontend;
const spl_exec_backend_t *backend;
spl_exec_phase_t phase;
usize viewpoint;
usize generation;
spl_exec_unit_entry_vec_t units;
spl_exec_plan_entry_vec_t plans;
spl_exec_result_entry_vec_t results;
VEC(spl_exec_host_t) hosts;
spl_exec_stats_t stats;
};
static bool unit_key_eq(const spl_exec_unit_key_t *a, const spl_exec_unit_key_t *b) {
return a->callee == b->callee && a->phase == b->phase && a->viewpoint == b->viewpoint &&
a->specialization == b->specialization;
}
static bool plan_key_eq(const spl_exec_plan_entry_t *e, spl_ir_func_ref_t root,
spl_exec_phase_t phase, usize viewpoint, usize generation) {
return e->root == root && e->phase == phase && e->viewpoint == viewpoint &&
e->generation == generation;
}
static void plan_clone(spl_exec_plan_t *dst, const spl_exec_plan_t *src) {
dst->root = src->root;
vec_init(dst->order);
for (usize i = 0; i < vec_size(src->order); ++i)
vec_push(dst->order, vec_at(src->order, i));
}
void spl_exec_plan_drop(spl_exec_plan_t *plan) {
if (!plan)
return;
vec_free(plan->order);
memset(plan, 0, sizeof(*plan));
}
static void exec_unload_unit(spl_exec_t *exec, spl_exec_unit_entry_t *entry) {
if (!entry->unit)
return;
if (exec->backend && exec->backend->unload)
exec->backend->unload(exec, entry->unit);
free(entry->unit);
entry->unit = NULL;
entry->loaded = false;
}
spl_exec_t *spl_exec_create(spl_ir_t *ir, spl_layout_t *layout,
const spl_exec_frontend_t *frontend,
const spl_exec_backend_t *backend) {
spl_exec_t *exec = calloc(1, sizeof(*exec));
if (!exec)
return NULL;
exec->ir = ir;
exec->layout = layout;
exec->frontend = frontend;
exec->backend = backend;
exec->phase = SPL_EXEC_PHASE_META;
exec->viewpoint = 0;
exec->generation = 1;
vec_init(exec->units);
vec_init(exec->plans);
vec_init(exec->results);
vec_init(exec->hosts);
return exec;
}
void spl_exec_destroy(spl_exec_t *exec) {
if (!exec)
return;
for (usize i = 0; i < vec_size(exec->units); ++i)
exec_unload_unit(exec, &vec_at(exec->units, i));
vec_free(exec->units);
for (usize i = 0; i < vec_size(exec->plans); ++i)
spl_exec_plan_drop(&vec_at(exec->plans, i).plan);
vec_free(exec->plans);
for (usize i = 0; i < vec_size(exec->results); ++i)
free(vec_at(exec->results, i).args);
vec_free(exec->results);
vec_free(exec->hosts);
free(exec);
}
void spl_exec_set_phase(spl_exec_t *exec, spl_exec_phase_t phase, usize viewpoint) {
if (!exec)
return;
exec->phase = phase;
exec->viewpoint = viewpoint;
}
static void exec_flush(spl_exec_t *exec) {
for (usize i = 0; i < vec_size(exec->units); ++i)
exec_unload_unit(exec, &vec_at(exec->units, i));
exec->units.size = 0;
for (usize i = 0; i < vec_size(exec->plans); ++i)
spl_exec_plan_drop(&vec_at(exec->plans, i).plan);
exec->plans.size = 0;
for (usize i = 0; i < vec_size(exec->results); ++i)
free(vec_at(exec->results, i).args);
exec->results.size = 0;
}
void spl_exec_bump_generation(spl_exec_t *exec) {
if (!exec)
return;
exec_flush(exec);
exec->generation += 1;
}
usize spl_exec_generation(const spl_exec_t *exec) { return exec ? exec->generation : 0; }
const spl_exec_stats_t *spl_exec_stats_view(const spl_exec_t *exec) {
return exec ? &exec->stats : NULL;
}
const spl_exec_frontend_t *spl_exec_frontend_of(const spl_exec_t *exec) {
return exec ? exec->frontend : NULL;
}
const spl_exec_backend_t *spl_exec_backend_of(const spl_exec_t *exec) {
return exec ? exec->backend : NULL;
}
const spl_ir_t *spl_exec_ir(const spl_exec_t *exec) {
return exec ? exec->ir : NULL;
}
spl_layout_t *spl_exec_layout(const spl_exec_t *exec) {
return exec ? exec->layout : NULL;
}
const spl_exec_host_t *spl_exec_find_host(spl_exec_t *exec, const char *name) {
if (!exec || !name)
return NULL;
for (usize i = 0; i < vec_size(exec->hosts); ++i) {
spl_exec_host_t *host = &vec_at(exec->hosts, i);
if (host->name && strcmp(host->name, name) == 0)
return host;
}
return NULL;
}
bool spl_exec_register_host(spl_exec_t *exec, const spl_exec_host_t *host) {
if (!exec || !host || !host->name || !host->fn)
return false;
if (spl_exec_find_host(exec, host->name))
return false;
vec_push(exec->hosts, *host);
return true;
}
static spl_exec_unit_entry_t *exec_find_unit(spl_exec_t *exec,
const spl_exec_unit_key_t *key) {
for (usize i = 0; i < vec_size(exec->units); ++i) {
spl_exec_unit_entry_t *entry = &vec_at(exec->units, i);
if (unit_key_eq(&entry->key, key))
return entry;
}
return NULL;
}
static spl_exec_unit_entry_t *exec_compile_unit(spl_exec_t *exec,
const spl_exec_unit_key_t *key) {
spl_exec_unit_entry_t *existing = exec_find_unit(exec, key);
if (existing) {
exec->stats.unit_cache_hits += 1;
return existing;
}
if (!exec->frontend || !exec->frontend->compile)
return NULL;
if (exec->frontend->ready && !exec->frontend->ready(exec, key))
return NULL;
spl_exec_unit_t *unit = calloc(1, sizeof(*unit));
if (!unit)
return NULL;
unit->key = *key;
if (!exec->frontend->compile(exec, key, unit)) {
free(unit);
return NULL;
}
spl_exec_unit_entry_t entry = {.key = *key, .unit = unit, .loaded = false};
vec_push(exec->units, entry);
exec->stats.unit_compiles += 1;
return &vec_at(exec->units, vec_size(exec->units) - 1);
}
static bool fn_vec_contains(const spl_ir_func_ref_vec_t *v, spl_ir_func_ref_t fn) {
for (usize i = 0; i < vec_size(*v); ++i) {
if (vec_at(*v, i) == fn)
return true;
}
return false;
}
static bool plan_visit(spl_exec_t *exec, spl_ir_func_ref_t fn, spl_ir_func_ref_vec_t *visited,
spl_ir_func_ref_vec_t *order) {
if (fn_vec_contains(visited, fn))
return true;
if (!spl_ir_func(exec->ir, fn))
return false;
vec_push(*visited, fn);
spl_exec_unit_key_t key = {
.callee = fn,
.phase = exec->phase,
.viewpoint = exec->viewpoint,
.specialization = 0,
};
if (!exec_compile_unit(exec, &key))
return false;
spl_ir_func_ref_vec_t callees;
vec_init(callees);
spl_ir_func_callees(exec->ir, fn, &callees);
for (usize i = 0; i < vec_size(callees); ++i) {
if (!plan_visit(exec, vec_at(callees, i), visited, order)) {
vec_free(callees);
return false;
}
}
vec_free(callees);
vec_push(*order, fn);
return true;
}
bool spl_exec_plan_build(spl_exec_t *exec, spl_ir_func_ref_t root, spl_exec_plan_t *out) {
if (!exec || !exec->ir || !out || !spl_ir_func(exec->ir, root))
return false;
memset(out, 0, sizeof(*out));
for (usize i = 0; i < vec_size(exec->plans); ++i) {
spl_exec_plan_entry_t *entry = &vec_at(exec->plans, i);
if (plan_key_eq(entry, root, exec->phase, exec->viewpoint, exec->generation)) {
plan_clone(out, &entry->plan);
exec->stats.plan_cache_hits += 1;
return true;
}
}
spl_exec_plan_t plan = {.root = root};
vec_init(plan.order);
spl_ir_func_ref_vec_t visited;
vec_init(visited);
if (!plan_visit(exec, root, &visited, &plan.order)) {
vec_free(visited);
spl_exec_plan_drop(&plan);
return false;
}
vec_free(visited);
spl_exec_plan_entry_t entry = {
.root = root,
.phase = exec->phase,
.viewpoint = exec->viewpoint,
.generation = exec->generation,
.plan = plan,
};
vec_push(exec->plans, entry);
exec->stats.plan_builds += 1;
plan_clone(out, &plan);
return true;
}
bool spl_exec_compile_plan(spl_exec_t *exec, spl_exec_plan_t *plan) {
if (!exec || !plan)
return false;
for (usize i = 0; i < vec_size(plan->order); ++i) {
spl_ir_func_ref_t fn = vec_at(plan->order, i);
spl_exec_unit_key_t key = {
.callee = fn,
.phase = exec->phase,
.viewpoint = exec->viewpoint,
.specialization = 0,
};
if (!exec_compile_unit(exec, &key))
return false;
spl_exec_unit_entry_t *entry = exec_find_unit(exec, &key);
if (!entry || !entry->unit || !exec->backend || !exec->backend->load)
return false;
if (!entry->loaded) {
if (!exec->backend->load(exec, entry->unit))
return false;
entry->loaded = true;
}
}
return true;
}
static bool exec_unit_is_pure(spl_exec_t *exec, const spl_exec_unit_key_t *key) {
return exec->frontend && exec->frontend->is_pure && exec->frontend->is_pure(exec, key);
}
static bool args_equal(const usize *a, usize nargs, const usize *b) {
if (nargs == 0)
return true;
return a && b && memcmp(a, b, nargs * sizeof(*a)) == 0;
}
static usize *args_clone(const usize *args, usize nargs) {
if (nargs == 0)
return NULL;
usize *copy = malloc(nargs * sizeof(*copy));
if (!copy)
return NULL;
memcpy(copy, args, nargs * sizeof(*copy));
return copy;
}
bool spl_exec_execute_plan(spl_exec_t *exec, const spl_exec_plan_t *plan, const usize *args,
usize nargs, usize *out) {
if (!exec || !plan || !out)
return false;
spl_exec_unit_key_t key = {
.callee = plan->root,
.phase = exec->phase,
.viewpoint = exec->viewpoint,
.specialization = 0,
};
spl_exec_unit_entry_t *entry = exec_find_unit(exec, &key);
if (!entry || !entry->unit)
return false;
if (exec_unit_is_pure(exec, &key)) {
for (usize i = 0; i < vec_size(exec->results); ++i) {
spl_exec_result_entry_t *cached = &vec_at(exec->results, i);
if (cached->generation != exec->generation)
continue;
if (!unit_key_eq(&cached->key, &key))
continue;
if (cached->nargs != nargs || !args_equal(cached->args, nargs, args))
continue;
*out = cached->result;
exec->stats.result_cache_hits += 1;
return true;
}
}
usize result = 0;
if (!exec->backend->invoke(exec, entry->unit, args, nargs, &result))
return false;
exec->stats.invokes += 1;
*out = result;
if (exec_unit_is_pure(exec, &key)) {
spl_exec_result_entry_t cached = {
.key = key,
.generation = exec->generation,
.nargs = nargs,
.args = args_clone(args, nargs),
.result = result,
};
vec_push(exec->results, cached);
}
return true;
}
bool spl_exec_run(spl_exec_t *exec, spl_ir_func_ref_t root, const usize *args, usize nargs,
usize *out) {
spl_exec_plan_t plan;
if (!spl_exec_plan_build(exec, root, &plan))
return false;
bool ok = spl_exec_compile_plan(exec, &plan) && spl_exec_execute_plan(exec, &plan, args, nargs, out);
spl_exec_plan_drop(&plan);
return ok;
}
+109
View File
@@ -0,0 +1,109 @@
#include "spl_exec_frontend.h"
#include "spl_ast2ir.h"
#include "spl_ir.h"
#include <stdlib.h>
struct spl_exec_frontend_ctx {
spl_sema_t *sema;
spl_ir_link_t *link;
spl_ir_builder_t ir;
spl_ast2ir_t a2ir;
bool ir_ok;
bool a2ir_ok;
spl_exec_frontend_t vtable;
};
spl_exec_frontend_ctx_t *spl_exec_frontend_create(spl_sema_t *sema) {
if (!sema)
return NULL;
spl_exec_frontend_ctx_t *ctx = calloc(1, sizeof(*ctx));
if (!ctx)
return NULL;
ctx->sema = sema;
spl_ir_builder_init_shared(&ctx->ir, sema->type->ir_types);
ctx->ir_ok = true;
ctx->link = spl_ir_link_create(&ctx->ir.ir, sema);
if (!ctx->link) {
spl_ir_builder_drop(&ctx->ir);
free(ctx);
return NULL;
}
spl_ast2ir_init(&ctx->a2ir, &ctx->ir, sema->layout, sema);
ctx->a2ir.link = ctx->link;
ctx->a2ir_ok = true;
ctx->a2ir.mode = SPL_AST2IR_EXEC;
ctx->a2ir.diag = sema->diag;
ctx->vtable.ready = NULL;
ctx->vtable.compile = NULL;
ctx->vtable.is_pure = NULL;
ctx->vtable.user = ctx;
return ctx;
}
void spl_exec_frontend_destroy(spl_exec_frontend_ctx_t *ctx) {
if (!ctx)
return;
if (ctx->a2ir_ok)
spl_ast2ir_drop(&ctx->a2ir);
spl_ir_link_destroy(ctx->link);
if (ctx->ir_ok)
spl_ir_builder_drop(&ctx->ir);
free(ctx);
}
const spl_ir_t *spl_exec_frontend_ir(spl_exec_frontend_ctx_t *ctx) {
return ctx ? &ctx->ir.ir : NULL;
}
spl_ir_link_t *spl_exec_frontend_link(spl_exec_frontend_ctx_t *ctx) {
return ctx ? ctx->link : NULL;
}
static bool frontend_ready(spl_exec_t *exec, const spl_exec_unit_key_t *key) {
spl_exec_frontend_ctx_t *ctx = (spl_exec_frontend_ctx_t *)spl_exec_frontend_of(exec)->user;
usize def_id = 0;
if (!spl_ir_link_def_of_fn(ctx->link, key->callee, &def_id))
return false;
spl_def_node_t *def = spl_def_node(ctx->sema->type, def_id);
if (!def || def->kind != SPL_DEF_FN || !def->owner_ast)
return false;
spl_ast_node_t *fn = spl_ast_node(def->owner_ast, def->ast_node_ref);
return fn && fn->kind == SPL_AST_FN_DECL;
}
static bool frontend_compile(spl_exec_t *exec, const spl_exec_unit_key_t *key,
spl_exec_unit_t *out) {
spl_exec_frontend_ctx_t *ctx = (spl_exec_frontend_ctx_t *)spl_exec_frontend_of(exec)->user;
usize def_id = 0;
if (!spl_ir_link_def_of_fn(ctx->link, key->callee, &def_id))
return false;
spl_def_node_t *def = spl_def_node(ctx->sema->type, def_id);
if (!def || !def->owner_ast)
return false;
if (!spl_ast2ir_lower_fn(&ctx->a2ir, def->owner_ast, def->ast_node_ref))
return false;
if (spl_ir_link_reserve_fn(ctx->link, def_id) != key->callee)
return false;
out->state = (void *)(uintptr_t)key->callee;
return true;
}
static bool frontend_is_pure(spl_exec_t *exec, const spl_exec_unit_key_t *key) {
(void)exec;
(void)key;
return false;
}
const spl_exec_frontend_t *spl_exec_frontend_vtable(spl_exec_frontend_ctx_t *ctx) {
if (!ctx)
return NULL;
ctx->vtable.ready = frontend_ready;
ctx->vtable.compile = frontend_compile;
ctx->vtable.is_pure = frontend_is_pure;
ctx->vtable.user = ctx;
return &ctx->vtable;
}
+217
View File
@@ -0,0 +1,217 @@
#include "spl_exec_vm.h"
#include "spl_ir2vm.h"
#include "stage0/spl_vm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct spl_exec_vm_ctx {
const spl_ir_t *ir;
spl_layout_t *layout;
const spl_attr_t *attr;
spl_ir2vm_t gen;
spl_vm_t vm;
bool gen_ok;
bool vm_ok;
bool ready;
spl_exec_backend_t vtable;
};
spl_exec_vm_ctx_t *spl_exec_vm_create(const spl_ir_t *ir, spl_layout_t *layout,
const spl_attr_t *attr) {
if (!ir || !layout || !attr)
return NULL;
spl_exec_vm_ctx_t *ctx = calloc(1, sizeof(*ctx));
if (!ctx)
return NULL;
ctx->ir = ir;
ctx->layout = layout;
ctx->attr = attr;
return ctx;
}
void spl_exec_vm_destroy(spl_exec_vm_ctx_t *ctx) {
if (!ctx)
return;
if (ctx->vm_ok)
spl_vm_drop(&ctx->vm);
if (ctx->gen_ok)
spl_ir2vm_drop(&ctx->gen);
free(ctx);
}
static bool vm_load(spl_exec_t *exec, spl_exec_unit_t *unit) {
(void)exec;
(void)unit;
spl_exec_vm_ctx_t *ctx = (spl_exec_vm_ctx_t *)spl_exec_backend_of(exec)->user;
ctx->ready = false;
return true;
}
static bool vm_is_aggregate(spl_exec_vm_ctx_t *ctx, spl_ir_type_id_t tid) {
const spl_ir_type_node_t *tn = spl_ir_type_node(ctx->ir->types, tid);
if (!tn)
return false;
return tn->kind == SPL_IR_TYPE_ARRAY || tn->kind == SPL_IR_TYPE_STRUCT ||
tn->kind == SPL_IR_TYPE_UNION || tn->kind == SPL_IR_TYPE_ENUM;
}
static usize vm_type_size(spl_exec_vm_ctx_t *ctx, spl_ir_type_id_t tid) {
const spl_layout_info_t *info = spl_layout_info_of(ctx->layout, tid);
return info ? (info->size_bits + 7) / 8 : 0;
}
static spl_ir_func_t *vm_find_fn(spl_exec_vm_ctx_t *ctx, const char *name) {
if (!name)
return NULL;
for (usize i = 1; i < vec_size(ctx->ir->funcs); ++i) {
spl_ir_func_t *f = &vec_at(ctx->ir->funcs, i);
if (f->name && strcmp(f->name, name) == 0)
return f;
}
return NULL;
}
static spl_vm_val_t vm_foreign(spl_vm_t *vm, const spl_vm_call_t *call, void *user) {
spl_exec_t *exec = (spl_exec_t *)user;
spl_exec_vm_ctx_t *ctx = (spl_exec_vm_ctx_t *)spl_exec_backend_of(exec)->user;
const spl_exec_host_t *host = spl_exec_find_host(exec, call->name);
if (!host) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "compile-time host `%s` is not registered",
call->name ? call->name : "?");
vm->exit_code = 1;
return 0;
}
spl_ir_func_t *fn = vm_find_fn(ctx, call->name);
if (!fn) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host signature for `%s` not found",
call->name ? call->name : "?");
vm->exit_code = 1;
return 0;
}
const spl_ir_type_node_t *ftn = spl_ir_type_node(ctx->ir->types, fn->fn_tid);
if (!ftn || ftn->kind != SPL_IR_TYPE_FN || vec_size(ftn->fn_type.params) != call->nargs) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host signature mismatch for `%s`",
call->name ? call->name : "?");
vm->exit_code = 1;
return 0;
}
spl_exec_value_t args[16];
if (call->nargs > 16) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host argument count too large");
vm->exit_code = 1;
return 0;
}
for (usize i = 0; i < call->nargs; ++i) {
spl_ir_type_id_t pt = vec_at(ftn->fn_type.params, i);
memset(&args[i], 0, sizeof(args[i]));
args[i].type = pt;
if (vm_is_aggregate(ctx, pt)) {
usize size = vm_type_size(ctx, pt);
args[i].size = size;
args[i].mem.off = (usize)call->args[i];
args[i].mem.ptr = spl_vm_xlate(vm, call->args[i], size);
if (!args[i].mem.ptr) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host aggregate argument is invalid");
vm->exit_code = 1;
return 0;
}
} else {
args[i].bits = (uint64_t)call->args[i];
}
}
spl_exec_value_t ret = {0};
spl_ir_type_id_t ret_tid = ftn->fn_type.ret;
ret.type = ret_tid;
if (vm_is_aggregate(ctx, ret_tid)) {
usize size = vm_type_size(ctx, ret_tid);
ret.size = size;
ret.mem.off = (usize)spl_vm_mem_alloc(vm, size);
ret.mem.ptr = spl_vm_xlate(vm, (spl_vm_val_t)ret.mem.off, size);
if (!ret.mem.off || !ret.mem.ptr) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "host aggregate return is unavailable");
vm->exit_code = 1;
return 0;
}
}
if (!host->fn(exec, host->user, args, call->nargs, &ret)) {
snprintf(vm->error_msg, sizeof(vm->error_msg), "compile-time host `%s` failed",
call->name ? call->name : "?");
vm->exit_code = 1;
return 0;
}
return vm_is_aggregate(ctx, ret_tid) ? (spl_vm_val_t)ret.mem.off : (spl_vm_val_t)ret.bits;
}
static bool vm_rebuild(spl_exec_t *exec, spl_exec_vm_ctx_t *ctx) {
if (ctx->vm_ok) {
spl_vm_drop(&ctx->vm);
ctx->vm_ok = false;
}
if (ctx->gen_ok) {
spl_ir2vm_drop(&ctx->gen);
ctx->gen_ok = false;
}
spl_ir2vm_init(&ctx->gen, ctx->ir, ctx->layout, ctx->attr);
ctx->gen_ok = true;
spl_layout_resolve(ctx->layout, ctx->ir->types);
if (spl_ir2vm_run(&ctx->gen) != 0)
return false;
spl_vm_init(&ctx->vm);
ctx->vm_ok = true;
if (spl_vm_load_prog(&ctx->vm, &ctx->gen.prog) != 0)
return false;
spl_vm_set_foreign(&ctx->vm, vm_foreign, exec);
ctx->ready = true;
return true;
}
static bool vm_invoke(spl_exec_t *exec, spl_exec_unit_t *unit, const usize *args, usize nargs,
usize *out) {
spl_exec_vm_ctx_t *ctx = (spl_exec_vm_ctx_t *)spl_exec_backend_of(exec)->user;
if (!ctx->ready && !vm_rebuild(exec, ctx))
return false;
spl_ir_func_ref_t fn_ref = (spl_ir_func_ref_t)(uintptr_t)unit->state;
const spl_ir_func_t *fn = spl_ir_func((spl_ir_t *)ctx->ir, fn_ref);
if (!fn || !fn->name)
return false;
spl_vm_call_t call = {
.name = fn->name,
.args = (const spl_vm_val_t *)args,
.nargs = nargs,
.ret = 0,
};
if (spl_vm_invoke(&ctx->vm, &call) != 0)
return false;
if (ctx->vm.exit_code)
return false;
*out = (usize)call.ret;
return true;
}
static void vm_unload(spl_exec_t *exec, spl_exec_unit_t *unit) {
(void)exec;
(void)unit;
}
const spl_exec_backend_t *spl_exec_vm_vtable(spl_exec_vm_ctx_t *ctx) {
if (!ctx)
return NULL;
ctx->vtable.load = vm_load;
ctx->vtable.invoke = vm_invoke;
ctx->vtable.unload = vm_unload;
ctx->vtable.user = ctx;
return &ctx->vtable;
}
File renamed without changes.
+38 -17
View File
@@ -1,7 +1,7 @@
#ifndef __SPL_AST_H__
#define __SPL_AST_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_attr.h"
#include "spl_dbg.h"
#include "spl_tok.h"
@@ -13,7 +13,8 @@
X(SPL_AST_CONTAINER_MEMBERS, V0, container_members) \
X(SPL_AST_EXTERNAL_TAG_ITEM, V0, external_tag_item) \
X(SPL_AST_TAG_ITEM, V0, tag_item) \
X(SPL_AST_COMPTIME_DECL, V0, comptime_decl) \
X(SPL_AST_MOD_DECL, V0, mod_decl) \
X(SPL_AST_IMPORT_DECL, V0, import_decl) \
X(SPL_AST_TOP_LEVEL_BLOCK, V0, top_level_block) \
X(SPL_AST_FN_DECL, V0, fn_decl) \
X(SPL_AST_VAR_DECL, V0, var_decl) \
@@ -25,7 +26,6 @@
X(SPL_AST_STATEMENT_BREAK, V0, statement_break) \
X(SPL_AST_STATEMENT_CONTINUE, V0, statement_continue) \
X(SPL_AST_STATEMENT_DEFER, V0, statement_defer) \
X(SPL_AST_STATEMENT_COMPTIME, V0, statement_comptime) \
X(SPL_AST_STATEMENT_DECL, V0, statement_decl) \
X(SPL_AST_STATEMENT_EXPR, V0, statement_expr) \
X(SPL_AST_AGGREGATE_MEMBER, V0, aggregate_member) \
@@ -50,7 +50,7 @@
X(SPL_AST_EXPR_TUPLE, V0, tuple) \
X(SPL_AST_EXPR_ARRAY_LIT, V0, array_literal) \
X(SPL_AST_EXPR_AGGREGATE_LIT, V0, aggregate_literal) \
X(SPL_AST_EXPR_COMPTIME_CALL, V0, comptime_call) \
X(SPL_AST_EXPR_COMPILE_CALL, V0, compile_call) \
X(SPL_AST_EXPR_BLOCK, V0, block) \
X(SPL_AST_EXPR_IF, V0, if_expr) \
X(SPL_AST_EXPR_IFVAR, V0, ifvar_expr) \
@@ -66,7 +66,7 @@
X(SPL_AST_TYPE_FN, V0, type_fn) \
X(SPL_AST_TYPE_PAREN, V0, type_paren) \
X(SPL_AST_TYPE_AGGREGATE, V0, type_aggregate) \
X(SPL_AST_TYPE_COMPTIME_CALL, V0, type_comptime_call) \
X(SPL_AST_TYPE_COMPILE_CALL, V0, type_compile_call) \
X(SPL_AST_PATTERN_IDENT, V0, pattern_ident) \
X(SPL_AST_PATTERN_UNDERSCORE, V0, pattern_underscore) \
X(SPL_AST_PATTERN_DOT, V0, pattern_dot) \
@@ -143,6 +143,12 @@ typedef enum {
SPL_UNARY_OP_DEREF,
} spl_unary_op_t;
typedef enum {
SPL_FN_KIND_NORMAL,
SPL_FN_KIND_META,
SPL_FN_KIND_MACRO,
} spl_fn_kind_t;
struct spl_ast_node;
typedef struct spl_ast_node spl_ast_node_t;
typedef usize spl_ast_node_ref_t;
@@ -153,7 +159,9 @@ struct spl_ast_node {
spl_dbg_node_t dbg;
usize resolved_def_id;
usize resolved_outer_def_id;
usize resolved_lang_tid;
usize resolved_ns_id;
usize expected_lang_tid;
spl_attr_id_vec_t attrs;
@@ -164,12 +172,14 @@ struct spl_ast_node {
struct {
spl_ast_node_ref_vec_t external_tags;
spl_ast_node_ref_t module;
spl_ast_node_ref_vec_t declarations;
} container_members;
struct {
spl_ast_node_ref_vec_t tag_list;
bool is_comptime;
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
spl_fn_kind_t fn_kind;
const char *name;
spl_ast_node_ref_vec_t params;
spl_ast_node_ref_t ret_type;
@@ -177,6 +187,7 @@ struct spl_ast_node {
} fn_decl;
struct {
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
spl_ast_node_ref_t pattern;
spl_ast_node_ref_t type;
@@ -184,12 +195,14 @@ struct spl_ast_node {
} var_const_decl;
struct {
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
spl_ast_node_ref_t pattern;
spl_ast_node_ref_t type_expr;
} type_decl;
struct {
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
const char *name;
spl_ast_node_ref_t type_expr;
@@ -210,11 +223,22 @@ struct spl_ast_node {
} tag_item;
struct {
spl_ast_node_ref_t body;
} comptime_decl;
spl_ast_node_ref_vec_t decorator_list;
const char *path;
bool has_body;
spl_ast_node_ref_vec_t decls;
} mod_decl;
struct {
spl_ast_node_ref_vec_t tag_list;
spl_ast_node_ref_vec_t decorator_list;
bool is_path;
const char *path;
const char *alias;
} import_decl;
struct {
spl_ast_node_ref_vec_t decorator_list;
spl_ast_node_ref_vec_t attr_list;
spl_ast_node_ref_t block;
} top_level_block;
@@ -234,9 +258,6 @@ struct spl_ast_node {
struct {
spl_ast_node_ref_t body;
} statement_defer;
struct {
spl_ast_node_ref_t body;
} statement_comptime;
struct {
spl_ast_node_ref_t decl;
} statement_decl;
@@ -339,7 +360,9 @@ struct spl_ast_node {
struct {
const char *name;
spl_ast_node_ref_vec_t args;
} comptime_call;
} compile_call;
struct {
spl_ast_node_ref_vec_t stmts;
@@ -384,7 +407,6 @@ struct spl_ast_node {
} match_expr;
struct {
bool is_comptime;
spl_ast_node_ref_vec_t params;
spl_ast_node_ref_t ret_type;
} fn_type;
@@ -410,7 +432,6 @@ struct spl_ast_node {
} type_slice;
struct {
bool is_comptime;
spl_ast_node_ref_vec_t params;
spl_ast_node_ref_t ret_type;
} type_fn;
@@ -427,7 +448,7 @@ struct spl_ast_node {
struct {
const char *name;
spl_ast_node_ref_vec_t args;
} type_comptime_call;
} type_compile_call;
struct {
const char *name;
@@ -5,26 +5,44 @@
#include "spl_ir.h"
#include "spl_sema.h"
typedef MAP(spl_def_id_t, spl_ir_node_ref_t) spl_def2ir_map_t;
typedef MAP(spl_def_id_t, spl_ir_value_t) spl_def2ir_map_t;
typedef struct {
usize cont_blk;
usize defer_base;
const char *label;
spl_ir_node_ref_vec_t breaks;
spl_ir_node_ref_t result_slot;
spl_type_id_t result_tid;
spl_ir_value_t result_slot;
spl_ir_type_id_t result_tid;
} spl_loop_ctx_t;
typedef VEC(spl_loop_ctx_t) spl_loop_ctx_vec_t;
typedef VEC(spl_ast_node_ref_t) spl_defer_stack_t;
typedef struct {
spl_ast_t *ast;
spl_ast_node_ref_t decl;
} spl_module_init_t;
typedef VEC(spl_module_init_t) spl_module_init_vec_t;
typedef enum {
SPL_AST2IR_RUNTIME,
SPL_AST2IR_META,
SPL_AST2IR_EXEC,
} spl_ast2ir_mode_t;
struct spl_ir_link;
typedef struct {
const spl_sema_t *sema;
struct spl_ir_link *link;
spl_ir_builder_t *ir;
spl_ast_t *ast;
spl_layout_t *layout; /* 借用 splc0 的 layout */
spl_ast2ir_mode_t mode;
spl_def2ir_map_t def2ir_map;
MAP(spl_def_id_t, usize) global_map;
spl_module_init_vec_t module_inits;
spl_loop_ctx_vec_t loop_stack;
spl_defer_stack_t defer_stack;
spl_lang_type_id_t cur_ret_lang;
@@ -37,6 +55,13 @@ void spl_ast2ir_init(spl_ast2ir_t *ast2ir, spl_ir_builder_t *ir, spl_layout_t *l
const spl_sema_t *sema);
void spl_ast2ir_drop(spl_ast2ir_t *ast2ir);
/* 生成函数在 IR 中的符号名;meta 与运行期共用同一规则。 */
bool spl_ast2ir_fn_name(const spl_sema_t *sema, const spl_attr_t *attr, const spl_ast_t *ast,
const spl_ast_node_t *fn, char *out, usize cap);
/* 只 lowering 一个函数;exec 的按函数编译入口。 */
bool spl_ast2ir_lower_fn(spl_ast2ir_t *ast2ir, spl_ast_t *ast, spl_ast_node_ref_t fn_ref);
void spl_ast2ir_run(spl_ast2ir_t *ast2ir, spl_ast_ptr_vec_t ast_vec);
#endif /* __SPL_AST2IR_H__ */
@@ -1,7 +1,7 @@
#ifndef __SPL_ATTR_H__
#define __SPL_ATTR_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_mpa.h"
typedef enum {
+85
View File
@@ -0,0 +1,85 @@
#ifndef __SPL_CFG_H__
#define __SPL_CFG_H__
#include "stage0/include/utils.h"
/* 通用有向图:调用图(函数)和过程内控制流图(基本块)共用同一套算法。
node 0 是哨兵,真实节点从 1 开始。 */
typedef usize spl_cfg_node_t;
typedef usize spl_cfg_edge_ref_t;
typedef VEC(spl_cfg_node_t) spl_cfg_node_vec_t;
typedef VEC(usize) spl_cfg_index_vec_t;
typedef enum {
SPL_CFG_NODE_FN,
SPL_CFG_NODE_BLOCK,
SPL_CFG_NODE_HOST,
SPL_CFG_NODE_EXIT,
} spl_cfg_node_kind_t;
typedef enum {
SPL_CFG_EDGE_CALL,
SPL_CFG_EDGE_FUNC_REF,
SPL_CFG_EDGE_BR_TRUE,
SPL_CFG_EDGE_BR_FALSE,
SPL_CFG_EDGE_JMP,
SPL_CFG_EDGE_HOST,
} spl_cfg_edge_kind_t;
typedef struct {
spl_cfg_node_kind_t kind;
const char *name;
/* 通用 payload:调用图里是 def_id,控制流图里是 IR 节点引用。 */
usize user;
} spl_cfg_node_info_t;
typedef struct {
spl_cfg_node_t from;
spl_cfg_node_t to;
spl_cfg_edge_kind_t kind;
} spl_cfg_edge_t;
typedef struct {
VEC(spl_cfg_node_info_t) nodes;
VEC(spl_cfg_edge_t) edges;
/* CSR 邻接:out_edges[out_start[n] .. out_start[n+1]) 是边的下标。 */
spl_cfg_index_vec_t out_start;
spl_cfg_index_vec_t out_edges;
spl_cfg_index_vec_t in_start;
spl_cfg_index_vec_t in_edges;
/* 1-based SCC id;0 表示未计算。 */
spl_cfg_index_vec_t scc;
/* 拓扑序:topo[i] 是节点;边 from -> to 保证 from 在 to 之前。 */
spl_cfg_index_vec_t topo;
bool finalized;
bool scc_done;
bool topo_done;
} spl_cfg_t;
void spl_cfg_init(spl_cfg_t *cfg);
void spl_cfg_drop(spl_cfg_t *cfg);
spl_cfg_node_t spl_cfg_add_node(spl_cfg_t *cfg, spl_cfg_node_info_t info);
void spl_cfg_add_edge(spl_cfg_t *cfg, spl_cfg_node_t from, spl_cfg_node_t to,
spl_cfg_edge_kind_t kind);
const spl_cfg_node_info_t *spl_cfg_node_info(const spl_cfg_t *cfg, spl_cfg_node_t node);
usize spl_cfg_node_count(const spl_cfg_t *cfg);
/* 构建 CSR;add_node/add_edge 后内部算法会自动重建。 */
bool spl_cfg_finalize(spl_cfg_t *cfg);
/* 强连通分量;同一 SCC 内节点 scc[..] 相同。 */
bool spl_cfg_scc(spl_cfg_t *cfg);
/* 拓扑序;要求图已 finalize。 */
bool spl_cfg_topo(spl_cfg_t *cfg);
/* 从 root 出发沿所有边可达的节点(包含 root)。 */
bool spl_cfg_closure(spl_cfg_t *cfg, spl_cfg_node_t root, spl_cfg_node_vec_t *out);
const char *spl_cfg_node_kind_name(spl_cfg_node_kind_t kind);
const char *spl_cfg_edge_kind_name(spl_cfg_edge_kind_t kind);
void spl_cfg_dump(const spl_cfg_t *cfg, FILE *out);
#endif /* __SPL_CFG_H__ */
+14
View File
@@ -0,0 +1,14 @@
#ifndef __SPL_CFG_AST_H__
#define __SPL_CFG_AST_H__
#include "spl_cfg.h"
#include "spl_sema.h"
/* 从 AST/符号构建函数级调用图:
- FN 节点 user = def_id;
- CALL = 直接调用;
- FUNC_REF = 函数符号被当作值使用;
- HOST = @sap.* 等编译期 host 调用。 */
bool spl_cfg_ast_build(spl_cfg_t *cfg, spl_sema_t *sema, const spl_ast_ptr_vec_t *asts);
#endif /* __SPL_CFG_AST_H__ */
+11
View File
@@ -0,0 +1,11 @@
#ifndef __SPL_CFG_IR_H__
#define __SPL_CFG_IR_H__
#include "spl_cfg.h"
#include "spl_ir.h"
/* 从单个 IR 函数构建基本块控制流图;entry 返回入口 block 节点。 */
bool spl_cfg_ir_build(spl_cfg_t *cfg, const spl_ir_t *ir, spl_ir_func_ref_t fid,
spl_cfg_node_t *entry);
#endif /* __SPL_CFG_IR_H__ */
File renamed without changes.
@@ -1,7 +1,7 @@
#ifndef __SPL_DIAG_H__
#define __SPL_DIAG_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_dbg.h"
typedef enum {
+114
View File
@@ -0,0 +1,114 @@
#ifndef __SPL_EXEC_H__
#define __SPL_EXEC_H__
#include "spl_ir.h"
#include "spl_layout.h"
/* 编译期执行底座:unit/plan/cache/backend。
不依赖 SPL 语义;meta/macro/普通函数都只是可编译函数。 */
typedef enum {
SPL_EXEC_PHASE_MACRO,
SPL_EXEC_PHASE_SEMA,
SPL_EXEC_PHASE_META,
} spl_exec_phase_t;
typedef struct {
spl_ir_func_ref_t callee;
spl_exec_phase_t phase;
usize viewpoint;
usize specialization;
} spl_exec_unit_key_t;
typedef struct {
spl_ir_func_ref_t root;
spl_ir_func_ref_vec_t order; /* 只含 FN,callee 在前 */
} spl_exec_plan_t;
typedef struct {
spl_exec_unit_key_t key;
void *state; /* backend 私有 */
} spl_exec_unit_t;
typedef struct spl_exec spl_exec_t;
typedef struct {
bool (*ready)(spl_exec_t *exec, const spl_exec_unit_key_t *key);
bool (*compile)(spl_exec_t *exec, const spl_exec_unit_key_t *key, spl_exec_unit_t *out);
bool (*is_pure)(spl_exec_t *exec, const spl_exec_unit_key_t *key);
void *user;
} spl_exec_frontend_t;
typedef struct {
bool (*load)(spl_exec_t *exec, spl_exec_unit_t *unit);
bool (*invoke)(spl_exec_t *exec, spl_exec_unit_t *unit, const usize *args, usize nargs,
usize *out);
void (*unload)(spl_exec_t *exec, spl_exec_unit_t *unit);
void *user;
} spl_exec_backend_t;
typedef struct {
usize plan_builds;
usize plan_cache_hits;
usize unit_compiles;
usize unit_cache_hits;
usize invokes;
usize result_cache_hits;
} spl_exec_stats_t;
typedef enum {
SPL_EXEC_CAP_READ = 1u << 0,
SPL_EXEC_CAP_WRITE = 1u << 1,
SPL_EXEC_CAP_DIAG = 1u << 2,
SPL_EXEC_CAP_IO = 1u << 3,
} spl_exec_capability_t;
typedef struct {
spl_ir_type_id_t type;
usize size;
union {
uint64_t bits; /* 标量 */
struct {
usize off; /* VM 地址空间偏移;用于返回值回拷 */
void *ptr; /* 对应的宿主可写指针 */
} mem; /* 聚合 */
};
} spl_exec_value_t;
typedef bool (*spl_exec_host_fn)(spl_exec_t *exec, void *user, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret);
typedef struct {
const char *name;
usize capabilities;
spl_exec_host_fn fn;
void *user;
} spl_exec_host_t;
bool spl_exec_register_host(spl_exec_t *exec, const spl_exec_host_t *host);
const spl_exec_host_t *spl_exec_find_host(spl_exec_t *exec, const char *name);
spl_exec_t *spl_exec_create(spl_ir_t *ir, spl_layout_t *layout,
const spl_exec_frontend_t *frontend,
const spl_exec_backend_t *backend);
void spl_exec_destroy(spl_exec_t *exec);
void spl_exec_set_phase(spl_exec_t *exec, spl_exec_phase_t phase, usize viewpoint);
void spl_exec_bump_generation(spl_exec_t *exec);
usize spl_exec_generation(const spl_exec_t *exec);
const spl_exec_stats_t *spl_exec_stats_view(const spl_exec_t *exec);
const spl_exec_frontend_t *spl_exec_frontend_of(const spl_exec_t *exec);
const spl_exec_backend_t *spl_exec_backend_of(const spl_exec_t *exec);
const spl_ir_t *spl_exec_ir(const spl_exec_t *exec);
spl_layout_t *spl_exec_layout(const spl_exec_t *exec);
bool spl_exec_plan_build(spl_exec_t *exec, spl_ir_func_ref_t root, spl_exec_plan_t *out);
bool spl_exec_compile_plan(spl_exec_t *exec, spl_exec_plan_t *plan);
bool spl_exec_execute_plan(spl_exec_t *exec, const spl_exec_plan_t *plan, const usize *args,
usize nargs, usize *out);
void spl_exec_plan_drop(spl_exec_plan_t *plan);
/* 便捷入口:plan -> compile -> execute。 */
bool spl_exec_run(spl_exec_t *exec, spl_ir_func_ref_t root, const usize *args, usize nargs,
usize *out);
#endif /* __SPL_EXEC_H__ */
+17
View File
@@ -0,0 +1,17 @@
#ifndef __SPL_EXEC_FRONTEND_H__
#define __SPL_EXEC_FRONTEND_H__
#include "spl_exec.h"
#include "spl_ir.h"
#include "spl_ir_link.h"
#include "spl_sema.h"
typedef struct spl_exec_frontend_ctx spl_exec_frontend_ctx_t;
spl_exec_frontend_ctx_t *spl_exec_frontend_create(spl_sema_t *sema);
void spl_exec_frontend_destroy(spl_exec_frontend_ctx_t *ctx);
const spl_exec_frontend_t *spl_exec_frontend_vtable(spl_exec_frontend_ctx_t *ctx);
const spl_ir_t *spl_exec_frontend_ir(spl_exec_frontend_ctx_t *ctx);
spl_ir_link_t *spl_exec_frontend_link(spl_exec_frontend_ctx_t *ctx);
#endif /* __SPL_EXEC_FRONTEND_H__ */
+15
View File
@@ -0,0 +1,15 @@
#ifndef __SPL_EXEC_VM_H__
#define __SPL_EXEC_VM_H__
#include "spl_exec.h"
#include "spl_ir.h"
#include "spl_layout.h"
typedef struct spl_exec_vm_ctx spl_exec_vm_ctx_t;
spl_exec_vm_ctx_t *spl_exec_vm_create(const spl_ir_t *ir, spl_layout_t *layout,
const spl_attr_t *attr);
void spl_exec_vm_destroy(spl_exec_vm_ctx_t *ctx);
const spl_exec_backend_t *spl_exec_vm_vtable(spl_exec_vm_ctx_t *ctx);
#endif /* __SPL_EXEC_VM_H__ */
@@ -1,7 +1,7 @@
#ifndef __SPL_FOLD_H__
#define __SPL_FOLD_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
/* 通用 intrusive 哈希集合,对应 LLVM FoldingSet 的桶链部分。
- 节点表由调用方持有,节点自带 next 字段;
@@ -1,7 +1,7 @@
#ifndef __SPL_INTRIN_H__
#define __SPL_INTRIN_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_lang_type.h"
typedef enum {
@@ -54,7 +54,7 @@ typedef struct {
spl_intrin_t spl_intrin_lookup_call(const char *name);
spl_intrin_t spl_intrin_lookup_field(spl_lang_type_kind_t recv_kind, const char *field);
spl_intrin_t spl_intrin_lookup_cast(spl_type_t *type, spl_type_id_t ft, spl_type_id_t tt);
spl_intrin_t spl_intrin_lookup_cast(spl_ir_type_table_t *type, spl_ir_type_id_t ft, spl_ir_type_id_t tt);
const spl_intrin_info_t *spl_intrin_info(spl_intrin_t kind);
+263 -142
View File
@@ -1,10 +1,10 @@
#ifndef __SPL_IR_H__
#define __SPL_IR_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_attr.h"
#include "spl_dbg.h"
#include "spl_type.h"
#include "spl_ir_type.h"
/* clang-format off */
#define SPL_IR_FN_TABLE \
@@ -39,14 +39,12 @@
X(case.int2float, V0, SPL_IR_CASE_INT2FLOAT) \
X(case.float2int, V0, SPL_IR_CASE_FLOAT2INT) \
X(mem.alloca, V0, SPL_IR_MEM_ALLOCA) \
X(mem.global_alloc, V0, SPL_IR_MEM_GLOBAL_ALLOC) \
X(mem.load, V0, SPL_IR_MEM_LOAD) \
X(mem.store, V0, SPL_IR_MEM_STORE) \
X(mem.offset, V0, SPL_IR_MEM_OFFSET) \
X(mem.field, V0, SPL_IR_MEM_FIELD_PTR) \
X(mem.copy, V0, SPL_IR_MEM_COPY) \
X(mem.set, V0, SPL_IR_MEM_SET) \
X(type.const, V0, SPL_IR_TYPE_CONST) \
X(type.bitsizeof, V0, SPL_IR_TYPE_BITSIZEOF) \
X(type.sizeof, V0, SPL_IR_TYPE_SIZEOF) \
X(type.alignof, V0, SPL_IR_TYPE_ALIGNOF) \
@@ -65,6 +63,7 @@
X(control.trap, V0, SPL_IR_CONTROL_TRAP) \
X(dbg.breakpoint, V0, SPL_IR_DBG_BREAKPOINT) \
X(dbg.panic, V0, SPL_IR_DBG_PANIC) \
/* clang-format on */
typedef enum {
#ifdef X
@@ -74,12 +73,129 @@ typedef enum {
SPL_IR_FN_TABLE
#undef X
} spl_ir_kind_t;
/* clang-format on */
typedef usize spl_ir_node_ref_t; /* 0 is error */
typedef VEC(spl_ir_node_ref_t) spl_ir_node_ref_vec_t;
typedef usize spl_ir_func_ref_t; /* 0 is error */
typedef VEC(spl_ir_func_ref_t) spl_ir_func_ref_vec_t;
/* 抽象机器的值:指令结果、常量或全局实体句柄。常量按 tid 的 SPL_IR_TYPE_* 解释:
* BOOL/INT(<=64) -> int_bits,FLOAT -> float_bits,FN -> fn,
* PTR -> 仅表示 null,其余需要去重的量 -> const_id。
* GLOBAL 表示模块级全局实体的地址,载荷是 global_id。 */
typedef enum {
SPL_IR_VALUE_INST,
SPL_IR_VALUE_CONST,
SPL_IR_VALUE_GLOBAL,
} spl_ir_value_kind_t;
typedef struct {
spl_ir_value_kind_t kind;
spl_ir_type_id_t tid; /* CONST 时有效;INST 必须为 0 */
union {
spl_ir_node_ref_t inst;
uint64_t int_bits;
double float_bits;
spl_ir_func_ref_t fn;
usize global_id;
usize const_id;
};
} spl_ir_value_t;
typedef VEC(spl_ir_value_t) spl_ir_value_vec_t;
static inline spl_ir_value_t spl_ir_value_none(void) {
spl_ir_value_t v = {0};
return v;
}
static inline bool spl_ir_value_is_none(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_INST && v.inst == 0;
}
static inline spl_ir_value_t spl_ir_value_inst(spl_ir_node_ref_t ref) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_INST;
v.inst = ref;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_int(spl_ir_type_id_t tid, uint64_t bits) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.int_bits = bits;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_float(spl_ir_type_id_t tid, double bits) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.float_bits = bits;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_fn(spl_ir_type_id_t tid, spl_ir_func_ref_t fn) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.fn = fn;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_null(spl_ir_type_id_t tid) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.global_id = 0;
return v;
}
static inline spl_ir_value_t spl_ir_value_global(spl_ir_type_id_t ptr_tid, usize gid) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_GLOBAL;
v.tid = ptr_tid;
v.global_id = gid;
return v;
}
static inline spl_ir_value_t spl_ir_value_const_pool(spl_ir_type_id_t tid, usize const_id) {
spl_ir_value_t v = {0};
v.kind = SPL_IR_VALUE_CONST;
v.tid = tid;
v.const_id = const_id;
return v;
}
static inline spl_ir_node_ref_t spl_ir_value_inst_ref(spl_ir_value_t v) {
return v.kind == SPL_IR_VALUE_INST ? v.inst : 0;
}
/* 常量池项:只放需要去重的量,标量直接内联在 Value 里。 */
typedef struct {
spl_ir_type_id_t tid;
union {
struct {
unsigned char *data;
usize len;
} bytes;
struct {
uint64_t *limbs;
usize count;
} big_int;
};
} spl_ir_const_t;
typedef VEC(spl_ir_const_t) spl_ir_const_vec_t;
/* 全局存储声明。引用是 PTR 常量(global_id),不是指令。 */
typedef struct {
const char *name;
spl_ir_type_id_t tid; /* 对象类型 */
spl_ir_value_t init;
bool readonly;
} spl_ir_global_t;
typedef VEC(spl_ir_global_t) spl_ir_global_vec_t;
#define SPL_ENUM_TAG_FIELD_IDX 0
@@ -88,115 +204,99 @@ typedef struct {
spl_dbg_node_t dbg;
spl_attr_id_vec_t attrs;
union {
spl_type_id_t tid;
spl_ir_type_id_t tid;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t left;
spl_ir_node_ref_t right;
spl_ir_type_id_t tid;
spl_ir_value_t left;
spl_ir_value_t right;
} arith;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t a;
spl_ir_node_ref_t b;
spl_ir_type_id_t tid;
spl_ir_value_t a;
spl_ir_value_t b;
} cmp;
struct {
spl_type_id_t from_tid;
spl_type_id_t to_tid;
spl_ir_node_ref_t val;
spl_ir_type_id_t from_tid;
spl_ir_type_id_t to_tid;
spl_ir_value_t val;
} cast;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t count;
spl_ir_type_id_t tid;
spl_ir_value_t count;
} mem_alloc;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t const_node;
} mem_global_alloc;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_type_id_t tid;
spl_ir_value_t ptr;
} mem_load;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_node_ref_t val;
spl_ir_type_id_t tid;
spl_ir_value_t ptr;
spl_ir_value_t val;
} mem_store;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_node_ref_t offset;
spl_ir_type_id_t tid;
spl_ir_value_t ptr;
spl_ir_value_t offset;
} mem_offset;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t agg;
spl_ir_type_id_t tid;
spl_ir_value_t agg;
usize field_idx;
} mem_field_ptr;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t dst;
spl_ir_node_ref_t src;
spl_ir_node_ref_t size;
spl_ir_type_id_t tid;
spl_ir_value_t dst;
spl_ir_value_t src;
spl_ir_value_t size;
} mem_copy;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t dst;
spl_ir_node_ref_t val;
spl_ir_node_ref_t size;
spl_ir_type_id_t tid;
spl_ir_value_t dst;
spl_ir_value_t val;
spl_ir_value_t size;
} mem_set;
struct {
spl_type_id_t tid;
union {
bool bool_lit;
void *ptr_lit;
usize int_lit;
double float_lit;
// const char *cstr_lit;
char ch_lit;
spl_ir_func_ref_t fn;
};
} type_const;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
} bitsizeof;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
} ir_sizeof;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
} ir_alignof;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t field_idx;
spl_ir_type_id_t tid;
spl_ir_value_t field_idx;
} ir_offsetof;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
} field_count;
struct {
spl_type_id_t tid;
spl_ir_node_ref_vec_t fields;
spl_ir_type_id_t tid;
spl_ir_value_vec_t fields;
} agg_construct;
struct {
spl_type_id_t tid;
spl_type_id_t field_tid;
spl_ir_type_id_t tid;
spl_ir_type_id_t field_tid;
usize field_idx;
spl_ir_node_ref_t val;
spl_ir_value_t val;
} agg_extract;
struct {
spl_type_id_t tid;
spl_ir_type_id_t tid;
usize field_idx;
spl_ir_node_ref_t agg;
spl_ir_node_ref_t field;
spl_ir_value_t agg;
spl_ir_value_t field;
} agg_insert;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t cond;
spl_ir_node_ref_t true_val;
spl_ir_node_ref_t false_val;
spl_ir_type_id_t tid;
spl_ir_value_t cond;
spl_ir_value_t true_val;
spl_ir_value_t false_val;
} control_select;
struct {
spl_ir_node_ref_t cond;
spl_ir_value_t cond;
spl_ir_node_ref_t true_label;
spl_ir_node_ref_t false_label;
} control_br;
@@ -204,17 +304,17 @@ typedef struct {
spl_ir_node_ref_t label;
} control_jmp;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t func;
spl_ir_node_ref_vec_t params;
spl_ir_type_id_t tid;
spl_ir_value_t func;
spl_ir_value_vec_t params;
} control_call;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t idx;
spl_ir_type_id_t tid;
spl_ir_value_t idx;
} control_param;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t val;
spl_ir_type_id_t tid;
spl_ir_value_t val;
} control_ret;
struct {
@@ -228,7 +328,8 @@ typedef VEC(spl_ir_node_t) spl_ir_node_vec_t;
typedef struct {
const char *name;
spl_attr_id_vec_t attrs;
spl_type_id_t fn_tid;
spl_ir_type_id_t fn_tid;
bool extern_fn;
spl_ir_node_vec_t nodes;
} spl_ir_func_t;
typedef VEC(spl_ir_func_t) spl_ir_func_vec_t;
@@ -244,10 +345,22 @@ typedef struct {
typedef VEC(spl_ir_fix_t) spl_ir_fix_vec_t;
typedef struct {
spl_ir_type_id_t tid;
const unsigned char *data;
usize len;
} spl_ir_const_key_t;
typedef struct {
spl_ir_type_table_t *types; /* 主 IR 拥有;meta IR 与主 IR 共享。 */
bool owns_types;
spl_ir_func_vec_t funcs;
spl_ir_const_vec_t consts;
spl_ir_global_vec_t globals;
MAP(spl_ir_const_key_t, usize) const_index;
} spl_ir_t;
void spl_ir_init(spl_ir_t *ir);
void spl_ir_init_shared(spl_ir_t *ir, spl_ir_type_table_t *types);
void spl_ir_drop(spl_ir_t *ir);
spl_ir_node_ref_t spl_ir_alloc_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
@@ -255,12 +368,23 @@ spl_ir_func_ref_t spl_ir_alloc_fn(spl_ir_t *ir);
spl_ir_node_t *spl_ir_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_node_ref_t node_id);
spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
spl_ir_const_t *spl_ir_const(spl_ir_t *ir, usize const_id);
/* INST 返回对应节点;CONST 返回 NULL。 */
spl_ir_node_t *spl_ir_value_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_value_t v);
/* 遍历节点里所有值型操作数(块标签除外)。 */
typedef void (*spl_ir_value_cb_t)(void *ud, spl_ir_value_t v);
void spl_ir_node_visit_values(spl_ir_node_t *n, spl_ir_value_cb_t cb, void *ud);
/* 一个函数体里出现的可静态发现的函数引用(直接调用与函数值常量)。
extern 函数不进入结果;结果按出现顺序去重。 */
void spl_ir_func_callees(spl_ir_t *ir, spl_ir_func_ref_t fn, spl_ir_func_ref_vec_t *out);
bool spl_ir_func_is_extern(spl_ir_t *ir, spl_ir_func_ref_t fn);
/* f 是否声明为 extern(属性表内名为 "extern" 的属性);命中返回该属性节点,否则 NULL。
供各后端复用,避免 "extern" 字符串判断散落多处。 */
spl_attr_node_t *spl_ir_fn_extern_attr(const spl_attr_t *attr, const spl_ir_func_t *f);
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty, const spl_attr_t *attr);
void spl_ir_dump(spl_ir_t *ir, const spl_attr_t *attr);
const char *spl_ir_kind_name(spl_ir_kind_t kind);
typedef struct {
@@ -310,12 +434,13 @@ typedef struct {
X(case_float2int, SPL_IR_CASE_FLOAT2INT)
/* clang-format on */
void spl_ir_builder_init(spl_ir_builder_t *b);
void spl_ir_builder_init_shared(spl_ir_builder_t *b, spl_ir_type_table_t *types);
void spl_ir_builder_drop(spl_ir_builder_t *b);
spl_ir_func_ref_t spl_ir_builder_fn_begin(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid);
spl_ir_type_id_t fn_tid);
spl_ir_func_ref_t spl_ir_builder_fn_reserve(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid);
spl_ir_type_id_t fn_tid);
void spl_ir_builder_fn_begin_at(spl_ir_builder_t *b, spl_ir_func_ref_t fid);
void spl_ir_builder_fn_end(spl_ir_builder_t *b);
@@ -323,102 +448,98 @@ usize spl_ir_builder_block_begin(spl_ir_builder_t *b);
void spl_ir_builder_block_end(spl_ir_builder_t *b);
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t tid, \
spl_ir_node_ref_t left, spl_ir_node_ref_t right);
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_ir_type_id_t tid, \
spl_ir_value_t left, spl_ir_value_t right);
SPL_IR_BIN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t tid, \
spl_ir_node_ref_t val);
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_ir_type_id_t tid, \
spl_ir_value_t val);
SPL_IR_UN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t tid, \
spl_ir_node_ref_t a, spl_ir_node_ref_t b);
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t tid, \
spl_ir_value_t a, spl_ir_value_t b);
SPL_IR_CMP_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t from_tid, \
spl_type_id_t to_tid, spl_ir_node_ref_t val);
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_ir_type_id_t from_tid, \
spl_ir_type_id_t to_tid, spl_ir_value_t val);
SPL_IR_CAST_TABLE
#undef X
/* memory */
spl_ir_node_ref_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t count);
spl_ir_node_ref_t spl_ir_builder_mem_global_alloc(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t const_node);
spl_ir_node_ref_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr);
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t val);
spl_ir_node_ref_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t offset);
spl_ir_node_ref_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t agg, usize field_idx);
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t src,
spl_ir_node_ref_t size);
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t val,
spl_ir_node_ref_t size);
spl_ir_value_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t count);
spl_ir_value_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t ptr);
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t ptr, spl_ir_value_t val);
spl_ir_value_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t ptr, spl_ir_value_t offset);
spl_ir_value_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t agg,
usize field_idx);
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t dst,
spl_ir_value_t src, spl_ir_value_t size);
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t dst,
spl_ir_value_t val, spl_ir_value_t size);
/* type const */
/* 常量:标量内联;需要去重的量进常量池并返回 const_id。 */
spl_ir_node_ref_t spl_ir_builder_type_const_ptr(spl_ir_builder_t *b, spl_type_id_t tid, void *val);
spl_ir_node_ref_t spl_ir_builder_type_const_bool(spl_ir_builder_t *b, spl_type_id_t tid, bool val);
spl_ir_node_ref_t spl_ir_builder_type_const_int(spl_ir_builder_t *b, spl_type_id_t tid, usize val);
spl_ir_node_ref_t spl_ir_builder_type_const_float(spl_ir_builder_t *b, spl_type_id_t tid,
double val);
spl_ir_node_ref_t spl_ir_builder_type_const_bytes(spl_ir_builder_t *b, spl_type_id_t tid,
const void *data, usize len);
spl_ir_node_ref_t spl_ir_builder_type_const_char(spl_ir_builder_t *b, spl_type_id_t tid, char val);
spl_ir_node_ref_t spl_ir_builder_type_const_fn(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_func_ref_t val);
spl_ir_value_t spl_ir_builder_const_int(spl_ir_type_id_t tid, uint64_t bits);
spl_ir_value_t spl_ir_builder_const_bool(spl_ir_type_id_t tid, bool val);
spl_ir_value_t spl_ir_builder_const_float(spl_ir_type_id_t tid, double val);
spl_ir_value_t spl_ir_builder_const_null(spl_ir_type_id_t tid);
spl_ir_value_t spl_ir_builder_const_fn(spl_ir_type_id_t tid, spl_ir_func_ref_t fn);
spl_ir_value_t spl_ir_builder_global_addr(spl_ir_type_id_t ptr_tid, usize global_id);
spl_ir_value_t spl_ir_builder_const_bytes(spl_ir_builder_t *b, spl_ir_type_id_t tid, const void *data,
usize len);
usize spl_ir_builder_global_declare(spl_ir_builder_t *b, const char *name, spl_ir_type_id_t tid,
spl_ir_value_t init, bool readonly);
/* type */
spl_ir_node_ref_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t field_idx);
spl_ir_node_ref_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_value_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_ir_type_id_t tid);
spl_ir_value_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_ir_type_id_t tid);
spl_ir_value_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_ir_type_id_t tid);
spl_ir_value_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t field_idx);
spl_ir_value_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_ir_type_id_t tid);
/* agg */
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_ir_type_id_t tid);
void spl_ir_builder_agg_construct_field(spl_ir_builder_t *b, spl_ir_node_ref_t node,
spl_ir_node_ref_t field);
spl_ir_node_ref_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_type_id_t tid,
spl_type_id_t field_tid, usize field_idx,
spl_ir_node_ref_t val);
spl_ir_node_ref_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_type_id_t tid, usize field_idx,
spl_ir_node_ref_t agg, spl_ir_node_ref_t field);
spl_ir_value_t field);
spl_ir_value_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_type_id_t field_tid, usize field_idx,
spl_ir_value_t val);
spl_ir_value_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_ir_type_id_t tid, usize field_idx,
spl_ir_value_t agg, spl_ir_value_t field);
/* control */
spl_ir_node_ref_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t cond, spl_ir_node_ref_t true_val,
spl_ir_node_ref_t false_val);
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_node_ref_t cond);
spl_ir_value_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t cond, spl_ir_value_t true_val,
spl_ir_value_t false_val);
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_value_t cond);
void spl_ir_builder_control_br_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref, usize true_block,
usize false_block);
spl_ir_node_ref_t spl_ir_builder_control_jmp(spl_ir_builder_t *b);
void spl_ir_builder_control_jmp_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref,
usize target_block);
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t func);
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t func);
void spl_ir_builder_control_call_param(spl_ir_builder_t *b, spl_ir_node_ref_t call_node,
spl_ir_node_ref_t arg);
spl_ir_node_ref_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t idx);
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t val);
spl_ir_value_t arg);
spl_ir_value_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t idx);
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t val);
spl_ir_node_ref_t spl_ir_builder_control_unreachable(spl_ir_builder_t *b);
spl_ir_node_ref_t spl_ir_builder_control_trap(spl_ir_builder_t *b);
@@ -4,13 +4,12 @@
#include "spl_attr.h"
#include "spl_ir.h"
#include "spl_layout.h"
#include "spl_type.h"
/* 生成结果的字节缓冲(C 源码文本);调用方负责初始化与释放。 */
typedef VEC(char) spl_ir2c_buf_t;
/* 生成 C99 源码追加到 out;返回 false 表示遇到不支持的结构(已在输出中就地标注)。 */
bool spl_ir2c_run(const spl_ir_t *ir, const spl_type_t *type, spl_layout_t *layout,
const spl_attr_t *attr, spl_ir2c_buf_t *out);
bool spl_ir2c_run(const spl_ir_t *ir, spl_layout_t *layout, const spl_attr_t *attr,
spl_ir2c_buf_t *out);
#endif /* __SPL_IR2C_H__ */
@@ -4,25 +4,25 @@
#include "spl_diag.h"
#include "spl_ir.h"
#include "spl_layout.h"
#include "spl_type.h"
#include "../stage0/spl_mcode.h"
#include "stage0/spl_mcode.h"
typedef MAP(spl_ir_func_ref_t, isize) spl_extern_idx_map_t;
typedef struct {
const spl_ir_t *ir;
const spl_type_t *type;
const spl_ir_type_table_t *type;
const spl_attr_t *attr;
spl_extern_idx_map_t extern_native;
VEC(isize) global_data_idx;
spl_prog_t prog;
spl_layout_t *layout; /* 借用 splc0 的 layout(size/align/offset 唯一来源) */
spl_diag_t *diag;
} spl_ir2vm_t;
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, const spl_type_t *type,
spl_layout_t *layout, const spl_attr_t *attr);
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, spl_layout_t *layout,
const spl_attr_t *attr);
void spl_ir2vm_drop(spl_ir2vm_t *ctx);
int spl_ir2vm_run(spl_ir2vm_t *ctx);
+18
View File
@@ -0,0 +1,18 @@
#ifndef __SPL_IR_LINK_H__
#define __SPL_IR_LINK_H__
#include "spl_ir.h"
#include "spl_sema.h"
/* 前端与 IR 的双向绑定:def/lang_type <-> ir_func/ir_type。
公开接口只暴露 IR 身份;前端结构体在实现文件里使用。 */
typedef struct spl_ir_link spl_ir_link_t;
spl_ir_link_t *spl_ir_link_create(spl_ir_t *ir, spl_sema_t *sema);
void spl_ir_link_destroy(spl_ir_link_t *link);
spl_ir_func_ref_t spl_ir_link_reserve_fn(spl_ir_link_t *link, usize def_id);
spl_ir_value_t spl_ir_link_fn_value(spl_ir_link_t *link, usize def_id);
bool spl_ir_link_def_of_fn(const spl_ir_link_t *link, spl_ir_func_ref_t fn, usize *out_def);
#endif /* __SPL_IR_LINK_H__ */
+121
View File
@@ -0,0 +1,121 @@
#ifndef __SPL_IR_TYPE_H__
#define __SPL_IR_TYPE_H__
#include "stage0/include/utils.h"
#include "spl_fold.h"
/* 类型 intern 用的哈希混合(FNV-1a 风格,顺序敏感)。
hash 只用于选择桶;相等判定始终由结构比较完成。 */
static inline usize spl_hash_mix(usize h, usize x) {
h ^= x;
h *= (usize)1099511628211ULL;
return h;
}
static inline usize spl_hash_mix_str(usize h, const char *s) {
if (!s) {
return spl_hash_mix(h, 0);
}
while (*s) {
h = spl_hash_mix(h, (usize)(unsigned char)*s);
s++;
}
return spl_hash_mix(h, 0); /* 终止符参与混合,避免名称拼接歧义 */
}
static inline usize spl_hash_seed(void) { return (usize)14695981039346656037ULL; }
typedef usize spl_ir_type_id_t;
typedef VEC(spl_ir_type_id_t) spl_ir_type_id_vec_t;
typedef enum {
SPL_IR_TYPE_ERROR,
SPL_IR_TYPE_UNIT,
SPL_IR_TYPE_BOOL,
SPL_IR_TYPE_INT,
SPL_IR_TYPE_FLOAT,
SPL_IR_TYPE_PTR,
SPL_IR_TYPE_ARRAY,
SPL_IR_TYPE_STRUCT,
SPL_IR_TYPE_UNION,
SPL_IR_TYPE_ENUM,
SPL_IR_TYPE_FN,
} spl_ir_type_kind_t;
typedef enum {
SPL_IR_TYPE_LAYOUT_AUTO,
SPL_IR_TYPE_LAYOUT_EXTERN_C,
SPL_IR_TYPE_LAYOUT_PACKED,
} spl_ir_type_layout_mode_t;
typedef struct {
spl_ir_type_layout_mode_t mode;
usize fixed_align_bits;
} spl_ir_type_layout_t;
typedef struct {
const char *name;
spl_ir_type_id_t type_id;
usize ast_node_ref;
} spl_ir_type_member_t;
typedef VEC(spl_ir_type_member_t) spl_ir_type_member_vec_t;
typedef struct {
spl_ir_type_kind_t kind;
spl_ir_type_layout_t layout;
union {
struct {
usize bits;
int is_signed;
} int_type;
struct {
usize bits;
} float_type;
struct {
spl_ir_type_id_t pointee;
} ptr_type;
struct {
spl_ir_type_id_t element;
usize len;
} array_type;
struct {
spl_ir_type_member_vec_t variants;
spl_ir_type_id_t tag_type;
} agg_type;
struct {
spl_ir_type_id_vec_t params;
spl_ir_type_id_t ret;
} fn_type;
};
usize hash_next; /* 同 hash 桶内下一个类型 id;0 表示链尾。不参与相等比较。 */
} spl_ir_type_node_t;
typedef VEC(spl_ir_type_node_t) spl_ir_type_node_vec_t;
typedef struct {
spl_ir_type_node_vec_t type_table;
spl_fold_t type_fold;
} spl_ir_type_table_t;
void spl_ir_type_table_init(spl_ir_type_table_t *type);
void spl_ir_type_table_drop(spl_ir_type_table_t *type);
spl_ir_type_node_t *spl_ir_type_node(const spl_ir_type_table_t *type, spl_ir_type_id_t id);
spl_ir_type_id_t spl_ir_type_push(spl_ir_type_table_t *type, spl_ir_type_node_t *type_node);
spl_ir_type_id_t spl_ir_type_builder_simple(spl_ir_type_table_t *type, spl_ir_type_kind_t kind);
spl_ir_type_id_t spl_ir_type_builder_int(spl_ir_type_table_t *type, usize bits, int is_signed);
spl_ir_type_id_t spl_ir_type_builder_float(spl_ir_type_table_t *type, usize bits);
spl_ir_type_id_t spl_ir_type_builder_ptr(spl_ir_type_table_t *type, spl_ir_type_id_t pointee);
spl_ir_type_id_t spl_ir_type_builder_array(spl_ir_type_table_t *type, spl_ir_type_id_t element, usize len);
spl_ir_type_id_t spl_ir_type_builder_fn(spl_ir_type_table_t *type, spl_ir_type_id_t ret, const spl_ir_type_id_t *params,
usize nparams);
spl_ir_type_id_t spl_ir_type_builder_agg(spl_ir_type_table_t *type, spl_ir_type_kind_t tk,
spl_ir_type_member_vec_t *variants, spl_ir_type_id_t tag_type,
spl_ir_type_layout_t layout);
void spl_ir_type_dump(spl_ir_type_table_t *type, spl_ir_type_id_t id);
const spl_ir_type_member_t *spl_ir_type_member(spl_ir_type_table_t *type, spl_ir_type_id_t tid, const char *name);
bool spl_ir_type_member_idx(spl_ir_type_table_t *type, spl_ir_type_id_t tid, const char *name, usize *out_idx);
#endif /* __SPL_IR_TYPE_H__ */
@@ -1,10 +1,10 @@
#ifndef __SPL_LANG_TYPE_H__
#define __SPL_LANG_TYPE_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
#include "spl_dbg.h"
#include "spl_mpa.h"
#include "spl_type.h"
#include "spl_ir_type.h"
typedef usize spl_lang_type_id_t;
typedef VEC(spl_lang_type_id_t) spl_lang_type_id_vec_t;
@@ -39,9 +39,19 @@ typedef struct {
} spl_lang_method_t;
typedef VEC(spl_lang_method_t) spl_lang_method_vec_t;
typedef struct {
const char *name;
spl_lang_type_id_t type;
spl_def_id_t def_id;
usize ast_node_ref;
} spl_lang_member_t;
typedef VEC(spl_lang_member_t) spl_lang_member_vec_t;
typedef struct {
spl_lang_type_kind_t kind;
spl_type_id_t ir_type_id;
spl_ir_type_id_t ir_type_id;
spl_def_id_t def_id; /* 非 0 表示声明身份;合成类型为 0。 */
spl_lang_member_vec_t members;
spl_lang_method_vec_t methods;
union {
spl_lang_type_id_t elem;
@@ -50,6 +60,13 @@ typedef struct {
spl_lang_type_id_vec_t params;
spl_lang_type_id_t ret;
} fn;
struct {
usize bits;
int is_signed;
} int_type;
struct {
usize bits;
} float_type;
} extra;
usize hash_next; /* 同 hash 桶内下一个类型 id;0 表示链尾。不参与相等比较。 */
} spl_lang_type_node_t;
@@ -74,10 +91,18 @@ typedef enum {
SPL_DECL_ERROR,
} spl_decl_state_t;
/* 函数 def 的执行阶段;NORMAL 才进入运行期 IR。 */
typedef enum {
SPL_DEF_FN_NORMAL,
SPL_DEF_FN_META,
SPL_DEF_FN_MACRO,
} spl_def_fn_kind_t;
struct spl_ast;
typedef struct {
spl_def_node_kind_t kind;
spl_def_fn_kind_t fn_kind;
const char *name;
spl_dbg_node_t dbg_node;
spl_lang_type_id_t lang_id;
@@ -89,26 +114,31 @@ typedef struct {
typedef VEC(spl_def_node_t) spl_def_node_vec_t;
typedef struct {
spl_type_t ir;
spl_ir_type_table_t *ir_types; /* 借用 IR 模块的类型表,不拥有 */
spl_lang_type_vec_t lang_table;
spl_fold_t lang_fold;
spl_def_node_vec_t def_table;
} spl_lang_type_t;
void spl_lang_type_init(spl_lang_type_t *type);
void spl_lang_type_init(spl_lang_type_t *type, spl_ir_type_table_t *ir_types);
void spl_lang_type_drop(spl_lang_type_t *type);
spl_lang_type_node_t *spl_lang_type_node(const spl_lang_type_t *type, spl_lang_type_id_t id);
spl_lang_type_id_t spl_lang_node_push(spl_lang_type_t *type, spl_lang_type_node_t *node);
spl_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id);
spl_ir_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id);
const spl_lang_member_t *spl_lang_member_at(spl_lang_type_t *type, spl_lang_type_id_t agg,
usize idx);
bool spl_lang_member_idx(spl_lang_type_t *type, spl_lang_type_id_t agg, const char *name,
usize *out_idx);
/* 前向引用支持:reserve 一个 type_table 空槽位(kind=ERROR)作为身份锚点,
让 *Node / []Node 这类成员能拿到稳定 pointee;成员解析完后再调 define
把真实内容填进去。占位槽位**不写 type_fold**,不参与 hash-consing——
后续相同形状的类型走 spl_type_node_push 会生成独立 id,语义等价。 */
spl_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type);
void spl_lang_define_ir(spl_lang_type_t *type, spl_type_id_t id, spl_type_node_t *node);
后续相同形状的类型走 spl_ir_type_push 会生成独立 id,语义等价。 */
spl_ir_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type);
void spl_lang_define_ir(spl_lang_type_t *type, spl_ir_type_id_t id, spl_ir_type_node_t *node);
spl_lang_type_id_t spl_lang_make_error(spl_lang_type_t *type);
spl_lang_type_id_t spl_lang_make_infer(spl_lang_type_t *type);
@@ -129,6 +159,10 @@ spl_lang_type_id_t spl_lang_make_fn(spl_lang_type_t *type, spl_lang_type_id_t re
spl_lang_type_id_t spl_lang_make_aggregate(spl_lang_type_t *type, spl_lang_type_kind_t kind,
const char *name, const spl_lang_type_id_t *members,
usize nmembers);
spl_lang_type_id_t spl_lang_make_struct_named(spl_lang_type_t *type, const char *name,
const char *const *field_names,
const spl_lang_type_id_t *field_types,
usize nfields);
spl_lang_type_id_t spl_lang_make_varargs(spl_lang_type_t *type);
spl_lang_type_id_t spl_type_lookup_builtin(spl_lang_type_t *type, const char *name);
@@ -144,8 +178,10 @@ spl_def_id_t spl_def_alloc(spl_lang_type_t *type, spl_def_node_kind_t kind, cons
spl_dbg_node_t dbg, struct spl_ast *owner_ast, usize ast_node_ref);
void spl_def_resolve(spl_lang_type_t *type, spl_def_id_t id, spl_lang_type_id_t lang_id);
spl_def_node_t *spl_def_node(const spl_lang_type_t *type, spl_def_id_t id);
bool spl_def_is_compile_time(const spl_def_node_t *def);
bool spl_def_is_macro_fn(const spl_def_node_t *def);
spl_lang_type_id_t spl_def_get_lang_id(spl_lang_type_t *type, spl_def_id_t def_id);
spl_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id);
spl_ir_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id);
void spl_lang_type_dump(spl_lang_type_t *type, spl_lang_type_id_t id);
void spl_type_def_dump(spl_lang_type_t *type, spl_def_id_t id);
@@ -1,7 +1,7 @@
#ifndef __SPL_LAYOUT_H__
#define __SPL_LAYOUT_H__
#include "spl_type.h"
#include "spl_ir_type.h"
typedef struct {
usize size;
@@ -47,11 +47,11 @@ typedef struct {
void spl_layout_init(spl_layout_t *layout, spl_layout_target_t *target);
void spl_layout_drop(spl_layout_t *layout);
void spl_layout_resolve(spl_layout_t *layout, spl_type_t *type);
void spl_layout_resolve(spl_layout_t *layout, const spl_ir_type_table_t *type);
void spl_layout_add_scalar(spl_layout_t *layout, usize size, usize abi_align);
void spl_layout_add_ptr(spl_layout_t *layout, usize addr_space, usize size, usize align);
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_type_id_t id);
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_ir_type_id_t id);
#endif /* __SPL_LAYOUT_H__ */
File renamed without changes.
+29
View File
@@ -0,0 +1,29 @@
#ifndef __SPL_META_H__
#define __SPL_META_H__
#include "spl_sema.h"
#include "spl_sap.h"
typedef struct spl_meta spl_meta_t;
/* 编译期执行环境:把 meta/macro 函数编译到独立 IR,并默认用 VM 执行。
生命周期由调用方持有;内部只借用 sema 的 type/layout/attr/ns。 */
spl_meta_t *spl_meta_create(spl_sema_t *sema);
void spl_meta_destroy(spl_meta_t *meta);
/* 惰性编译所有编译期函数。失败返回 false,诊断已写入 sema->diag。 */
bool spl_meta_prepare(spl_meta_t *meta);
/* 按 def_id 调用编译期函数;args/out 是标量位模式。 */
bool spl_meta_invoke(spl_meta_t *meta, spl_def_id_t def_id, const usize *args, usize nargs,
usize *out);
/* sema 在 @ 调用点执行 meta fn,并把结果落回 n。 */
spl_lang_type_id_t spl_meta_eval_call(spl_sema_t *sema, spl_ast_node_t *n, spl_def_id_t def_id);
/* 语言绑定层暴露给 sema 的 SAP 能力。 */
spl_sap_t *spl_meta_sap(spl_meta_t *meta);
spl_sap_handle_t spl_meta_register_handle(spl_meta_t *meta, spl_ast_t *ast,
spl_ast_node_ref_t ref);
#endif /* __SPL_META_H__ */
+63
View File
@@ -0,0 +1,63 @@
#ifndef __SPL_MODULE_H__
#define __SPL_MODULE_H__
#include "spl_ast.h"
#include "spl_diag.h"
#include "spl_lang_type.h"
#include "spl_namespace.h"
typedef usize spl_module_id_t;
typedef enum {
SPL_MODULE_LOADING,
SPL_MODULE_LOADED,
SPL_MODULE_ERROR,
} spl_module_state_t;
typedef struct {
spl_module_id_t id;
char *name;
char *file_path;
spl_ast_t *ast;
spl_ast_node_ref_t container;
spl_module_id_t parent;
spl_def_id_t def_id;
spl_lang_type_id_t lang_id;
spl_ns_id_t ns;
spl_module_state_t state;
int sema_state;
} spl_module_t;
typedef struct {
VEC(spl_module_t) modules;
MAP(const char *, spl_module_id_t) by_name;
MAP(const char *, spl_module_id_t) by_path;
} spl_module_registry_t;
void spl_module_registry_init(spl_module_registry_t *reg);
void spl_module_registry_drop(spl_module_registry_t *reg);
/* 由文件路径推导默认模块名:去扩展名,非法标识符字符映射为 '_'。
结果写入 out,成功返回 true。 */
bool spl_module_name_from_path(const char *path, char *out, usize cap);
/* 读取文件头 mod 声明的点分路径;没有声明返回 NULL。 */
const char *spl_module_declared_name(spl_ast_t *ast);
/* 登记一个已解析的文件模块。declared_name 为空时使用文件名推导。
重名或重路径冲突返回 0 并写诊断。 */
spl_module_id_t spl_module_register(spl_module_registry_t *reg, spl_ast_t *ast,
const char *file_path, const char *declared_name,
spl_diag_t *diag);
spl_module_t *spl_module_get(spl_module_registry_t *reg, spl_module_id_t id);
spl_module_id_t spl_module_find_name(spl_module_registry_t *reg, const char *name);
spl_module_id_t spl_module_find_ast(spl_module_registry_t *reg, spl_ast_t *ast);
/* 返回模块名最后一个点分段的起点;名字中必须含该段。 */
const char *spl_module_last_segment(const char *name);
/* 返回模块 container_members 节点引用;无 AST 返回 0。 */
spl_ast_node_ref_t spl_module_container(spl_module_t *mod);
#endif /* __SPL_MODULE_H__ */
File renamed without changes.
+71
View File
@@ -0,0 +1,71 @@
#ifndef __SPL_NAMESPACE_H__
#define __SPL_NAMESPACE_H__
#include "spl_lang_type.h"
typedef usize spl_ns_id_t;
typedef enum {
SPL_SYMBOL_KIND_ERROR,
SPL_SYMBOL_KIND_VAR,
SPL_SYMBOL_KIND_MEMBER,
SPL_SYMBOL_KIND_FN,
SPL_SYMBOL_KIND_TYPE,
} spl_symbol_kind_t;
typedef struct {
const char *name;
spl_symbol_kind_t kind;
spl_def_id_t node;
} spl_symbol_t;
typedef VEC(const char *) spl_symbol_path_t;
typedef enum {
SPL_NS_ROOT,
SPL_NS_MODULE,
SPL_NS_AGGREGATE,
SPL_NS_FUNCTION,
SPL_NS_BLOCK,
} spl_ns_kind_t;
typedef struct {
spl_ns_id_t id;
spl_ns_id_t parent;
spl_ns_kind_t kind;
const char *name;
const char *qualified;
MAP(const char *, spl_symbol_t) symbols;
usize owner_kind;
usize owner_id;
} spl_ns_node_t;
typedef VEC(spl_ns_node_t) spl_ns_node_vec_t;
typedef struct {
spl_ns_node_vec_t nodes;
spl_ns_id_t root;
spl_ns_id_t current;
} spl_namespace_t;
void spl_ns_init(spl_namespace_t *ns);
void spl_ns_drop(spl_namespace_t *ns);
spl_ns_id_t spl_ns_root(spl_namespace_t *ns);
spl_ns_id_t spl_ns_create(spl_namespace_t *ns, spl_ns_id_t parent, spl_ns_kind_t kind,
const char *name, usize owner_kind, usize owner_id);
spl_ns_id_t spl_ns_alloc(spl_namespace_t *ns, spl_ns_kind_t kind, const char *name);
bool spl_ns_enter(spl_namespace_t *ns, spl_ns_id_t id);
bool spl_ns_leave(spl_namespace_t *ns);
bool spl_ns_insert(spl_namespace_t *ns, spl_ns_id_t id, spl_symbol_t symbol);
bool spl_ns_lookup(spl_namespace_t *ns, const char *name, spl_symbol_t *out);
bool spl_ns_lookup_local(spl_namespace_t *ns, spl_ns_id_t id, const char *name,
spl_symbol_t *out);
const char *spl_ns_qualified(spl_namespace_t *ns, spl_ns_id_t id);
bool spl_ns_symbol_qualified(spl_namespace_t *ns, spl_ns_id_t id, const char *local_name,
char *out, usize cap);
spl_ns_id_t spl_ns_child(spl_namespace_t *ns, spl_ns_id_t parent, const char *name);
#endif /* __SPL_NAMESPACE_H__ */
@@ -8,6 +8,7 @@ typedef struct spl_parser {
spl_ast_t *ast;
spl_diag_t *diag;
usize pos;
usize last_tok_line;
int failed;
int stop_agg;
usize error_count;
+53
View File
@@ -0,0 +1,53 @@
#ifndef __SPL_SAP_H__
#define __SPL_SAP_H__
#include "spl_ast.h"
#include "spl_exec.h"
#include "spl_lang_type.h"
/* SAP 句柄:0 = 空;其余是 spl_sap_t 句柄表下标。 */
typedef usize spl_sap_handle_t;
typedef struct spl_sap spl_sap_t;
typedef enum {
SPL_SAP_ARG_HANDLE,
SPL_SAP_ARG_USIZE,
SPL_SAP_ARG_VIEW,
} spl_sap_arg_kind_t;
typedef bool (*spl_sap_host_fn)(spl_sap_t *sap, spl_exec_t *exec, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret);
typedef struct {
const char *name;
usize nparams;
spl_sap_arg_kind_t params[4];
spl_sap_arg_kind_t ret;
spl_sap_host_fn host;
} spl_sap_op_t;
spl_sap_t *spl_sap_create(spl_lang_type_t *type);
void spl_sap_destroy(spl_sap_t *sap);
const spl_sap_op_t *spl_sap_lookup(const char *name);
const spl_sap_op_t *spl_sap_ops(usize *count);
spl_lang_type_id_t spl_sap_arg_type(spl_sap_t *sap, spl_sap_arg_kind_t kind);
spl_lang_type_id_t spl_sap_op_fn_type(spl_sap_t *sap, const spl_sap_op_t *op);
spl_lang_type_id_t spl_sap_meta_view_type(spl_sap_t *sap);
const char *const *spl_sap_meta_view_fields(usize *count);
/* AST kind 域由 SPL_AST_KIND_TABLE 自动生成。 */
usize spl_sap_kind_count(void);
const char *spl_sap_kind_name(usize kind);
spl_sap_handle_t spl_sap_handle_register(spl_sap_t *sap, spl_ast_t *ast,
spl_ast_node_ref_t ref);
bool spl_sap_handle_node(spl_sap_t *sap, spl_sap_handle_t handle, spl_ast_t **ast,
spl_ast_node_ref_t *ref);
bool spl_sap_bind(spl_exec_t *exec, spl_sap_t *sap);
bool spl_sap_type_lookup(spl_sap_t *sap, const char *name, spl_lang_type_id_t *out);
#endif /* __SPL_SAP_H__ */
@@ -4,11 +4,13 @@
#include "spl_ast.h"
#include "spl_attr.h"
#include "spl_diag.h"
#include "spl_ir.h"
#include "spl_lang_type.h"
#include "spl_layout.h"
#include "spl_mpa.h"
#include "spl_scope.h"
#include "spl_type.h"
#include "spl_module.h"
#include "spl_namespace.h"
#include "spl_ir_type.h"
typedef struct spl_module_loader spl_module_loader_t;
struct spl_module_loader {
@@ -19,27 +21,41 @@ struct spl_module_loader {
void *user;
};
struct spl_meta;
struct spl_ir_link;
typedef struct {
spl_ast_t *ast;
spl_lang_type_t *type;
spl_ir_t *ir; /* 当前 IR 程序;由 driver/meta 借用 */
struct spl_ir_link *ir_link; /* 前端 <-> IR 绑定;由 driver 借用 */
spl_layout_t *layout; /* 由 splc0 拥有并解析;sema 仅借用 */
spl_scope_t *scope;
spl_namespace_t *ns;
spl_symbol_t root;
spl_attr_t *attr;
struct spl_meta *meta; /* 编译期执行环境;可为 NULL(只做 sema 时) */
spl_lang_type_id_t current_aggregate_lang;
spl_lang_type_id_t current_fn_ret_tid;
spl_lang_type_id_t current_loop_break_tid;
spl_def_fn_kind_t current_fn_kind;
spl_symbol_path_t label_stack;
const spl_module_loader_t *loader;
spl_module_registry_t *modules;
spl_diag_t *diag;
} spl_sema_t;
void spl_sema_init(spl_sema_t *sema, spl_ast_t *ast, spl_lang_type_t *type,
spl_layout_t *layout, spl_scope_t *scope, spl_attr_t *attr);
spl_layout_t *layout, spl_namespace_t *ns, spl_attr_t *attr);
void spl_sema_drop(spl_sema_t *sema);
void spl_sema_run_module(spl_sema_t *sema, spl_ast_node_ref_t module_ref);
void spl_sema_run(spl_sema_t *sema);
void spl_sema_dump(spl_sema_t *sema);
/* 编译期执行器复用 sema 的表达式推断/转换;供 meta 模块调用。 */
spl_lang_type_id_t spl_sema_infer_expr(spl_sema_t *sema, spl_ast_node_ref_t ref);
spl_lang_type_id_t spl_sema_coerce_expr(spl_sema_t *sema, spl_ast_node_ref_t ref,
spl_lang_type_id_t expected);
spl_lang_type_id_t spl_sema_eval_decl(spl_sema_t *sema, spl_def_id_t def_id);
#endif /* __SPL_SEMA_H__ */
@@ -2,7 +2,7 @@
#ifndef __SPL_TOK_H__
#define __SPL_TOK_H__
#include "../stage0/include/utils.h"
#include "stage0/include/utils.h"
/* clang-format off */
#define KEYWORD_TABLE \
@@ -10,26 +10,26 @@
X(as , KW_AS , SPL_V0) \
X(bool , KW_BOOL , SPL_V0) \
X(break , KW_BREAK , SPL_V0) \
X(catch , KW_CATCH , SPL_V0) \
X(comptime , KW_COMPTIME , SPL_V0) \
X(const , KW_CONST , SPL_V0) \
X(continue , KW_CONTINUE , SPL_V0) \
X(defer , KW_DEFER , SPL_V0) \
X(else , KW_ELSE , SPL_V0) \
X(enum , KW_ENUM , SPL_V0) \
X(errdefer , KW_ERRDEFER , SPL_V0) \
X(false , KW_FALSE , SPL_V0) \
X(fn , KW_FN , SPL_V0) \
X(for , KW_FOR , SPL_V0) \
X(if , KW_IF , SPL_V0) \
X(import , KW_IMPORT , SPL_V0) \
X(loop , KW_LOOP , SPL_V0) \
X(macro , KW_MACRO , SPL_V0) \
X(match , KW_MATCH , SPL_V0) \
X(meta , KW_META , SPL_V0) \
X(mod , KW_MOD , SPL_V0) \
X(null , KW_NULL , SPL_V0) \
X(ret , KW_RET , SPL_V0) \
X(shape , KW_SHAPE , SPL_V0) \
X(struct , KW_STRUCT , SPL_V0) \
X(true , KW_TRUE , SPL_V0) \
X(try , KW_TRY , SPL_V0) \
X(type , KW_TYPE , SPL_V0) \
X(undefined , KW_UNDEFINED , SPL_V0) \
X(union , KW_UNION , SPL_V0) \
@@ -93,11 +93,9 @@
X(";" , TOK_SEMICOLON , SPL_V0 ) \
X("," , TOK_COMMA , SPL_V0 ) \
X(":" , TOK_COLON , SPL_V0 ) \
X(":=" , TOK_COLON_ASSIGN , SPL_V0 ) \
X("." , TOK_DOT , SPL_V0 ) \
X(".." , TOK_RANGE , SPL_V0 ) \
X("..." , TOK_ELLIPSIS , SPL_V0 ) \
X("?" , TOK_COND , SPL_V0 ) \
X(ident , TOK_IDENT , SPL_V0 ) \
X(int , TOK_INT_LITERAL , SPL_V0 ) \
X(float , TOK_FLOAT_LITERAL , SPL_V0 ) \
+1 -1
View File
@@ -3,7 +3,7 @@
/* 字节码(VM 层)优化 pass:输入输出都是 spl_prog_t,纯函数式、可开关。 */
#include "../stage0/spl_mcode.h"
#include "stage0/spl_mcode.h"
void spl_prog_peephole(spl_prog_t *prog);
void spl_prog_opt(spl_prog_t *prog);
+138 -128
View File
@@ -12,62 +12,86 @@ typedef struct {
spl_ir_t *ir;
spl_ir_func_ref_t caller;
spl_ir_func_ref_t callee;
spl_ir_node_ref_t shift; /* new = old + shift */
usize nparams;
spl_ir_node_ref_t *param_ref;
spl_ir_node_ref_t *param_arg;
/* callee Ref -> caller Value;Param 直接映射到实参,其余映射到克隆节点。 */
spl_ir_value_t *val_map;
usize val_map_size;
} inline_ctx_t;
static spl_ir_node_t *nd(spl_ir_t *ir, spl_ir_func_ref_t fid, spl_ir_node_ref_t ref) {
return spl_ir_node(ir, fid, ref);
}
/* ---- 引用重写(克隆体旧 ref -> 新 ref) ---- */
/* ---- 引用重写(克隆体旧 ref -> 新 value) ---- */
static spl_ir_node_ref_t rw(inline_ctx_t *c, spl_ir_node_ref_t r) {
if (r == 0)
return 0;
for (usize i = 0; i < c->nparams; i++)
if (c->param_ref[i] == r)
return c->param_arg[i];
return r + c->shift;
static spl_ir_value_t rw_value(inline_ctx_t *c, spl_ir_value_t v) {
if (v.kind != SPL_IR_VALUE_INST || v.inst == 0)
return v;
if (v.inst < c->val_map_size) {
spl_ir_value_t mapped = c->val_map[v.inst];
if (mapped.kind != SPL_IR_VALUE_INST || mapped.inst != 0)
return mapped;
}
Assert(false && "unmapped callee value ref");
return v;
}
typedef spl_ir_node_ref_t (*ref_xform_t)(void *ud, spl_ir_node_ref_t ref);
static spl_ir_node_ref_t rw_label(inline_ctx_t *c, spl_ir_node_ref_t ref) {
if (ref == 0)
return 0;
return spl_ir_value_inst_ref(rw_value(c, spl_ir_value_inst(ref)));
}
static void xform_vec(spl_ir_node_ref_vec_t *v, ref_xform_t fx, void *ud) {
typedef spl_ir_value_t (*value_xform_t)(void *ud, spl_ir_value_t v);
static void xform_value_vec(spl_ir_value_vec_t *v, value_xform_t fx, void *ud) {
for (usize i = 0; i < vec_size(*v); i++)
vec_at(*v, i) = fx(ud, vec_at(*v, i));
}
/* 对节点的所有「值引用」字段应用 fx;块标签字段不在此列(由调用方单独处理)。 */
static void xform_node_value_refs(spl_ir_node_t *n, ref_xform_t fx, void *ud) {
/* 对节点的所有「值」字段应用 fx;块标签字段由 rw_node 单独处理。 */
static void xform_node_values(spl_ir_node_t *n, value_xform_t fx, void *ud) {
switch (n->kind) {
case SPL_IR_ARITH_ADD: case SPL_IR_ARITH_SUB: case SPL_IR_ARITH_MUL:
case SPL_IR_ARITH_DIV: case SPL_IR_ARITH_REM: case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS: case SPL_IR_ARITH_AND: case SPL_IR_ARITH_OR:
case SPL_IR_ARITH_XOR: case SPL_IR_ARITH_SHL: case SPL_IR_ARITH_SHR:
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
case SPL_IR_ARITH_MUL:
case SPL_IR_ARITH_DIV:
case SPL_IR_ARITH_REM:
case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS:
case SPL_IR_ARITH_AND:
case SPL_IR_ARITH_OR:
case SPL_IR_ARITH_XOR:
case SPL_IR_ARITH_SHL:
case SPL_IR_ARITH_SHR:
case SPL_IR_ARITH_NOT:
n->arith.left = fx(ud, n->arith.left);
n->arith.right = fx(ud, n->arith.right);
break;
case SPL_IR_CMP_EQ: case SPL_IR_CMP_NE: case SPL_IR_CMP_LT:
case SPL_IR_CMP_LE: case SPL_IR_CMP_GT: case SPL_IR_CMP_GE:
case SPL_IR_CMP_EQ:
case SPL_IR_CMP_NE:
case SPL_IR_CMP_LT:
case SPL_IR_CMP_LE:
case SPL_IR_CMP_GT:
case SPL_IR_CMP_GE:
n->cmp.a = fx(ud, n->cmp.a);
n->cmp.b = fx(ud, n->cmp.b);
break;
case SPL_IR_CAST_TRUNC: case SPL_IR_CAST_ZEXT: case SPL_IR_CAST_SEXT:
case SPL_IR_CAST_FEXT: case SPL_IR_CAST_FTRUNC: case SPL_IR_CAST_BITCAST:
case SPL_IR_CAST_PTR2INT: case SPL_IR_CAST_INT2PTR: case SPL_IR_CAST_BOOL2INT:
case SPL_IR_CASE_INT2FLOAT: case SPL_IR_CASE_FLOAT2INT:
case SPL_IR_CAST_TRUNC:
case SPL_IR_CAST_ZEXT:
case SPL_IR_CAST_SEXT:
case SPL_IR_CAST_FEXT:
case SPL_IR_CAST_FTRUNC:
case SPL_IR_CAST_BITCAST:
case SPL_IR_CAST_PTR2INT:
case SPL_IR_CAST_INT2PTR:
case SPL_IR_CAST_BOOL2INT:
case SPL_IR_CASE_INT2FLOAT:
case SPL_IR_CASE_FLOAT2INT:
n->cast.val = fx(ud, n->cast.val);
break;
case SPL_IR_MEM_ALLOCA:
n->mem_alloc.count = fx(ud, n->mem_alloc.count);
break;
case SPL_IR_MEM_GLOBAL_ALLOC:
n->mem_global_alloc.const_node = fx(ud, n->mem_global_alloc.const_node);
break;
case SPL_IR_MEM_LOAD:
n->mem_load.ptr = fx(ud, n->mem_load.ptr);
break;
@@ -96,7 +120,7 @@ static void xform_node_value_refs(spl_ir_node_t *n, ref_xform_t fx, void *ud) {
n->ir_offsetof.field_idx = fx(ud, n->ir_offsetof.field_idx);
break;
case SPL_IR_AGG_CONSTRUCT:
xform_vec(&n->agg_construct.fields, fx, ud);
xform_value_vec(&n->agg_construct.fields, fx, ud);
break;
case SPL_IR_AGG_EXTRACT:
n->agg_extract.val = fx(ud, n->agg_extract.val);
@@ -121,27 +145,24 @@ static void xform_node_value_refs(spl_ir_node_t *n, ref_xform_t fx, void *ud) {
break;
case SPL_IR_CONTROL_CALL:
n->control_call.func = fx(ud, n->control_call.func);
xform_vec(&n->control_call.params, fx, ud);
xform_value_vec(&n->control_call.params, fx, ud);
break;
default:
break;
}
}
static spl_ir_node_ref_t rw_thunk(void *ud, spl_ir_node_ref_t r) {
return rw((inline_ctx_t *)ud, r);
}
static spl_ir_value_t rw_thunk(void *ud, spl_ir_value_t v) { return rw_value((inline_ctx_t *)ud, v); }
/* 克隆体旧 ref -> 新 ref;块标签也参与平移。 */
static void rw_node(inline_ctx_t *c, spl_ir_node_t *n) {
xform_node_value_refs(n, rw_thunk, c);
xform_node_values(n, rw_thunk, c);
switch (n->kind) {
case SPL_IR_CONTROL_BR:
n->control_br.true_label = rw(c, n->control_br.true_label);
n->control_br.false_label = rw(c, n->control_br.false_label);
n->control_br.true_label = rw_label(c, n->control_br.true_label);
n->control_br.false_label = rw_label(c, n->control_br.false_label);
break;
case SPL_IR_CONTROL_JMP:
n->control_jmp.label = rw(c, n->control_jmp.label);
n->control_jmp.label = rw_label(c, n->control_jmp.label);
break;
default:
break;
@@ -166,6 +187,22 @@ static void clone_ref_vec(spl_ir_node_ref_vec_t *dst, const spl_ir_node_ref_vec_
dst->cap = n;
}
static void clone_value_vec(spl_ir_value_vec_t *dst, const spl_ir_value_vec_t *src) {
dst->size = 0;
dst->cap = 0;
dst->data = NULL;
usize n = vec_size(*src);
if (n == 0)
return;
spl_ir_value_t *p = (spl_ir_value_t *)malloc(sizeof(spl_ir_value_t) * n);
if (!p)
return;
memcpy(p, src->data, sizeof(spl_ir_value_t) * n);
dst->data = p;
dst->size = n;
dst->cap = n;
}
static void clone_node(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t dst_ref,
const spl_ir_node_t *src) {
spl_ir_node_t *dst = nd(ir, caller, dst_ref);
@@ -177,18 +214,20 @@ static void clone_node(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
clone_ref_vec((spl_ir_node_ref_vec_t *)&dst->attrs,
(const spl_ir_node_ref_vec_t *)&src->attrs);
if (src->kind == SPL_IR_AGG_CONSTRUCT)
clone_ref_vec(&dst->agg_construct.fields, &src->agg_construct.fields);
clone_value_vec(&dst->agg_construct.fields, &src->agg_construct.fields);
else if (src->kind == SPL_IR_CONTROL_CALL)
clone_ref_vec(&dst->control_call.params, &src->control_call.params);
clone_value_vec(&dst->control_call.params, &src->control_call.params);
}
/* ---- 调用图可达性(防环) ---- */
static spl_ir_func_ref_t call_callee(spl_ir_t *ir, spl_ir_func_ref_t fid, spl_ir_node_t *call) {
spl_ir_node_t *fn = nd(ir, fid, call->control_call.func);
if (!fn || fn->kind != SPL_IR_TYPE_CONST)
(void)ir;
(void)fid;
spl_ir_value_t fn = call->control_call.func;
if (fn.kind != SPL_IR_VALUE_CONST)
return 0;
return fn->type_const.fn;
return fn.fn;
}
static bool reaches(spl_ir_t *ir, spl_ir_func_ref_t from, spl_ir_func_ref_t target,
@@ -234,38 +273,27 @@ static bool reaches_succ(spl_ir_t *ir, spl_ir_func_ref_t from, spl_ir_func_ref_t
typedef struct {
spl_ir_node_ref_t clone_ref;
spl_ir_node_ref_t val;
spl_ir_value_t val;
} ret_rec_t;
static bool param_index(spl_ir_t *ir, spl_ir_func_ref_t fid, spl_ir_node_t *p, usize *out) {
spl_ir_node_t *idx = nd(ir, fid, p->control_param.idx);
if (!idx || idx->kind != SPL_IR_TYPE_CONST)
static bool param_index(spl_ir_node_t *p, usize *out) {
spl_ir_value_t idx = p->control_param.idx;
if (idx.kind != SPL_IR_VALUE_CONST)
return false;
*out = idx->type_const.int_lit;
*out = (usize)idx.int_bits;
return true;
}
static spl_ir_node_ref_t find_const_src(spl_ir_t *ir, spl_ir_func_ref_t fid) {
spl_ir_func_t *f = spl_ir_func(ir, fid);
if (!f)
return 0;
for (usize i = 1; i < vec_size(f->nodes); i++) {
spl_ir_node_t *x = nd(ir, fid, i);
if (x && x->kind == SPL_IR_TYPE_CONST)
return i;
}
return 0;
}
/* 值引用定点替换:等于 ci 的改为 ret_new。 */
typedef struct {
spl_ir_node_ref_t ci;
spl_ir_node_ref_t ret_new;
spl_ir_value_t ret_new;
} replace_one_t;
static spl_ir_node_ref_t replace_one(void *ud, spl_ir_node_ref_t r) {
static spl_ir_value_t replace_one(void *ud, spl_ir_value_t v) {
replace_one_t *p = ud;
return r == p->ci ? p->ret_new : r;
if (v.kind == SPL_IR_VALUE_INST && v.inst == p->ci)
return p->ret_new;
return v;
}
static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t ci,
@@ -285,7 +313,6 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
usize nargs = vec_size(call->control_call.params);
/* 统计参数与返回,分配动态映射。 */
usize cnodes = vec_size(calf->nodes);
usize in_params = 0;
usize in_rets = 0;
@@ -306,100 +333,85 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
c.ir = ir;
c.caller = caller;
c.callee = callee;
c.nparams = in_params;
c.param_ref = (spl_ir_node_ref_t *)malloc(sizeof(spl_ir_node_ref_t) * (in_params ? in_params : 1));
c.param_arg = (spl_ir_node_ref_t *)malloc(sizeof(spl_ir_node_ref_t) * (in_params ? in_params : 1));
c.val_map_size = cnodes;
c.val_map = (spl_ir_value_t *)calloc(cnodes ? cnodes : 1, sizeof(spl_ir_value_t));
ret_rec_t *recs = (ret_rec_t *)malloc(sizeof(ret_rec_t) * (in_rets ? in_rets : 1));
if (!c.param_ref || !c.param_arg || !recs) {
free(c.param_ref);
free(c.param_arg);
if (!c.val_map || !recs) {
free(c.val_map);
free(recs);
return false;
}
spl_type_id_t ret_tid = call->control_call.tid;
bool ok = true;
/* 参数映射(旧 ref -> 实参 ref)。 */
usize pi = 0;
for (usize i = 1; i < cnodes; i++) {
/* 参数:直接映射到实参 Value。 */
for (usize i = 1; i < cnodes && ok; i++) {
spl_ir_node_t *x = nd(ir, callee, i);
if (x && x->kind == SPL_IR_CONTROL_PARAM) {
usize idx = 0;
if (!param_index(ir, callee, x, &idx) || idx >= nargs) {
free(c.param_ref);
free(c.param_arg);
free(recs);
return false;
if (!param_index(x, &idx) || idx >= nargs) {
ok = false;
break;
}
c.param_ref[pi] = i;
c.param_arg[pi] = vec_at(call->control_call.params, idx);
pi++;
c.val_map[i] = vec_at(call->control_call.params, idx);
}
}
if (!ok) {
free(c.val_map);
free(recs);
return false;
}
bool has_val = false;
for (usize i = 1; i < cnodes; i++) {
spl_ir_node_t *x = nd(ir, callee, i);
if (x && x->kind == SPL_IR_CONTROL_RET && x->control_ret.val != 0)
if (x && x->kind == SPL_IR_CONTROL_RET && !spl_ir_value_is_none(x->control_ret.val))
has_val = true;
}
spl_ir_node_ref_t const_src = find_const_src(ir, callee);
if (has_val && const_src == 0) {
free(c.param_ref);
free(c.param_arg);
free(recs);
return false;
}
/* 释放调用点原 params(随后 ci 改为 jmp) */
spl_ir_type_id_t ret_tid = call->control_call.tid;
/* 释放调用点原 params(实参已映射进 val_map)。 */
vec_free(call->control_call.params);
/* 克隆体入口前置:常量 1 + ret 槽 */
spl_ir_node_ref_t body_entry = 0;
spl_ir_node_ref_t slot_ref = 0;
if (has_val) {
spl_ir_node_ref_t c_ref = spl_ir_alloc_node(ir, caller);
clone_node(ir, caller, c_ref, nd(ir, callee, const_src));
spl_ir_node_t *cn = nd(ir, caller, c_ref);
cn->kind = SPL_IR_TYPE_CONST;
cn->type_const.int_lit = 1;
slot_ref = spl_ir_alloc_node(ir, caller);
spl_ir_node_t *sn = nd(ir, caller, slot_ref);
memset(sn, 0, sizeof(*sn));
sn->kind = SPL_IR_MEM_ALLOCA;
sn->mem_alloc.tid = ret_tid;
sn->mem_alloc.count = c_ref;
body_entry = c_ref;
sn->mem_alloc.count = spl_ir_value_const_int(0, 1);
body_entry = slot_ref;
}
c.shift = vec_size(cf->nodes) - 1;
if (!has_val)
body_entry = vec_size(cf->nodes);
/* 克隆体 */
usize nrec = 0;
/* 第一遍:为非 Param 节点分配目标下标,保证前向块标签可解析。 */
for (usize i = 1; i < cnodes; i++) {
spl_ir_node_t *src = nd(ir, callee, i);
if (!src || src->kind == SPL_IR_CONTROL_PARAM)
continue;
spl_ir_node_ref_t dst_ref = spl_ir_alloc_node(ir, caller);
if (dst_ref == 0) {
free(c.param_ref);
free(c.param_arg);
free(c.val_map);
free(recs);
return false;
}
c.val_map[i] = spl_ir_value_inst(dst_ref);
if (body_entry == 0)
body_entry = dst_ref;
}
/* 第二遍:复制内容、重写引用,并把 ret 改成 jmp 占位。 */
usize nrec = 0;
for (usize i = 1; i < cnodes; i++) {
spl_ir_node_t *src = nd(ir, callee, i);
if (!src || src->kind == SPL_IR_CONTROL_PARAM)
continue;
spl_ir_node_ref_t dst_ref = spl_ir_value_inst_ref(c.val_map[i]);
clone_node(ir, caller, dst_ref, src);
rw_node(&c, nd(ir, caller, dst_ref));
spl_ir_node_t *x = nd(ir, caller, dst_ref);
/* 克隆进来的 Param 使用处已替换为实参,节点本身不能留在调用者里
* 改变其参数个数;退化为无害常量。 */
if (src->kind == SPL_IR_CONTROL_PARAM) {
x->kind = SPL_IR_TYPE_CONST;
x->type_const.tid = 0;
x->type_const.int_lit = 0;
continue;
}
if (x->kind == SPL_IR_CONTROL_RET) {
recs[nrec].clone_ref = dst_ref;
recs[nrec].val = x->control_ret.val;
@@ -409,16 +421,15 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
}
}
spl_ir_node_ref_t ret_new = 0;
spl_ir_value_t ret_new = spl_ir_value_none();
if (has_val) {
spl_ir_node_ref_t join = spl_ir_alloc_node(ir, caller);
spl_ir_node_t *jn = nd(ir, caller, join);
memset(jn, 0, sizeof(*jn));
jn->kind = SPL_IR_MEM_LOAD;
jn->mem_load.tid = ret_tid;
jn->mem_load.ptr = slot_ref;
jn->mem_load.ptr = spl_ir_value_inst(slot_ref);
/* join 之后跳回调用点的后继(原代码此处靠 fallthrough)。 */
spl_ir_node_ref_t jc = spl_ir_alloc_node(ir, caller);
spl_ir_node_t *jcn = nd(ir, caller, jc);
memset(jcn, 0, sizeof(*jcn));
@@ -431,7 +442,7 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
memset(stn, 0, sizeof(*stn));
stn->kind = SPL_IR_MEM_STORE;
stn->mem_store.tid = ret_tid;
stn->mem_store.ptr = slot_ref;
stn->mem_store.ptr = spl_ir_value_inst(slot_ref);
stn->mem_store.val = recs[k].val;
spl_ir_node_ref_t jr = spl_ir_alloc_node(ir, caller);
@@ -443,7 +454,7 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
spl_ir_node_t *rn = nd(ir, caller, recs[k].clone_ref);
rn->control_jmp.label = st;
}
ret_new = join;
ret_new = spl_ir_value_inst(join);
} else {
for (usize k = 0; k < nrec; k++) {
spl_ir_node_t *rn = nd(ir, caller, recs[k].clone_ref);
@@ -461,11 +472,10 @@ static bool try_inline(spl_ir_t *ir, spl_ir_func_ref_t caller, spl_ir_node_ref_t
for (usize j = 1; j < orig_len; j++) {
spl_ir_node_t *x = nd(ir, caller, j);
if (x)
xform_node_value_refs(x, replace_one, &rep);
xform_node_values(x, replace_one, &rep);
}
free(c.param_ref);
free(c.param_arg);
free(c.val_map);
free(recs);
return true;
}
@@ -490,7 +500,7 @@ static int opt_function(spl_ir_t *ir, spl_ir_func_ref_t fid, const spl_attr_t *a
if (!func_has_attr(attr, calf, "inline") || func_has_attr(attr, calf, "noinline"))
continue;
/* extern 是占位体,绝不能内联。 */
if (func_has_attr(attr, calf, "extern"))
if (calf->extern_fn || func_has_attr(attr, calf, "extern"))
continue;
/* 防环:callee 传递可达 caller 时拒绝(覆盖直接/间接互递归)。 */
memset(mark, 0, nfuncs);
+441 -197
View File
@@ -1,4 +1,6 @@
#include "spl_ir.h"
#include <stdlib.h>
#include <string.h>
const char *spl_ir_kind_name(spl_ir_kind_t kind) {
static const char *const names[] = {
@@ -11,9 +13,44 @@ const char *spl_ir_kind_name(spl_ir_kind_t kind) {
return "?";
}
static usize const_key_hash(spl_ir_const_key_t k) {
usize h = MAP_HASH_INT((usize)k.tid);
for (usize i = 0; i < k.len; ++i)
h = ((h << 5) + h) ^ (usize)k.data[i];
return h;
}
static int const_key_cmp(spl_ir_const_key_t a, spl_ir_const_key_t b) {
if (a.tid != b.tid || a.len != b.len)
return 1;
if (a.len == 0)
return 0;
return memcmp(a.data, b.data, a.len);
}
void spl_ir_init(spl_ir_t *ir) {
ir->types = calloc(1, sizeof(*ir->types));
spl_ir_type_table_init(ir->types);
ir->owns_types = true;
vec_init(ir->funcs);
vec_push(ir->funcs, (spl_ir_func_t){0});
vec_init(ir->consts);
vec_push(ir->consts, (spl_ir_const_t){0});
vec_init(ir->globals);
vec_push(ir->globals, (spl_ir_global_t){0});
map_init(ir->const_index, const_key_hash, const_key_cmp);
}
void spl_ir_init_shared(spl_ir_t *ir, spl_ir_type_table_t *types) {
ir->types = types;
ir->owns_types = false;
vec_init(ir->funcs);
vec_push(ir->funcs, (spl_ir_func_t){0});
vec_init(ir->consts);
vec_push(ir->consts, (spl_ir_const_t){0});
vec_init(ir->globals);
vec_push(ir->globals, (spl_ir_global_t){0});
map_init(ir->const_index, const_key_hash, const_key_cmp);
}
static void node_drop_vecs(spl_ir_node_t *n) {
@@ -43,8 +80,24 @@ void spl_ir_drop(spl_ir_t *ir) {
}
vec_free(f->attrs);
vec_free(f->nodes);
free((char *)f->name);
}
vec_free(ir->funcs);
for (usize i = 1; i < vec_size(ir->consts); ++i) {
spl_ir_const_t *c = &vec_at(ir->consts, i);
/* 当前池里只有字节块;大整数分支尚未产生,避免 union 双重释放。 */
free(c->bytes.data);
}
vec_free(ir->consts);
for (usize i = 1; i < vec_size(ir->globals); ++i)
free((char *)vec_at(ir->globals, i).name);
vec_free(ir->globals);
map_free(ir->const_index);
if (ir->owns_types && ir->types) {
spl_ir_type_table_drop(ir->types);
free(ir->types);
}
ir->types = NULL;
}
spl_ir_func_ref_t spl_ir_alloc_fn(spl_ir_t *ir) {
@@ -86,6 +139,168 @@ spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id) {
return &vec_at(ir->funcs, fn_id);
}
spl_ir_const_t *spl_ir_const(spl_ir_t *ir, usize const_id) {
if (!ir || const_id == 0 || const_id >= vec_size(ir->consts))
return NULL;
return &vec_at(ir->consts, const_id);
}
spl_ir_node_t *spl_ir_value_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_value_t v) {
if (v.kind != SPL_IR_VALUE_INST || v.inst == 0)
return NULL;
return spl_ir_node(ir, fn_id, v.inst);
}
void spl_ir_node_visit_values(spl_ir_node_t *n, spl_ir_value_cb_t cb, void *ud) {
if (!n || !cb)
return;
switch (n->kind) {
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
case SPL_IR_ARITH_MUL:
case SPL_IR_ARITH_DIV:
case SPL_IR_ARITH_REM:
case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS:
case SPL_IR_ARITH_AND:
case SPL_IR_ARITH_OR:
case SPL_IR_ARITH_XOR:
case SPL_IR_ARITH_SHL:
case SPL_IR_ARITH_SHR:
case SPL_IR_ARITH_NOT:
cb(ud, n->arith.left);
cb(ud, n->arith.right);
break;
case SPL_IR_CMP_EQ:
case SPL_IR_CMP_NE:
case SPL_IR_CMP_LT:
case SPL_IR_CMP_LE:
case SPL_IR_CMP_GT:
case SPL_IR_CMP_GE:
cb(ud, n->cmp.a);
cb(ud, n->cmp.b);
break;
case SPL_IR_CAST_TRUNC:
case SPL_IR_CAST_ZEXT:
case SPL_IR_CAST_SEXT:
case SPL_IR_CAST_FEXT:
case SPL_IR_CAST_FTRUNC:
case SPL_IR_CAST_BITCAST:
case SPL_IR_CAST_PTR2INT:
case SPL_IR_CAST_INT2PTR:
case SPL_IR_CAST_BOOL2INT:
case SPL_IR_CASE_INT2FLOAT:
case SPL_IR_CASE_FLOAT2INT:
cb(ud, n->cast.val);
break;
case SPL_IR_MEM_ALLOCA:
cb(ud, n->mem_alloc.count);
break;
case SPL_IR_MEM_LOAD:
cb(ud, n->mem_load.ptr);
break;
case SPL_IR_MEM_STORE:
cb(ud, n->mem_store.ptr);
cb(ud, n->mem_store.val);
break;
case SPL_IR_MEM_OFFSET:
cb(ud, n->mem_offset.ptr);
cb(ud, n->mem_offset.offset);
break;
case SPL_IR_MEM_FIELD_PTR:
cb(ud, n->mem_field_ptr.agg);
break;
case SPL_IR_MEM_COPY:
cb(ud, n->mem_copy.dst);
cb(ud, n->mem_copy.src);
cb(ud, n->mem_copy.size);
break;
case SPL_IR_MEM_SET:
cb(ud, n->mem_set.dst);
cb(ud, n->mem_set.val);
cb(ud, n->mem_set.size);
break;
case SPL_IR_TYPE_OFFSETOF:
cb(ud, n->ir_offsetof.field_idx);
break;
case SPL_IR_AGG_CONSTRUCT:
for (usize i = 0; i < vec_size(n->agg_construct.fields); ++i)
cb(ud, vec_at(n->agg_construct.fields, i));
break;
case SPL_IR_AGG_EXTRACT:
cb(ud, n->agg_extract.val);
break;
case SPL_IR_AGG_INSERT:
cb(ud, n->agg_insert.agg);
cb(ud, n->agg_insert.field);
break;
case SPL_IR_CONTROL_SELECT:
cb(ud, n->control_select.cond);
cb(ud, n->control_select.true_val);
cb(ud, n->control_select.false_val);
break;
case SPL_IR_CONTROL_BR:
cb(ud, n->control_br.cond);
break;
case SPL_IR_CONTROL_PARAM:
cb(ud, n->control_param.idx);
break;
case SPL_IR_CONTROL_RET:
cb(ud, n->control_ret.val);
break;
case SPL_IR_CONTROL_CALL:
cb(ud, n->control_call.func);
for (usize i = 0; i < vec_size(n->control_call.params); ++i)
cb(ud, vec_at(n->control_call.params, i));
break;
default:
break;
}
}
typedef struct {
spl_ir_t *ir;
spl_ir_func_ref_vec_t *out;
} spl_ir_callee_scan_t;
static bool callee_contains(const spl_ir_func_ref_vec_t *out, spl_ir_func_ref_t fn) {
for (usize i = 0; i < vec_size(*out); ++i) {
if (vec_at(*out, i) == fn)
return true;
}
return false;
}
static void callee_scan_value(void *ud, spl_ir_value_t v) {
spl_ir_callee_scan_t *scan = (spl_ir_callee_scan_t *)ud;
if (v.kind != SPL_IR_VALUE_CONST || !v.tid || !v.fn)
return;
spl_ir_type_node_t *tn = spl_ir_type_node(scan->ir->types, v.tid);
if (!tn || tn->kind != SPL_IR_TYPE_FN)
return;
spl_ir_func_t *callee = spl_ir_func(scan->ir, v.fn);
if (!callee || callee->extern_fn)
return;
if (!callee_contains(scan->out, v.fn))
vec_push(*scan->out, v.fn);
}
bool spl_ir_func_is_extern(spl_ir_t *ir, spl_ir_func_ref_t fn) {
spl_ir_func_t *f = spl_ir_func(ir, fn);
return f && f->extern_fn;
}
void spl_ir_func_callees(spl_ir_t *ir, spl_ir_func_ref_t fn, spl_ir_func_ref_vec_t *out) {
if (!ir || !out)
return;
spl_ir_func_t *f = spl_ir_func(ir, fn);
if (!f)
return;
spl_ir_callee_scan_t scan = {.ir = ir, .out = out};
for (usize i = 1; i < vec_size(f->nodes); ++i)
spl_ir_node_visit_values(&vec_at(f->nodes, i), callee_scan_value, &scan);
}
spl_attr_node_t *spl_ir_fn_extern_attr(const spl_attr_t *attr, const spl_ir_func_t *f) {
if (!attr || !f)
return NULL;
@@ -97,9 +312,9 @@ spl_attr_node_t *spl_ir_fn_extern_attr(const spl_attr_t *attr, const spl_ir_func
return NULL;
}
static inline void ir_dump_type(const spl_type_t *ty, spl_type_id_t tid) {
static inline void ir_dump_type(const spl_ir_type_table_t *ty, spl_ir_type_id_t tid) {
printf("(");
spl_type_pure_dump((spl_type_t *)ty, tid);
spl_ir_type_dump((spl_ir_type_table_t *)ty, tid);
printf(")");
}
@@ -111,7 +326,31 @@ static inline void ir_dump_ref(spl_ir_node_ref_t ref) {
}
}
static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
static inline void ir_dump_value(const spl_ir_type_table_t *ty, spl_ir_value_t v) {
if (v.kind == SPL_IR_VALUE_INST) {
ir_dump_ref(v.inst);
return;
}
if (v.kind == SPL_IR_VALUE_GLOBAL) {
printf(" g#%zu", v.global_id);
return;
}
spl_ir_type_node_t *t = spl_ir_type_node((spl_ir_type_table_t *)ty, v.tid);
if (t && t->kind == SPL_IR_TYPE_FLOAT)
printf(" float=%f", v.float_bits);
else if (t && t->kind == SPL_IR_TYPE_FN)
printf(" fn#%zu", v.fn);
else if (t && t->kind == SPL_IR_TYPE_PTR)
printf(" null");
else if (t && t->kind == SPL_IR_TYPE_INT && t->int_type.bits == 8)
printf(" char='%c'", (char)v.int_bits);
else if (t && (t->kind == SPL_IR_TYPE_ARRAY))
printf(" c#%zu", v.const_id);
else
printf(" int=%llu", (unsigned long long)v.int_bits);
}
static void ir_dump_node(const spl_ir_type_table_t *ty, spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
@@ -124,14 +363,14 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
case SPL_IR_ARITH_SHL:
case SPL_IR_ARITH_SHR:
ir_dump_type(ty, n->arith.tid);
ir_dump_ref(n->arith.left);
ir_dump_ref(n->arith.right);
ir_dump_value(ty, n->arith.left);
ir_dump_value(ty, n->arith.right);
break;
case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS:
case SPL_IR_ARITH_NOT:
ir_dump_type(ty, n->arith.tid);
ir_dump_ref(n->arith.left);
ir_dump_value(ty, n->arith.left);
break;
case SPL_IR_CMP_EQ:
case SPL_IR_CMP_NE:
@@ -140,8 +379,8 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
case SPL_IR_CMP_GT:
case SPL_IR_CMP_GE:
ir_dump_type(ty, n->cmp.tid);
ir_dump_ref(n->cmp.a);
ir_dump_ref(n->cmp.b);
ir_dump_value(ty, n->cmp.a);
ir_dump_value(ty, n->cmp.b);
break;
case SPL_IR_CAST_TRUNC:
case SPL_IR_CAST_ZEXT:
@@ -155,67 +394,46 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
case SPL_IR_CASE_INT2FLOAT:
case SPL_IR_CASE_FLOAT2INT:
printf(" ");
spl_type_pure_dump((spl_type_t *)ty, n->cast.from_tid);
spl_ir_type_dump((spl_ir_type_table_t *)ty, n->cast.from_tid);
printf(" -> ");
spl_type_pure_dump((spl_type_t *)ty, n->cast.to_tid);
ir_dump_ref(n->cast.val);
spl_ir_type_dump((spl_ir_type_table_t *)ty, n->cast.to_tid);
ir_dump_value(ty, n->cast.val);
break;
case SPL_IR_MEM_ALLOCA:
ir_dump_type(ty, n->mem_alloc.tid);
ir_dump_ref(n->mem_alloc.count);
break;
case SPL_IR_MEM_GLOBAL_ALLOC:
ir_dump_type(ty, n->mem_global_alloc.tid);
printf(" g#%zu", n->mem_global_alloc.const_node);
ir_dump_value(ty, n->mem_alloc.count);
break;
case SPL_IR_MEM_LOAD:
ir_dump_type(ty, n->mem_load.tid);
ir_dump_ref(n->mem_load.ptr);
ir_dump_value(ty, n->mem_load.ptr);
break;
case SPL_IR_MEM_STORE:
ir_dump_type(ty, n->mem_store.tid);
ir_dump_ref(n->mem_store.ptr);
ir_dump_ref(n->mem_store.val);
ir_dump_value(ty, n->mem_store.ptr);
ir_dump_value(ty, n->mem_store.val);
break;
case SPL_IR_MEM_OFFSET:
ir_dump_type(ty, n->mem_offset.tid);
ir_dump_ref(n->mem_offset.ptr);
ir_dump_ref(n->mem_offset.offset);
ir_dump_value(ty, n->mem_offset.ptr);
ir_dump_value(ty, n->mem_offset.offset);
break;
case SPL_IR_MEM_FIELD_PTR:
ir_dump_type(ty, n->mem_field_ptr.tid);
ir_dump_ref(n->mem_field_ptr.agg);
ir_dump_value(ty, n->mem_field_ptr.agg);
printf(" #%zu", n->mem_field_ptr.field_idx);
break;
case SPL_IR_MEM_COPY:
ir_dump_type(ty, n->mem_copy.tid);
ir_dump_ref(n->mem_copy.dst);
ir_dump_ref(n->mem_copy.src);
ir_dump_ref(n->mem_copy.size);
ir_dump_value(ty, n->mem_copy.dst);
ir_dump_value(ty, n->mem_copy.src);
ir_dump_value(ty, n->mem_copy.size);
break;
case SPL_IR_MEM_SET:
ir_dump_type(ty, n->mem_set.tid);
ir_dump_ref(n->mem_set.dst);
ir_dump_ref(n->mem_set.val);
ir_dump_ref(n->mem_set.size);
ir_dump_value(ty, n->mem_set.dst);
ir_dump_value(ty, n->mem_set.val);
ir_dump_value(ty, n->mem_set.size);
break;
case SPL_IR_TYPE_CONST: {
ir_dump_type(ty, n->type_const.tid);
spl_type_node_t *t = spl_type_node((spl_type_t *)ty, n->type_const.tid);
if (t && t->kind == SPL_TYPE_FLOAT) {
printf(" float=%f", n->type_const.float_lit);
} else if (t && t->kind == SPL_TYPE_FN) {
printf(" fn#%zu", n->type_const.fn);
} else if (t && t->kind == SPL_TYPE_ARRAY) {
/* 字节常量:不打印宿主指针(不确定),只标记 bytes。 */
printf(" bytes");
} else if (t && t->kind == SPL_TYPE_INT && t->int_type.bits == 8) {
printf(" char='%c'", n->type_const.ch_lit);
} else {
printf(" int=%zu", n->type_const.int_lit);
}
break;
}
case SPL_IR_TYPE_BITSIZEOF:
ir_dump_type(ty, n->bitsizeof.tid);
break;
@@ -227,34 +445,34 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
break;
case SPL_IR_TYPE_OFFSETOF:
ir_dump_type(ty, n->ir_offsetof.tid);
ir_dump_ref(n->ir_offsetof.field_idx);
ir_dump_value(ty, n->ir_offsetof.field_idx);
break;
case SPL_IR_TYPE_FIELD_COUNT:
ir_dump_type(ty, n->field_count.tid);
break;
case SPL_IR_AGG_CONSTRUCT:
ir_dump_type(ty, n->agg_construct.tid);
vec_for(n->agg_construct.fields, i) ir_dump_ref(vec_at(n->agg_construct.fields, i));
vec_for(n->agg_construct.fields, i) ir_dump_value(ty, vec_at(n->agg_construct.fields, i));
break;
case SPL_IR_AGG_EXTRACT:
ir_dump_type(ty, n->agg_extract.tid);
printf(" #%zu", n->agg_extract.field_idx);
ir_dump_ref(n->agg_extract.val);
ir_dump_value(ty, n->agg_extract.val);
break;
case SPL_IR_AGG_INSERT:
ir_dump_type(ty, n->agg_insert.tid);
printf(" #%zu", n->agg_insert.field_idx);
ir_dump_ref(n->agg_insert.agg);
ir_dump_ref(n->agg_insert.field);
ir_dump_value(ty, n->agg_insert.agg);
ir_dump_value(ty, n->agg_insert.field);
break;
case SPL_IR_CONTROL_SELECT:
ir_dump_type(ty, n->control_select.tid);
ir_dump_ref(n->control_select.cond);
ir_dump_ref(n->control_select.true_val);
ir_dump_ref(n->control_select.false_val);
ir_dump_value(ty, n->control_select.cond);
ir_dump_value(ty, n->control_select.true_val);
ir_dump_value(ty, n->control_select.false_val);
break;
case SPL_IR_CONTROL_BR:
ir_dump_ref(n->control_br.cond);
ir_dump_value(ty, n->control_br.cond);
ir_dump_ref(n->control_br.true_label);
ir_dump_ref(n->control_br.false_label);
break;
@@ -263,16 +481,16 @@ static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
break;
case SPL_IR_CONTROL_CALL:
ir_dump_type(ty, n->control_call.tid);
ir_dump_ref(n->control_call.func);
vec_for(n->control_call.params, i) ir_dump_ref(vec_at(n->control_call.params, i));
ir_dump_value(ty, n->control_call.func);
vec_for(n->control_call.params, i) ir_dump_value(ty, vec_at(n->control_call.params, i));
break;
case SPL_IR_CONTROL_PARAM:
ir_dump_type(ty, n->control_param.tid);
ir_dump_ref(n->control_param.idx);
ir_dump_value(ty, n->control_param.idx);
break;
case SPL_IR_CONTROL_RET:
ir_dump_type(ty, n->control_ret.tid);
ir_dump_ref(n->control_ret.val);
ir_dump_value(ty, n->control_ret.val);
break;
case SPL_IR_CONTROL_UNREACHABLE:
case SPL_IR_CONTROL_TRAP:
@@ -296,14 +514,36 @@ static void ir_dump_attr_list(const spl_attr_t *attr, spl_attr_id_vec_t *ids) {
printf("]");
}
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty, const spl_attr_t *attr) {
void spl_ir_dump(spl_ir_t *ir, const spl_attr_t *attr) {
const spl_ir_type_table_t *ty = ir->types;
for (usize i = 1; i < vec_size(ir->consts); ++i) {
spl_ir_const_t *c = &vec_at(ir->consts, i);
printf("const c#%zu ", i);
spl_ir_type_dump((spl_ir_type_table_t *)ty, c->tid);
spl_ir_type_node_t *tn = spl_ir_type_node((spl_ir_type_table_t *)ty, c->tid);
if (tn && tn->kind == SPL_IR_TYPE_ARRAY)
printf(" bytes=%zu", c->bytes.len);
printf("\n");
}
for (usize i = 1; i < vec_size(ir->globals); ++i) {
spl_ir_global_t *g = &vec_at(ir->globals, i);
printf("global g#%zu %s ", i, g->readonly ? "const" : "var");
spl_ir_type_dump((spl_ir_type_table_t *)ty, g->tid);
if (g->name)
printf(" %s", g->name);
if (!spl_ir_value_is_none(g->init)) {
printf(" =");
ir_dump_value(ty, g->init);
}
printf("\n");
}
vec_for(ir->funcs, i) {
if (i == 0)
continue;
spl_ir_func_t *func = &vec_at(ir->funcs, i);
printf("func %s %%%zu", func->name ? func->name : "?", i);
printf(" tid = ");
spl_type_pure_dump((spl_type_t *)ty, func->fn_tid);
spl_ir_type_dump((spl_ir_type_table_t *)ty, func->fn_tid);
ir_dump_attr_list(attr, &func->attrs);
printf("\n");
@@ -344,8 +584,19 @@ static spl_ir_node_ref_t builder_alloc_node(spl_ir_builder_t *b, spl_ir_kind_t k
return ref;
}
static void spl_ir_builder_reset(spl_ir_builder_t *b);
void spl_ir_builder_init(spl_ir_builder_t *b) {
spl_ir_init(&b->ir);
spl_ir_builder_reset(b);
}
void spl_ir_builder_init_shared(spl_ir_builder_t *b, spl_ir_type_table_t *types) {
spl_ir_init_shared(&b->ir, types);
spl_ir_builder_reset(b);
}
static void spl_ir_builder_reset(spl_ir_builder_t *b) {
b->current_fn = 0;
b->dbg = (spl_dbg_node_t){0};
vec_init(b->blocks);
@@ -361,13 +612,13 @@ void spl_ir_builder_drop(spl_ir_builder_t *b) {
}
spl_ir_func_ref_t spl_ir_builder_fn_begin(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid) {
spl_ir_type_id_t fn_tid) {
if (b->current_fn) {
spl_ir_builder_fn_end(b);
}
spl_ir_func_ref_t fid = spl_ir_alloc_fn(&b->ir);
spl_ir_func_t *f = spl_ir_func(&b->ir, fid);
f->name = name;
f->name = name ? strdup(name) : NULL;
vec_init(f->attrs);
f->fn_tid = fn_tid;
@@ -380,10 +631,10 @@ spl_ir_func_ref_t spl_ir_builder_fn_begin(spl_ir_builder_t *b, const char *name,
}
spl_ir_func_ref_t spl_ir_builder_fn_reserve(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid) {
spl_ir_type_id_t fn_tid) {
spl_ir_func_ref_t fid = spl_ir_alloc_fn(&b->ir);
spl_ir_func_t *f = spl_ir_func(&b->ir, fid);
f->name = name;
f->name = name ? strdup(name) : NULL;
vec_init(f->attrs);
f->fn_tid = fn_tid;
return fid;
@@ -458,86 +709,141 @@ void spl_ir_builder_block_end(spl_ir_builder_t *b) {
}
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_tid, \
spl_ir_node_ref_t x_left, spl_ir_node_ref_t x_right) { \
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t x_tid, \
spl_ir_value_t x_left, spl_ir_value_t x_right) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->arith.tid = x_tid; \
n->arith.left = x_left; \
n->arith.right = x_right; \
return ref; \
return spl_ir_value_inst(ref); \
}
SPL_IR_BIN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_tid, \
spl_ir_node_ref_t x_val) { \
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t x_tid, \
spl_ir_value_t x_val) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->arith.tid = x_tid; \
n->arith.left = x_val; \
n->arith.right = 0; \
return ref; \
n->arith.right = spl_ir_value_none(); \
return spl_ir_value_inst(ref); \
}
SPL_IR_UN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_tid, \
spl_ir_node_ref_t x_a, spl_ir_node_ref_t x_b) { \
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t x_tid, \
spl_ir_value_t x_a, spl_ir_value_t x_b) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->cmp.tid = x_tid; \
n->cmp.a = x_a; \
n->cmp.b = x_b; \
return ref; \
return spl_ir_value_inst(ref); \
}
SPL_IR_CMP_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_from, \
spl_type_id_t x_to, spl_ir_node_ref_t x_val) { \
spl_ir_value_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_ir_type_id_t x_from, \
spl_ir_type_id_t x_to, spl_ir_value_t x_val) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->cast.from_tid = x_from; \
n->cast.to_tid = x_to; \
n->cast.val = x_val; \
return ref; \
return spl_ir_value_inst(ref); \
}
SPL_IR_CAST_TABLE
#undef X
spl_ir_node_ref_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t count) {
spl_ir_value_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t count) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_ALLOCA);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_alloc.tid = tid;
n->mem_alloc.count = count;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_mem_global_alloc(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t const_node) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_GLOBAL_ALLOC);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_global_alloc.tid = tid;
n->mem_global_alloc.const_node = const_node;
return ref;
static usize const_pool_add(spl_ir_t *ir, spl_ir_type_id_t tid, const void *data, usize len) {
spl_ir_const_key_t key = {.tid = tid, .data = data, .len = len};
usize id = 0;
if (map_get(ir->const_index, key, &id))
return id;
spl_ir_const_t entry = {0};
entry.tid = tid;
entry.bytes.len = len;
entry.bytes.data = malloc(len ? len : 1);
if (!entry.bytes.data)
return 0;
if (len)
memcpy(entry.bytes.data, data, len);
vec_push(ir->consts, entry);
id = vec_size(ir->consts) - 1;
/* 去重键必须指向池内稳定副本,调用方的指针可能马上失效。 */
key.data = entry.bytes.data;
map_put(ir->const_index, key, id);
return id;
}
spl_ir_node_ref_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr) {
spl_ir_value_t spl_ir_builder_const_bytes(spl_ir_builder_t *b, spl_ir_type_id_t tid, const void *data,
usize len) {
usize id = const_pool_add(&b->ir, tid, data, len);
return spl_ir_value_const_pool(tid, id);
}
spl_ir_value_t spl_ir_builder_const_int(spl_ir_type_id_t tid, uint64_t bits) {
return spl_ir_value_const_int(tid, bits);
}
spl_ir_value_t spl_ir_builder_const_bool(spl_ir_type_id_t tid, bool val) {
return spl_ir_value_const_int(tid, val ? 1 : 0);
}
spl_ir_value_t spl_ir_builder_const_float(spl_ir_type_id_t tid, double val) {
return spl_ir_value_const_float(tid, val);
}
spl_ir_value_t spl_ir_builder_const_null(spl_ir_type_id_t tid) {
return spl_ir_value_const_null(tid);
}
spl_ir_value_t spl_ir_builder_const_fn(spl_ir_type_id_t tid, spl_ir_func_ref_t fn) {
return spl_ir_value_const_fn(tid, fn);
}
spl_ir_value_t spl_ir_builder_global_addr(spl_ir_type_id_t ptr_tid, usize global_id) {
return spl_ir_value_global(ptr_tid, global_id);
}
usize spl_ir_builder_global_declare(spl_ir_builder_t *b, const char *name, spl_ir_type_id_t tid,
spl_ir_value_t init, bool readonly) {
spl_ir_global_t g = {
.name = name ? strdup(name) : NULL,
.tid = tid,
.init = init,
.readonly = readonly,
};
vec_push(b->ir.globals, g);
return vec_size(b->ir.globals) - 1;
}
spl_ir_value_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t ptr) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_LOAD);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_load.tid = tid;
n->mem_load.ptr = ptr;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t val) {
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t ptr, spl_ir_value_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_STORE);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_store.tid = tid;
@@ -546,29 +852,28 @@ spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_type_id_t ti
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t offset) {
spl_ir_value_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t ptr,
spl_ir_value_t offset) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_OFFSET);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_offset.tid = tid;
n->mem_offset.ptr = ptr;
n->mem_offset.offset = offset;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t agg, usize field_idx) {
spl_ir_value_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t agg,
usize field_idx) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_FIELD_PTR);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_field_ptr.tid = tid;
n->mem_field_ptr.agg = agg;
n->mem_field_ptr.field_idx = field_idx;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t src,
spl_ir_node_ref_t size) {
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t dst,
spl_ir_value_t src, spl_ir_value_t size) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_COPY);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_copy.tid = tid;
@@ -578,9 +883,8 @@ spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_type_id_t tid
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t val,
spl_ir_node_ref_t size) {
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_ir_type_id_t tid, spl_ir_value_t dst,
spl_ir_value_t val, spl_ir_value_t size) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_SET);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_set.tid = tid;
@@ -590,104 +894,44 @@ spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_type_id_t tid,
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_bool(spl_ir_builder_t *b, spl_type_id_t tid, bool val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.bool_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_ptr(spl_ir_builder_t *b, spl_type_id_t tid, void *val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.ptr_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_int(spl_ir_builder_t *b, spl_type_id_t tid, usize val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.int_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_float(spl_ir_builder_t *b, spl_type_id_t tid,
double val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.float_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_bytes(spl_ir_builder_t *b, spl_type_id_t tid,
const void *data, usize len) {
(void)len;
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.ptr_lit = (void *)data;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_char(spl_ir_builder_t *b, spl_type_id_t tid, char val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.ch_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_fn(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_func_ref_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.fn = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_value_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_BITSIZEOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->bitsizeof.tid = tid;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_value_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_SIZEOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->ir_sizeof.tid = tid;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_value_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_ALIGNOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->ir_alignof.tid = tid;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t field_idx) {
spl_ir_value_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t field_idx) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_OFFSETOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->ir_offsetof.tid = tid;
n->ir_offsetof.field_idx = field_idx;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_value_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_FIELD_COUNT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->field_count.tid = tid;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_ir_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_AGG_CONSTRUCT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->agg_construct.tid = tid;
@@ -696,48 +940,48 @@ spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_type_id_
}
void spl_ir_builder_agg_construct_field(spl_ir_builder_t *b, spl_ir_node_ref_t node,
spl_ir_node_ref_t field) {
spl_ir_value_t field) {
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, node);
Assert(n != NULL);
vec_push(n->agg_construct.fields, field);
}
spl_ir_node_ref_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_type_id_t tid,
spl_type_id_t field_tid, usize field_idx,
spl_ir_node_ref_t val) {
spl_ir_value_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_type_id_t field_tid, usize field_idx,
spl_ir_value_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_AGG_EXTRACT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->agg_extract.tid = tid;
n->agg_extract.field_tid = field_tid;
n->agg_extract.field_idx = field_idx;
n->agg_extract.val = val;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_type_id_t tid, usize field_idx,
spl_ir_node_ref_t agg, spl_ir_node_ref_t field) {
spl_ir_value_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_ir_type_id_t tid, usize field_idx,
spl_ir_value_t agg, spl_ir_value_t field) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_AGG_INSERT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->agg_insert.tid = tid;
n->agg_insert.field_idx = field_idx;
n->agg_insert.agg = agg;
n->agg_insert.field = field;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t cond, spl_ir_node_ref_t true_val,
spl_ir_node_ref_t false_val) {
spl_ir_value_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t cond, spl_ir_value_t true_val,
spl_ir_value_t false_val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_SELECT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_select.tid = tid;
n->control_select.cond = cond;
n->control_select.true_val = true_val;
n->control_select.false_val = false_val;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_node_ref_t cond) {
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_value_t cond) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_BR);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_br.cond = cond;
@@ -777,8 +1021,8 @@ void spl_ir_builder_control_jmp_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref
vec_push(b->fixups, fx);
}
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t func) {
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t func) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_CALL);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_call.tid = tid;
@@ -788,23 +1032,23 @@ spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_type_id_t
}
void spl_ir_builder_control_call_param(spl_ir_builder_t *b, spl_ir_node_ref_t call_node,
spl_ir_node_ref_t arg) {
spl_ir_value_t arg) {
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, call_node);
Assert(n != NULL);
vec_push(n->control_call.params, arg);
}
spl_ir_node_ref_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t idx) {
spl_ir_value_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t idx) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_PARAM);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_param.tid = tid;
n->control_param.idx = idx;
return ref;
return spl_ir_value_inst(ref);
}
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t val) {
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_ir_type_id_t tid,
spl_ir_value_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_RET);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_ret.tid = tid;
+116 -173
View File
@@ -1,45 +1,41 @@
#include "spl_type.h"
#include "spl_ir_type.h"
static usize spl_type_hash(spl_type_node_t n) {
static usize spl_type_hash(spl_ir_type_node_t n) {
usize hash = spl_hash_seed();
hash = spl_hash_mix(hash, (usize)n.kind);
switch (n.kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_UNIT:
case SPL_TYPE_ANY:
case SPL_TYPE_NEVER:
case SPL_TYPE_INFER:
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_ERROR:
case SPL_IR_TYPE_UNIT:
case SPL_IR_TYPE_BOOL:
break;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
hash = spl_hash_mix(hash, n.int_type.bits);
hash = spl_hash_mix(hash, (usize)n.int_type.is_signed);
break;
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
hash = spl_hash_mix(hash, n.float_type.bits);
break;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
hash = spl_hash_mix(hash, n.ptr_type.pointee);
break;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
hash = spl_hash_mix(hash, n.array_type.element);
hash = spl_hash_mix(hash, n.array_type.len);
break;
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
hash = spl_hash_mix(hash, (usize)n.layout.mode);
hash = spl_hash_mix(hash, n.layout.fixed_align_bits);
hash = spl_hash_mix(hash, n.agg_type.tag_type);
hash = spl_hash_mix(hash, vec_size(n.agg_type.variants));
for (usize i = 0; i < vec_size(n.agg_type.variants); i++) {
spl_type_member_t *m = &vec_at(n.agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(n.agg_type.variants, i);
hash = spl_hash_mix(hash, m->type_id);
hash = spl_hash_mix_str(hash, m->name);
}
break;
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
hash = spl_hash_mix(hash, n.fn_type.ret);
hash = spl_hash_mix(hash, vec_size(n.fn_type.params));
for (usize i = 0; i < vec_size(n.fn_type.params); i++) {
@@ -50,31 +46,27 @@ static usize spl_type_hash(spl_type_node_t n) {
return hash;
}
static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
static int spl_type_eq(spl_ir_type_node_t n1, spl_ir_type_node_t n2) {
if (n1.kind != n2.kind)
return 1;
switch (n1.kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_UNIT:
case SPL_TYPE_ANY:
case SPL_TYPE_NEVER:
case SPL_TYPE_INFER:
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_ERROR:
case SPL_IR_TYPE_UNIT:
case SPL_IR_TYPE_BOOL:
return 0;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
return (n1.int_type.bits != n2.int_type.bits) ||
(n1.int_type.is_signed != n2.int_type.is_signed);
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
return n1.float_type.bits != n2.float_type.bits;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
return n1.ptr_type.pointee != n2.ptr_type.pointee;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
return (n1.array_type.element != n2.array_type.element) ||
(n1.array_type.len != n2.array_type.len);
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
if (n1.layout.mode != n2.layout.mode ||
n1.layout.fixed_align_bits != n2.layout.fixed_align_bits)
return 1;
@@ -83,8 +75,8 @@ static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
if (vec_size(n1.agg_type.variants) != vec_size(n2.agg_type.variants))
return 1;
for (usize i = 0; i < vec_size(n1.agg_type.variants); i++) {
spl_type_member_t *a = &n1.agg_type.variants.data[i];
spl_type_member_t *b = &n2.agg_type.variants.data[i];
spl_ir_type_member_t *a = &n1.agg_type.variants.data[i];
spl_ir_type_member_t *b = &n2.agg_type.variants.data[i];
if (a->type_id != b->type_id)
return 1;
if ((a->name == NULL) != (b->name == NULL))
@@ -93,7 +85,7 @@ static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
return 1;
}
return 0;
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
if (n1.fn_type.ret != n2.fn_type.ret)
return 1;
if (vec_size(n1.fn_type.params) != vec_size(n2.fn_type.params))
@@ -107,15 +99,14 @@ static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
return 1;
}
static void spl_type_node_free_vecs(spl_type_node_t *tn) {
static void spl_ir_type_node_free_vecs(spl_ir_type_node_t *tn) {
switch (tn->kind) {
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM:
vec_free(tn->agg_type.variants);
break;
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
vec_free(tn->fn_type.params);
break;
default:
@@ -125,96 +116,60 @@ static void spl_type_node_free_vecs(spl_type_node_t *tn) {
/* spl_fold 回调:只在链内做结构比较(同桶已保证 hash 相同)。 */
static int spl_type_fold_eq(void *ctx, spl_fold_id_t node, const void *probe) {
spl_type_t *type = (spl_type_t *)ctx;
return spl_type_eq(vec_at(type->type_table, node), *(const spl_type_node_t *)probe) == 0;
spl_ir_type_table_t *type = (spl_ir_type_table_t *)ctx;
return spl_type_eq(vec_at(type->type_table, node), *(const spl_ir_type_node_t *)probe) == 0;
}
static spl_fold_id_t spl_type_fold_next(void *ctx, spl_fold_id_t node) {
spl_type_t *type = (spl_type_t *)ctx;
spl_ir_type_table_t *type = (spl_ir_type_table_t *)ctx;
return vec_at(type->type_table, node).hash_next;
}
static void spl_type_fold_set_next(void *ctx, spl_fold_id_t node, spl_fold_id_t next) {
spl_type_t *type = (spl_type_t *)ctx;
spl_ir_type_table_t *type = (spl_ir_type_table_t *)ctx;
vec_at(type->type_table, node).hash_next = next;
}
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *tn) {
spl_ir_type_id_t spl_ir_type_push(spl_ir_type_table_t *type, spl_ir_type_node_t *tn) {
usize hash = spl_type_hash(*tn);
spl_type_id_t existing = spl_fold_find(&type->type_fold, hash, tn);
spl_ir_type_id_t existing = spl_fold_find(&type->type_fold, hash, tn);
if (existing) {
spl_type_node_free_vecs(tn);
spl_ir_type_node_free_vecs(tn);
return existing;
}
spl_type_id_t id = vec_size(type->type_table);
spl_ir_type_id_t id = vec_size(type->type_table);
vec_push(type->type_table, *tn);
spl_fold_insert(&type->type_fold, hash, id);
tn->kind = SPL_TYPE_ERROR;
tn->kind = SPL_IR_TYPE_ERROR;
return id;
}
void spl_type_init(spl_type_t *type) {
void spl_ir_type_table_init(spl_ir_type_table_t *type) {
vec_init(type->type_table);
spl_type_node_t type_node = {0};
spl_ir_type_node_t type_node = {0};
vec_push(type->type_table, type_node);
spl_fold_init(&type->type_fold, type, spl_type_fold_eq, spl_type_fold_next,
spl_type_fold_set_next);
}
void spl_type_drop(spl_type_t *type) {
void spl_ir_type_table_drop(spl_ir_type_table_t *type) {
for (usize i = 0; i < vec_size(type->type_table); i++) {
spl_type_node_t *n = &vec_at(type->type_table, i);
spl_type_node_free_vecs(n);
spl_ir_type_node_t *n = &vec_at(type->type_table, i);
spl_ir_type_node_free_vecs(n);
}
spl_fold_drop(&type->type_fold);
vec_free(type->type_table);
}
spl_type_node_t *spl_type_node(const spl_type_t *type, spl_type_id_t id) {
spl_ir_type_node_t *spl_ir_type_node(const spl_ir_type_table_t *type, spl_ir_type_id_t id) {
if (!id || id >= vec_size(type->type_table))
return NULL;
return &vec_at(type->type_table, id);
}
bool spl_type_is_subtype(const spl_type_t *type, spl_type_id_t sub, spl_type_id_t super) {
if (sub == 0 || super == 0)
return false;
if (sub == super)
return true;
spl_type_node_t *nsub = spl_type_node(type, sub);
spl_type_node_t *nsuper = spl_type_node(type, super);
if (!nsub || !nsuper)
return false;
if (nsub->kind == SPL_TYPE_NEVER)
return true;
if (nsuper->kind == SPL_TYPE_ANY)
return true;
if (nsub->kind == SPL_TYPE_INT && nsuper->kind == SPL_TYPE_INT) {
if (nsub->int_type.bits == 0)
return true;
if (nsub->int_type.is_signed == nsuper->int_type.is_signed) {
return nsub->int_type.bits <= nsuper->int_type.bits;
}
if (!nsub->int_type.is_signed && nsuper->int_type.is_signed) {
return nsuper->int_type.bits > nsub->int_type.bits;
}
return false;
}
if (nsub->kind == SPL_TYPE_FLOAT && nsuper->kind == SPL_TYPE_FLOAT) {
if (nsub->float_type.bits == 0)
return true;
return nsub->float_type.bits <= nsuper->float_type.bits;
}
return false;
}
static void spl_type_pure_dump_rec(spl_type_t *type, spl_type_id_t id, spl_type_id_vec_t *stack) {
static void spl_ir_type_dump_rec(spl_ir_type_table_t *type, spl_ir_type_id_t id, spl_ir_type_id_vec_t *stack) {
for (usize i = 0; i < vec_size(*stack); i++) {
if (vec_at(*stack, i) == id) {
printf("<rec#%zu>", id);
@@ -227,104 +182,92 @@ static void spl_type_pure_dump_rec(spl_type_t *type, spl_type_id_t id, spl_type_
}
vec_push(*stack, id);
spl_type_node_t *n = spl_type_node(type, id);
spl_ir_type_node_t *n = spl_ir_type_node(type, id);
if (!n) {
printf("none");
(void)vec_pop(*stack);
return;
}
switch (n->kind) {
case SPL_TYPE_ERROR:
case SPL_IR_TYPE_ERROR:
printf("error");
break;
case SPL_TYPE_UNIT:
case SPL_IR_TYPE_UNIT:
printf("unit");
break;
case SPL_TYPE_ANY:
printf("any");
break;
case SPL_TYPE_NEVER:
printf("never");
break;
case SPL_TYPE_INFER:
printf("infer");
break;
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_BOOL:
printf("bool");
break;
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
if (n->int_type.bits == 0)
printf("comptime_int");
else
printf("%s%zu", n->int_type.is_signed ? "i" : "u", n->int_type.bits);
break;
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
if (n->float_type.bits == 0)
printf("comptime_float");
else
printf("f%zu", n->float_type.bits);
break;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
printf("*");
spl_type_pure_dump_rec(type, n->ptr_type.pointee, stack);
spl_ir_type_dump_rec(type, n->ptr_type.pointee, stack);
break;
case SPL_TYPE_ARRAY:
case SPL_IR_TYPE_ARRAY:
printf("[%zu]", n->array_type.len);
spl_type_pure_dump_rec(type, n->array_type.element, stack);
spl_ir_type_dump_rec(type, n->array_type.element, stack);
break;
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE: {
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM: {
const char *kw = "struct";
if (n->kind == SPL_TYPE_UNION)
if (n->kind == SPL_IR_TYPE_UNION)
kw = "union";
else if (n->kind == SPL_TYPE_ENUM)
else if (n->kind == SPL_IR_TYPE_ENUM)
kw = "enum";
else if (n->kind == SPL_TYPE_SHAPE)
kw = "shape";
printf("%s{", kw);
for (usize i = 0; i < vec_size(n->agg_type.variants); i++) {
if (i)
printf(", ");
spl_type_member_t *m = &n->agg_type.variants.data[i];
spl_ir_type_member_t *m = &n->agg_type.variants.data[i];
printf("%s:", m->name ? m->name : "?");
spl_type_pure_dump_rec(type, m->type_id, stack);
spl_ir_type_dump_rec(type, m->type_id, stack);
}
printf("}");
break;
}
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
printf("fn(");
for (usize i = 0; i < vec_size(n->fn_type.params); i++) {
if (i)
printf(",");
spl_type_pure_dump_rec(type, vec_at(n->fn_type.params, i), stack);
spl_ir_type_dump_rec(type, vec_at(n->fn_type.params, i), stack);
}
printf(")");
spl_type_pure_dump_rec(type, n->fn_type.ret, stack);
spl_ir_type_dump_rec(type, n->fn_type.ret, stack);
break;
}
(void)vec_pop(*stack);
}
void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id) {
spl_type_id_vec_t stack;
void spl_ir_type_dump(spl_ir_type_table_t *type, spl_ir_type_id_t id) {
spl_ir_type_id_vec_t stack;
vec_init(stack);
spl_type_pure_dump_rec(type, id, &stack);
spl_ir_type_dump_rec(type, id, &stack);
vec_free(stack);
}
static const spl_type_member_t *spl_type_agg_member_find(spl_type_t *type, spl_type_id_t tid,
static const spl_ir_type_member_t *spl_ir_type_member_find(spl_ir_type_table_t *type, spl_ir_type_id_t tid,
const char *name, usize *out_idx) {
spl_type_node_t *n = spl_type_node(type, tid);
spl_ir_type_node_t *n = spl_ir_type_node(type, tid);
if (!n || !name)
return NULL;
if (n->kind == SPL_TYPE_STRUCT || n->kind == SPL_TYPE_UNION || n->kind == SPL_TYPE_ENUM ||
n->kind == SPL_TYPE_SHAPE) {
if (n->kind == SPL_IR_TYPE_STRUCT || n->kind == SPL_IR_TYPE_UNION ||
n->kind == SPL_IR_TYPE_ENUM) {
for (usize i = 0; i < vec_size(n->agg_type.variants); i++) {
spl_type_member_t *m = &n->agg_type.variants.data[i];
spl_ir_type_member_t *m = &n->agg_type.variants.data[i];
if (m->name && strcmp(m->name, name) == 0) {
if (out_idx)
*out_idx = i;
@@ -335,82 +278,82 @@ static const spl_type_member_t *spl_type_agg_member_find(spl_type_t *type, spl_t
return NULL;
}
const spl_type_member_t *spl_type_agg_member(spl_type_t *type, spl_type_id_t tid,
const spl_ir_type_member_t *spl_ir_type_member(spl_ir_type_table_t *type, spl_ir_type_id_t tid,
const char *name) {
return spl_type_agg_member_find(type, tid, name, NULL);
return spl_ir_type_member_find(type, tid, name, NULL);
}
bool spl_type_agg_member_idx(spl_type_t *type, spl_type_id_t tid, const char *name,
bool spl_ir_type_member_idx(spl_ir_type_table_t *type, spl_ir_type_id_t tid, const char *name,
usize *out_idx) {
return spl_type_agg_member_find(type, tid, name, out_idx) != NULL;
return spl_ir_type_member_find(type, tid, name, out_idx) != NULL;
}
spl_type_id_t spl_type_builder_simple(spl_type_t *type, spl_type_node_kind_t kind) {
spl_type_node_t tn = {0};
spl_ir_type_id_t spl_ir_type_builder_simple(spl_ir_type_table_t *type, spl_ir_type_kind_t kind) {
spl_ir_type_node_t tn = {0};
tn.kind = kind;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
return spl_type_node_push(type, &tn);
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_int(spl_type_t *type, usize bits, int is_signed) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_INT;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_id_t spl_ir_type_builder_int(spl_ir_type_table_t *type, usize bits, int is_signed) {
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_INT;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
tn.int_type.bits = bits;
tn.int_type.is_signed = is_signed;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_float(spl_type_t *type, usize bits) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_FLOAT;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_id_t spl_ir_type_builder_float(spl_ir_type_table_t *type, usize bits) {
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_FLOAT;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
tn.float_type.bits = bits;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_ptr(spl_type_t *type, spl_type_id_t pointee) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_PTR;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_id_t spl_ir_type_builder_ptr(spl_ir_type_table_t *type, spl_ir_type_id_t pointee) {
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_PTR;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
tn.ptr_type.pointee = pointee;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_array(spl_type_t *type, spl_type_id_t element, usize len) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_ARRAY;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_id_t spl_ir_type_builder_array(spl_ir_type_table_t *type, spl_ir_type_id_t element, usize len) {
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_ARRAY;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
tn.array_type.element = element;
tn.array_type.len = len;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_fn(spl_type_t *type, spl_type_id_t ret, const spl_type_id_t *params,
spl_ir_type_id_t spl_ir_type_builder_fn(spl_ir_type_table_t *type, spl_ir_type_id_t ret, const spl_ir_type_id_t *params,
usize nparams) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_FN;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
spl_ir_type_node_t tn = {0};
tn.kind = SPL_IR_TYPE_FN;
tn.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
vec_init(tn.fn_type.params);
for (usize i = 0; i < nparams; i++) {
vec_push(tn.fn_type.params, params[i]);
}
tn.fn_type.ret = ret;
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
spl_type_id_t spl_type_builder_agg(spl_type_t *type, spl_type_node_kind_t tk,
spl_type_member_vec_t *variants, spl_type_id_t tag_type,
spl_type_layout_t layout) {
spl_type_node_t tn = {0};
spl_ir_type_id_t spl_ir_type_builder_agg(spl_ir_type_table_t *type, spl_ir_type_kind_t tk,
spl_ir_type_member_vec_t *variants, spl_ir_type_id_t tag_type,
spl_ir_type_layout_t layout) {
spl_ir_type_node_t tn = {0};
tn.kind = tk;
tn.layout = layout;
tn.agg_type.variants = *variants;
vec_init(*variants);
if (tk == SPL_TYPE_ENUM) {
if (tk == SPL_IR_TYPE_ENUM) {
tn.agg_type.tag_type = tag_type;
} else {
tn.agg_type.tag_type = 0;
}
return spl_type_node_push(type, &tn);
return spl_ir_type_push(type, &tn);
}
+39 -37
View File
@@ -9,7 +9,7 @@ static void infos_grow(spl_layout_t *layout, usize n) {
}
}
static spl_layout_info_t *infos_at(spl_layout_t *layout, spl_type_id_t id) {
static spl_layout_info_t *infos_at(spl_layout_t *layout, spl_ir_type_id_t id) {
if (id == 0 || id >= vec_size(layout->infos))
return NULL;
return &vec_at(layout->infos, id);
@@ -84,20 +84,20 @@ static const spl_layout_ptr_t *default_ptr(spl_layout_t *layout) {
return &vec_at(layout->pointers, 0);
}
static bool layout_scalar(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_info_t *out) {
static bool layout_scalar(spl_layout_t *layout, spl_ir_type_node_t *tn, spl_layout_info_t *out) {
usize size_bits = 0;
switch (tn->kind) {
case SPL_TYPE_INT:
case SPL_IR_TYPE_INT:
if (tn->int_type.bits == 0)
return false; /* comptime_int 未落地 */
size_bits = tn->int_type.bits;
break;
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_FLOAT:
if (tn->float_type.bits == 0)
return false; /* comptime_float 未落地 */
size_bits = tn->float_type.bits;
break;
case SPL_TYPE_BOOL:
case SPL_IR_TYPE_BOOL:
size_bits = 8;
break;
default:
@@ -129,11 +129,11 @@ static usize round_up_bits(usize x, usize align_bits) {
return (x + a - 1) / a * a;
}
static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_info_t *out) {
static bool layout_agg(spl_layout_t *layout, spl_ir_type_node_t *tn, spl_layout_info_t *out) {
usize n = vec_size(tn->agg_type.variants);
if (tn->kind == SPL_TYPE_ENUM) {
spl_type_id_t tag_tid = tn->agg_type.tag_type;
if (tn->kind == SPL_IR_TYPE_ENUM) {
spl_ir_type_id_t tag_tid = tn->agg_type.tag_type;
if (!tag_tid)
return false;
spl_layout_info_t *tag_info = infos_at(layout, tag_tid);
@@ -145,7 +145,7 @@ static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_inf
usize payload_size_bits = 0;
for (usize i = 0; i < n; ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(tn->agg_type.variants, i);
if (m->type_id == 0) /* 无载荷变体 */
continue;
spl_layout_info_t *fi = infos_at(layout, m->type_id);
@@ -168,7 +168,7 @@ static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_inf
vec_push(out->field_bit_offsets, 0);
vec_push(out->field_bit_sizes, tag_info->size_bits);
for (usize i = 0; i < n; ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(tn->agg_type.variants, i);
usize fsize = 0;
if (m->type_id) {
spl_layout_info_t *fi = infos_at(layout, m->type_id);
@@ -189,10 +189,10 @@ static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_inf
usize max_align_bits = 8;
usize offset_bits = 0;
bool is_union = (tn->kind == SPL_TYPE_UNION);
bool is_union = (tn->kind == SPL_IR_TYPE_UNION);
for (usize i = 0; i < n; ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(tn->agg_type.variants, i);
usize fsize_bits = 0;
usize fsize_align = 8;
if (m->type_id) {
@@ -236,12 +236,12 @@ static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_inf
return true;
}
static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t id) {
static void resolve_type(spl_layout_t *layout, const spl_ir_type_table_t *type, spl_ir_type_id_t id) {
spl_layout_info_t *info = infos_at(layout, id);
if (!info || info->resolved)
return;
spl_type_node_t *tn = spl_type_node(type, id);
spl_ir_type_node_t *tn = spl_ir_type_node(type, id);
if (!tn)
return;
@@ -250,30 +250,23 @@ static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t i
info->resolved = true;
switch (tn->kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_INFER:
case SPL_TYPE_NEVER:
case SPL_TYPE_UNIT:
case SPL_IR_TYPE_ERROR:
case SPL_IR_TYPE_UNIT:
info->size_bits = 0;
info->align_bits = 8;
return;
case SPL_TYPE_ANY:
/* 顶层类型按不透明指针处理 */
layout_ptr(layout, info);
return;
case SPL_TYPE_BOOL:
case SPL_TYPE_INT:
case SPL_TYPE_FLOAT:
case SPL_IR_TYPE_BOOL:
case SPL_IR_TYPE_INT:
case SPL_IR_TYPE_FLOAT:
layout_scalar(layout, tn, info);
return;
case SPL_TYPE_PTR:
case SPL_IR_TYPE_PTR:
layout_ptr(layout, info);
return;
case SPL_TYPE_ARRAY: {
case SPL_IR_TYPE_ARRAY: {
resolve_type(layout, type, tn->array_type.element);
spl_layout_info_t *elem = infos_at(layout, tn->array_type.element);
if (!elem || !elem->resolved)
@@ -283,14 +276,13 @@ static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t i
return;
}
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE: {
if (tn->kind == SPL_TYPE_ENUM && tn->agg_type.tag_type)
case SPL_IR_TYPE_STRUCT:
case SPL_IR_TYPE_UNION:
case SPL_IR_TYPE_ENUM: {
if (tn->kind == SPL_IR_TYPE_ENUM && tn->agg_type.tag_type)
resolve_type(layout, type, tn->agg_type.tag_type);
for (usize i = 0; i < vec_size(tn->agg_type.variants); ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
spl_ir_type_member_t *m = &vec_at(tn->agg_type.variants, i);
if (m->type_id)
resolve_type(layout, type, m->type_id);
}
@@ -298,7 +290,7 @@ static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t i
return;
}
case SPL_TYPE_FN:
case SPL_IR_TYPE_FN:
/* 函数类型按函数指针布局 */
for (usize i = 0; i < vec_size(tn->fn_type.params); ++i)
resolve_type(layout, type, vec_at(tn->fn_type.params, i));
@@ -308,13 +300,23 @@ static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t i
}
}
void spl_layout_resolve(spl_layout_t *layout, spl_type_t *type) {
void spl_layout_resolve(spl_layout_t *layout, const spl_ir_type_table_t *type) {
infos_grow(layout, vec_size(type->type_table));
for (usize i = 0; i < vec_size(layout->infos); ++i) {
spl_layout_info_t *info = &vec_at(layout->infos, i);
vec_free(info->field_bit_offsets);
vec_free(info->field_bit_sizes);
vec_init(info->field_bit_offsets);
vec_init(info->field_bit_sizes);
info->size_bits = 0;
info->align_bits = 0;
info->resolved = false;
}
for (usize i = 1; i < vec_size(type->type_table); ++i)
resolve_type(layout, type, i);
}
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_type_id_t id) {
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_ir_type_id_t id) {
spl_layout_info_t *info = infos_at(layout, id);
if (!info || !info->resolved)
return NULL;
@@ -434,7 +434,6 @@ spl_tok_vec_t spl_lex(const char *source, const char *fname) {
TRY_OP2('|', '=', TOK_ASSIGN_OR, TOK_OR)
TRY_OP2('^', '=', TOK_ASSIGN_XOR, TOK_XOR)
TRY_OP2('-', '>', TOK_RIGHT_ARROW, TOK_SUB)
TRY_OP2(':', '=', TOK_COLON_ASSIGN, TOK_COLON)
/* Single-character operators */
TRY_OP1('+', TOK_ADD);
@@ -463,7 +462,6 @@ spl_tok_vec_t spl_lex(const char *source, const char *fname) {
TRY_OP1('#', TOK_SHARP);
TRY_OP1('@', TOK_AT);
TRY_OP1('$', TOK_DOLLAR);
TRY_OP1('?', TOK_COND);
LOG_ERROR("%s:%zu:%zu: unknown character '%c' (0x%02x)", fname ? fname : "<null>", line, col,
(c >= 32 && c < 127) ? c : '?', (unsigned char)c);
File renamed without changes.
File diff suppressed because it is too large. Load diff
File renamed without changes.
@@ -83,14 +83,14 @@ spl_intrin_t spl_intrin_lookup_field(spl_lang_type_kind_t recv_kind, const char
return SPL_INTRIN_NONE;
}
spl_intrin_t spl_intrin_lookup_cast(spl_type_t *type, spl_type_id_t ft, spl_type_id_t tt) {
spl_intrin_t spl_intrin_lookup_cast(spl_ir_type_table_t *type, spl_ir_type_id_t ft, spl_ir_type_id_t tt) {
/* 这是 `as` 的展开规则表。要调整 as 的语义,改这里。 */
spl_type_node_t *f = spl_type_node(type, ft);
spl_type_node_t *t = spl_type_node(type, tt);
spl_ir_type_node_t *f = spl_ir_type_node(type, ft);
spl_ir_type_node_t *t = spl_ir_type_node(type, tt);
if (!f || !t)
return SPL_INTRIN_NONE;
if (f->kind == SPL_TYPE_INT && t->kind == SPL_TYPE_INT) {
if (f->kind == SPL_IR_TYPE_INT && t->kind == SPL_IR_TYPE_INT) {
usize fb = f->int_type.bits;
usize tb = t->int_type.bits;
if (fb == tb)
@@ -99,15 +99,15 @@ spl_intrin_t spl_intrin_lookup_cast(spl_type_t *type, spl_type_id_t ft, spl_type
return SPL_INTRIN_TRUNCATE;
return SPL_INTRIN_INT_CAST;
}
if (f->kind == SPL_TYPE_FLOAT && t->kind == SPL_TYPE_FLOAT)
if (f->kind == SPL_IR_TYPE_FLOAT && t->kind == SPL_IR_TYPE_FLOAT)
return SPL_INTRIN_FLOAT_CAST;
if (f->kind == SPL_TYPE_BOOL && t->kind == SPL_TYPE_INT)
if (f->kind == SPL_IR_TYPE_BOOL && t->kind == SPL_IR_TYPE_INT)
return SPL_INTRIN_BOOL2INT;
if (f->kind == SPL_TYPE_PTR && t->kind == SPL_TYPE_INT)
if (f->kind == SPL_IR_TYPE_PTR && t->kind == SPL_IR_TYPE_INT)
return SPL_INTRIN_PTR2INT;
if (f->kind == SPL_TYPE_INT && t->kind == SPL_TYPE_PTR)
if (f->kind == SPL_IR_TYPE_INT && t->kind == SPL_IR_TYPE_PTR)
return SPL_INTRIN_INT2PTR;
if (f->kind == SPL_TYPE_PTR && t->kind == SPL_TYPE_PTR)
if (f->kind == SPL_IR_TYPE_PTR && t->kind == SPL_IR_TYPE_PTR)
return SPL_INTRIN_PTR_CAST;
/* int float 刻意不在这里:只能通过显式 builtin 调用。
+135
View File
@@ -0,0 +1,135 @@
#include "spl_ir_link.h"
#include "spl_ast2ir.h"
#include "spl_lang_type.h"
#include "spl_sema.h"
#include <stdlib.h>
#include <string.h>
typedef struct {
usize def_id;
spl_ir_func_ref_t fn;
} spl_ir_link_fn_entry_t;
typedef VEC(spl_ir_link_fn_entry_t) spl_ir_link_fn_vec_t;
struct spl_ir_link {
spl_ir_t *ir;
spl_sema_t *sema;
spl_ir_link_fn_vec_t fns;
};
spl_ir_link_t *spl_ir_link_create(spl_ir_t *ir, spl_sema_t *sema) {
if (!ir || !sema)
return NULL;
spl_ir_link_t *link = calloc(1, sizeof(*link));
if (!link)
return NULL;
link->ir = ir;
link->sema = sema;
vec_init(link->fns);
return link;
}
void spl_ir_link_destroy(spl_ir_link_t *link) {
if (!link)
return;
vec_free(link->fns);
free(link);
}
static spl_ir_link_fn_entry_t *link_find_def(spl_ir_link_t *link, usize def_id) {
for (usize i = 0; i < vec_size(link->fns); ++i) {
spl_ir_link_fn_entry_t *entry = &vec_at(link->fns, i);
if (entry->def_id == def_id)
return entry;
}
return NULL;
}
static spl_ir_link_fn_entry_t *link_find_fn(spl_ir_link_t *link, spl_ir_func_ref_t fn) {
for (usize i = 0; i < vec_size(link->fns); ++i) {
spl_ir_link_fn_entry_t *entry = &vec_at(link->fns, i);
if (entry->fn == fn)
return entry;
}
return NULL;
}
spl_ir_func_ref_t spl_ir_link_reserve_fn(spl_ir_link_t *link, usize def_id) {
if (!link || !def_id)
return 0;
spl_ir_link_fn_entry_t *existing = link_find_def(link, def_id);
if (existing)
return existing->fn;
spl_def_node_t *def = spl_def_node(link->sema->type, def_id);
if (!def || def->kind != SPL_DEF_FN || !def->owner_ast)
return 0;
spl_lang_type_id_t fn_lang = def->lang_id;
if (!fn_lang)
return 0;
spl_lang_type_node_t *fn_ln = spl_lang_type_node(link->sema->type, fn_lang);
if (!fn_ln || fn_ln->kind != SPL_LANG_TYPE_FN || !fn_ln->ir_type_id)
return 0;
char name_buf[1024];
const char *name = def->name;
spl_ast_node_t *fn_node = spl_ast_node(def->owner_ast, def->ast_node_ref);
if (fn_node && fn_node->kind == SPL_AST_FN_DECL &&
spl_ast2ir_fn_name(link->sema, link->sema->attr, def->owner_ast, fn_node, name_buf,
sizeof(name_buf)))
name = name_buf;
spl_ir_func_ref_t fn = spl_ir_alloc_fn(link->ir);
spl_ir_func_t *irf = spl_ir_func(link->ir, fn);
if (!irf)
return 0;
irf->name = name ? strdup(name) : NULL;
vec_init(irf->attrs);
irf->fn_tid = fn_ln->ir_type_id;
if (fn_node && fn_node->kind == SPL_AST_FN_DECL && link->sema->attr) {
for (usize i = 0; i < vec_size(fn_node->attrs); ++i) {
spl_attr_node_t *an = spl_attr_node(link->sema->attr, vec_at(fn_node->attrs, i));
if (an && an->info && an->info->name && strcmp(an->info->name, "extern") == 0) {
irf->extern_fn = true;
break;
}
}
}
spl_ir_link_fn_entry_t entry = {.def_id = def_id, .fn = fn};
vec_push(link->fns, entry);
return fn;
}
spl_ir_value_t spl_ir_link_fn_value(spl_ir_link_t *link, usize def_id) {
spl_ir_func_ref_t fn = spl_ir_link_reserve_fn(link, def_id);
if (!fn)
return spl_ir_value_none();
spl_ir_link_fn_entry_t *entry = link_find_fn(link, fn);
if (!entry)
return spl_ir_value_none();
spl_def_node_t *def = spl_def_node(link->sema->type, entry->def_id);
if (!def || !def->lang_id)
return spl_ir_value_none();
spl_lang_type_node_t *fn_ln = spl_lang_type_node(link->sema->type, def->lang_id);
if (!fn_ln || !fn_ln->ir_type_id)
return spl_ir_value_none();
return spl_ir_value_const_fn(fn_ln->ir_type_id, fn);
}
bool spl_ir_link_def_of_fn(const spl_ir_link_t *link, spl_ir_func_ref_t fn, usize *out_def) {
if (!link || !fn)
return false;
for (usize i = 0; i < vec_size(link->fns); ++i) {
const spl_ir_link_fn_entry_t *entry = &vec_at(link->fns, i);
if (entry->fn == fn) {
if (out_def)
*out_def = entry->def_id;
return true;
}
}
return false;
}
+96
View File
@@ -0,0 +1,96 @@
#include "spl_meta.h"
#include "spl_exec.h"
#include "spl_exec_frontend.h"
#include "spl_exec_vm.h"
#include "spl_sap.h"
#include <stdlib.h>
struct spl_meta {
spl_sema_t *sema;
spl_exec_frontend_ctx_t *frontend;
spl_exec_vm_ctx_t *backend;
spl_exec_t *exec;
spl_sap_t *sap;
bool prepared;
bool failed;
};
spl_meta_t *spl_meta_create(spl_sema_t *sema) {
if (!sema)
return NULL;
spl_meta_t *m = calloc(1, sizeof(*m));
if (!m)
return NULL;
m->sema = sema;
m->sap = spl_sap_create(sema->type);
if (!m->sap) {
free(m);
return NULL;
}
return m;
}
void spl_meta_destroy(spl_meta_t *m) {
if (!m)
return;
if (m->exec)
spl_exec_destroy(m->exec);
spl_sap_destroy(m->sap);
spl_exec_vm_destroy(m->backend);
spl_exec_frontend_destroy(m->frontend);
free(m);
}
bool spl_meta_prepare(spl_meta_t *m) {
if (!m)
return false;
if (m->prepared)
return !m->failed;
m->prepared = true;
m->frontend = spl_exec_frontend_create(m->sema);
if (!m->frontend) {
m->failed = true;
return false;
}
m->backend = spl_exec_vm_create(spl_exec_frontend_ir(m->frontend), m->sema->layout,
m->sema->attr);
if (!m->backend) {
m->failed = true;
return false;
}
m->exec = spl_exec_create((spl_ir_t *)spl_exec_frontend_ir(m->frontend), m->sema->layout,
spl_exec_frontend_vtable(m->frontend),
spl_exec_vm_vtable(m->backend));
if (!m->exec) {
m->failed = true;
return false;
}
spl_exec_set_phase(m->exec, SPL_EXEC_PHASE_META, 0);
if (!spl_sap_bind(m->exec, m->sap)) {
m->failed = true;
return false;
}
return true;
}
spl_sap_t *spl_meta_sap(spl_meta_t *m) { return m ? m->sap : NULL; }
spl_sap_handle_t spl_meta_register_handle(spl_meta_t *m, spl_ast_t *ast,
spl_ast_node_ref_t ref) {
if (!m || !m->sap)
return 0;
return spl_sap_handle_register(m->sap, ast, ref);
}
bool spl_meta_invoke(spl_meta_t *m, spl_def_id_t def_id, const usize *args, usize nargs,
usize *out) {
if (!m || !out || !spl_meta_prepare(m))
return false;
spl_ir_func_ref_t fn = spl_ir_link_reserve_fn(spl_exec_frontend_link(m->frontend), def_id);
if (!fn)
return false;
return spl_exec_run(m->exec, fn, args, nargs, out);
}
+134
View File
@@ -0,0 +1,134 @@
#include "spl_meta.h"
static bool meta_const_bits(spl_ast_node_t *n, usize *out) {
if (!n)
return false;
switch (n->kind) {
case SPL_AST_EXPR_INT_LIT:
*out = (usize)n->int_lit.bits;
return true;
case SPL_AST_EXPR_BOOL_LIT:
*out = n->bool_lit.val ? 1 : 0;
return true;
case SPL_AST_EXPR_CHAR_LIT:
*out = (usize)(unsigned char)n->char_lit.val;
return true;
case SPL_AST_EXPR_NULL_LIT:
*out = 0;
return true;
default:
return false;
}
}
spl_lang_type_id_t spl_meta_eval_call(spl_sema_t *sema, spl_ast_node_t *n, spl_def_id_t def_id) {
if (!sema->meta) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_UNHANDLED_NODE, &n->dbg,
"compile-time execution is not available");
return 0;
}
spl_def_node_t *def = spl_def_node(sema->type, def_id);
if (!def) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_UNDEFINED_SYMBOL, &n->dbg,
"meta function definition not found");
return 0;
}
spl_lang_type_id_t fn_tid = def->lang_id;
if (fn_tid == 0)
fn_tid = spl_sema_eval_decl(sema, def_id);
spl_lang_type_node_t *fn = spl_lang_type_node(sema->type, fn_tid);
if (!fn || fn->kind != SPL_LANG_TYPE_FN) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_NOT_A_FUNCTION, &n->dbg,
"`@%s` is not a meta function", n->compile_call.name);
return 0;
}
usize nargs = vec_size(n->compile_call.args);
usize nparams = vec_size(fn->extra.fn.params);
if (nargs != nparams) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_ARG_COUNT_MISMATCH, &n->dbg,
"meta call argument count mismatch (expected %zu, got %zu)", nparams, nargs);
return 0;
}
/* 后续求值会继续 push lang_table,先把签名拷出来。 */
spl_lang_type_id_t ret_tid = fn->extra.fn.ret;
spl_lang_type_id_t *params = nparams ? malloc(nparams * sizeof(*params)) : NULL;
if (nparams && !params) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_INTERNAL, &n->dbg, "out of memory");
return 0;
}
for (usize i = 0; i < nparams; ++i)
params[i] = vec_at(fn->extra.fn.params, i);
if (sema->current_fn_kind != SPL_DEF_FN_NORMAL) {
/* 编译期函数体内部:这里只做类型检查,调用留到 meta IR 执行。 */
for (usize i = 0; i < nparams; ++i) {
spl_ast_node_ref_t aref = vec_at(n->compile_call.args, i);
if (!spl_sema_coerce_expr(sema, aref, params[i])) {
free(params);
return 0;
}
}
free(params);
n->resolved_def_id = def_id;
n->resolved_lang_tid = ret_tid;
return ret_tid;
}
usize *bits = nparams ? calloc(nparams, sizeof(*bits)) : NULL;
if (nparams && !bits) {
free(params);
spl_diag_error(sema->diag, SPL_DIAG_KIND_INTERNAL, &n->dbg, "out of memory");
return 0;
}
for (usize i = 0; i < nparams; ++i) {
spl_ast_node_ref_t aref = vec_at(n->compile_call.args, i);
if (!spl_sema_coerce_expr(sema, aref, params[i])) {
free(params);
free(bits);
return 0;
}
spl_ast_node_t *arg = spl_ast_node(sema->ast, aref);
if (!meta_const_bits(arg, &bits[i])) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_TYPE_MISMATCH, arg ? &arg->dbg : &n->dbg,
"meta call argument must be a compile-time constant");
free(params);
free(bits);
return 0;
}
}
free(params);
usize result = 0;
bool ok = spl_meta_invoke(sema->meta, def_id, bits, nparams, &result);
free(bits);
if (!ok) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_INTERNAL, &n->dbg,
"compile-time call `@%s` failed", n->compile_call.name);
return 0;
}
spl_lang_type_node_t *ret = spl_lang_type_node(sema->type, ret_tid);
if (ret && ret->kind == SPL_LANG_TYPE_INT) {
vec_free(n->compile_call.args);
n->kind = SPL_AST_EXPR_INT_LIT;
n->int_lit.bits = (uint64_t)result;
} else if (ret && ret->kind == SPL_LANG_TYPE_BOOL) {
vec_free(n->compile_call.args);
n->kind = SPL_AST_EXPR_BOOL_LIT;
n->bool_lit.val = result != 0;
} else if (ret && ret->kind == SPL_LANG_TYPE_UNIT) {
return ret_tid;
} else {
spl_diag_error(sema->diag, SPL_DIAG_KIND_TYPE_MISMATCH, &n->dbg,
"meta call result type cannot land as a constant yet");
return 0;
}
n->resolved_lang_tid = ret_tid;
return ret_tid;
}
+166
View File
@@ -0,0 +1,166 @@
#include "spl_module.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
static const char *path_basename(const char *path) {
const char *base = path;
for (const char *p = path; *p; ++p)
if (*p == '/' || *p == '\\')
base = p + 1;
return base;
}
bool spl_module_name_from_path(const char *path, char *out, usize cap) {
if (!path || !out || cap == 0)
return false;
const char *base = path_basename(path);
const char *dot = strrchr(base, '.');
usize len = dot && dot != base ? (usize)(dot - base) : strlen(base);
if (len == 0)
return false;
usize w = 0;
if (isdigit((unsigned char)base[0])) {
if (w + 1 >= cap)
return false;
out[w++] = '_';
}
for (usize i = 0; i < len && w + 1 < cap; ++i) {
unsigned char c = (unsigned char)base[i];
out[w++] = (isalnum(c) || c == '_') ? (char)c : '_';
}
out[w] = '\0';
return w > 0;
}
const char *spl_module_declared_name(spl_ast_t *ast) {
if (!ast || !ast->root)
return NULL;
spl_ast_node_t *root = spl_ast_node(ast, ast->root);
if (!root || root->kind != SPL_AST_ROOT || !root->root.members)
return NULL;
spl_ast_node_t *cm = spl_ast_node(ast, root->root.members);
if (!cm || cm->kind != SPL_AST_CONTAINER_MEMBERS || !cm->container_members.module)
return NULL;
spl_ast_node_t *mod = spl_ast_node(ast, cm->container_members.module);
if (!mod || mod->kind != SPL_AST_MOD_DECL)
return NULL;
return mod->mod_decl.path;
}
spl_ast_node_ref_t spl_module_container(spl_module_t *mod) {
if (!mod || !mod->ast || !mod->ast->root)
return 0;
spl_ast_node_t *root = spl_ast_node(mod->ast, mod->ast->root);
if (!root || root->kind != SPL_AST_ROOT)
return 0;
return root->root.members;
}
const char *spl_module_last_segment(const char *name) {
if (!name)
return NULL;
const char *last = name;
for (const char *p = name; *p; ++p)
if (*p == '.')
last = p + 1;
return last;
}
void spl_module_registry_init(spl_module_registry_t *reg) {
vec_init(reg->modules);
map_init(reg->by_name, MAP_HASH_STR, MAP_CMP_STR);
map_init(reg->by_path, MAP_HASH_STR, MAP_CMP_STR);
}
void spl_module_registry_drop(spl_module_registry_t *reg) {
for (usize i = 0; i < vec_size(reg->modules); ++i) {
free(vec_at(reg->modules, i).name);
free(vec_at(reg->modules, i).file_path);
}
vec_free(reg->modules);
map_free(reg->by_name);
map_free(reg->by_path);
}
spl_module_t *spl_module_get(spl_module_registry_t *reg, spl_module_id_t id) {
if (!reg || id == 0 || id > vec_size(reg->modules))
return NULL;
return &vec_at(reg->modules, id - 1);
}
spl_module_id_t spl_module_find_name(spl_module_registry_t *reg, const char *name) {
spl_module_id_t id = 0;
if (!reg || !name)
return 0;
if (map_get(reg->by_name, name, &id))
return id;
return 0;
}
spl_module_id_t spl_module_find_ast(spl_module_registry_t *reg, spl_ast_t *ast) {
if (!reg || !ast)
return 0;
for (usize i = 0; i < vec_size(reg->modules); ++i)
if (vec_at(reg->modules, i).ast == ast)
return vec_at(reg->modules, i).id;
return 0;
}
spl_module_id_t spl_module_register(spl_module_registry_t *reg, spl_ast_t *ast,
const char *file_path, const char *declared_name,
spl_diag_t *diag) {
if (!reg || !ast)
return 0;
char derived[256];
const char *name = declared_name;
if (!name || !*name) {
if (!file_path || !spl_module_name_from_path(file_path, derived, sizeof derived)) {
spl_diag_error(diag, SPL_DIAG_KIND_INTERNAL, NULL, "cannot derive module name");
return 0;
}
name = derived;
}
spl_module_id_t existing_path = 0;
if (file_path && map_get(reg->by_path, file_path, &existing_path))
return existing_path;
spl_module_id_t existing_name = 0;
if (map_get(reg->by_name, name, &existing_name)) {
spl_module_t *old = spl_module_get(reg, existing_name);
spl_diag_error(diag, SPL_DIAG_KIND_DUPLICATE_SYMBOL, NULL,
"duplicate module `%s` (already loaded from `%s`)", name,
old && old->file_path ? old->file_path : "?");
return 0;
}
spl_module_t mod = {0};
mod.id = vec_size(reg->modules) + 1;
mod.name = strdup(name);
mod.file_path = file_path ? strdup(file_path) : NULL;
mod.ast = ast;
mod.state = SPL_MODULE_LOADED;
mod.sema_state = 0;
spl_ast_node_t *root = spl_ast_node(ast, ast->root);
if (root && root->kind == SPL_AST_ROOT && root->root.members) {
mod.container = root->root.members;
spl_ast_node_t *cm = spl_ast_node(ast, mod.container);
if (cm && cm->kind == SPL_AST_CONTAINER_MEMBERS && cm->container_members.module) {
spl_ast_node_t *header = spl_ast_node(ast, cm->container_members.module);
if (header && header->kind == SPL_AST_MOD_DECL)
mod.state = SPL_MODULE_LOADED;
}
}
vec_push(reg->modules, mod);
spl_module_t *stored = &vec_at(reg->modules, vec_size(reg->modules) - 1);
map_put(reg->by_name, stored->name, stored->id);
if (stored->file_path)
map_put(reg->by_path, stored->file_path, stored->id);
return stored->id;
}
+167
View File
@@ -0,0 +1,167 @@
#include "spl_namespace.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *ns_strdup(const char *s) {
if (!s)
return NULL;
usize n = strlen(s);
char *r = malloc(n + 1);
if (!r)
return NULL;
memcpy(r, s, n + 1);
return r;
}
static const char *ns_name_or_default(const char *name, spl_ns_id_t id, char *buf, usize cap) {
if (name && *name)
return name;
snprintf(buf, cap, "$ns%zu", id);
return buf;
}
void spl_ns_init(spl_namespace_t *ns) {
vec_init(ns->nodes);
spl_ns_node_t dummy = {0};
vec_push(ns->nodes, dummy);
ns->root = 0;
ns->current = 0;
ns->root = spl_ns_create(ns, 0, SPL_NS_ROOT, "pkg", 0, 0);
ns->current = ns->root;
}
void spl_ns_drop(spl_namespace_t *ns) {
for (usize i = 0; i < vec_size(ns->nodes); ++i) {
free((char *)vec_at(ns->nodes, i).name);
free((char *)vec_at(ns->nodes, i).qualified);
map_free(vec_at(ns->nodes, i).symbols);
}
vec_free(ns->nodes);
ns->root = 0;
ns->current = 0;
}
spl_ns_id_t spl_ns_root(spl_namespace_t *ns) {
if (!ns)
return 0;
if (ns->root == 0)
ns->root = spl_ns_create(ns, 0, SPL_NS_ROOT, "pkg", 0, 0);
return ns->root;
}
spl_ns_id_t spl_ns_create(spl_namespace_t *ns, spl_ns_id_t parent, spl_ns_kind_t kind,
const char *name, usize owner_kind, usize owner_id) {
if (!ns)
return 0;
spl_ns_id_t id = vec_size(ns->nodes);
char name_buf[32];
const char *resolved_name = ns_name_or_default(name, id, name_buf, sizeof name_buf);
const char *parent_qualified = NULL;
if (parent && parent < vec_size(ns->nodes))
parent_qualified = vec_at(ns->nodes, parent).qualified;
usize cap = strlen(resolved_name) + (parent_qualified ? strlen(parent_qualified) + 2 : 1);
char *qualified = malloc(cap);
if (!qualified)
return 0;
if (parent_qualified && *parent_qualified)
snprintf(qualified, cap, "%s.%s", parent_qualified, resolved_name);
else
snprintf(qualified, cap, "%s", resolved_name);
spl_ns_node_t node = {0};
node.id = id;
node.parent = parent;
node.kind = kind;
node.name = ns_strdup(resolved_name);
node.qualified = qualified;
node.owner_kind = owner_kind;
node.owner_id = owner_id;
map_init(node.symbols, MAP_HASH_STR, MAP_CMP_STR);
vec_push(ns->nodes, node);
if (!ns->root)
ns->root = id;
return id;
}
spl_ns_id_t spl_ns_alloc(spl_namespace_t *ns, spl_ns_kind_t kind, const char *name) {
if (!ns)
return 0;
spl_ns_id_t parent = ns->current ? ns->current : spl_ns_root(ns);
return spl_ns_create(ns, parent, kind, name, 0, 0);
}
bool spl_ns_enter(spl_namespace_t *ns, spl_ns_id_t id) {
if (!ns || id == 0 || id >= vec_size(ns->nodes))
return false;
ns->current = id;
return true;
}
bool spl_ns_leave(spl_namespace_t *ns) {
if (!ns || ns->current == 0)
return false;
ns->current = vec_at(ns->nodes, ns->current).parent;
return true;
}
bool spl_ns_insert(spl_namespace_t *ns, spl_ns_id_t id, spl_symbol_t symbol) {
if (!ns || id == 0 || id >= vec_size(ns->nodes) || !symbol.name)
return false;
spl_ns_node_t *node = &vec_at(ns->nodes, id);
spl_symbol_t old = {0};
if (map_get(node->symbols, symbol.name, &old))
return false;
map_put(node->symbols, symbol.name, symbol);
return true;
}
bool spl_ns_lookup(spl_namespace_t *ns, const char *name, spl_symbol_t *out) {
if (!ns || !name || !out)
return false;
spl_ns_id_t id = ns->current ? ns->current : ns->root;
for (; id != 0 && id < vec_size(ns->nodes); id = vec_at(ns->nodes, id).parent) {
if (map_get(vec_at(ns->nodes, id).symbols, name, out))
return true;
}
return false;
}
bool spl_ns_lookup_local(spl_namespace_t *ns, spl_ns_id_t id, const char *name,
spl_symbol_t *out) {
if (!ns || id == 0 || id >= vec_size(ns->nodes) || !name || !out)
return false;
return map_get(vec_at(ns->nodes, id).symbols, name, out);
}
const char *spl_ns_qualified(spl_namespace_t *ns, spl_ns_id_t id) {
if (!ns || id == 0 || id >= vec_size(ns->nodes))
return NULL;
return vec_at(ns->nodes, id).qualified;
}
bool spl_ns_symbol_qualified(spl_namespace_t *ns, spl_ns_id_t id, const char *local_name,
char *out, usize cap) {
if (!out || cap == 0)
return false;
const char *prefix = spl_ns_qualified(ns, id);
if (!prefix || !local_name)
return false;
int n = snprintf(out, cap, "%s.%s", prefix, local_name);
return n >= 0 && (usize)n < cap;
}
spl_ns_id_t spl_ns_child(spl_namespace_t *ns, spl_ns_id_t parent, const char *name) {
if (!ns || !name)
return 0;
for (usize i = 1; i < vec_size(ns->nodes); ++i) {
spl_ns_node_t *n = &vec_at(ns->nodes, i);
if (n->parent == parent && n->name && strcmp(n->name, name) == 0)
return n->id;
}
return 0;
}
+390 -179
View File
@@ -87,11 +87,18 @@ static inline const spl_tok_t *peek(spl_parser_t *p) {
static inline const spl_tok_t *advance(spl_parser_t *p) {
const spl_tok_t *t = peek(p);
if (t && t->type != TOK_EOF)
if (t && t->type != TOK_EOF) {
p->last_tok_line = t->line;
p->pos++;
}
return t;
}
static inline int line_changed(const spl_parser_t *p) {
const spl_tok_t *t = &vec_at(p->ast->input, p->pos);
return t->line > p->last_tok_line;
}
static inline spl_ast_node_t *node_at(spl_ast_t *ast, spl_ast_node_ref_t ref) {
return &ast->node_buckets.data[ref];
}
@@ -209,7 +216,6 @@ static int can_start_expr(spl_tok_type_t t) {
case KW_UNDEFINED:
case TOK_IDENT:
case TOK_AT:
case TOK_SHARP:
case TOK_DOLLAR:
case TOK_L_PAREN:
case TOK_L_BRACKET:
@@ -220,6 +226,10 @@ static int can_start_expr(spl_tok_type_t t) {
case TOK_BIT_NOT:
case TOK_AND:
case TOK_MUL:
case KW_RET:
case KW_BREAK:
case KW_CONTINUE:
case KW_DEFER:
case KW_IF:
case KW_WHILE:
case KW_LOOP:
@@ -245,7 +255,10 @@ static int can_start_statement(spl_tok_type_t t) {
case KW_VAR:
case KW_CONST:
case KW_TYPE:
case KW_COMPTIME:
case KW_FN:
case KW_META:
case KW_MACRO:
case TOK_SHARP:
return 1;
default:
return 0;
@@ -266,13 +279,17 @@ static spl_ast_node_ref_t parse_expr(spl_parser_t *p);
static spl_ast_node_ref_vec_t parse_expr_list(spl_parser_t *p);
static spl_ast_node_ref_t parse_block(spl_parser_t *p);
static spl_ast_node_ref_t parse_type_expr(spl_parser_t *p);
static spl_ast_node_ref_t parse_type_comptime_call(spl_parser_t *p);
static spl_ast_node_ref_t parse_type_compile_call(spl_parser_t *p);
static spl_ast_node_ref_t parse_statement(spl_parser_t *p);
static spl_ast_node_ref_t parse_container_declaration(spl_parser_t *p);
static spl_ast_node_ref_t parse_param_decl_impl(spl_parser_t *p);
static spl_ast_node_ref_t parse_pattern(spl_parser_t *p);
static spl_ast_node_ref_t parse_pattern_atom(spl_parser_t *p);
static spl_ast_node_ref_t parse_pattern_aggregate(spl_parser_t *p, const spl_tok_t *start);
static void parse_decorators(spl_parser_t *p, spl_ast_node_ref_vec_t *out);
static void parse_attributes(spl_parser_t *p, spl_ast_node_ref_vec_t *out);
static void parse_external_tags(spl_parser_t *p, spl_ast_node_ref_vec_t *out);
static const char *parse_dotted_path(spl_parser_t *p, const char *what);
static spl_ast_node_ref_t parse_cast(spl_parser_t *p);
static spl_ast_node_ref_t parse_prefix(spl_parser_t *p);
@@ -280,7 +297,7 @@ static spl_ast_node_ref_t parse_postfix(spl_parser_t *p);
static spl_ast_node_ref_t parse_primary(spl_parser_t *p);
static spl_ast_node_ref_vec_t parse_aggregate_fields(spl_parser_t *p);
static spl_ast_node_ref_t parse_array_literal(spl_parser_t *p);
static spl_ast_node_ref_t parse_comptime_call(spl_parser_t *p);
static spl_ast_node_ref_t parse_compile_call(spl_parser_t *p);
static spl_ast_node_ref_t parse_if_expr(spl_parser_t *p);
static spl_ast_node_ref_t parse_while_expr(spl_parser_t *p);
static spl_ast_node_ref_t parse_loop_expr(spl_parser_t *p);
@@ -290,7 +307,6 @@ static spl_ast_node_ref_t parse_ret_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_break_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_continue_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_defer_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_comptime_stmt(spl_parser_t *p);
static spl_ast_node_ref_t parse_label(spl_parser_t *p);
/* ---------- Pattern ---------- */
@@ -395,6 +411,9 @@ static spl_ast_node_ref_t parse_pattern_atom(spl_parser_t *p) {
case KW_NULL:
advance(p);
return new_node(p, SPL_AST_EXPR_NULL_LIT, t);
case KW_UNDEFINED:
advance(p);
return new_node(p, SPL_AST_EXPR_UNDEFINED_LIT, t);
case TOK_IDENT: {
advance(p);
@@ -510,49 +529,129 @@ static spl_ast_node_ref_t parse_pattern(spl_parser_t *p) {
/* ---------- 声明 ---------- */
static void parse_tag_list(spl_parser_t *p, spl_ast_node_ref_vec_t *out, int is_external,
int allow_at) {
while (!p->failed) {
const spl_tok_t *t = peek(p);
if (!t || (t->type != TOK_AT && t->type != TOK_SHARP))
return;
if (!allow_at && t->type == TOK_AT)
return;
static const char *parse_dotted_path(spl_parser_t *p, const char *what) {
const spl_tok_t *t = peek(p);
if (!t || t->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected %s", what);
return NULL;
}
int is_at = (t->type == TOK_AT);
usize cap = 64;
usize len = 0;
char *buf = malloc(cap);
if (!buf)
return NULL;
while (1) {
if (len + t->len + 2 > cap) {
cap = (len + t->len + 2) * 2;
char *grown = realloc(buf, cap);
if (!grown) {
free(buf);
return NULL;
}
buf = grown;
}
memcpy(buf + len, t->lexeme, t->len);
len += t->len;
advance(p);
if (is_external) {
t = peek(p);
if (!t || t->type != TOK_NOT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected '!' in external tag");
return;
}
advance(p);
}
if (!peek(p) || peek(p)->type != TOK_DOT)
break;
advance(p);
t = peek(p);
if (!t || t->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected identifier after '.'");
break;
}
buf[len++] = '.';
}
const char *name = intern_string(p->ast, buf, len);
free(buf);
return name;
}
static spl_ast_node_ref_t parse_tag_item(spl_parser_t *p, const spl_tok_t *start, int is_external,
int is_at) {
spl_ast_node_ref_t ref =
new_node(p, is_external ? SPL_AST_EXTERNAL_TAG_ITEM : SPL_AST_TAG_ITEM, start);
spl_ast_node_t *tag = node_at(p->ast, ref);
tag->tag_item.is_at = is_at;
tag->tag_item.is_external = is_external;
vec_init(tag->tag_item.args);
if (is_at) {
const char *name = parse_dotted_path(p, "decorator name");
if (!name)
return ref;
node_at(p->ast, ref)->tag_item.name = name;
} else {
const spl_tok_t *t = peek(p);
if (!t || t->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected tag name");
return ref;
}
advance(p);
SET_STR_FIELD(p->ast, tag->tag_item.name, t);
}
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_L_PAREN) {
advance(p);
spl_ast_node_ref_vec_t args = parse_expr_list(p);
node_at(p->ast, ref)->tag_item.args = args;
expect(p, TOK_R_PAREN, "')' in tag args");
}
return ref;
}
static void parse_attributes(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
while (!p->failed) {
const spl_tok_t *t = peek(p);
if (!t || t->type != TOK_SHARP)
return;
advance(p);
spl_ast_node_ref_t ref = parse_tag_item(p, t, 0, 0);
vec_push(*out, ref);
}
}
static void parse_decorators(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
while (!p->failed) {
const spl_tok_t *t = peek(p);
if (!t || t->type != TOK_AT)
return;
advance(p);
spl_ast_node_ref_t ref = parse_tag_item(p, t, 0, 1);
vec_push(*out, ref);
}
}
static void parse_external_tags(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
while (!p->failed) {
const spl_tok_t *t = peek(p);
if (!t || t->type != TOK_SHARP)
return;
usize save = p->pos;
usize save_line = p->last_tok_line;
advance(p);
const spl_tok_t *bang = peek(p);
if (!bang || bang->type != TOK_NOT) {
p->pos = save;
p->last_tok_line = save_line;
return;
}
advance(p);
spl_ast_node_ref_t ref =
new_node(p, is_external ? SPL_AST_EXTERNAL_TAG_ITEM : SPL_AST_TAG_ITEM, t);
spl_ast_node_t *tag = node_at(p->ast, ref);
tag->tag_item.is_at = is_at;
tag->tag_item.is_external = is_external;
SET_STR_FIELD(p->ast, tag->tag_item.name, t);
t = peek(p);
if (t && t->type == TOK_L_PAREN) {
advance(p);
spl_ast_node_ref_vec_t args = parse_expr_list(p);
node_at(p->ast, ref)->tag_item.args = args;
if (!expect(p, TOK_R_PAREN, "')' in tag args"))
return;
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name, "expected external tag name");
return;
}
spl_ast_node_ref_t ref = parse_tag_item(p, t, 1, 0);
node_at(p->ast, ref)->tag_item.name =
intern_string(p->ast, name->lexeme, name->len);
vec_push(*out, ref);
}
}
@@ -565,7 +664,7 @@ static void parse_param_list(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
if (t->type == TOK_R_PAREN) {
break;
} else if (t->type == TOK_AT || t->type == TOK_SHARP || t->type == TOK_IDENT) {
} else if (t->type == TOK_SHARP || t->type == TOK_IDENT) {
spl_ast_node_ref_t pd = parse_param_decl_impl(p);
if (pd)
vec_push(*out, pd);
@@ -594,7 +693,7 @@ static void parse_param_list(spl_parser_t *p, spl_ast_node_ref_vec_t *out) {
static spl_ast_node_ref_t parse_param_decl_impl(spl_parser_t *p) {
spl_ast_node_ref_vec_t attr_list;
vec_init(attr_list);
parse_tag_list(p, &attr_list, 0, 1);
parse_attributes(p, &attr_list);
const spl_tok_t *name = peek(p);
if (!name || (name->type != TOK_IDENT && name->type != KW_UNDERSCORE)) {
@@ -609,7 +708,7 @@ static spl_ast_node_ref_t parse_param_decl_impl(spl_parser_t *p) {
return 0;
}
parse_tag_list(p, &attr_list, 0, 0);
parse_attributes(p, &attr_list);
spl_ast_node_ref_t type_expr = parse_type_expr(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_PARAM_DECL, name);
@@ -620,8 +719,9 @@ static spl_ast_node_ref_t parse_param_decl_impl(spl_parser_t *p) {
return ref;
}
static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t tag_list) {
const spl_tok_t *kw = peek(p);
static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t decorator_list,
spl_ast_node_ref_vec_t attr_list, spl_fn_kind_t fn_kind,
const spl_tok_t *kw) {
if (!kw || kw->type != KW_FN)
return 0;
advance(p);
@@ -629,13 +729,15 @@ static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name ? name : kw, "expected function name");
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
advance(p);
if (!expect(p, TOK_L_PAREN, "'(' in function declaration")) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
@@ -643,7 +745,8 @@ static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t
vec_init(params);
parse_param_list(p, &params);
if (!expect(p, TOK_R_PAREN, "')' in function declaration")) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
vec_free(params);
return 0;
}
@@ -664,15 +767,17 @@ static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t
} else {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_UNRECOGNIZED, t,
"function declaration must end with ';' or block");
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
vec_free(params);
return 0;
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_FN_DECL, kw);
spl_ast_node_t *fn = node_at(p->ast, ref);
MOVE_VEC(fn->fn_decl.tag_list, tag_list);
fn->fn_decl.is_comptime = 0;
MOVE_VEC(fn->fn_decl.decorator_list, decorator_list);
MOVE_VEC(fn->fn_decl.attr_list, attr_list);
fn->fn_decl.fn_kind = fn_kind;
SET_STR_FIELD(p->ast, fn->fn_decl.name, name);
fn->fn_decl.params = params;
fn->fn_decl.ret_type = ret_type;
@@ -680,27 +785,34 @@ static spl_ast_node_ref_t parse_fn_decl(spl_parser_t *p, spl_ast_node_ref_vec_t
return ref;
}
static spl_ast_node_ref_t parse_type_decl(spl_parser_t *p, spl_ast_node_ref_vec_t tag_list) {
static spl_ast_node_ref_t parse_type_decl(spl_parser_t *p, spl_ast_node_ref_vec_t decorator_list,
spl_ast_node_ref_vec_t attr_list) {
const spl_tok_t *kw = peek(p);
if (!kw || kw->type != KW_TYPE)
if (!kw || kw->type != KW_TYPE) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
advance(p);
spl_ast_node_ref_t pattern = parse_pattern(p);
if (!pattern) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, peek(p), "expected pattern after 'type'");
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
if (!expect(p, TOK_ASSIGN, "'=' in type declaration")) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TYPE_DECL, kw);
spl_ast_node_t *td = node_at(p->ast, ref);
MOVE_VEC(td->type_decl.attr_list, tag_list);
MOVE_VEC(td->type_decl.decorator_list, decorator_list);
MOVE_VEC(td->type_decl.attr_list, attr_list);
td->type_decl.pattern = pattern;
spl_ast_node_ref_t type_expr = parse_type_expr(p);
@@ -713,20 +825,31 @@ static spl_ast_node_ref_t parse_type_decl(spl_parser_t *p, spl_ast_node_ref_vec_
return ref;
}
static spl_ast_node_ref_t parse_var_const_decl(spl_parser_t *p, spl_ast_node_ref_vec_t tag_list,
int is_const) {
static spl_ast_node_ref_t parse_var_const_decl(spl_parser_t *p,
spl_ast_node_ref_vec_t decorator_list,
spl_ast_node_ref_vec_t attr_list, int is_const) {
const spl_tok_t *kw = peek(p);
if (!kw)
if (!kw) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
if (is_const && kw->type != KW_CONST)
}
if (is_const && kw->type != KW_CONST) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
if (!is_const && kw->type != KW_VAR)
}
if (!is_const && kw->type != KW_VAR) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
advance(p);
spl_ast_node_ref_t pattern = parse_pattern(p);
if (!pattern) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
@@ -749,7 +872,8 @@ static spl_ast_node_ref_t parse_var_const_decl(spl_parser_t *p, spl_ast_node_ref
spl_ast_node_ref_t ref = new_node(p, is_const ? SPL_AST_CONST_DECL : SPL_AST_VAR_DECL, kw);
spl_ast_node_t *vc = node_at(p->ast, ref);
MOVE_VEC(vc->var_const_decl.attr_list, tag_list);
MOVE_VEC(vc->var_const_decl.decorator_list, decorator_list);
MOVE_VEC(vc->var_const_decl.attr_list, attr_list);
vc->var_const_decl.pattern = pattern;
vc->var_const_decl.type = type_expr;
vc->var_const_decl.init_expr = init_expr;
@@ -760,10 +884,15 @@ static spl_ast_node_ref_t parse_var_const_decl(spl_parser_t *p, spl_ast_node_ref
return ref;
}
static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p, spl_ast_node_ref_vec_t tag_list) {
static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p,
spl_ast_node_ref_vec_t decorator_list,
spl_ast_node_ref_vec_t attr_list) {
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT)
if (!name || name->type != TOK_IDENT) {
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
advance(p);
spl_ast_node_ref_t type_expr = 0;
@@ -771,7 +900,7 @@ static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p, spl_ast_node_ref_ve
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_COLON) {
advance(p);
parse_tag_list(p, &tag_list, 0, 0);
parse_attributes(p, &attr_list);
type_expr = parse_type_expr(p);
t = peek(p);
if (t && t->type == TOK_ASSIGN) {
@@ -785,7 +914,8 @@ static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p, spl_ast_node_ref_ve
spl_ast_node_ref_t ref = new_node(p, SPL_AST_MEMBER_DECL, name);
spl_ast_node_t *md = node_at(p->ast, ref);
MOVE_VEC(md->member_decl.attr_list, tag_list);
MOVE_VEC(md->member_decl.decorator_list, decorator_list);
MOVE_VEC(md->member_decl.attr_list, attr_list);
SET_STR_FIELD(p->ast, md->member_decl.name, name);
md->member_decl.type_expr = type_expr;
md->member_decl.init_expr = init_expr;
@@ -796,61 +926,178 @@ static spl_ast_node_ref_t parse_member_decl(spl_parser_t *p, spl_ast_node_ref_ve
return ref;
}
static spl_ast_node_ref_t parse_comptime_decl(spl_parser_t *p) {
static spl_ast_node_ref_t parse_mod_decl(spl_parser_t *p, spl_ast_node_ref_vec_t decorator_list) {
const spl_tok_t *kw = peek(p);
if (!kw || kw->type != KW_COMPTIME)
if (!kw || kw->type != KW_MOD) {
vec_free(decorator_list);
return 0;
}
advance(p);
spl_ast_node_ref_t body = 0;
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_L_BRACE)
body = parse_block(p);
else
body = parse_expr(p);
const char *path = parse_dotted_path(p, "module path");
if (!path) {
vec_free(decorator_list);
return 0;
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_COMPTIME_DECL, kw);
node_at(p->ast, ref)->comptime_decl.body = body;
spl_ast_node_ref_t ref = new_node(p, SPL_AST_MOD_DECL, kw);
spl_ast_node_t *mod = node_at(p->ast, ref);
MOVE_VEC(mod->mod_decl.decorator_list, decorator_list);
mod->mod_decl.path = path;
mod->mod_decl.has_body = false;
vec_init(mod->mod_decl.decls);
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_SEMICOLON) {
advance(p);
return ref;
}
if (!t || t->type != TOK_L_BRACE) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "expected ';' or '{' after module path");
return ref;
}
advance(p);
mod = node_at(p->ast, ref);
mod->mod_decl.has_body = true;
while (!p->failed) {
t = peek(p);
if (!t || t->type == TOK_EOF) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t, "module missing '}'");
break;
}
if (t->type == TOK_R_BRACE) {
advance(p);
break;
}
spl_ast_node_ref_t decl = parse_container_declaration(p);
mod = node_at(p->ast, ref);
if (decl)
vec_push(mod->mod_decl.decls, decl);
else
break;
t = peek(p);
if (t && (t->type == TOK_COMMA || t->type == TOK_SEMICOLON))
advance(p);
}
return ref;
}
static spl_ast_node_ref_t parse_import_decl(spl_parser_t *p,
spl_ast_node_ref_vec_t decorator_list) {
const spl_tok_t *kw = peek(p);
if (!kw || kw->type != KW_IMPORT) {
vec_free(decorator_list);
return 0;
}
advance(p);
bool is_path = true;
const char *path = NULL;
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_STRING_LITERAL) {
advance(p);
usize len = 0;
path = parse_string_literal(p, t, &len);
is_path = false;
} else {
path = parse_dotted_path(p, "import path");
if (!path) {
vec_free(decorator_list);
return 0;
}
}
const char *alias = NULL;
t = peek(p);
if (t && t->type == KW_AS) {
advance(p);
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name, "expected alias after 'as'");
vec_free(decorator_list);
return 0;
}
advance(p);
alias = intern_string(p->ast, name->lexeme, name->len);
t = peek(p);
}
if (t && t->type == TOK_SEMICOLON)
advance(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_IMPORT_DECL, kw);
spl_ast_node_t *imp = node_at(p->ast, ref);
MOVE_VEC(imp->import_decl.decorator_list, decorator_list);
imp->import_decl.is_path = is_path;
imp->import_decl.path = path;
imp->import_decl.alias = alias;
return ref;
}
static spl_ast_node_ref_t parse_container_declaration(spl_parser_t *p) {
spl_ast_node_ref_vec_t tag_list;
vec_init(tag_list);
parse_tag_list(p, &tag_list, 0, 0);
spl_ast_node_ref_vec_t decorator_list;
vec_init(decorator_list);
parse_decorators(p, &decorator_list);
spl_ast_node_ref_vec_t attr_list;
vec_init(attr_list);
parse_attributes(p, &attr_list);
const spl_tok_t *t = peek(p);
if (!t || t->type == TOK_EOF) {
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
switch (t->type) {
case KW_FN:
return parse_fn_decl(p, tag_list);
return parse_fn_decl(p, decorator_list, attr_list, SPL_FN_KIND_NORMAL, t);
case KW_META:
case KW_MACRO: {
spl_fn_kind_t fn_kind = (t->type == KW_META) ? SPL_FN_KIND_META : SPL_FN_KIND_MACRO;
advance(p);
const spl_tok_t *fn_kw = peek(p);
if (!fn_kw || fn_kw->type != KW_FN) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, fn_kw, "expected 'fn' after '%s'",
fn_kind == SPL_FN_KIND_META ? "meta" : "macro");
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
return parse_fn_decl(p, decorator_list, attr_list, fn_kind, fn_kw);
}
case KW_TYPE:
return parse_type_decl(p, tag_list);
return parse_type_decl(p, decorator_list, attr_list);
case KW_VAR:
return parse_var_const_decl(p, tag_list, 0);
return parse_var_const_decl(p, decorator_list, attr_list, 0);
case KW_CONST:
return parse_var_const_decl(p, tag_list, 1);
return parse_var_const_decl(p, decorator_list, attr_list, 1);
case TOK_IDENT:
return parse_member_decl(p, tag_list);
case KW_COMPTIME:
vec_free(tag_list);
return parse_comptime_decl(p);
return parse_member_decl(p, decorator_list, attr_list);
case KW_MOD:
vec_free(attr_list);
return parse_mod_decl(p, decorator_list);
case KW_IMPORT:
vec_free(attr_list);
return parse_import_decl(p, decorator_list);
case TOK_L_BRACE: {
spl_ast_node_ref_t block = parse_block(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TOP_LEVEL_BLOCK, t);
spl_ast_node_t *tb = node_at(p->ast, ref);
MOVE_VEC(tb->top_level_block.tag_list, tag_list);
MOVE_VEC(tb->top_level_block.decorator_list, decorator_list);
MOVE_VEC(tb->top_level_block.attr_list, attr_list);
tb->top_level_block.block = block;
return ref;
}
default:
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_UNRECOGNIZED, t, "unrecognized declaration");
advance(p); /* 消费该 token,避免调用方在错误恢复时原地死循环 */
vec_free(tag_list);
vec_free(decorator_list);
vec_free(attr_list);
return 0;
}
}
@@ -871,7 +1118,6 @@ static spl_ast_node_ref_t parse_type_base(spl_parser_t *p) {
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TYPE_FN, bt);
spl_ast_node_t *fn_type = node_at(p->ast, ref);
fn_type->type_fn.is_comptime = 0;
vec_init(fn_type->type_fn.params);
while (!p->failed && peek(p) && peek(p)->type != TOK_R_PAREN) {
@@ -945,25 +1191,22 @@ static spl_ast_node_ref_t parse_type_base(spl_parser_t *p) {
return ref;
}
if (bt->type == TOK_AT || bt->type == TOK_SHARP)
return parse_type_comptime_call(p);
if (bt->type == TOK_AT)
return parse_type_compile_call(p);
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_UNRECOGNIZED, bt, "unrecognized type");
return 0;
}
static spl_ast_node_ref_t parse_type_comptime_call(spl_parser_t *p) {
static spl_ast_node_ref_t parse_type_compile_call(spl_parser_t *p) {
const spl_tok_t *start = peek(p);
if (!start || (start->type != TOK_AT && start->type != TOK_SHARP))
if (!start || start->type != TOK_AT)
return 0;
advance(p);
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name, "expected comptime name");
const char *name = parse_dotted_path(p, "compile-time call name");
if (!name)
return 0;
}
advance(p);
spl_ast_node_ref_vec_t args;
vec_init(args);
@@ -972,16 +1215,16 @@ static spl_ast_node_ref_t parse_type_comptime_call(spl_parser_t *p) {
if (t && t->type == TOK_L_PAREN) {
advance(p);
args = parse_expr_list(p);
if (!expect(p, TOK_R_PAREN, "')' in comptime type")) {
if (!expect(p, TOK_R_PAREN, "')' in compile-time type")) {
vec_free(args);
return 0;
}
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TYPE_COMPTIME_CALL, start);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_TYPE_COMPILE_CALL, start);
spl_ast_node_t *cc = node_at(p->ast, ref);
SET_STR_FIELD(p->ast, cc->type_comptime_call.name, name);
cc->type_comptime_call.args = args;
cc->type_compile_call.name = name;
cc->type_compile_call.args = args;
return ref;
}
@@ -1369,6 +1612,14 @@ static spl_ast_node_ref_t parse_prefix(spl_parser_t *p) {
spl_unary_op_t uop;
switch (t->type) {
case KW_RET:
return parse_ret_stmt(p);
case KW_BREAK:
return parse_break_stmt(p);
case KW_CONTINUE:
return parse_continue_stmt(p);
case KW_DEFER:
return parse_defer_stmt(p);
case TOK_SUB:
uop = SPL_UNARY_OP_MINUS;
break;
@@ -1599,8 +1850,7 @@ static spl_ast_node_ref_t parse_primary(spl_parser_t *p) {
case TOK_L_BRACE:
return parse_block(p);
case TOK_AT:
case TOK_SHARP:
return parse_comptime_call(p);
return parse_compile_call(p);
case TOK_L_PAREN: {
advance(p);
@@ -1693,18 +1943,15 @@ static spl_ast_node_ref_t parse_array_literal(spl_parser_t *p) {
return ref;
}
static spl_ast_node_ref_t parse_comptime_call(spl_parser_t *p) {
static spl_ast_node_ref_t parse_compile_call(spl_parser_t *p) {
const spl_tok_t *start = peek(p);
if (!start || (start->type != TOK_AT && start->type != TOK_SHARP))
if (!start || start->type != TOK_AT)
return 0;
advance(p);
const spl_tok_t *name = peek(p);
if (!name || name->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, name, "expected comptime name");
const char *name = parse_dotted_path(p, "compile-time call name");
if (!name)
return 0;
}
advance(p);
spl_ast_node_ref_vec_t args;
vec_init(args);
@@ -1713,16 +1960,16 @@ static spl_ast_node_ref_t parse_comptime_call(spl_parser_t *p) {
if (t && t->type == TOK_L_PAREN) {
advance(p);
args = parse_expr_list(p);
if (!expect(p, TOK_R_PAREN, "')' in comptime call")) {
if (!expect(p, TOK_R_PAREN, "')' in compile-time call")) {
vec_free(args);
return 0;
}
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_EXPR_COMPTIME_CALL, start);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_EXPR_COMPILE_CALL, start);
spl_ast_node_t *cc = node_at(p->ast, ref);
SET_STR_FIELD(p->ast, cc->comptime_call.name, name);
cc->comptime_call.args = args;
cc->compile_call.name = name;
cc->compile_call.args = args;
return ref;
}
@@ -1998,10 +2245,6 @@ static spl_ast_node_ref_t parse_ret_stmt(spl_parser_t *p) {
if (t && can_start_expr(t->type))
expr = parse_expr(p);
t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_RET, kw);
node_at(p->ast, ref)->statement_ret.expr = expr;
return ref;
@@ -2019,10 +2262,6 @@ static spl_ast_node_ref_t parse_break_stmt(spl_parser_t *p) {
if (t && can_start_expr(t->type))
expr = parse_expr(p);
t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_BREAK, kw);
node_at(p->ast, ref)->statement_break.label = label;
node_at(p->ast, ref)->statement_break.expr = expr;
@@ -2037,10 +2276,6 @@ static spl_ast_node_ref_t parse_continue_stmt(spl_parser_t *p) {
spl_ast_node_ref_t label = parse_label(p);
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_CONTINUE, kw);
node_at(p->ast, ref)->statement_continue.label = label;
return ref;
@@ -2060,9 +2295,6 @@ static spl_ast_node_ref_t parse_defer_stmt(spl_parser_t *p) {
body = parse_statement(p);
} else {
body = parse_expr(p);
t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
}
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_DEFER, kw);
@@ -2070,24 +2302,6 @@ static spl_ast_node_ref_t parse_defer_stmt(spl_parser_t *p) {
return ref;
}
static spl_ast_node_ref_t parse_comptime_stmt(spl_parser_t *p) {
const spl_tok_t *kw = peek(p);
if (!kw || kw->type != KW_COMPTIME)
return 0;
advance(p);
spl_ast_node_ref_t body = 0;
const spl_tok_t *t = peek(p);
if (t && t->type == TOK_L_BRACE)
body = parse_block(p);
else
body = parse_expr(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_COMPTIME, kw);
node_at(p->ast, ref)->statement_comptime.body = body;
return ref;
}
static spl_ast_node_ref_t parse_statement(spl_parser_t *p) {
const spl_tok_t *t = peek(p);
if (!t)
@@ -2102,25 +2316,16 @@ static spl_ast_node_ref_t parse_statement(spl_parser_t *p) {
return parse_continue_stmt(p);
case KW_DEFER:
return parse_defer_stmt(p);
case KW_COMPTIME:
return parse_comptime_stmt(p);
case KW_FN:
case KW_META:
case KW_MACRO:
case KW_VAR:
case KW_CONST:
case KW_TYPE: {
spl_ast_node_ref_vec_t tag_list;
vec_init(tag_list);
parse_tag_list(p, &tag_list, 0, 0);
spl_ast_node_ref_t decl;
if (t->type == KW_VAR)
decl = parse_var_const_decl(p, tag_list, 0);
else if (t->type == KW_CONST)
decl = parse_var_const_decl(p, tag_list, 1);
else
decl = parse_type_decl(p, tag_list);
case KW_TYPE:
case TOK_SHARP: {
spl_ast_node_ref_t decl = parse_container_declaration(p);
if (!decl)
return 0;
spl_ast_node_ref_t ref = new_node(p, SPL_AST_STATEMENT_DECL, t);
node_at(p->ast, ref)->statement_decl.decl = decl;
return ref;
@@ -2167,10 +2372,12 @@ static spl_ast_node_ref_t parse_block(spl_parser_t *p) {
if (can_start_statement(t->type)) {
spl_ast_node_ref_t stmt = parse_statement(p);
block = node_at(p->ast, ref);
if (stmt)
vec_push(block->block.stmts, stmt);
else
if (!stmt)
break;
vec_push(block->block.stmts, stmt);
t = peek(p);
if (t && t->type == TOK_SEMICOLON)
advance(p);
} else if (can_start_expr(t->type)) {
spl_ast_node_ref_t expr = parse_expr(p);
if (!expr)
@@ -2192,7 +2399,7 @@ static spl_ast_node_ref_t parse_block(spl_parser_t *p) {
(k == SPL_AST_EXPR_BLOCK || k == SPL_AST_EXPR_IF || k == SPL_AST_EXPR_IFVAR ||
k == SPL_AST_EXPR_WHILE || k == SPL_AST_EXPR_LOOP || k == SPL_AST_EXPR_FOR ||
k == SPL_AST_EXPR_MATCH);
if (block_like)
if (block_like || line_changed(p))
vec_push(block->block.stmts, expr);
else {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, t,
@@ -2215,6 +2422,7 @@ void spl_parser_init(spl_parser_t *parser) {
parser->ast = NULL;
parser->diag = NULL;
parser->pos = 0;
parser->last_tok_line = 0;
parser->failed = 0;
parser->stop_agg = 0;
parser->error_count = 0;
@@ -2241,6 +2449,7 @@ void spl_ast_parse(spl_parser_t *parser, spl_ast_t *ast) {
parser->ast = ast;
parser->pos = 0;
parser->last_tok_line = 0;
parser->failed = 0;
parser->stop_agg = 0;
@@ -2248,27 +2457,28 @@ void spl_ast_parse(spl_parser_t *parser, spl_ast_t *ast) {
vec_init(external_tags);
spl_ast_node_ref_vec_t declarations;
vec_init(declarations);
spl_ast_node_ref_t module_ref = 0;
while (!parser->failed) {
const spl_tok_t *t = peek(parser);
if (!t || t->type == TOK_EOF)
break;
if (t->type == TOK_AT || t->type == TOK_SHARP) {
usize save_pos = parser->pos;
const spl_tok_t *t2 = NULL;
parser->pos++;
t2 = peek(parser);
parser->pos = save_pos;
if (t2 && t2->type == TOK_NOT) {
parse_tag_list(parser, &external_tags, 1, 1);
if (t->type == TOK_SHARP) {
usize before = vec_size(external_tags);
parse_external_tags(parser, &external_tags);
if (vec_size(external_tags) > before)
continue;
}
}
spl_ast_node_ref_t decl = parse_container_declaration(parser);
if (decl) {
vec_push(declarations, decl);
spl_ast_node_t *dn = node_at(ast, decl);
if (dn->kind == SPL_AST_MOD_DECL && !dn->mod_decl.has_body && module_ref == 0 &&
vec_size(declarations) == 0)
module_ref = decl;
else
vec_push(declarations, decl);
} else if (!parser->failed) {
const spl_tok_t *at = peek(parser);
if (at && at->type != TOK_EOF) {
@@ -2282,6 +2492,7 @@ void spl_ast_parse(spl_parser_t *parser, spl_ast_t *ast) {
spl_ast_node_ref_t container_members = new_node(parser, SPL_AST_CONTAINER_MEMBERS, NULL);
spl_ast_node_t *cm = node_at(ast, container_members);
cm->container_members.external_tags = external_tags;
cm->container_members.module = module_ref;
cm->container_members.declarations = declarations;
spl_ast_node_ref_t root = new_node(parser, SPL_AST_ROOT, NULL);
+260
View File
@@ -0,0 +1,260 @@
#include "spl_sap.h"
#include <stdlib.h>
#include <string.h>
typedef struct {
spl_ast_t *ast;
spl_ast_node_ref_t ref;
} sap_handle_entry_t;
typedef VEC(sap_handle_entry_t) sap_handle_vec_t;
typedef struct {
spl_sap_t *sap;
const spl_sap_op_t *op;
} sap_binding_t;
typedef VEC(sap_binding_t) sap_binding_vec_t;
struct spl_sap {
spl_lang_type_t *type;
spl_lang_type_id_t meta_view_tid;
sap_handle_vec_t handles;
sap_binding_vec_t bindings;
};
static bool sap_host_kind_count(spl_sap_t *sap, spl_exec_t *exec, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret) {
(void)sap;
(void)exec;
(void)args;
if (nargs != 0)
return false;
ret->bits = spl_sap_kind_count();
return true;
}
static bool sap_host_kind(spl_sap_t *sap, spl_exec_t *exec, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret) {
(void)exec;
if (nargs != 1)
return false;
ret->bits = 0;
spl_sap_handle_t handle = (spl_sap_handle_t)args[0].bits;
if (!handle)
return true;
spl_ast_t *ast = NULL;
spl_ast_node_ref_t ref = 0;
if (!spl_sap_handle_node(sap, handle, &ast, &ref))
return false;
spl_ast_node_t *node = spl_ast_node(ast, ref);
if (!node)
return false;
ret->bits = (usize)node->kind;
return true;
}
static bool sap_write_usize(spl_exec_value_t *ret, usize bit_offset, usize value) {
usize off = bit_offset / 8;
if (!ret || !ret->mem.ptr || off + sizeof(value) > ret->size)
return false;
memcpy((unsigned char *)ret->mem.ptr + off, &value, sizeof(value));
return true;
}
static bool sap_host_view(spl_sap_t *sap, spl_exec_t *exec, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret) {
if (nargs != 1 || !ret || !ret->mem.ptr || !ret->size)
return false;
spl_layout_t *layout = spl_exec_layout(exec);
const spl_layout_info_t *info = layout ? spl_layout_info_of(layout, ret->type) : NULL;
if (!info || vec_size(info->field_bit_offsets) < 3)
return false;
memset(ret->mem.ptr, 0, ret->size);
spl_sap_handle_t handle = (spl_sap_handle_t)args[0].bits;
if (!handle)
return true;
spl_ast_t *ast = NULL;
spl_ast_node_ref_t ref = 0;
if (!spl_sap_handle_node(sap, handle, &ast, &ref))
return false;
spl_ast_node_t *node = spl_ast_node(ast, ref);
if (!node)
return false;
usize values[3] = {(usize)node->kind, (usize)node->dbg.line, (usize)node->dbg.col};
for (usize i = 0; i < 3; ++i) {
if (!sap_write_usize(ret, vec_at(info->field_bit_offsets, i), values[i]))
return false;
}
return true;
}
static const spl_sap_op_t g_sap_ops[] = {
{"sap.kind_count", 0, {0}, SPL_SAP_ARG_USIZE, sap_host_kind_count},
{"sap.kind", 1, {SPL_SAP_ARG_HANDLE}, SPL_SAP_ARG_USIZE, sap_host_kind},
{"sap.view", 1, {SPL_SAP_ARG_HANDLE}, SPL_SAP_ARG_VIEW, sap_host_view},
};
static const usize g_sap_op_count = sizeof(g_sap_ops) / sizeof(g_sap_ops[0]);
const spl_sap_op_t *spl_sap_lookup(const char *name) {
if (!name)
return NULL;
for (usize i = 0; i < g_sap_op_count; ++i) {
if (strcmp(g_sap_ops[i].name, name) == 0)
return &g_sap_ops[i];
}
return NULL;
}
const spl_sap_op_t *spl_sap_ops(usize *count) {
if (count)
*count = g_sap_op_count;
return g_sap_ops;
}
spl_lang_type_id_t spl_sap_meta_view_type(spl_sap_t *sap) {
if (!sap || !sap->type)
return 0;
if (sap->meta_view_tid)
return sap->meta_view_tid;
static const char *const names[] = {"kind", "line", "col"};
spl_lang_type_id_t usize_tid = spl_lang_make_int(sap->type, sizeof(void *) * 8, 0);
spl_lang_type_id_t types[3] = {usize_tid, usize_tid, usize_tid};
sap->meta_view_tid = spl_lang_make_struct_named(sap->type, "sap.MetaView", names, types, 3);
return sap->meta_view_tid;
}
const char *const *spl_sap_meta_view_fields(usize *count) {
static const char *const fields[] = {"kind", "line", "col"};
if (count)
*count = 3;
return fields;
}
spl_lang_type_id_t spl_sap_arg_type(spl_sap_t *sap, spl_sap_arg_kind_t kind) {
if (!sap || !sap->type)
return 0;
if (kind == SPL_SAP_ARG_VIEW)
return spl_sap_meta_view_type(sap);
/* Handle 与 usize 在编译期值表示上相同;ViewPoint 再区分。 */
return spl_lang_make_int(sap->type, sizeof(void *) * 8, 0);
}
spl_lang_type_id_t spl_sap_op_fn_type(spl_sap_t *sap, const spl_sap_op_t *op) {
if (!sap || !sap->type || !op || op->nparams > 4)
return 0;
spl_lang_type_id_t params[4];
for (usize i = 0; i < op->nparams; ++i)
params[i] = spl_sap_arg_type(sap, op->params[i]);
spl_lang_type_id_t ret = spl_sap_arg_type(sap, op->ret);
return spl_lang_make_fn(sap->type, ret, params, op->nparams);
}
usize spl_sap_kind_count(void) { return (usize)SPL_AST_COUNT; }
const char *spl_sap_kind_name(usize kind) {
if (kind >= spl_sap_kind_count())
return "?";
return spl_ast_kind_name((spl_ast_node_kind_t)kind);
}
spl_sap_t *spl_sap_create(spl_lang_type_t *type) {
if (!type)
return NULL;
spl_sap_t *sap = calloc(1, sizeof(*sap));
if (!sap)
return NULL;
sap->type = type;
vec_init(sap->handles);
vec_init(sap->bindings);
/* 0 号句柄保留为空。 */
sap_handle_entry_t none = {0};
vec_push(sap->handles, none);
return sap;
}
void spl_sap_destroy(spl_sap_t *sap) {
if (!sap)
return;
vec_free(sap->handles);
vec_free(sap->bindings);
free(sap);
}
spl_sap_handle_t spl_sap_handle_register(spl_sap_t *sap, spl_ast_t *ast,
spl_ast_node_ref_t ref) {
if (!sap || !ast || !ref)
return 0;
for (usize i = 1; i < vec_size(sap->handles); ++i) {
sap_handle_entry_t *entry = &vec_at(sap->handles, i);
if (entry->ast == ast && entry->ref == ref)
return i;
}
sap_handle_entry_t entry = {.ast = ast, .ref = ref};
vec_push(sap->handles, entry);
return vec_size(sap->handles) - 1;
}
bool spl_sap_handle_node(spl_sap_t *sap, spl_sap_handle_t handle, spl_ast_t **ast,
spl_ast_node_ref_t *ref) {
if (!sap || !handle || handle >= vec_size(sap->handles))
return false;
sap_handle_entry_t *entry = &vec_at(sap->handles, handle);
if (ast)
*ast = entry->ast;
if (ref)
*ref = entry->ref;
return true;
}
bool spl_sap_type_lookup(spl_sap_t *sap, const char *name, spl_lang_type_id_t *out) {
if (!sap || !name || !out)
return false;
if (strcmp(name, "Handle") == 0) {
*out = spl_sap_arg_type(sap, SPL_SAP_ARG_HANDLE);
return *out != 0;
}
if (strcmp(name, "MetaView") == 0) {
*out = spl_sap_meta_view_type(sap);
return *out != 0;
}
return false;
}
static bool sap_host_adapter(spl_exec_t *exec, void *user, const spl_exec_value_t *args,
usize nargs, spl_exec_value_t *ret) {
sap_binding_t *binding = (sap_binding_t *)user;
if (!binding || !binding->op || !binding->op->host)
return false;
return binding->op->host(binding->sap, exec, args, nargs, ret);
}
bool spl_sap_bind(spl_exec_t *exec, spl_sap_t *sap) {
if (!exec || !sap)
return false;
sap->bindings.size = 0;
for (usize i = 0; i < g_sap_op_count; ++i) {
sap_binding_t binding = {.sap = sap, .op = &g_sap_ops[i]};
vec_push(sap->bindings, binding);
}
for (usize i = 0; i < vec_size(sap->bindings); ++i) {
sap_binding_t *binding = &vec_at(sap->bindings, i);
spl_exec_host_t host = {
.name = binding->op->name,
.capabilities = SPL_EXEC_CAP_READ,
.fn = sap_host_adapter,
.user = binding,
};
if (!spl_exec_register_host(exec, &host))
return false;
}
return true;
}
@@ -1,8 +1,19 @@
#include "spl_lang_type.h"
static bool spl_lang_is_aggregate_kind(spl_lang_type_kind_t kind) {
return kind == SPL_LANG_TYPE_STRUCT || kind == SPL_LANG_TYPE_UNION ||
kind == SPL_LANG_TYPE_ENUM || kind == SPL_LANG_TYPE_SHAPE;
}
static usize spl_lang_type_hash(spl_lang_type_node_t n) {
usize hash = spl_hash_seed();
hash = spl_hash_mix(hash, (usize)n.kind);
if (spl_lang_is_aggregate_kind(n.kind)) {
/* 声明聚合按 def 唯一;合成聚合按已 intern 的 IR 形状唯一。
members/methods 可能在 reserve 之后才填,不能参与 hash。 */
hash = spl_hash_mix(hash, n.def_id ? n.def_id : n.ir_type_id);
return hash;
}
hash = spl_hash_mix(hash, n.ir_type_id);
switch (n.kind) {
case SPL_LANG_TYPE_PTR:
@@ -23,16 +34,12 @@ static usize spl_lang_type_hash(spl_lang_type_node_t n) {
hash = spl_hash_mix(hash, vec_at(n.extra.fn.params, i));
}
break;
case SPL_LANG_TYPE_STRUCT:
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
hash = spl_hash_mix(hash, vec_size(n.methods));
for (usize i = 0; i < vec_size(n.methods); i++) {
spl_lang_method_t *m = &vec_at(n.methods, i);
hash = spl_hash_mix(hash, m->def_id);
hash = spl_hash_mix_str(hash, m->name);
}
case SPL_LANG_TYPE_INT:
hash = spl_hash_mix(hash, n.extra.int_type.bits);
hash = spl_hash_mix(hash, (usize)n.extra.int_type.is_signed);
break;
case SPL_LANG_TYPE_FLOAT:
hash = spl_hash_mix(hash, n.extra.float_type.bits);
break;
default:
break;
@@ -41,7 +48,14 @@ static usize spl_lang_type_hash(spl_lang_type_node_t n) {
}
static int spl_lang_type_eq(spl_lang_type_node_t n1, spl_lang_type_node_t n2) {
if (n1.kind != n2.kind || n1.ir_type_id != n2.ir_type_id)
if (n1.kind != n2.kind)
return 1;
if (spl_lang_is_aggregate_kind(n1.kind)) {
if (n1.def_id || n2.def_id)
return n1.def_id != n2.def_id;
return n1.ir_type_id != n2.ir_type_id;
}
if (n1.ir_type_id != n2.ir_type_id)
return 1;
switch (n1.kind) {
case SPL_LANG_TYPE_PTR:
@@ -66,29 +80,18 @@ static int spl_lang_type_eq(spl_lang_type_node_t n1, spl_lang_type_node_t n2) {
return 1;
}
return 0;
case SPL_LANG_TYPE_STRUCT:
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
if (vec_size(n1.methods) != vec_size(n2.methods))
return 1;
for (usize i = 0; i < vec_size(n1.methods); i++) {
spl_lang_method_t *a = &vec_at(n1.methods, i);
spl_lang_method_t *b = &vec_at(n2.methods, i);
if (a->def_id != b->def_id)
return 1;
if ((a->name == NULL) != (b->name == NULL))
return 1;
if (a->name && strcmp(a->name, b->name) != 0)
return 1;
}
return 0;
case SPL_LANG_TYPE_INT:
return (n1.extra.int_type.bits != n2.extra.int_type.bits) ||
(n1.extra.int_type.is_signed != n2.extra.int_type.is_signed);
case SPL_LANG_TYPE_FLOAT:
return n1.extra.float_type.bits != n2.extra.float_type.bits;
default:
return 0;
}
}
static void spl_lang_node_free_extra(spl_lang_type_node_t *n) {
vec_free(n->members);
switch (n->kind) {
case SPL_LANG_TYPE_TUPLE:
vec_free(n->extra.elems);
@@ -140,8 +143,8 @@ spl_lang_type_id_t spl_lang_node_push(spl_lang_type_t *type, spl_lang_type_node_
return id;
}
void spl_lang_type_init(spl_lang_type_t *type) {
spl_type_init(&type->ir);
void spl_lang_type_init(spl_lang_type_t *type, spl_ir_type_table_t *ir_types) {
type->ir_types = ir_types;
vec_init(type->lang_table);
spl_lang_type_node_t lang_node = {0};
@@ -162,8 +165,7 @@ void spl_lang_type_drop(spl_lang_type_t *type) {
vec_free(type->lang_table);
vec_free(type->def_table);
spl_type_drop(&type->ir);
type->ir_types = NULL;
}
spl_lang_type_node_t *spl_lang_type_node(const spl_lang_type_t *type, spl_lang_type_id_t id) {
@@ -178,32 +180,64 @@ spl_def_node_t *spl_def_node(const spl_lang_type_t *type, spl_def_id_t id) {
return &vec_at(type->def_table, id);
}
spl_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id) {
bool spl_def_is_compile_time(const spl_def_node_t *def) {
return def && def->fn_kind != SPL_DEF_FN_NORMAL;
}
bool spl_def_is_macro_fn(const spl_def_node_t *def) {
return def && def->fn_kind == SPL_DEF_FN_MACRO;
}
spl_ir_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id) {
spl_lang_type_node_t *n = spl_lang_type_node(type, lang_id);
return n ? n->ir_type_id : 0;
}
spl_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type) {
spl_type_node_t empty = {0};
empty.kind = SPL_TYPE_ERROR;
empty.layout.mode = SPL_TYPE_LAYOUT_AUTO;
vec_push(type->ir.type_table, empty);
return vec_size(type->ir.type_table) - 1;
const spl_lang_member_t *spl_lang_member_at(spl_lang_type_t *type, spl_lang_type_id_t agg,
usize idx) {
spl_lang_type_node_t *n = spl_lang_type_node(type, agg);
if (!n || idx >= vec_size(n->members))
return NULL;
return &vec_at(n->members, idx);
}
void spl_lang_define_ir(spl_lang_type_t *type, spl_type_id_t id, spl_type_node_t *node) {
if (!id || id >= vec_size(type->ir.type_table))
bool spl_lang_member_idx(spl_lang_type_t *type, spl_lang_type_id_t agg, const char *name,
usize *out_idx) {
spl_lang_type_node_t *n = spl_lang_type_node(type, agg);
if (!n || !name)
return false;
for (usize i = 0; i < vec_size(n->members); ++i) {
spl_lang_member_t *m = &vec_at(n->members, i);
if (m->name && strcmp(m->name, name) == 0) {
if (out_idx)
*out_idx = i;
return true;
}
}
return false;
}
spl_ir_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type) {
spl_ir_type_node_t empty = {0};
empty.kind = SPL_IR_TYPE_ERROR;
empty.layout.mode = SPL_IR_TYPE_LAYOUT_AUTO;
vec_push(type->ir_types->type_table, empty);
return vec_size(type->ir_types->type_table) - 1;
}
void spl_lang_define_ir(spl_lang_type_t *type, spl_ir_type_id_t id, spl_ir_type_node_t *node) {
if (!id || id >= vec_size(type->ir_types->type_table))
return;
spl_type_node_t *slot = &vec_at(type->ir.type_table, id);
spl_ir_type_node_t *slot = &vec_at(type->ir_types->type_table, id);
/* slot 原是空 ERROR 节点,无 vec 字段可释放。node 的 vec 字段 move 进 slot。
占位 id 不写 type_fold,不参与 hash-consing。 */
*slot = *node;
node->kind = SPL_TYPE_ERROR;
node->kind = SPL_IR_TYPE_ERROR;
}
static spl_lang_type_id_t spl_lang_node_simple(spl_lang_type_t *type,
spl_lang_type_kind_t lang_kind,
spl_type_id_t ir_type_id) {
spl_ir_type_id_t ir_type_id) {
spl_lang_type_node_t node = {0};
node.kind = lang_kind;
node.ir_type_id = ir_type_id;
@@ -211,51 +245,60 @@ static spl_lang_type_id_t spl_lang_node_simple(spl_lang_type_t *type,
}
spl_lang_type_id_t spl_lang_make_error(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_ERROR);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_ERROR);
return spl_lang_node_simple(type, SPL_LANG_TYPE_ERROR, ir);
}
spl_lang_type_id_t spl_lang_make_infer(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_INFER);
return spl_lang_node_simple(type, SPL_LANG_TYPE_INFER, ir);
return spl_lang_node_simple(type, SPL_LANG_TYPE_INFER, 0);
}
spl_lang_type_id_t spl_lang_make_never(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_NEVER);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_UNIT);
return spl_lang_node_simple(type, SPL_LANG_TYPE_NEVER, ir);
}
spl_lang_type_id_t spl_lang_make_any(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_ANY);
spl_ir_type_id_t unit = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_UNIT);
spl_ir_type_id_t ir = spl_ir_type_builder_ptr(type->ir_types, unit);
return spl_lang_node_simple(type, SPL_LANG_TYPE_ANY, ir);
}
spl_lang_type_id_t spl_lang_make_unit(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_UNIT);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_UNIT);
return spl_lang_node_simple(type, SPL_LANG_TYPE_UNIT, ir);
}
spl_lang_type_id_t spl_lang_make_bool(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_BOOL);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_BOOL);
return spl_lang_node_simple(type, SPL_LANG_TYPE_BOOL, ir);
}
spl_lang_type_id_t spl_lang_make_int(spl_lang_type_t *type, usize bits, int is_signed) {
spl_type_id_t ir = spl_type_builder_int(&type->ir, bits, is_signed);
return spl_lang_node_simple(type, SPL_LANG_TYPE_INT, ir);
spl_ir_type_id_t ir = spl_ir_type_builder_int(type->ir_types, bits, is_signed);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_INT;
node.ir_type_id = ir;
node.extra.int_type.bits = bits;
node.extra.int_type.is_signed = is_signed;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_float(spl_lang_type_t *type, usize bits) {
spl_type_id_t ir = spl_type_builder_float(&type->ir, bits);
return spl_lang_node_simple(type, SPL_LANG_TYPE_FLOAT, ir);
spl_ir_type_id_t ir = spl_ir_type_builder_float(type->ir_types, bits);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_FLOAT;
node.ir_type_id = ir;
node.extra.float_type.bits = bits;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_array(spl_lang_type_t *type, spl_lang_type_id_t elem_lang,
usize len) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
spl_ir_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
if (!elem_ir)
return 0;
spl_type_id_t ir = spl_type_builder_array(&type->ir, elem_ir, len);
spl_ir_type_id_t ir = spl_ir_type_builder_array(type->ir_types, elem_ir, len);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_ARRAY;
node.ir_type_id = ir;
@@ -264,10 +307,10 @@ spl_lang_type_id_t spl_lang_make_array(spl_lang_type_t *type, spl_lang_type_id_t
}
spl_lang_type_id_t spl_lang_make_ptr(spl_lang_type_t *type, spl_lang_type_id_t pointee_lang) {
spl_type_id_t pointee_ir = spl_lang_type_get_ir_type(type, pointee_lang);
spl_ir_type_id_t pointee_ir = spl_lang_type_get_ir_type(type, pointee_lang);
if (!pointee_ir)
return 0;
spl_type_id_t ir = spl_type_builder_ptr(&type->ir, pointee_ir);
spl_ir_type_id_t ir = spl_ir_type_builder_ptr(type->ir_types, pointee_ir);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_PTR;
node.ir_type_id = ir;
@@ -276,99 +319,109 @@ spl_lang_type_id_t spl_lang_make_ptr(spl_lang_type_t *type, spl_lang_type_id_t p
}
spl_lang_type_id_t spl_lang_make_slice(spl_lang_type_t *type, spl_lang_type_id_t elem_lang) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
spl_ir_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
if (!elem_ir)
return 0;
spl_lang_type_id_t ptr_lang = spl_lang_make_ptr(type, elem_lang);
spl_lang_type_id_t usize_lang = spl_lang_make_int(type, sizeof(void *) * 8, 0);
spl_type_id_t ptr_ir = spl_lang_type_get_ir_type(type, ptr_lang);
spl_type_id_t usize_ir = spl_lang_type_get_ir_type(type, usize_lang);
spl_ir_type_id_t ptr_ir = spl_lang_type_get_ir_type(type, ptr_lang);
spl_ir_type_id_t usize_ir = spl_lang_type_get_ir_type(type, usize_lang);
spl_type_member_vec_t members;
spl_ir_type_member_vec_t members;
vec_init(members);
spl_type_member_t m1 = {.name = "ptr", .type_id = ptr_ir};
spl_type_member_t m2 = {.name = "len", .type_id = usize_ir};
spl_ir_type_member_t m1 = {.name = "ptr", .type_id = ptr_ir};
spl_ir_type_member_t m2 = {.name = "len", .type_id = usize_ir};
vec_push(members, m1);
vec_push(members, m2);
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t struct_ir = spl_type_builder_agg(&type->ir, SPL_TYPE_STRUCT, &members, 0, layout);
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t struct_ir = spl_ir_type_builder_agg(type->ir_types, SPL_IR_TYPE_STRUCT, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_SLICE;
node.ir_type_id = struct_ir;
node.extra.elem = elem_lang;
vec_init(node.members);
vec_push(node.members, ((spl_lang_member_t){.name = "ptr", .type = ptr_lang}));
vec_push(node.members, ((spl_lang_member_t){.name = "len", .type = usize_lang}));
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_tuple(spl_lang_type_t *type, const spl_lang_type_id_t *elems,
usize count) {
spl_type_member_vec_t members;
spl_ir_type_member_vec_t members;
vec_init(members);
for (usize i = 0; i < count; i++) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elems[i]);
spl_ir_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elems[i]);
if (!elem_ir) {
vec_free(members);
return 0;
}
char name[32];
snprintf(name, sizeof(name), "%zu", i);
spl_type_member_t m = {.name = strdup(name), .type_id = elem_ir};
spl_ir_type_member_t m = {.name = strdup(name), .type_id = elem_ir};
vec_push(members, m);
}
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t struct_ir = spl_type_builder_agg(&type->ir, SPL_TYPE_STRUCT, &members, 0, layout);
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t struct_ir = spl_ir_type_builder_agg(type->ir_types, SPL_IR_TYPE_STRUCT, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_TUPLE;
node.ir_type_id = struct_ir;
vec_init(node.extra.elems);
vec_init(node.members);
for (usize i = 0; i < count; i++) {
vec_push(node.extra.elems, elems[i]);
char name[32];
snprintf(name, sizeof(name), "%zu", i);
vec_push(node.members, ((spl_lang_member_t){.name = strdup(name), .type = elems[i]}));
}
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_range(spl_lang_type_t *type, spl_lang_type_id_t elem_lang) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
spl_ir_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
if (!elem_ir)
return 0;
spl_type_member_vec_t members;
spl_ir_type_member_vec_t members;
vec_init(members);
spl_type_member_t m1 = {.name = "start", .type_id = elem_ir};
spl_type_member_t m2 = {.name = "end", .type_id = elem_ir};
spl_ir_type_member_t m1 = {.name = "start", .type_id = elem_ir};
spl_ir_type_member_t m2 = {.name = "end", .type_id = elem_ir};
vec_push(members, m1);
vec_push(members, m2);
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t struct_ir = spl_type_builder_agg(&type->ir, SPL_TYPE_STRUCT, &members, 0, layout);
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t struct_ir = spl_ir_type_builder_agg(type->ir_types, SPL_IR_TYPE_STRUCT, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_RANGE;
node.ir_type_id = struct_ir;
node.extra.elem = elem_lang;
vec_init(node.members);
vec_push(node.members, ((spl_lang_member_t){.name = "start", .type = elem_lang}));
vec_push(node.members, ((spl_lang_member_t){.name = "end", .type = elem_lang}));
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_fn(spl_lang_type_t *type, spl_lang_type_id_t ret_lang,
const spl_lang_type_id_t *params_lang, usize nparams) {
spl_type_id_t ret_ir = spl_lang_type_get_ir_type(type, ret_lang);
spl_ir_type_id_t ret_ir = spl_lang_type_get_ir_type(type, ret_lang);
if (!ret_ir)
return 0;
spl_type_id_vec_t param_irs;
spl_ir_type_id_vec_t param_irs;
vec_init(param_irs);
for (usize i = 0; i < nparams; i++) {
spl_type_id_t pir = spl_lang_type_get_ir_type(type, params_lang[i]);
spl_ir_type_id_t pir = spl_lang_type_get_ir_type(type, params_lang[i]);
if (!pir) {
vec_free(param_irs);
return 0;
}
vec_push(param_irs, pir);
}
spl_type_id_t fn_ir =
spl_type_builder_fn(&type->ir, ret_ir, param_irs.data, vec_size(param_irs));
spl_ir_type_id_t fn_ir =
spl_ir_type_builder_fn(type->ir_types, ret_ir, param_irs.data, vec_size(param_irs));
vec_free(param_irs);
spl_lang_type_node_t node = {0};
@@ -387,48 +440,85 @@ spl_lang_type_id_t spl_lang_make_aggregate(spl_lang_type_t *type, spl_lang_type_
usize nmembers) {
(void)name; // TODO
spl_type_node_kind_t tk;
spl_ir_type_kind_t tk;
switch (kind) {
case SPL_LANG_TYPE_STRUCT:
tk = SPL_TYPE_STRUCT;
tk = SPL_IR_TYPE_STRUCT;
break;
case SPL_LANG_TYPE_UNION:
tk = SPL_TYPE_UNION;
tk = SPL_IR_TYPE_UNION;
break;
case SPL_LANG_TYPE_ENUM:
tk = SPL_TYPE_ENUM;
tk = SPL_IR_TYPE_ENUM;
break;
case SPL_LANG_TYPE_SHAPE:
tk = SPL_TYPE_SHAPE;
tk = SPL_IR_TYPE_STRUCT;
break;
default:
return 0;
}
spl_type_member_vec_t members;
spl_ir_type_member_vec_t members;
vec_init(members);
spl_lang_type_node_t node = {0};
node.kind = kind;
vec_init(node.members);
for (usize i = 0; i < nmembers; i++) {
spl_type_id_t member_ir = spl_lang_type_get_ir_type(type, members_lang[i]);
spl_ir_type_id_t member_ir = spl_lang_type_get_ir_type(type, members_lang[i]);
if (!member_ir) {
vec_free(members);
vec_free(node.members);
return 0;
}
char field_name[32];
snprintf(field_name, sizeof(field_name), "%zu", i);
spl_type_member_t m = {.name = strdup(field_name), .type_id = member_ir};
const char *stored_name = strdup(field_name);
spl_ir_type_member_t m = {.name = stored_name, .type_id = member_ir};
vec_push(members, m);
vec_push(node.members, ((spl_lang_member_t){.name = stored_name, .type = members_lang[i]}));
}
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t agg_ir = spl_type_builder_agg(&type->ir, tk, &members, 0, layout);
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t agg_ir = spl_ir_type_builder_agg(type->ir_types, tk, &members, 0, layout);
node.ir_type_id = agg_ir;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_struct_named(spl_lang_type_t *type, const char *name,
const char *const *field_names,
const spl_lang_type_id_t *field_types,
usize nfields) {
(void)name;
if (!type || (nfields > 0 && (!field_names || !field_types)))
return 0;
spl_ir_type_member_vec_t members;
vec_init(members);
spl_lang_type_node_t node = {0};
node.kind = kind;
node.kind = SPL_LANG_TYPE_STRUCT;
vec_init(node.members);
for (usize i = 0; i < nfields; ++i) {
spl_ir_type_id_t member_ir = spl_lang_type_get_ir_type(type, field_types[i]);
if (!member_ir) {
vec_free(members);
vec_free(node.members);
return 0;
}
const char *stored_name = strdup(field_names[i]);
spl_ir_type_member_t m = {.name = stored_name, .type_id = member_ir};
vec_push(members, m);
vec_push(node.members, ((spl_lang_member_t){.name = stored_name, .type = field_types[i]}));
}
spl_ir_type_layout_t layout = {.mode = SPL_IR_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_ir_type_id_t agg_ir = spl_ir_type_builder_agg(type->ir_types, SPL_IR_TYPE_STRUCT, &members, 0, layout);
node.ir_type_id = agg_ir;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_varargs(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_UNIT);
spl_ir_type_id_t ir = spl_ir_type_builder_simple(type->ir_types, SPL_IR_TYPE_UNIT);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_VARARGS;
node.ir_type_id = ir;
@@ -482,19 +572,11 @@ bool spl_lang_type_is_subtype(const spl_lang_type_t *type, spl_lang_type_id_t su
if (nsuper->kind == SPL_LANG_TYPE_ANY)
return true;
if (nsub->kind == SPL_LANG_TYPE_INT && nsuper->kind == SPL_LANG_TYPE_INT) {
spl_type_node_t *ir_sub = spl_type_node(&type->ir, nsub->ir_type_id);
if (!ir_sub)
return false;
return ir_sub->int_type.bits == 0;
}
if (nsub->kind == SPL_LANG_TYPE_INT && nsuper->kind == SPL_LANG_TYPE_INT)
return nsub->extra.int_type.bits == 0;
if (nsub->kind == SPL_LANG_TYPE_FLOAT && nsuper->kind == SPL_LANG_TYPE_FLOAT) {
spl_type_node_t *ir_sub = spl_type_node(&type->ir, nsub->ir_type_id);
if (!ir_sub)
return false;
return ir_sub->float_type.bits == 0;
}
if (nsub->kind == SPL_LANG_TYPE_FLOAT && nsuper->kind == SPL_LANG_TYPE_FLOAT)
return nsub->extra.float_type.bits == 0;
/* null(*never)可隐式转换为函数指针:函数值按指针布局,可空。 */
if (nsuper->kind == SPL_LANG_TYPE_FN && nsub->kind == SPL_LANG_TYPE_PTR) {
@@ -543,12 +625,8 @@ spl_lang_type_id_t spl_lang_type_join(const spl_lang_type_t *type, spl_lang_type
bool b_flt = nb->kind == SPL_LANG_TYPE_FLOAT;
if (a_int && b_int) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (!ira || !irb)
return 0;
bool a_ct = ira->int_type.bits == 0;
bool b_ct = irb->int_type.bits == 0;
bool a_ct = na->extra.int_type.bits == 0;
bool b_ct = nb->extra.int_type.bits == 0;
if (a_ct && b_ct)
return a;
if (a_ct)
@@ -559,12 +637,8 @@ spl_lang_type_id_t spl_lang_type_join(const spl_lang_type_t *type, spl_lang_type
}
if (a_flt && b_flt) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (!ira || !irb)
return 0;
bool a_ct = ira->float_type.bits == 0;
bool b_ct = irb->float_type.bits == 0;
bool a_ct = na->extra.float_type.bits == 0;
bool b_ct = nb->extra.float_type.bits == 0;
if (a_ct && b_ct)
return a;
if (a_ct)
@@ -575,16 +649,12 @@ spl_lang_type_id_t spl_lang_type_join(const spl_lang_type_t *type, spl_lang_type
}
if (a_int && b_flt) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (ira && irb && ira->int_type.bits == 0 && irb->float_type.bits == 0)
if (na->extra.int_type.bits == 0 && nb->extra.float_type.bits == 0)
return spl_lang_make_float((spl_lang_type_t *)type, 0);
return 0;
}
if (a_flt && b_int) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (ira && irb && ira->float_type.bits == 0 && irb->int_type.bits == 0)
if (na->extra.float_type.bits == 0 && nb->extra.int_type.bits == 0)
return spl_lang_make_float((spl_lang_type_t *)type, 0);
return 0;
}
@@ -628,13 +698,10 @@ bool spl_lang_mpa_int_fits(const spl_lang_type_t *type, spl_lang_type_id_t targe
spl_lang_type_node_t *nt = spl_lang_type_node(type, target);
if (!nt || nt->kind != SPL_LANG_TYPE_INT)
return false;
spl_type_node_t *ir = spl_type_node(&type->ir, nt->ir_type_id);
if (!ir)
return false;
uint32_t bits = (uint32_t)ir->int_type.bits;
uint32_t bits = (uint32_t)nt->extra.int_type.bits;
if (bits == 0)
return true;
bool target_signed = ir->int_type.is_signed != 0;
bool target_signed = nt->extra.int_type.is_signed != 0;
uint64_t uval = v.bits;
if (target_signed) {
@@ -677,7 +744,7 @@ spl_lang_type_id_t spl_def_get_lang_id(spl_lang_type_t *type, spl_def_id_t def_i
return d ? d->lang_id : 0;
}
spl_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id) {
spl_ir_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id) {
spl_lang_type_id_t lang = spl_def_get_lang_id(type, def_id);
return lang ? spl_lang_type_get_ir_type(type, lang) : 0;
}
@@ -724,30 +791,26 @@ static void spl_lang_type_dump_rec(spl_lang_type_t *type, spl_lang_type_id_t id,
case SPL_LANG_TYPE_VARARGS:
printf("...");
break;
case SPL_LANG_TYPE_INT: {
spl_type_node_t *tn = spl_type_node(&type->ir, n->ir_type_id);
if (tn && tn->int_type.bits == 0)
case SPL_LANG_TYPE_INT:
if (n->extra.int_type.bits == 0)
printf("comptime_int");
else
spl_type_pure_dump(&type->ir, n->ir_type_id);
printf("%s%zu", n->extra.int_type.is_signed ? "i" : "u", n->extra.int_type.bits);
break;
}
case SPL_LANG_TYPE_FLOAT: {
spl_type_node_t *tn = spl_type_node(&type->ir, n->ir_type_id);
if (tn && tn->float_type.bits == 0)
case SPL_LANG_TYPE_FLOAT:
if (n->extra.float_type.bits == 0)
printf("comptime_float");
else
spl_type_pure_dump(&type->ir, n->ir_type_id);
printf("f%zu", n->extra.float_type.bits);
break;
}
case SPL_LANG_TYPE_PTR:
printf("*");
spl_lang_type_dump_rec(type, n->extra.elem, stack);
break;
case SPL_LANG_TYPE_ARRAY: {
spl_type_node_t *tn = spl_type_node(&type->ir, n->ir_type_id);
spl_ir_type_node_t *tn = spl_ir_type_node(type->ir_types, n->ir_type_id);
printf("[%zu]", tn->array_type.len);
spl_type_pure_dump(&type->ir, n->ir_type_id);
spl_ir_type_dump(type->ir_types, n->ir_type_id);
} break;
case SPL_LANG_TYPE_SLICE:
printf("[]");
@@ -781,7 +844,7 @@ static void spl_lang_type_dump_rec(spl_lang_type_t *type, spl_lang_type_id_t id,
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
spl_type_pure_dump(&type->ir, n->ir_type_id);
spl_ir_type_dump(type->ir_types, n->ir_type_id);
break;
}
File diff suppressed because it is too large. Load diff
-46
View File
@@ -1,46 +0,0 @@
#include "spl_scope.h"
void spl_scope_init(spl_scope_t *scope) {
vec_init(scope->scopes);
vec_push(scope->scopes, (spl_scope_node_t){0});
scope->current_scope = 0;
scope->root_scope = 0;
}
void spl_scope_drop(spl_scope_t *scope) {
for (usize i = 0; i < vec_size(scope->scopes); ++i) {
map_free(vec_at(scope->scopes, i).symbols);
}
vec_free(scope->scopes);
scope->current_scope = 0;
scope->root_scope = 0;
}
spl_scope_id_t spl_scope_alloc(spl_scope_t *scope) {
spl_scope_node_t n = {0};
n.parent = scope->current_scope;
map_init(n.symbols, MAP_HASH_STR, MAP_CMP_STR);
vec_push(scope->scopes, n);
return vec_size(scope->scopes) - 1;
}
bool spl_scope_insert(spl_scope_t *scope, spl_scope_id_t id, spl_symbol_t symbol) {
Assert(id != 0 && id < vec_size(scope->scopes));
spl_scope_node_t *node = &vec_at(scope->scopes, id);
spl_symbol_t old = {0};
if (map_get(node->symbols, symbol.name, &old))
return false;
map_put(node->symbols, symbol.name, symbol);
return true;
}
bool spl_scope_find(spl_scope_t *scope, const char *name, spl_symbol_t *out) {
if (!scope || !name || !out)
return false;
for (spl_scope_id_t id = scope->current_scope; id != 0; id = vec_at(scope->scopes, id).parent) {
spl_scope_node_t *s = &vec_at(scope->scopes, id);
if (map_get(s->symbols, name, out))
return true;
}
return false;
}
-42
View File
@@ -1,42 +0,0 @@
#ifndef __SPL_SCOPE_H__
#define __SPL_SCOPE_H__
#include "spl_lang_type.h"
typedef usize spl_scope_id_t;
typedef enum {
SPL_SYMBOL_KIND_ERROR,
SPL_SYMBOL_KIND_VAR,
SPL_SYMBOL_KIND_MEMBER,
SPL_SYMBOL_KIND_FN,
SPL_SYMBOL_KIND_TYPE,
} spl_symbol_kind_t;
typedef struct {
const char *name;
spl_symbol_kind_t kind;
spl_def_id_t node;
} spl_symbol_t;
typedef VEC(const char *) spl_symbol_path_t;
typedef struct {
spl_scope_id_t parent;
MAP(const char *, spl_symbol_t) symbols;
} spl_scope_node_t;
typedef VEC(spl_scope_node_t) spl_scope_node_vec_t;
typedef struct {
spl_scope_node_vec_t scopes;
spl_scope_id_t root_scope;
spl_scope_id_t current_scope;
} spl_scope_t;
void spl_scope_init(spl_scope_t *scope);
void spl_scope_drop(spl_scope_t *scope);
spl_scope_id_t spl_scope_alloc(spl_scope_t *scope);
bool spl_scope_insert(spl_scope_t *scope, spl_scope_id_t id, spl_symbol_t symbol);
bool spl_scope_find(spl_scope_t *scop, const char *symbol_name, spl_symbol_t *out);
#endif /* __SPL_SCOPE_H__ */
-129
View File
@@ -1,129 +0,0 @@
#ifndef __SPL_TYPE_H__
#define __SPL_TYPE_H__
#include "../stage0/include/utils.h"
#include "spl_fold.h"
/* 类型 intern 用的哈希混合(FNV-1a 风格,顺序敏感)。
hash 只用于选择桶;相等判定始终由结构比较完成。 */
static inline usize spl_hash_mix(usize h, usize x) {
h ^= x;
h *= (usize)1099511628211ULL;
return h;
}
static inline usize spl_hash_mix_str(usize h, const char *s) {
if (!s) {
return spl_hash_mix(h, 0);
}
while (*s) {
h = spl_hash_mix(h, (usize)(unsigned char)*s);
s++;
}
return spl_hash_mix(h, 0); /* 终止符参与混合,避免名称拼接歧义 */
}
static inline usize spl_hash_seed(void) { return (usize)14695981039346656037ULL; }
typedef usize spl_type_id_t;
typedef VEC(spl_type_id_t) spl_type_id_vec_t;
typedef enum {
SPL_TYPE_ERROR,
SPL_TYPE_NEVER, // bottom type
SPL_TYPE_ANY, // top type
SPL_TYPE_UNIT,
SPL_TYPE_INFER,
SPL_TYPE_BOOL,
SPL_TYPE_INT,
SPL_TYPE_FLOAT,
SPL_TYPE_PTR,
SPL_TYPE_ARRAY,
SPL_TYPE_STRUCT,
SPL_TYPE_UNION,
SPL_TYPE_ENUM,
SPL_TYPE_FN,
SPL_TYPE_SHAPE,
} spl_type_node_kind_t;
typedef enum {
SPL_TYPE_LAYOUT_AUTO,
SPL_TYPE_LAYOUT_EXTERN_C,
SPL_TYPE_LAYOUT_PACKED,
} spl_type_layout_mode_t;
typedef struct {
spl_type_layout_mode_t mode;
usize fixed_align_bits;
} spl_type_layout_t;
typedef struct {
const char *name;
spl_type_id_t type_id;
usize ast_node_ref;
} spl_type_member_t;
typedef VEC(spl_type_member_t) spl_type_member_vec_t;
typedef struct {
spl_type_node_kind_t kind;
spl_type_layout_t layout;
union {
struct {
usize bits;
int is_signed;
} int_type;
struct {
usize bits;
} float_type;
struct {
spl_type_id_t pointee;
} ptr_type;
struct {
spl_type_id_t element;
usize len;
} array_type;
struct {
spl_type_member_vec_t variants;
spl_type_id_t tag_type;
} agg_type;
struct {
spl_type_id_vec_t params;
spl_type_id_t ret;
} fn_type;
struct {
} shape_type;
};
usize hash_next; /* 同 hash 桶内下一个类型 id;0 表示链尾。不参与相等比较。 */
} spl_type_node_t;
typedef VEC(spl_type_node_t) spl_type_node_vec_t;
typedef struct {
spl_type_node_vec_t type_table;
spl_fold_t type_fold;
} spl_type_t;
void spl_type_init(spl_type_t *type);
void spl_type_drop(spl_type_t *type);
spl_type_node_t *spl_type_node(const spl_type_t *type, spl_type_id_t id);
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *type_node);
spl_type_id_t spl_type_builder_simple(spl_type_t *type, spl_type_node_kind_t kind);
spl_type_id_t spl_type_builder_int(spl_type_t *type, usize bits, int is_signed);
spl_type_id_t spl_type_builder_float(spl_type_t *type, usize bits);
spl_type_id_t spl_type_builder_ptr(spl_type_t *type, spl_type_id_t pointee);
spl_type_id_t spl_type_builder_array(spl_type_t *type, spl_type_id_t element, usize len);
spl_type_id_t spl_type_builder_fn(spl_type_t *type, spl_type_id_t ret, const spl_type_id_t *params,
usize nparams);
spl_type_id_t spl_type_builder_agg(spl_type_t *type, spl_type_node_kind_t tk,
spl_type_member_vec_t *variants, spl_type_id_t tag_type,
spl_type_layout_t layout);
void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id);
bool spl_type_is_subtype(const spl_type_t *type, spl_type_id_t sub, spl_type_id_t super);
const spl_type_member_t *spl_type_agg_member(spl_type_t *type, spl_type_id_t tid, const char *name);
bool spl_type_agg_member_idx(spl_type_t *type, spl_type_id_t tid, const char *name, usize *out_idx);
#endif /* __SPL_TYPE_H__ */
+37 -2
View File
@@ -68,6 +68,7 @@ type Body = enum {
ExprNullLit,
ExprUndefinedLit,
ExprIdent: struct { name: ByteView },
ExprLambda: struct { params: Vec, ret_type: usize, body: usize },
ExprUnary: struct { op: Punct, operand: usize },
ExprBinary: struct { op: Punct, left: usize, right: usize },
ExprCall: struct { callee: usize, args: Vec },
@@ -85,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 },
@@ -96,6 +98,7 @@ type Body = enum {
label: usize,
iter_exprs: Vec,
pattern: usize,
pattern_type: usize,
body: usize,
else_branch: usize,
},
@@ -111,7 +114,7 @@ type Body = enum {
TypeSlice: struct { elem_type: usize },
TypeFn: struct { is_comptime: bool, params: Vec, ret_type: usize },
TypeParen: struct { types: Vec },
TypeAggregate: struct { kind_name: ByteView, members: Vec },
TypeAggregate: struct { kind_name: ByteView, conforms: Vec, members: Vec },
TypeComptimeCall: struct { name: ByteView, args: Vec },
PatternIdent: struct { name: ByteView },
PatternUnderscore,
@@ -123,6 +126,11 @@ type Body = enum {
PatternRef: struct { pat: usize },
ExprComptime: struct { body: usize },
ExprComptimeInit: struct { name: ByteView, args: Vec, fields: Vec },
AssocDecl: struct { attr_list: Vec, name: ByteView },
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 {
@@ -138,6 +146,7 @@ fn kind_name(body: Body): []u8 {
.VarDecl(_) => { ret "var_decl"; },
.ConstDecl(_) => { ret "const_decl"; },
.TypeDecl(_) => { ret "type_decl"; },
.AssocDecl(_) => { ret "assoc_decl"; },
.MemberDecl(_) => { ret "member_decl"; },
.ParamDecl(_) => { ret "param_decl"; },
.StatementRet(_) => { ret "statement_ret"; },
@@ -161,6 +170,7 @@ fn kind_name(body: Body): []u8 {
.ExprNullLit => { ret "null_lit"; },
.ExprUndefinedLit => { ret "undefined_lit"; },
.ExprIdent(_) => { ret "ident"; },
.ExprLambda(_) => { ret "lambda"; },
.ExprUnary(_) => { ret "unary"; },
.ExprBinary(_) => { ret "binary"; },
.ExprCall(_) => { ret "call"; },
@@ -172,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"; },
@@ -190,6 +201,10 @@ fn kind_name(body: Body): []u8 {
.TypeFn(_) => { ret "type_fn"; },
.TypeParen(_) => { ret "type_paren"; },
.TypeAggregate(_) => { ret "type_aggregate"; },
.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"; },
@@ -441,6 +456,9 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
dump_opt(ast, buf, stack, d.pattern, false) &&
dump_opt(ast, buf, stack, d.type_expr, true);
},
.AssocDecl(d) => {
ok = dump_list(ast, buf, stack, d.attr_list);
},
.MemberDecl(d) => {
ok = dump_list(ast, buf, stack, d.attr_list) &&
dump_opt(ast, buf, stack, d.type_expr, false) &&
@@ -481,6 +499,11 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
.ExprNullLit => {},
.ExprUndefinedLit => {},
.ExprIdent(x) => {},
.ExprLambda(x) => {
ok = dump_list(ast, buf, stack, x.params) &&
dump_opt(ast, buf, stack, x.ret_type, false) &&
dump_opt(ast, buf, stack, x.body, true);
},
.ExprUnary(u) => { ok = dump_opt(ast, buf, stack, u.operand, true); },
.ExprBinary(b) => {
ok = dump_opt(ast, buf, stack, b.left, false) &&
@@ -511,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) &&
@@ -546,6 +573,7 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
ok = dump_opt(ast, buf, stack, f.label, false) &&
dump_list(ast, buf, stack, f.iter_exprs) &&
dump_opt(ast, buf, stack, f.pattern, false) &&
dump_opt(ast, buf, stack, f.pattern_type, true) &&
dump_opt(ast, buf, stack, f.body, false) &&
dump_opt(ast, buf, stack, f.else_branch, true);
},
@@ -566,7 +594,14 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
dump_opt(ast, buf, stack, f.ret_type, true);
},
.TypeParen(p) => { ok = dump_list(ast, buf, stack, p.types); },
.TypeAggregate(a) => { ok = dump_list(ast, buf, stack, a.members); },
.TypeAggregate(a) => {
ok = dump_list(ast, buf, stack, a.conforms) &&
dump_list(ast, buf, stack, a.members);
},
.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 => {},
+14 -4
View File
@@ -561,6 +561,16 @@ fn cg_unop(cg: *Cgen, ref: usize, n: *IrEntry, op: Op) {
}
}
fn tid_is_float(ctx: *Ir2Vm, tid: usize): bool {
var te = TypeTable.node(ctx.ty, tid);
if te == null { ret false; }
match te.node {
.Float(_) => { ret true; },
_ => {},
}
ret false;
}
fn cg_cmp(cg: *Cgen, ref: usize, n: *IrEntry, op: Op) {
match n.body {
.Cmp(c) => {
@@ -1059,19 +1069,19 @@ fn cg_node(cg: *Cgen, ref: usize, n: *IrEntry) {
.CmpNe => { cg_cmp(cg, ref, n, .Ne); },
.CmpLt => {
var k = cmp_tid(n);
if tid_is_signed(ctx, k) { cg_cmp(cg, ref, n, .Slt); } else { cg_cmp(cg, ref, n, .Ult); }
if tid_is_signed(ctx, k) || tid_is_float(ctx, k) { cg_cmp(cg, ref, n, .Slt); } else { cg_cmp(cg, ref, n, .Ult); }
},
.CmpLe => {
var k = cmp_tid(n);
if tid_is_signed(ctx, k) { cg_cmp(cg, ref, n, .Sle); } else { cg_cmp(cg, ref, n, .Ule); }
if tid_is_signed(ctx, k) || tid_is_float(ctx, k) { cg_cmp(cg, ref, n, .Sle); } else { cg_cmp(cg, ref, n, .Ule); }
},
.CmpGt => {
var k = cmp_tid(n);
if tid_is_signed(ctx, k) { cg_cmp(cg, ref, n, .Sgt); } else { cg_cmp(cg, ref, n, .Ugt); }
if tid_is_signed(ctx, k) || tid_is_float(ctx, k) { cg_cmp(cg, ref, n, .Sgt); } else { cg_cmp(cg, ref, n, .Ugt); }
},
.CmpGe => {
var k = cmp_tid(n);
if tid_is_signed(ctx, k) { cg_cmp(cg, ref, n, .Sge); } else { cg_cmp(cg, ref, n, .Uge); }
if tid_is_signed(ctx, k) || tid_is_float(ctx, k) { cg_cmp(cg, ref, n, .Sge); } else { cg_cmp(cg, ref, n, .Uge); }
},
.CastTrunc => { cg_cast(cg, ref, n); },
+1 -1
View File
@@ -1,6 +1,6 @@
// Expect retcode = 0
// 字节流 -> Vec<Token>。行为镜像 splc0(保证 diff):行注释作为 token 产出,块注释
// 字节流 -> Vec[Token]。行为镜像 splc0(保证 diff):行注释作为 token 产出,块注释
//(可嵌套)跳过,换行产 Endline,EOF 产 Eof。Token.text 借用输入,不复制。
type .{ .Vec, .VecResult } = @import("utils/vec.spl");
+402 -70
View File
@@ -22,10 +22,10 @@ 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 上下文(类型可作为表达式)
fn new(ast: *Ast, toks: Vec, diag: *Diag): Parser {
ret Parser {
.ast = ast,
@@ -34,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,
@@ -285,6 +286,7 @@ fn can_start_expr(kind: TokenKind): bool {
.Match => { ret true; },
.Comptime => { ret true; },
.Try => { ret true; },
.Fn => { ret true; },
_ => { ret false; },
}
},
@@ -311,6 +313,133 @@ fn can_start_expr(kind: TokenKind): bool {
ret false;
}
// comptime/type 调用实参可以是类型或表达式。`*` / `fn` / `const` 等纯类型起始
// token 在表达式位置没有合法前缀形式(解引用写 `.*`),必须由同一张表判定,
// 否则 `@F(bool)` 这类关键字类型会漏成“空实参”。
fn kind_starts_type(kind: TokenKind): bool {
match kind {
.Ident => { ret true; },
.Keyword(k) => {
match k {
.Type, .Bool, .Any, .Fn, .Const, .Struct, .Union, .Enum, .Shape => { ret true; },
_ => {},
}
},
.Punct(p) => {
match p {
.Mul, .LBracket, .At, .Sharp => { ret true; },
_ => {},
}
},
_ => {},
}
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);
}
// `fn(...)` 在表达式位置可能是 lambda,也可能是函数类型。
// 参数里出现 `ident :` 或返回类型后跟 `{` 时按 lambda 处理。
fn looks_like_lambda(self: *Parser): bool {
var i = self.pos;
var t = token_ptr(self, i);
if t == null || !kind_is_keyword(t.kind, .Fn) { ret false; }
i = i + 1;
t = token_ptr(self, i);
if t == null || !kind_is_punct(t.kind, .LParen) { ret false; }
i = i + 1;
var depth: usize = 1;
while true {
t = token_ptr(self, i);
if t == null { ret false; }
match t.kind {
.Punct(p) => {
match p {
.LParen => { depth = depth + 1; },
.RParen => {
depth = depth - 1;
if depth == 0 { break; }
},
_ => {},
}
},
.Ident => {
if depth == 1 {
var nx = token_ptr(self, i + 1);
if nx != null && kind_is_punct(nx.kind, .Colon) { ret true; }
}
},
_ => {},
}
i = i + 1;
}
i = i + 1;
t = token_ptr(self, i);
if t == null { ret false; }
if kind_is_punct(t.kind, .LBrace) { ret true; }
if kind_is_punct(t.kind, .Colon) {
i = i + 1;
while true {
t = token_ptr(self, i);
if t == null { ret false; }
match t.kind {
.Punct(p) => {
match p {
.LBrace => { ret true; },
.RParen, .Comma, .Semicolon, .Assign => { ret false; },
_ => {},
}
},
_ => {},
}
i = i + 1;
}
}
ret false;
}
fn parse_lambda(self: *Parser): usize {
var start = peek(self);
if start == null || !kind_is_keyword(start.kind, .Fn) { ret 0; }
advance(self);
if !expect_punct(self, .LParen, "'(' in lambda") { ret 0; }
var params = parse_param_list(self);
if !expect_punct(self, .RParen, "')' in lambda") { ret 0; }
var ret_type: usize = 0;
if at_punct(self, .Colon) {
advance(self);
ret_type = parse_type_expr(self);
}
var body = parse_block(self);
ret new_node(self, .ExprLambda(.{ .params = params, .ret_type = ret_type, .body = body }), start);
}
fn can_start_statement(kind: TokenKind): bool {
match kind {
.Keyword(k) => {
@@ -499,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(_) => {
@@ -668,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);
@@ -742,7 +890,9 @@ fn decorated_expr_follows(t: *Token): bool {
match t.kind {
.Punct(p) => {
match p {
.At, .Sharp, .LParen, .LBracket => { ret true; },
// `@Type(args)(...)` / `@Type(args)[...]` 是值构造与索引,
// 不能把前面的 `@Type(args)` 当装饰器。
.At, .Sharp => { ret true; },
_ => { ret false; },
}
},
@@ -753,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 {
@@ -810,10 +944,9 @@ fn parse_fn_decl(self: *Parser, tags: Vec, is_comptime: bool): usize {
advance(self);
ret_type = parse_type_expr(self);
t = peek(self);
} else if token_starts_type(t) {
// 省略冒号:`fn f() T { ... }`
ret_type = parse_type_expr(self);
t = peek(self);
} else if t != null && token_starts_type(t) {
parse_error(self, t, "expected ':' before return type");
ret 0;
}
var body: usize = 0;
if is_comptime { self.comptime_depth = self.comptime_depth + 1; }
@@ -841,6 +974,22 @@ fn parse_type_decl(self: *Parser, tags: Vec): usize {
var kw = peek(self);
if kw == null || !kind_is_keyword(kw.kind, .Type) { ret 0; }
advance(self);
var an = peek(self);
var anext = peek_next(self);
if an != null && anext != null {
var is_name = false;
match an.kind { .Ident => { is_name = true; }, _ => {} }
var is_end = kind_is_punct(anext.kind, .Semicolon) || kind_is_punct(anext.kind, .Comma);
if is_name && is_end {
advance(self);
var ref = new_node(self, .AssocDecl(.{
.attr_list = tags,
.name = an.text,
}), kw);
advance(self);
ret ref;
}
}
var pattern = parse_pattern(self);
if pattern == 0 { ret 0; }
if !expect_punct(self, .Assign, "'=' in type declaration") { ret 0; }
@@ -921,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);
}
@@ -1082,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();
@@ -1089,55 +1247,127 @@ fn parse_type_comptime_call(self: *Parser): usize {
advance(self);
args = parse_expr_list(self);
expect_punct(self, .RParen, "')' in comptime type");
} else if !ByteView.eq(name, ByteView.from_slice("self")) &&
!ByteView.eq(name, ByteView.from_slice("import")) {
// `@adapter Shape`:shape 使用点省略括号,参数是一个类型表达式。
var nt = peek(self);
if token_starts_type(nt) {
var a = parse_type_expr(self);
match Vec.push(&args, &a as *u8) { .Ok => {}, .Err(e) => {} }
}
} else if at_punct(self, .LBracket) {
// `@adapter[Shape + ...]`:type-only shape 使用点。
advance(self);
args = parse_shape_list(self, true);
expect_punct(self, .RBracket, "']' in shape use");
ret new_node(self,
.TypeShapeUse(.{ .adapter = name, .shapes = args }), start);
}
ret new_node(self,
.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");
var first = peek(self);
var named = false;
if first != null {
match first.kind {
.Ident => {
var nx = peek_next(self);
if nx != null && kind_is_punct(nx.kind, .Assign) { named = true; }
},
_ => {},
}
}
if !named {
parse_error(self, first, "type construction requires @Name(...)");
ret 0;
}
var binds = ref_vec();
while !self.failed && !at_punct(self, .RBracket) {
var bn = peek(self);
if bn == null { break; }
match bn.kind { .Ident => {}, _ => { break; } }
advance(self);
if !expect_punct(self, .Assign, "'=' in shape binding") { break; }
var bt_ty = parse_type_expr(self);
var bind = new_node(self, .TypeAssocBind(.{
.name = bn.text,
.ty = bt_ty,
}), bn);
match Vec.push(&binds, &bind as *u8) {
.Ok => {},
.Err(error) => { break; },
}
if at_punct(self, .Comma) {
advance(self);
continue;
}
break;
}
expect_punct(self, .RBracket, "']' in shape application");
ret new_node(self, .TypeShapeApply(.{
.base = bt.text,
.binds = binds,
}), bt);
}
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 = is_comptime,
.params = ref_vec(),
.ret_type = 0,
}), at);
var params = ref_vec();
while !self.failed && !at_punct(self, .RParen) {
var pt = parse_type_expr(self);
match Vec.push(&params, &pt as *u8) { .Ok => {}, .Err(e) => { ret 0; } }
if at_punct(self, .Comma) { advance(self); continue; }
break;
}
expect_punct(self, .RParen, "')' in function type");
var ret_ty: usize = 0;
if at_punct(self, .Colon) {
advance(self);
ret_ty = parse_type_expr(self);
}
var fnode = Ast.node(self.ast, ref);
match fnode.body {
.TypeFn(f) => {
f.params = params;
f.ret_type = ret_ty;
fnode.body = .TypeFn(f);
},
_ => {},
}
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);
if !expect_punct(self, .LParen, "'(' in function type") { ret 0; }
// 先分配 TYPE_FN,再解析参数与返回类型。
var ref = new_node(self, .TypeFn(.{
.is_comptime = false,
.params = ref_vec(),
.ret_type = 0,
}), bt);
var params = ref_vec();
while !self.failed && !at_punct(self, .RParen) {
var pt = parse_type_expr(self);
match Vec.push(&params, &pt as *u8) { .Ok => {}, .Err(e) => { ret 0; } }
if at_punct(self, .Comma) { advance(self); continue; }
break;
}
expect_punct(self, .RParen, "')' in function type");
var ret_ty: usize = 0;
if at_punct(self, .Colon) {
advance(self);
ret_ty = parse_type_expr(self);
}
var fnode = Ast.node(self.ast, ref);
match fnode.body {
.TypeFn(f) => {
f.params = params;
f.ret_type = ret_ty;
fnode.body = .TypeFn(f);
},
_ => {},
}
ret ref;
ret parse_fn_type(self, bt, false);
}
match bt.kind {
@@ -1152,17 +1382,24 @@ fn parse_type_base(self: *Parser): usize {
}
if kind_name.len != 0 {
advance(self);
var conforms = ref_vec();
if at_punct(self, .Colon) {
advance(self);
conforms = parse_shape_list(self, false);
}
if !expect_punct(self, .LBrace, "'{' in aggregate type") { ret 0; }
var members = ref_vec();
var ref = new_node(self, .TypeAggregate(.{
.kind_name = ByteView.from_slice(kind_name),
.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);
@@ -1183,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;
}
},
@@ -1192,6 +1432,12 @@ fn parse_type_base(self: *Parser): usize {
match bt.kind {
.Ident => {
advance(self);
// 类型应用:`Vec[i32]` / `Iter[Item = i32]`。
// 数组字面量元素类型(`[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)`)。
if at_punct(self, .LParen) {
advance(self);
@@ -1278,6 +1524,13 @@ fn parse_type_decorators(self: *Parser, out: *Vec) {
expect_punct(self, .RParen, "')' in decorator args");
}
var nt = peek(self);
// `@hook[...]` 紧贴名字时是 type-only shape use;留空格才是 decorator + 数组/切片类型。
if nt != null && kind_is_punct(nt.kind, .LBracket) &&
name.offset + name.text.len == nt.offset {
self.pos = save;
Vec.drop(&args);
ret;
}
if !token_starts_type(nt) {
self.pos = save;
Vec.drop(&args);
@@ -1304,6 +1557,27 @@ fn parse_type_expr(self: *Parser): usize {
ret r;
}
// shape 列表:`A + B`;调用方决定停在 `>` 还是 `{`。
fn parse_shape_list(self: *Parser, stop_at_rbracket: bool): Vec {
var out = ref_vec();
while !self.failed {
if stop_at_rbracket && at_punct(self, .RBracket) { break; }
if !stop_at_rbracket && at_punct(self, .LBrace) { break; }
var e = parse_type_expr(self);
if e == 0 { break; }
match Vec.push(&out, &e as *u8) {
.Ok => {},
.Err(error) => { ret out; },
}
if at_punct(self, .Add) {
advance(self);
continue;
}
break;
}
ret out;
}
fn parse_type_expr_core(self: *Parser): usize {
var t = peek(self);
if t == null { ret 0; }
@@ -1335,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);
}
@@ -1730,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 => {
@@ -1738,6 +2017,9 @@ fn parse_primary(self: *Parser): usize {
var cbody = parse_expr(self);
ret new_node(self, .ExprComptime(.{ .body = cbody }), t);
},
.Fn => {
if looks_like_lambda(self) { ret parse_lambda(self); }
},
.Struct, .Union, .Enum, .Shape => {
// 类型即表达式仅限 comptime 上下文。
if self.comptime_depth > 0 { ret parse_type_base(self); }
@@ -1796,6 +2078,13 @@ fn parse_primary(self: *Parser): usize {
.elems = elems,
}), t);
}
// `.(.Variant(payload))`:由期望类型定型的 variant 构造。
if kind_is_punct(nx.kind, .LParen) {
advance(self);
var inner = parse_expr(self);
if !expect_punct(self, .RParen, "')' after '.(...)' constructor") { ret 0; }
ret inner;
}
var is_ident = false;
match nx.kind { .Ident => { is_ident = true; }, _ => {} }
if is_ident { ret parse_variant_construct(self, t); }
@@ -1911,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) {
@@ -1959,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);
@@ -1995,16 +2307,16 @@ fn parse_expr_list(self: *Parser): Vec {
var vec = ref_vec();
if self.failed { ret vec; }
var t = peek(self);
if t == null || !can_start_expr(t.kind) { ret vec; }
var first = parse_expr(self);
if t == null || (!type_arg_start(t.kind) && !can_start_expr(t.kind)) { ret vec; }
var first = parse_type_or_expr_arg(self);
match Vec.push(&vec, &first as *u8) { .Ok => {}, .Err(e) => { ret vec; } }
while !self.failed {
var nt = peek(self);
if nt == null || !kind_is_punct(nt.kind, .Comma) { break; }
advance(self);
var nx = peek(self);
if nx == null || !can_start_expr(nx.kind) { break; }
var e = parse_expr(self);
if nx == null || (!type_arg_start(nx.kind) && !can_start_expr(nx.kind)) { break; }
var e = parse_type_or_expr_arg(self);
match Vec.push(&vec, &e as *u8) { .Ok => {}, .Err(er) => { ret vec; } }
}
ret vec;
@@ -2122,7 +2434,17 @@ fn parse_for_expr(self: *Parser): usize {
advance(self);
var pattern = parse_pattern(self);
if pattern == 0 { ret 0; }
if !expect_punct(self, .Colon, "':' after for pattern") { ret 0; }
var pattern_type: usize = 0;
if at_punct(self, .Colon) {
advance(self);
pattern_type = parse_type_expr(self);
if pattern_type == 0 { ret 0; }
}
if !at_keyword(self, .In) {
parse_error(self, peek(self), "'in' after for pattern");
ret 0;
}
advance(self);
var iter_exprs = ref_vec();
self.stop_agg = self.stop_agg + 1;
var e0 = parse_expr(self);
@@ -2145,6 +2467,7 @@ fn parse_for_expr(self: *Parser): usize {
.label = 0,
.iter_exprs = iter_exprs,
.pattern = pattern,
.pattern_type = pattern_type,
.body = body,
.else_branch = else_branch,
}), kw);
@@ -2170,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); }
@@ -2292,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);
}
@@ -2688,7 +3020,7 @@ fn expect_contains(buf: *ByteBuffer, needle: []u8) {
// stage3 语法:`comptime fn ... (t: type) type { ... }` 与省略冒号的返回类型。
fn test_parse_comptime_fn() {
var src: []u8 = "comptime fn vec(t: type) type { ret t; }\n";
var src: []u8 = "comptime fn vec(t: type): type { ret t; }\n";
var toks = lex_tokens(src);
defer { Vec.drop(&toks); }
+5 -1
View File
@@ -7,7 +7,7 @@ type .{ .ByteView } = @import("utils/byte_view.spl");
type Keyword = enum {
Any, As, Bool, Break, Catch, Comptime, Const, Continue, Defer, Else, Enum,
Errdefer, False, Fn, For, If, Loop, Match, Null, Ret, Shape, Struct, True,
Errdefer, False, Fn, For, If, In, Loop, Match, Null, Ret, Shape, Struct, True,
Try, Type, Undefined, Union, Var, While, Underscore,
}
@@ -75,6 +75,7 @@ fn keyword_of(text: ByteView): KeywordResult {
if c0 == 'a' && is(text, "as") { ret .Yes(.As); }
if c0 == 'f' && is(text, "fn") { ret .Yes(.Fn); }
if c0 == 'i' && is(text, "if") { ret .Yes(.If); }
if c0 == 'i' && is(text, "in") { ret .Yes(.In); }
ret .No;
}
if n == 3 {
@@ -147,6 +148,7 @@ fn keyword_name(kw: Keyword): []u8 {
.Fn => { ret "KW_FN"; },
.For => { ret "KW_FOR"; },
.If => { ret "KW_IF"; },
.In => { ret "KW_IN"; },
.Loop => { ret "KW_LOOP"; },
.Match => { ret "KW_MATCH"; },
.Null => { ret "KW_NULL"; },
@@ -259,6 +261,7 @@ fn expect_keyword(result: KeywordResult, expected: Keyword) {
fn test_keywords() {
expect_keyword(keyword_of(view("fn")), .Fn);
expect_keyword(keyword_of(view("in")), .In);
expect_keyword(keyword_of(view("while")), .While);
expect_keyword(keyword_of(view("_")), .Underscore);
match keyword_of(view("foo")) {
@@ -337,6 +340,7 @@ fn test_kind_names() {
expect_kind_name(.Keyword(.Fn), "KW_FN");
expect_kind_name(.Keyword(.For), "KW_FOR");
expect_kind_name(.Keyword(.If), "KW_IF");
expect_kind_name(.Keyword(.In), "KW_IN");
expect_kind_name(.Keyword(.Loop), "KW_LOOP");
expect_kind_name(.Keyword(.Match), "KW_MATCH");
expect_kind_name(.Keyword(.Null), "KW_NULL");
+208 -18
View File
@@ -91,14 +91,18 @@ errors: usize,
in_fn: bool, // 是否在函数体内(仅函数内才绑定局部名)
inject: *Vec, // 当前作用域的注入列表;`#!` 往这里 push(即上一层作用域)
root: Ref, // 文件 root(TopBlock)
lambdas: Vec, // 匿名 fn 生成的顶层 FnDecl
lambda_seq: usize,
fn new(ast: *Ast, ir: *B.HirNodeContainer): Ast2Hir {
ret Ast2Hir { .ast = ast, .ir = ir, .scopes = scope_new(), .errors = 0,
.in_fn = false, .inject = null, .root = 0 };
.in_fn = false, .inject = null, .root = 0,
.lambdas = Vec.blank(@sizeof(Ref), @alignof(Ref)), .lambda_seq = 0 };
}
fn drop(self: *Ast2Hir) {
scope_drop(&self.scopes);
Vec.drop(&self.lambdas);
}
fn new_vec(): Vec {
@@ -197,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;
@@ -323,6 +328,13 @@ fn lower_type_inner(self: *Ast2Hir, ref: usize): Ref {
ret emit(self, .FnType(.{ .params = finish_list(self, &params), .ret_ty = ret_ty }), n.span);
},
.TypeAggregate(x) => {
var conforms = new_vec();
var ci: usize = 0;
while ci < x.conforms.len {
var cref = (x.conforms.data as *usize)[ci];
push_ref(&conforms, lower_type(self, cref));
ci = ci + 1;
}
var decls = new_vec();
var fields = new_vec();
// 容器是作用域:成员里的 `#!` 注入到容器自身(上一层)。
@@ -342,11 +354,61 @@ fn lower_type_inner(self: *Ast2Hir, ref: usize): Ref {
self.inject = saved;
ret emit(self, .AggType(.{
.kind = agg_kind(x.kind_name),
.conforms = finish_list(self, &conforms),
.fields = finish_list(self, &fields),
.decls = finish_list(self, &decls),
.injected = finish_list(self, &injected),
}), n.span);
},
.TypeShapeApply(x) => {
var base = emit(self, .NamedType(sl(x.base)), n.span);
var binds = new_vec();
var bi: usize = 0;
while bi < x.binds.len {
var bref = (x.binds.data as *usize)[bi];
var bn = Ast.node(self.ast, bref);
if bn != null {
match bn.body {
.TypeAssocBind(b) => {
var bty = lower_type(self, b.ty);
push_ref(&binds, emit(self, .AssocBind(.{
.name = sl(b.name),
.ty = bty,
}), bn.span));
},
_ => {},
}
}
bi = bi + 1;
}
ret emit(self, .ShapeApply(.{
.base = base,
.binds = finish_list(self, &binds),
}), n.span);
},
.TypeShapeUse(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, .ShapeUse(.{
.adapter = sl(x.adapter),
.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);
@@ -464,6 +526,11 @@ fn lower_module(self: *Ast2Hir) {
Vec.drop(&tmp);
i = i + 1;
}
var li: usize = 0;
while li < self.lambdas.len {
push_ref(&decls, (self.lambdas.data as *Ref)[li]);
li = li + 1;
}
var block = emit(self, .Block(.{ .stmts = finish_list(self, &decls), .tail = 0 }), span_none());
self.root = emit_tagged(self, .TopBlock(block), span_none(), file_tags);
},
@@ -534,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;
}
@@ -548,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;
}
@@ -563,15 +630,21 @@ fn lower_decl(self: *Ast2Hir, ref: usize): Ref {
ret emit_tagged(self, .TypeDecl(.{ .name = sl(pattern_name(self, x.pattern)), .ty = ty }),
n.span, tags);
},
.AssocDecl(x) => {
var tags = lower_tags(self, x.attr_list);
ret emit_tagged(self, .AssocDecl(.{ .name = sl(x.name) }), n.span, tags);
},
.MemberDecl(x) => {
var ty: Ref = 0;
if x.type_expr != 0 { ty = lower_type(self, x.type_expr); }
ret emit(self, .FieldDecl(.{ .name = sl(x.name), .ty = ty }), n.span);
var tags = lower_tags(self, x.attr_list);
ret emit_tagged(self, .FieldDecl(.{ .name = sl(x.name), .ty = ty }), n.span, tags);
},
.AggregateMember(x) => {
var ty: Ref = 0;
if x.type_expr != 0 { ty = lower_type(self, x.type_expr); }
ret emit(self, .FieldDecl(.{ .name = sl(x.name), .ty = ty }), n.span);
var tags = lower_tags(self, x.attr_list);
ret emit_tagged(self, .FieldDecl(.{ .name = sl(x.name), .ty = ty }), n.span, tags);
},
_ => { ret syntax_err(self, ref); },
}
@@ -691,7 +764,7 @@ fn lower_stmt(self: *Ast2Hir, ref: usize): Ref {
ret 0;
}
fn lower_captures(self: *Ast2Hir, pattern: usize, out: *Vec) {
fn lower_captures(self: *Ast2Hir, pattern: usize, out: *Vec, members: *Vec, member: usize) {
if pattern == 0 { ret; }
var n = Ast.node(self.ast, pattern);
if n == null { ret; }
@@ -701,18 +774,21 @@ fn lower_captures(self: *Ast2Hir, pattern: usize, out: *Vec) {
.ty = 0, .init = 0 }), n.span);
if self.in_fn { scope_bind(&self.scopes, x.name, d); }
push_ref(out, d);
push_ref(members, member);
},
.PatternList(x) => {
var i: usize = 0;
while i < x.items.len {
lower_captures(self, (x.items.data as *usize)[i], out);
lower_captures(self, (x.items.data as *usize)[i], out, members,
if member == 0 { i + 1 } else { member });
i = i + 1;
}
},
.PatternTuple(x) => {
var i: usize = 0;
while i < x.items.len {
lower_captures(self, (x.items.data as *usize)[i], out);
lower_captures(self, (x.items.data as *usize)[i], out, members,
if member == 0 { i + 1 } else { member });
i = i + 1;
}
},
@@ -741,6 +817,59 @@ fn lower_ifvar(self: *Ast2Hir, vdecl: usize, then_block: usize, else_branch: usi
ret emit(self, .IfVar(.{ .pattern = pat, .init = value, .then = then, .els = els }), span);
}
fn lower_lambda(self: *Ast2Hir, params_ast: Vec, ret_ast: usize, body_ast: usize, span: Span): Ref {
var saved_scopes = self.scopes;
var saved_fn = self.in_fn;
var saved_inject = self.inject;
self.scopes = scope_new();
self.in_fn = true;
var injected = new_vec();
self.inject = &injected;
var params = new_vec();
var i: usize = 0;
while i < params_ast.len {
push_ref(&params, lower_decl(self, (params_ast.data as *usize)[i]));
i = i + 1;
}
var body: Ref = 0;
if body_ast != 0 { body = lower_block(self, body_ast); }
var ret_ty: Ref = 0;
if ret_ast != 0 { ret_ty = lower_type(self, ret_ast); }
var nb = ByteBuffer.new();
ByteBuffer.append(&nb, "__lambda_");
match append_usize(&nb, self.lambda_seq, 10, false) { .Ok => {}, .Err(error) => {} }
var name = B.dup_bytes(self.ir, ByteBuffer.as_slice(nb));
ByteBuffer.drop(&nb);
self.lambda_seq = self.lambda_seq + 1;
var none = new_vec();
var tag_args = new_vec();
var tag = emit(self, .Tag(.{
.is_at = false,
.name = "__lambda",
.args = finish_list(self, &tag_args),
}), span);
var tags: [1]Ref = .[tag];
var fn_ref = emit_tagged(self, .FnDecl(.{
.is_comptime = false,
.injected = finish_list(self, &none),
.name = name,
.params = finish_list(self, &params),
.ret_ty = ret_ty,
.body = body,
}), span, tags[0..1]);
push_ref(&self.lambdas, fn_ref);
self.inject = saved_inject;
Vec.drop(&injected);
self.in_fn = saved_fn;
scope_drop(&self.scopes);
self.scopes = saved_scopes;
ret emit(self, .FnRef(fn_ref), span);
}
fn lower_agg_lit(self: *Ast2Hir, name: ByteView, fields: Vec, span: Span): Ref {
var out = new_vec();
var i: usize = 0;
@@ -778,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);
@@ -829,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; }
},
_ => {},
}
}
@@ -848,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(_), .TypeComptimeCall(_) => { ret lower_type(self, ref); },
.TypeParen(_), .TypeAggregate(_), .TypeShapeApply(_), .TypeShapeUse(_),
.TypeShapeNoDefault(_), .TypeComptimeCall(_) => { ret lower_type(self, ref); },
_ => {},
}
var r = lower_expr_inner(self, ref);
@@ -883,6 +1026,9 @@ fn lower_expr_inner(self: *Ast2Hir, ref: usize): Ref {
if r != 0 { ret emit(self, .Local(r), n.span); }
ret emit(self, .Global(sl(x.name)), n.span);
},
.ExprLambda(x) => {
ret lower_lambda(self, x.params, x.ret_type, x.body, n.span);
},
.ExprUnary(x) => {
var o = lower_expr(self, x.operand);
match x.op {
@@ -1008,19 +1154,41 @@ fn lower_expr_inner(self: *Ast2Hir, ref: usize): Ref {
i = i + 1;
}
var caps = new_vec();
var cap_members = new_vec();
scope_begin(&self.scopes);
lower_captures(self, x.pattern, &caps);
lower_captures(self, x.pattern, &caps, &cap_members, 0);
var pattern_type: Ref = 0;
if x.pattern_type != 0 { pattern_type = lower_type(self, x.pattern_type); }
var body = lower_block(self, x.body);
var els: Ref = 0;
if x.else_branch != 0 { els = lower_block(self, x.else_branch); }
scope_end(&self.scopes);
ret emit(self, .Iter(.{
var margs = new_vec();
var mi: usize = 0;
while mi < cap_members.len {
var mv = (cap_members.data as *usize)[mi];
var mb = ByteBuffer.new();
append_usize(&mb, mv, 10, false);
var txt = B.dup_bytes(self.ir, ByteBuffer.as_slice(mb));
ByteBuffer.drop(&mb);
var lit = emit(self, .LitInt(txt), n.span);
push_ref(&margs, lit);
mi = mi + 1;
}
Vec.drop(&cap_members);
var ctag = emit(self, .Tag(.{ .name = "capture_members",
.args = finish_list(self, &margs),
.is_at = false }), n.span);
var tags: [1]Ref = .[ctag];
ret emit_tagged(self, .Iter(.{
.label = lower_label(self, x.label),
.inputs = finish_list(self, &inputs),
.captures = finish_list(self, &caps),
.pattern_type = pattern_type,
.body = body,
.else_body = els,
}), n.span);
}), n.span, tags[0..1]);
},
.ExprComptime(x) => {
var body = lower_expr(self, x.body);
@@ -1033,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) => {
@@ -1050,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();
@@ -1073,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(_) => { ret lower_type(self, ref); },
.TypeAggregate(_), .TypeShapeApply(_), .TypeShapeUse(_),
.TypeShapeNoDefault(_) => { ret lower_type(self, ref); },
_ => { ret syntax_err(self, ref); },
}
ret 0;
+78 -1
View File
@@ -1,4 +1,7 @@
#!builtin
#!role(builtins)
type meta = @import("meta");
// splc3 的预置头:把编译器底层能力以 `#builtin` 声明暴露给用户/comptime 代码。
// `#builtin(<id>)` 的 id 必须命中 stage3/intrinsic.spl 的 intrinsic_of_id。
@@ -10,8 +13,82 @@
#builtin(alignof) #extern(builtin) comptime fn alignof(t: type): usize;
#builtin(field_count) #extern(builtin) comptime fn field_count(t: type): usize;
#builtin(type_of) comptime fn type_of(v: any): type;
#builtin(self) comptime fn Self(): type;
#builtin(self) comptime fn self(): type;
// spl_ir 接口:单写/单读,经编译器生成的 VM ABI 调用(无显式桥)。
// `#extern(builtin)` 表示后端外部实现(等价于当前后端的 `#extern(vm)`)。
#builtin(echo) #extern(builtin) comptime fn echo(x: u8): u8;
// 运行期 panic:消息是动态切片,由宿主打印并终止。
#extern(vm) fn panic(msg: []u8): void;
type Ref = @import("./spl_ir.spl").Ref;
type Node = @import("./spl_ir.spl").Node;
#builtin(inspect) #extern(builtin) comptime fn inspect(n: Ref): Node;
#builtin(construct) #extern(builtin) comptime fn construct(n: Node): Ref;
// receiver hook:@Self 只挂在方法的第一个参数上。
// 参数类型是 *T 时取地址,是 T 时按值传递;implicit 本身已是指向接收者的指针时直接复用。
#hook(param)
macro fn Self(callee: Ref, value: Ref, implicit: Ref): Ref {
if implicit == 0 {
if value != 0 { ret value; }
ret 0;
}
var cn = @meta.inspect(callee);
match cn.kind {
.FnDecl(f) => {
var pn = @meta.inspect(f.params[0]);
match pn.kind {
.ParamDecl(p) => {
var tn = @meta.inspect(p.ty);
match tn.kind {
.PtrType(_) => {
if @ptr_ref(implicit) { ret implicit; }
ret @meta.construct(.{ .kind = .Addr(implicit) });
},
_ => {},
}
},
_ => {},
}
},
_ => {},
}
ret implicit;
}
// implicit 已是 `*T` 形式(局部变量或参数)时不再二次取地址。
comptime fn ptr_ref(r: Ref): bool {
var n = @meta.inspect(r);
var decl: Ref = 0;
match n.kind {
.Addr(_) => { ret true; },
.Local(p) => { decl = p; },
_ => {},
}
if decl == 0 { ret false; }
var dn = @meta.inspect(decl);
var ty: Ref = 0;
match dn.kind {
.ParamDecl(p) => { ty = p.ty; },
.VarDecl(v) => { ty = v.ty; },
_ => {},
}
if ty == 0 { ret false; }
var tn = @meta.inspect(ty);
match tn.kind {
.PtrType(_) => { ret true; },
.ShapeUse(x) => {
var sn = @meta.inspect(x.shapes[0]);
match sn.kind { .PtrType(_) => { ret true; }, _ => {} }
},
.ShapeNoDefault(xs) => {
var sn = @meta.inspect(xs[0]);
match sn.kind { .PtrType(_) => { ret true; }, _ => {} }
},
_ => {},
}
ret false;
}
+66 -5
View File
@@ -16,12 +16,33 @@ type ErrorCode = enum {
ShapeParamNotShape,
MacroCode,
FmtMissingArg,
FmtNonliteral,
FmtBadType,
HookNotMacro,
ParamHook,
Decorator,
DefaultMismatch,
ShapeMethodMissing,
ShapeAssocMismatch,
ShapeAssocUnbound,
ShapeMethodConflict,
OpNotImplemented,
NotIterable,
TryNoSuccess,
CatchHandlerType,
TryErrorMismatch,
CatchPattern,
ErrdeferNoError,
DuplicateSuccess,
TryNoError,
LambdaCapture,
// 值/声明/导入/控制流诊断;编号与 label() 固定在这里,增删只改本表。
NotAssignable,
AssignToConst,
MissingDeclType,
ImportFailed,
BreakOutsideLoop,
ContinueOutsideLoop,
VarargsNotAllowed,
};
fn number(code: ErrorCode): usize {
@@ -42,12 +63,32 @@ 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; },
.Decorator => { ret 315; },
.DefaultMismatch => { ret 704; },
.DefaultMismatch => { ret 316; },
.ShapeMethodMissing => { ret 317; },
.ShapeAssocMismatch => { ret 318; },
.ShapeAssocUnbound => { ret 319; },
.ShapeMethodConflict => { ret 320; },
.OpNotImplemented => { ret 321; },
.NotIterable => { ret 322; },
.TryNoSuccess => { ret 701; },
.CatchHandlerType => { ret 702; },
.TryErrorMismatch => { ret 703; },
.CatchPattern => { ret 705; },
.ErrdeferNoError => { ret 706; },
.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;
}
@@ -70,12 +111,32 @@ 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"; },
.Decorator => { ret "E0315"; },
.DefaultMismatch => { ret "E0704"; },
.DefaultMismatch => { ret "E0316"; },
.ShapeMethodMissing => { ret "E0317"; },
.ShapeAssocMismatch => { ret "E0318"; },
.ShapeAssocUnbound => { ret "E0319"; },
.ShapeMethodConflict => { ret "E0320"; },
.OpNotImplemented => { ret "E0321"; },
.NotIterable => { ret "E0322"; },
.TryNoSuccess => { ret "E0701"; },
.CatchHandlerType => { ret "E0702"; },
.TryErrorMismatch => { ret "E0703"; },
.CatchPattern => { ret "E0705"; },
.ErrdeferNoError => { ret "E0706"; },
.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 "";
}
+221
View File
@@ -0,0 +1,221 @@
#!role(lang)
// 语言内置类型的声明面。布局由 #repr(...) 映射到编译器内部表示,
// 方法体和 conformance 都写在这里。
type .{ .Iter, .Step, .Index, .IntoIter,
.Add, .Sub, .Mul, .Div, .Mod, .Neg,
.BitAnd, .BitOr, .BitXor, .Shl, .Shr, .BitNot,
.Eq, .Ord, .Ordering } = @import("ops");
#repr("slice")
#repr_field(_ptr, 0)
#repr_field(_len, 1)
comptime fn Slice(T: type): type {
ret struct: Iter[Item = T] + IntoIter[Item = T, Iter = @self] + Index[Output = T] {
_ptr: *T,
_len: usize,
fn len(@Self self: @self): usize {
ret self._len;
}
fn as_ptr(@Self self: *@self): *T {
ret self._ptr;
}
fn from_raw_parts(p: *T, n: usize): @self {
ret .{ ._ptr = p, ._len = n };
}
fn index(@Self self: *@self, i: usize): *T {
ret self._ptr + i;
}
fn iter(@Self self: *@self): @self {
ret self.*;
}
fn next(@Self self: *@self): @Step(T) {
if self._len == 0 {
ret .Done;
}
var v = self._ptr[0];
self._ptr = self._ptr + 1;
self._len = self._len - 1;
ret .Item(v);
}
};
}
#repr("array")
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: @self): usize;
#builtin(array_index)
fn index(@Self self: *@self, i: usize): *T;
#builtin(array_iter)
fn iter(@Self self: *@self): @Slice(T);
#builtin(array_as_ptr)
fn as_ptr(@Self self: *@self): *T;
};
}
#repr("int")
comptime fn Int(bits: usize, signed: bool): type {
ret struct: Add[Rhs = @self, Output = @self]
+ Sub[Rhs = @self, Output = @self]
+ Mul[Rhs = @self, Output = @self]
+ Div[Rhs = @self, Output = @self]
+ Mod[Rhs = @self, Output = @self]
+ Neg[Output = @self]
+ BitAnd[Rhs = @self, Output = @self]
+ BitOr[Rhs = @self, Output = @self]
+ BitXor[Rhs = @self, Output = @self]
+ Shl[Rhs = @self, Output = @self]
+ Shr[Rhs = @self, Output = @self]
+ BitNot[Output = @self]
+ Eq[Rhs = @self]
+ Ord[Rhs = @self] {
#op(add)
fn add(@Self lhs: @self, rhs: @self): @self;
#op(sub)
fn sub(@Self lhs: @self, rhs: @self): @self;
#op(mul)
fn mul(@Self lhs: @self, rhs: @self): @self;
#op(div)
fn div(@Self lhs: @self, rhs: @self): @self;
#op(mod)
fn rem(@Self lhs: @self, rhs: @self): @self;
#op(neg)
fn neg(@Self value: @self): @self;
#op(bit_and)
fn bit_and(@Self lhs: @self, rhs: @self): @self;
#op(bit_or)
fn bit_or(@Self lhs: @self, rhs: @self): @self;
#op(bit_xor)
fn bit_xor(@Self lhs: @self, rhs: @self): @self;
#op(shl)
fn shl(@Self lhs: @self, rhs: @self): @self;
#op(shr)
fn shr(@Self lhs: @self, rhs: @self): @self;
#op(bit_not)
fn bit_not(@Self value: @self): @self;
#op(eq)
fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord)
fn cmp(@Self lhs: @self, rhs: @self): Ordering;
};
}
#repr("float")
comptime fn Float(bits: usize): type {
ret struct: Add[Rhs = @self, Output = @self]
+ Sub[Rhs = @self, Output = @self]
+ Mul[Rhs = @self, Output = @self]
+ Div[Rhs = @self, Output = @self]
+ Mod[Rhs = @self, Output = @self]
+ Neg[Output = @self]
+ Eq[Rhs = @self]
+ Ord[Rhs = @self] {
#op(add)
fn add(@Self lhs: @self, rhs: @self): @self;
#op(sub)
fn sub(@Self lhs: @self, rhs: @self): @self;
#op(mul)
fn mul(@Self lhs: @self, rhs: @self): @self;
#op(div)
fn div(@Self lhs: @self, rhs: @self): @self;
#op(mod)
fn rem(@Self lhs: @self, rhs: @self): @self;
#op(neg)
fn neg(@Self value: @self): @self;
#op(eq)
fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord)
fn cmp(@Self lhs: @self, rhs: @self): Ordering;
};
}
#repr("bool")
comptime fn Bool(): type {
ret struct: Eq[Rhs = @self] + Ord[Rhs = @self] {
#op(eq)
fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord)
fn cmp(@Self lhs: @self, rhs: @self): Ordering;
};
}
comptime fn Range(): type {
ret struct: Iter[Item = usize] {
begin: usize,
end: usize,
fn next(@Self self: *@self): @Step(usize) {
if self.begin >= self.end {
ret .Done;
}
var v = self.begin;
self.begin = self.begin + 1;
ret .Item(v);
}
};
}
#repr("ptr")
comptime fn Ptr(key: usize): type {
ret struct: Add[Rhs = usize, Output = @self]
+ Sub[Rhs = usize, Output = @self]
+ Eq[Rhs = @self]
+ Ord[Rhs = @self] {
#op(add)
fn add(@Self lhs: @self, rhs: usize): @self;
#op(sub)
fn sub(@Self lhs: @self, rhs: usize): @self;
#op(eq)
fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord)
fn cmp(@Self lhs: @self, rhs: @self): Ordering;
};
}
#repr("fn")
comptime fn Fn(key: usize): type {
ret struct: Eq[Rhs = @self] + Ord[Rhs = @self] {
#op(eq)
fn eq(@Self lhs: @self, rhs: @self): bool;
#op(ord)
fn cmp(@Self lhs: @self, rhs: @self): Ordering;
};
}
+2
View File
@@ -1,3 +1,5 @@
#!builtin
// 元编程模块:HIR 反射接口。必须显式 `type meta = @import("meta")` 后使用。
type Ref = @import("./spl_ir.spl").Ref;
type Node = @import("./spl_ir.spl").Node;
+142
View File
@@ -0,0 +1,142 @@
#!role(ops)
// 语言运算符协议。运算符解析只认本模块的 shape;
// 用户模块里的同名 shape 不参与语言分派。
type Ordering = enum {
Less,
Equal,
Greater,
};
#lang(add)
type Add = shape {
type Rhs;
type Output;
fn add(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(sub)
type Sub = shape {
type Rhs;
type Output;
fn sub(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(mul)
type Mul = shape {
type Rhs;
type Output;
fn mul(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(div)
type Div = shape {
type Rhs;
type Output;
fn div(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(mod)
type Mod = shape {
type Rhs;
type Output;
fn rem(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(neg)
type Neg = shape {
type Output;
fn neg(@Self value: @self): Output;
};
#lang(bit_and)
type BitAnd = shape {
type Rhs;
type Output;
fn bit_and(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(bit_or)
type BitOr = shape {
type Rhs;
type Output;
fn bit_or(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(bit_xor)
type BitXor = shape {
type Rhs;
type Output;
fn bit_xor(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(shl)
type Shl = shape {
type Rhs;
type Output;
fn shl(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(shr)
type Shr = shape {
type Rhs;
type Output;
fn shr(@Self lhs: @self, rhs: Rhs): Output;
};
#lang(bit_not)
type BitNot = shape {
type Output;
fn bit_not(@Self value: @self): Output;
};
#lang(eq)
type Eq = shape {
type Rhs;
fn eq(@Self lhs: @self, rhs: Rhs): bool;
};
#lang(ord)
type Ord = shape {
type Rhs;
fn cmp(@Self lhs: @self, rhs: Rhs): Ordering;
};
#lang(index)
type Index = shape {
type Output;
fn index(@Self self: *@self, idx: usize): *Output;
};
type Len = shape {
fn len(@Self self: @self): usize;
};
comptime fn Step(T: type): type {
ret enum {
Item: T,
Done,
};
}
#lang(call)
type Call = shape {
type Args;
type Output;
fn call(self: @self, args: Args): Output;
};
#lang(iter)
type Iter = shape {
type Item;
fn next(@Self self: *@self): @Step(Item);
};
#lang(into_iter)
type IntoIter = shape {
type Item;
type Iter;
fn iter(@Self self: *@self): Iter;
};
+12 -6
View File
@@ -48,6 +48,7 @@ type Node = struct {
LessEqual,
GreaterThan,
GreaterEqual,
Reserved,
}
type Agg = enum {
@@ -79,14 +80,14 @@ 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 },
IfVar: struct { pattern: Ref, init: Ref, then: Ref, els: Ref },
Destructure: struct { pattern: Ref, init: Ref },
Loop: struct { label: Ref, body: Ref, ret_ty: Ref },
Iter: struct { label: Ref, inputs: []Ref, captures: []Ref, body: Ref, else_body: Ref },
Iter: struct { label: Ref, inputs: []Ref, captures: []Ref, pattern_type: Ref, body: Ref, else_body: Ref },
Break: struct { label: Ref, value: Ref },
Continue: struct { label: Ref },
Return: Ref,
@@ -109,8 +110,8 @@ type Node = struct {
PatList: []Ref,
PatTuple: []Ref,
PatField: struct { name: []u8, sub: Ref },
AggType: struct { kind: Agg, fields: []Ref, decls: []Ref, injected: []Ref },
PatFields: []Ref,
AggType: struct { kind: Agg, conforms: []Ref, fields: []Ref, decls: []Ref, injected: []Ref },
ArrayType: struct { len: Ref, elem: Ref },
SliceType: Ref,
PtrType: Ref,
@@ -148,7 +149,13 @@ 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 },
}
}
@@ -159,9 +166,8 @@ fn inspect(r: Ref): Node;
fn main() {
var n: Node = .{ .kind = .LitInt("123") };
@assert(n.tags.len == 0, "tags default empty");
match n.kind {
.LitInt(s) => { @assert(s.len == 3, "lit text kept"); },
.LitInt(s) => { @assert(s[0] == '1', "lit text kept"); },
_ => { @assert(false, "expected lit int"); },
}
+21 -20
View File
@@ -4,7 +4,8 @@
// 对齐 Zig 的 comptime(Sema 求值),求值内核换成嵌套 VM。
// 标量结果折回 LitInt/LitBool;聚合结果经 sret 在嵌套 VM 中构造后读回字节。
type Sema = @import("./sema.spl");
type SemaM = @import("./sema.spl");
type Sema = SemaM.Sema;
type Bld = @import("./spl_ir_builder.spl");
type LangType = @import("./lang_type.spl");
type .{ .LangKind } = @import("./lang_type.spl");
@@ -57,7 +58,7 @@ fn native_resolver(user: *any, name_off: u64, name_len: u64,
var handled = false;
var v = Reflect.dispatch(user, bv, nested, arg_base, &handled);
if handled { ret v; }
Sema.sema_error(user as *Sema, "unknown comptime native", nm);
SemaM.sema_error(user as *Sema, "unknown comptime native", nm);
ret 0;
}
@@ -72,7 +73,7 @@ fn is_agg_kind(k: LangKind): bool {
fn eval(user: *any, ref: usize): void {
var sema = user as *Sema;
var saved_mod = sema.cur_mod;
defer { Sema.switch_mod(sema, saved_mod); }
defer { SemaM.switch_mod(sema, saved_mod); }
var saved_ctb = sema.ct.building;
sema.ct.building = true;
defer { sema.ct.building = saved_ctb; }
@@ -81,9 +82,9 @@ fn eval(user: *any, ref: usize): void {
if n == null { ret; }
var body: usize = ref;
match n.kind { .Comptime(x) => { body = x; }, _ => {} }
var rl = Sema.tid_of(sema, body);
var rl = SemaM.tid_of(sema, body);
if rl == 0 { ret; }
var ret_ir = Sema.ir_of(sema, rl);
var ret_ir = SemaM.ir_of(sema, rl);
var agg = is_agg_kind(LangType.kind_of(&sema.types, rl));
var fn_ret_ir = ret_ir;
if agg { fn_ret_ir = TypeTable.make_ptr(&sema.types.ir, ret_ir); }
@@ -96,18 +97,18 @@ fn eval(user: *any, ref: usize): void {
// 分块边界:一次 comptime 点只编译 (root, 类型实参) 的可达函数闭包,
// 不发射未达函数。先分析可达体(可能新增 defs),再按正确 slots 容量建 Hir2Ir。
var root = Sema.ct_root_of(ref);
var reach = Sema.reachable_from(sema, root);
var root = SemaM.ct_root_of(ref);
var reach = SemaM.reachable_from(sema, root);
var changed = true;
while changed {
changed = false;
var ii: usize = 0;
while ii < reach.len {
var sym = (reach.data as *usize)[ii];
Sema.analyze_fn_body(sema, Sema.sym_at(sema, sym - 1).decl);
SemaM.analyze_fn_body(sema, SemaM.sym_at(sema, sym - 1).decl);
ii = ii + 1;
}
var r2 = Sema.reachable_from(sema, root);
var r2 = SemaM.reachable_from(sema, root);
if r2.len != reach.len { Vec.drop(&reach); reach = r2; changed = true; }
else { Vec.drop(&r2); }
}
@@ -120,9 +121,9 @@ fn eval(user: *any, ref: usize): void {
var ri: usize = 0;
while ri < reach.len {
var sym = (reach.data as *usize)[ri];
var s = Sema.sym_at(sema, sym - 1);
Sema.switch_mod(sema, s.mod);
var rr = IrBuilder.fn_reserve(&b, Hir2Ir.fn_name(&h2i, s.mod, s.owner, s.name, s.ref), Sema.ir_of(sema, s.fn_tid));
var s = SemaM.sym_at(sema, sym - 1);
SemaM.switch_mod(sema, s.mod);
var rr = IrBuilder.fn_reserve(&b, Hir2Ir.fn_name(&h2i, s.mod, s.owner, s.name, s.ref), SemaM.ir_of(sema, s.fn_tid));
(h2i.fn_refs.data as *usize)[sym - 1] = rr;
ri = ri + 1;
}
@@ -169,10 +170,10 @@ fn eval(user: *any, ref: usize): void {
var vf = (vm.prog.funcs.data as *VmFunc) + vfi;
var si2: usize = 0;
while si2 < sema.fn_syms.len {
var ss = Sema.sym_at(sema, si2);
var ss = SemaM.sym_at(sema, si2);
var stable = Hir2Ir.fn_name(&h2i, ss.mod, ss.owner, ss.name, ss.ref);
if ByteView.eq(vf.name, stable) {
Sema.record_ct_fn_ref(sema, vf.address, si2 + 1);
SemaM.record_ct_fn_ref(sema, vf.address, si2 + 1);
break;
}
si2 = si2 + 1;
@@ -204,26 +205,26 @@ fn eval(user: *any, ref: usize): void {
match ByteBuffer.append_repeat(&obuf, 0, size) { .Ok => {}, .Err(e) => { ret; } }
var dst = ByteBuffer.as_slice(obuf);
ignore_i32(vm_mem_read(nv, out, dst.ptr, size));
Sema.switch_mod(sema, saved_mod);
SemaM.switch_mod(sema, saved_mod);
var sid = Bld.dup_bytes(&sema.hir, dst);
var np = Bld.node_ptr(&sema.hir, ref);
np.kind = .ConstAgg(sid);
Sema.set_tid(sema, ref, rl);
SemaM.set_tid(sema, ref, rl);
ret;
}
if vm_call_name(nv, "__ct") != 0 { ret; }
ignore_i32(vm_run(nv));
var rv = vm_ret_val(nv);
Sema.switch_mod(sema, saved_mod);
SemaM.switch_mod(sema, saved_mod);
var k = LangType.kind_of(&sema.types, rl);
var np2 = Bld.node_ptr(&sema.hir, ref);
if @enum2int(k) == @enum2int(LangKind.Int) { Sema.set_ct_int(sema, ref, rv); }
if @enum2int(k) == @enum2int(LangKind.Int) { SemaM.set_ct_int(sema, ref, rv); }
else if @enum2int(k) == @enum2int(LangKind.Bool) {
if rv != 0 { np2.kind = .LitBool("true"); } else { np2.kind = .LitBool("false"); }
}
else if @enum2int(k) == @enum2int(LangKind.Type) { Sema.set_ct_int(sema, ref, rv); }
Sema.set_tid(sema, ref, rl);
else if @enum2int(k) == @enum2int(LangKind.Type) { SemaM.set_ct_int(sema, ref, rv); }
SemaM.set_tid(sema, ref, rl);
}
fn main() {}
+954 -169
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 387 files, more files were not shown because too many files have changed in this diff. Show more