Compare commits

..
4 Commits
52 changed files with 1502 additions and 1305 deletions

No files matched your search

+1
View File
@@ -97,6 +97,7 @@ typedef enum {
/* 间接内存访问 */ \
X(SPL_LOAD, "load", 0, 1, 1, "load sizeof(type)-bits zero-extended") \
X(SPL_STORE, "store", 0, 2, 0, "store low sizeof(type)-bits") \
X(SPL_MEMCPY, "memcpy", 0, 3, 0, "copy n bytes: pop dst, src, n (VM address space)") \
/* 原生接口 */ \
X(SPL_NCALL, "ncall", 1, 0, 1, "call native function by index") \
X(SPL_NLIB, "nlib", 1, 0, 0, "dlopen library (name idx)") \
-28
View File
@@ -87,32 +87,4 @@ SPL_FN u64 vm_timestamp(u64 kind) {
#define SPL_VM_EMBED_IMPLIMENTATION
#include "spl_vm_embed.h"
/* 配置层外部函数处理器(native 端):把 nested VM 未解析的 native 按名分发到
* 编译器生成的 `ct_*` 函数(表由 ir2c 生成,见 stage2/ir2c.spl)。 */
extern void *spl_ct_lookup(const char *name);
typedef spl_vm_val_t (*spl_native_ct_fn_t)(void *, spl_vm_val_t, spl_vm_val_t, spl_vm_val_t);
SPL_FN spl_vm_val_t spl_native_foreign(spl_vm_t *vm, const spl_vm_call_t *call, void *user) {
void *fn;
spl_vm_val_t a0 = 0, a1 = 0;
(void)vm;
if (!call)
return 0;
fn = spl_ct_lookup(call->name);
if (!fn)
return 0;
if (call->nargs > 0)
a0 = call->args[0];
if (call->nargs > 1)
a1 = call->args[1];
/* ct_* 统一形状:返回 u64,参数 (ctx, u64, u64);多余参数被忽略。 */
return ((spl_native_ct_fn_t)fn)(user, a0, a1, 0);
}
SPL_FN void vm_set_foreign(void *p, unsigned long long handler, void *ctx) {
(void)handler;
spl_vm_set_foreign((spl_vm_t *)p, spl_native_foreign, ctx);
}
#endif /* __SPL_RT_H__ */
+58 -33
View File
@@ -615,33 +615,51 @@ static spl_vm_val_t vm_timestamp(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
* nested-VM syscalls
* ================================================================= */
/* ---- 配置层的“外部函数处理器”:把某个 VM 未解析的 native 交给调用者 VM。
* 这是配置策略,不属于 VM 库 API;VM 本身只有通用 foreign 钩子。 ---- */
/* 通用双向桥(配置层策略,非 VM 平台 API):
* 在子 VM 上安装「未解析 native 处理器」,把子 VM 的未解析调用按名转发到
* 宿主(调用者)VM 中由 `entry` 指定的函数。宿主函数收到:
* (ctx, name_off, name_len, nested_vm, arg_base, nargs)
* 平台/C 侧**纯转发**:不复制实参、不限元数、不了解类型;聚合读写由宿主用
* vm_stack_get / vm_mem_read / vm_mem_alloc / vm_mem_write 自行完成。
* `entry` 由宿主显式给出,平台不预设任何函数名。 */
typedef struct {
spl_vm_t *caller;
spl_vm_t *host;
void *ctx;
} spl_foreign_t;
char entry[128];
} spl_bridge_t;
static spl_vm_val_t spl_foreign_reenter(spl_vm_t *vm, const spl_vm_call_t *call, void *user) {
spl_foreign_t *f = (spl_foreign_t *)user;
spl_vm_val_t tmp[20];
spl_vm_call_t c2;
int i;
(void)vm;
if (!f || !f->caller || !call || !call->name)
static spl_vm_val_t spl_bridge_forward(spl_vm_t *nested, const spl_vm_call_t *call, void *user) {
spl_bridge_t *b = (spl_bridge_t *)user;
spl_vm_val_t name_off;
spl_vm_val_t args[6];
spl_vm_call_t back;
usize n;
usize arg_base;
if (!b || !b->host || !call || !call->name || b->entry[0] == '\0')
return 0;
if (call->nargs + 1 > (usize)(sizeof(tmp) / sizeof(tmp[0])))
n = strlen(call->name);
/* 名拷进宿主 VM 内存,宿主按偏移读取。 */
name_off = spl_vm_mem_alloc(b->host, n + 1);
if (!name_off)
return 0;
tmp[0] = (spl_vm_val_t)(uintptr_t)f->ctx;
for (i = 0; i < (int)call->nargs; i++)
tmp[1 + i] = call->args ? call->args[i] : 0;
c2.name = call->name;
c2.args = tmp;
c2.nargs = call->nargs + 1;
c2.ret = 0;
if (spl_vm_invoke(f->caller, &c2) != 0)
if (spl_vm_mem_write(b->host, name_off, call->name, n + 1) != 0)
return 0;
return c2.ret;
arg_base = spl_vm_call_arg_base(nested, call);
if (arg_base == (usize)-1)
return 0;
args[0] = (spl_vm_val_t)(uintptr_t)b->ctx;
args[1] = name_off;
args[2] = (spl_vm_val_t)n;
args[3] = (spl_vm_val_t)(uintptr_t)nested;
args[4] = (spl_vm_val_t)arg_base;
args[5] = (spl_vm_val_t)call->nargs;
back.name = b->entry;
back.args = args;
back.nargs = 6;
back.ret = 0;
if (spl_vm_invoke(b->host, &back) != 0)
return 0;
return back.ret;
}
static spl_vm_val_t vm_new(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
@@ -655,25 +673,32 @@ static spl_vm_val_t vm_new(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
return (spl_vm_val_t)(uintptr_t)vm;
}
/* 配置入口:vm_set_foreign(vm, handler, ctx)。handler=0:把未解析 native 重入
* 当前调用者(_vm),ctx 透传前置。名与语义由配置层定义;VM 库不认识 foreign handler。 */
/* vm_set_foreign(vm, entry, ctx):宿主显式指定处理器函数名。 */
static spl_vm_val_t sc_vm_set_foreign(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
spl_vm_t *vm;
spl_foreign_t *f;
spl_bridge_t *b;
const spl_vm_val_t *entry;
const char *eptr;
usize elen;
CHECK_NARGS("vm_set_foreign", 3);
vm = (spl_vm_t *)(uintptr_t)args[0];
if (!vm || !_vm)
return -1;
if (args[1] != 0) /* 仅注册 handler 0(重入调用者) */
entry = (const spl_vm_val_t *)VM_XN(_vm, args[1], 2 * sizeof(spl_vm_val_t));
if (!entry)
return -1;
if (vm->foreign == spl_foreign_reenter && vm->foreign_ctx)
free(vm->foreign_ctx);
f = (spl_foreign_t *)malloc(sizeof(*f));
if (!f)
eptr = (const char *)VM_X(_vm, entry[0]);
elen = (usize)entry[1];
if (!eptr || elen == 0 || elen >= sizeof(((spl_bridge_t *)0)->entry))
return -1;
f->caller = _vm;
f->ctx = (void *)(uintptr_t)args[2];
spl_vm_set_foreign(vm, spl_foreign_reenter, f);
b = (spl_bridge_t *)malloc(sizeof(*b));
if (!b)
return -1;
b->host = _vm;
b->ctx = (void *)(uintptr_t)args[2];
memcpy(b->entry, eptr, elen);
b->entry[elen] = '\0';
spl_vm_set_foreign(vm, spl_bridge_forward, b);
return 0;
}
@@ -683,7 +708,7 @@ static spl_vm_val_t vm_drop(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
spl_vm_t *vm = (spl_vm_t *)(uintptr_t)args[0];
if (!vm)
return 0;
if (vm->foreign == spl_foreign_reenter && vm->foreign_ctx)
if (vm->foreign == spl_bridge_forward && vm->foreign_ctx)
free(vm->foreign_ctx);
if (vm->prog) {
spl_prog_drop(vm->prog);
+23
View File
@@ -785,6 +785,14 @@ int spl_vm_stack_set(spl_vm_t *vm, usize index, spl_vm_val_t val) {
return 0;
}
usize spl_vm_call_arg_base(spl_vm_t *vm, const spl_vm_call_t *call) {
if (!vm || !call || !call->args || !vm->stacks.data)
return (usize)-1;
if (call->args < vm->stacks.data)
return (usize)-1;
return (usize)(call->args - vm->stacks.data);
}
spl_vm_val_t spl_vm_mem_alloc(spl_vm_t *vm, usize size) { return spl_vm_asp_alloc(vm, size); }
int spl_vm_mem_read(spl_vm_t *vm, spl_vm_val_t off, void *dst, usize n) {
@@ -1358,6 +1366,7 @@ static int vm_loop(spl_vm_t *vm, size_t limit) {
DT(SPL_CALLI), DT(SPL_RET), DT(SPL_ALLOC),
DT(SPL_LADDR), DT(SPL_GADDR), DT(SPL_LOAD),
DT(SPL_STORE), DT(SPL_NCALL), DT(SPL_NLIB),
DT(SPL_MEMCPY),
DT(SPL_BK), DT(SPL_DBG), [SPL_ERROR] = &&L_default,
};
@@ -1679,6 +1688,20 @@ L_SPL_STORE:
memcpy(_addr, &_v, spl_type_size(ins->type));
DISPATCH();
}
L_SPL_MEMCPY:
{
spl_vm_val_t _n = POP();
spl_vm_val_t _src = POP();
spl_vm_val_t _dst = POP();
if (_n) {
void *_d = spl_vm_xlate(vm, _dst, (usize)_n);
void *_s = spl_vm_xlate(vm, _src, (usize)_n);
if (!_d || !_s)
VM_ERROR("MEMCPY: invalid address");
memmove(_d, _s, (usize)_n);
}
DISPATCH();
}
/* ========== Type Conversion ========== */
L_SPL_TRUNC:
+3
View File
@@ -127,6 +127,9 @@ usize spl_vm_sp(spl_vm_t *vm);
usize spl_vm_fp(spl_vm_t *vm);
spl_vm_val_t spl_vm_stack_get(spl_vm_t *vm, usize index);
int spl_vm_stack_set(spl_vm_t *vm, usize index, spl_vm_val_t val);
/* 本次调用实参在 VM 栈中的起始下标(外部处理器可按需用 stack_get 逐个读取,
* 无需在 C 侧了解参数类型/元数上限)。失败返回 (usize)-1。 */
usize spl_vm_call_arg_base(spl_vm_t *vm, const spl_vm_call_t *call);
spl_vm_val_t spl_vm_mem_alloc(spl_vm_t *vm, usize size);
int spl_vm_mem_read(spl_vm_t *vm, spl_vm_val_t off, void *dst, usize n);
int spl_vm_mem_write(spl_vm_t *vm, spl_vm_val_t off, const void *src, usize n);
+5
View File
@@ -424,6 +424,11 @@ static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t
dump_node(ast, node->pattern_field.pattern, stack, true);
break;
case SPL_AST_PATTERN_REF:
if (node->pattern_ref.pat)
dump_node(ast, node->pattern_ref.pat, stack, true);
break;
default:
break;
}
+6 -1
View File
@@ -73,7 +73,8 @@
X(SPL_AST_PATTERN_TUPLE, V0, pattern_tuple) \
X(SPL_AST_PATTERN_LIST, V0, pattern_list) \
X(SPL_AST_PATTERN_AGGREGATE, V0, pattern_aggregate) \
X(SPL_AST_PATTERN_FIELD, V0, pattern_field)
X(SPL_AST_PATTERN_FIELD, V0, pattern_field) \
X(SPL_AST_PATTERN_REF, V0, pattern_ref)
/* clang-format on */
typedef enum {
@@ -452,6 +453,10 @@ struct spl_ast_node {
const char *name;
spl_ast_node_ref_t pattern;
} pattern_field;
struct {
spl_ast_node_ref_t pat;
} pattern_ref;
};
};
+119 -17
View File
@@ -51,7 +51,8 @@ static void emit_deferred_until(spl_ast2ir_t *a, usize base) {
static void emit_decl(spl_ast2ir_t *a, spl_ast_node_ref_t ref);
static spl_ir_node_ref_t emit_var_decl(spl_ast2ir_t *a, spl_ast_node_t *n);
static void emit_pattern_bind(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref,
spl_ir_node_ref_t src_ptr, spl_type_id_t tid);
spl_ir_node_ref_t src_ptr, spl_type_id_t tid, int place_mode);
static int pattern_has_ref(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref);
static spl_ir_node_ref_t emit_match_check(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref,
spl_type_id_t scrut_ir, spl_ir_node_ref_t scrut_slot);
@@ -140,14 +141,52 @@ static spl_ir_node_ref_t emit_zero_value(spl_ast2ir_t *a, spl_type_id_t tid) {
}
}
/* 判断 pattern 是否包含 `&` 引用绑定(PATTERN_REF)。 */
static int pattern_has_ref(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref) {
if (!pat_ref)
return 0;
spl_ast_node_t *pat = spl_ast_node(a->ast, pat_ref);
if (!pat)
return 0;
switch (pat->kind) {
case SPL_AST_PATTERN_REF:
return 1;
case SPL_AST_PATTERN_LIST:
for (usize i = 0; i < vec_size(pat->pattern_list.patterns); ++i)
if (pattern_has_ref(a, vec_at(pat->pattern_list.patterns, i)))
return 1;
return 0;
case SPL_AST_PATTERN_TUPLE:
for (usize i = 0; i < vec_size(pat->pattern_tuple.patterns); ++i)
if (pattern_has_ref(a, vec_at(pat->pattern_tuple.patterns, i)))
return 1;
return 0;
case SPL_AST_PATTERN_DOT:
return pattern_has_ref(a, pat->pattern_dot.sub_pattern);
case SPL_AST_PATTERN_AGGREGATE:
for (usize i = 0; i < vec_size(pat->pattern_aggregate.fields); ++i) {
spl_ast_node_t *f =
spl_ast_node(a->ast, vec_at(pat->pattern_aggregate.fields, i));
if (f && f->kind == SPL_AST_PATTERN_FIELD &&
pattern_has_ref(a, f->pattern_field.pattern))
return 1;
}
return 0;
default:
return 0;
}
}
/* 把 pattern 里的 ident 绑到 src_ptr 指向内存的对应位置。
- PATTERN_IDENT: def2ir_map[def_id] = src_ptr
- PATTERN_IDENT: def2ir_map[def_id] = src_ptr(place_mode=0,值绑定别名源);
place_mode=1 时强制拷贝到新 slot(源为真实左值,值绑定必须拷贝)。
- PATTERN_REF: src_ptr 是该子位置的地址;分配 *T slot 存该地址,内层名绑到 slot。
- PATTERN_DOT: src_ptr 指向 enum,payload 在 mem_field(tid, src_ptr, vidx+1)
- PATTERN_TUPLE / PATTERN_AGGREGATE: 递归 mem_field
UB 语义:不做 tag 检查,调用者保证变体正确。
*/
static void emit_pattern_bind(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref,
spl_ir_node_ref_t src_ptr, spl_type_id_t tid) {
spl_ir_node_ref_t src_ptr, spl_type_id_t tid, int place_mode) {
if (!pat_ref || !src_ptr)
return;
spl_ast_node_t *pat = spl_ast_node(a->ast, pat_ref);
@@ -156,8 +195,30 @@ static void emit_pattern_bind(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref,
switch (pat->kind) {
case SPL_AST_PATTERN_IDENT: {
if (pat->resolved_def_id)
if (!pat->resolved_def_id)
return;
if (place_mode) {
spl_ir_node_ref_t slot =
spl_ir_builder_mem_alloca(a->ir, tid, const_usize(a, 1));
spl_ir_node_ref_t v = spl_ir_builder_mem_load(a->ir, tid, src_ptr);
spl_ir_builder_mem_store(a->ir, tid, slot, v);
map_put(a->def2ir_map, pat->resolved_def_id, slot);
} else {
map_put(a->def2ir_map, pat->resolved_def_id, src_ptr);
}
return;
}
case SPL_AST_PATTERN_REF: {
spl_ast_node_ref_t inner = pat->pattern_ref.pat;
spl_ast_node_t *in = spl_ast_node(a->ast, inner);
spl_type_id_t ptr_tid = in ? node_ir(a, in) : 0;
if (!ptr_tid)
ptr_tid = spl_type_builder_ptr(&a->sema->type->ir, tid);
spl_ir_node_ref_t slot =
spl_ir_builder_mem_alloca(a->ir, ptr_tid, const_usize(a, 1));
spl_ir_builder_mem_store(a->ir, ptr_tid, slot, src_ptr);
emit_pattern_bind(a, inner, slot, ptr_tid, 0);
return;
}
@@ -174,7 +235,7 @@ static void emit_pattern_bind(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref,
case SPL_AST_PATTERN_LIST:
for (usize i = 0; i < vec_size(pat->pattern_list.patterns); ++i)
emit_pattern_bind(a, vec_at(pat->pattern_list.patterns, i), src_ptr, tid);
emit_pattern_bind(a, vec_at(pat->pattern_list.patterns, i), src_ptr, tid, place_mode);
return;
case SPL_AST_PATTERN_TUPLE: {
@@ -188,7 +249,7 @@ static void emit_pattern_bind(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref,
for (usize i = 0; i < n; ++i) {
spl_type_id_t ft = vec_at(tn->agg_type.variants, i).type_id;
spl_ir_node_ref_t fp = spl_ir_builder_mem_field(a->ir, tid, src_ptr, i);
emit_pattern_bind(a, vec_at(pat->pattern_tuple.patterns, i), fp, ft);
emit_pattern_bind(a, vec_at(pat->pattern_tuple.patterns, i), fp, ft, place_mode);
}
return;
}
@@ -206,7 +267,7 @@ static void emit_pattern_bind(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref,
spl_type_id_t payload_ir = vec_at(tn->agg_type.variants, vidx).type_id;
spl_ir_node_ref_t pptr = spl_ir_builder_mem_field(a->ir, tid, src_ptr, vidx + 1);
if (pat->pattern_dot.sub_pattern)
emit_pattern_bind(a, pat->pattern_dot.sub_pattern, pptr, payload_ir);
emit_pattern_bind(a, pat->pattern_dot.sub_pattern, pptr, payload_ir, place_mode);
return;
}
@@ -224,7 +285,7 @@ static void emit_pattern_bind(spl_ast2ir_t *a, spl_ast_node_ref_t pat_ref,
spl_type_id_t ft = vec_at(tn->agg_type.variants, idx).type_id;
spl_ir_node_ref_t fp = spl_ir_builder_mem_field(a->ir, tid, src_ptr, idx);
if (f->pattern_field.pattern)
emit_pattern_bind(a, f->pattern_field.pattern, fp, ft);
emit_pattern_bind(a, f->pattern_field.pattern, fp, ft, place_mode);
}
return;
}
@@ -297,12 +358,32 @@ static spl_ir_node_ref_t emit_match_check(spl_ast2ir_t *a, spl_ast_node_ref_t pa
}
/* 分配 slot → store init 值 → bind pattern。
返回指向变量内存的指针(*tid),调用者可用于读取初值。 */
返回指向变量内存的指针(*tid),调用者可用于读取初值。
若 pattern 含 `&` 引用绑定:源必须是可寻址左值,直接在源 place 上绑定
(值绑定拷贝子值,引用绑定取子位置地址),返回该 place。 */
static spl_ir_node_ref_t emit_var_decl(spl_ast2ir_t *a, spl_ast_node_t *n) {
spl_type_id_t var_ir = node_ir(a, n);
if (!var_ir)
return 0;
spl_ast_node_ref_t pat_ref = n->var_const_decl.pattern;
if (pattern_has_ref(a, pat_ref)) {
if (!n->var_const_decl.init_expr) {
spl_diag_error(a->diag, SPL_DIAG_KIND_NO_LVALUE, &n->dbg,
"reference binding requires an initialized place");
return 0;
}
spl_ir_node_ref_t place = emit_lvalue(a, n->var_const_decl.init_expr);
if (!place) {
spl_ast_node_t *in = spl_ast_node(a->ast, n->var_const_decl.init_expr);
spl_diag_error(a->diag, SPL_DIAG_KIND_NO_LVALUE, in ? &in->dbg : &n->dbg,
"cannot bind by reference: initializer is not an lvalue");
return 0;
}
emit_pattern_bind(a, pat_ref, place, var_ir, 1);
return place;
}
spl_ir_node_ref_t slot = spl_ir_builder_mem_alloca(a->ir, var_ir, const_usize(a, 1));
if (n->var_const_decl.init_expr) {
@@ -311,7 +392,7 @@ static spl_ir_node_ref_t emit_var_decl(spl_ast2ir_t *a, spl_ast_node_t *n) {
spl_ir_builder_mem_store(a->ir, var_ir, slot, v);
}
emit_pattern_bind(a, n->var_const_decl.pattern, slot, var_ir);
emit_pattern_bind(a, pat_ref, slot, var_ir, 0);
return slot;
}
@@ -1396,12 +1477,32 @@ static spl_ir_node_ref_t emit_expr_raw(spl_ast2ir_t *a, spl_ast_node_ref_t ref)
if (!matched_ir)
return 0;
spl_ir_node_ref_t scrut_slot =
spl_ir_builder_mem_alloca(a->ir, matched_ir, const_usize(a, 1));
spl_ir_node_ref_t scrut_val = emit_expr(a, matched_ref);
if (!scrut_val)
return 0;
spl_ir_builder_mem_store(a->ir, matched_ir, scrut_slot, scrut_val);
spl_ir_node_ref_t scrut_slot = 0;
int matched_place_mode = 0;
for (usize i = 0; i < vec_size(n->match_expr.arms); ++i) {
spl_ast_node_t *arm = spl_ast_node(a->ast, vec_at(n->match_expr.arms, i));
if (arm && arm->kind == SPL_AST_MATCH_ARM &&
pattern_has_ref(a, arm->match_arm.pattern)) {
matched_place_mode = 1;
break;
}
}
if (matched_place_mode) {
scrut_slot = emit_lvalue(a, matched_ref);
if (!scrut_slot) {
spl_diag_error(a->diag, SPL_DIAG_KIND_NO_LVALUE,
matched_node ? &matched_node->dbg : &n->dbg,
"cannot bind by reference: matched value is not an lvalue");
return 0;
}
} else {
scrut_slot = spl_ir_builder_mem_alloca(a->ir, matched_ir, const_usize(a, 1));
spl_ir_node_ref_t scrut_val = emit_expr(a, matched_ref);
if (!scrut_val)
return 0;
spl_ir_builder_mem_store(a->ir, matched_ir, scrut_slot, scrut_val);
}
usize narms = vec_size(n->match_expr.arms);
spl_ir_node_ref_vec_t arm_branches;
@@ -1448,7 +1549,8 @@ static spl_ir_node_ref_t emit_expr_raw(spl_ast2ir_t *a, spl_ast_node_ref_t ref)
spl_ast_node_t *arm = spl_ast_node(a->ast, vec_at(n->match_expr.arms, i));
if (arm && arm->kind == SPL_AST_MATCH_ARM) {
emit_pattern_bind(a, arm->match_arm.pattern, scrut_slot, matched_ir);
emit_pattern_bind(a, arm->match_arm.pattern, scrut_slot, matched_ir,
matched_place_mode);
if (arm->match_arm.body)
emit_expr(a, arm->match_arm.body);
}
+5 -6
View File
@@ -1016,10 +1016,7 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
CG_LOAD(cg, SPL_PTR);
cg_load_slot(cg, n->control_ret.val, SPL_PTR);
CG_PUSH(cg, SPL_U64, sz);
int nat = get_or_add_native(ctx, "vm_memcpy");
CG_PUSH(cg, SPL_U64, (spl_vm_val_t)nat);
emit(cg, SPL_NCALL, SPL_VOID, 3);
emit(cg, SPL_DROP, SPL_VOID, 0);
emit(cg, SPL_MEMCPY, SPL_VOID, 0);
}
emit(cg, SPL_RET, SPL_VOID, 0);
break;
@@ -1084,7 +1081,9 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
spl_type_id_t ret_t = n->control_call.tid;
bool ret_is_sret = ir_is_aggregate(ctx, ret_t);
usize sret_off = 0;
usize j = 0;
/* j = 本节点已压入 tracked 块之上的值的个数(用于栈化 PICK 距离)。
先压 2 个 ABI 空闲 slot,故从 2 起算。 */
usize j = 2;
/* ABI:实参下方预留 2 个空闲 slot(PAD0/PAD1)。 */
CG_PUSH(cg, SPL_U64, 0);
@@ -1093,7 +1092,7 @@ static void cg_control(cgen_t *cg, usize ref, const spl_ir_node_t *n) {
if (ret_is_sret) {
sret_off = vec_at(cg->frame.slots, ref).data_off;
CG_LADDR(cg, sret_off);
j = 1;
j = 3;
}
for (usize i = 0; i < nargs; ++i) {
spl_ir_node_ref_t pref = vec_at(n->control_call.params, i);
+14
View File
@@ -417,6 +417,20 @@ static spl_ast_node_ref_t parse_pattern_atom(spl_parser_t *p) {
return ref;
}
case TOK_AND: {
/* `&name`:解包左值引用绑定。仅允许作用于绑定名。 */
advance(p);
const spl_tok_t *nx = peek(p);
if (!nx || nx->type != TOK_IDENT) {
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_EXPECTED, nx, "expected binding name after '&'");
return 0;
}
spl_ast_node_ref_t inner = parse_pattern_atom(p);
spl_ast_node_ref_t ref = new_node(p, SPL_AST_PATTERN_REF, t);
node_at(p->ast, ref)->pattern_ref.pat = inner;
return ref;
}
default:
PARSE_ERROR(p, SPL_DIAG_KIND_PARSE_UNRECOGNIZED, t, "unexpected token in pattern");
return 0;
+48 -16
View File
@@ -302,27 +302,23 @@ static spl_lang_type_id_t sema_build_aggregate(spl_sema_t *sema, spl_ast_node_t
spl_lang_type_id_t saved_agg = sema->current_aggregate_lang;
sema->current_aggregate_lang = agg_lang;
/* 聚合体自成命名空间:成员类型可引用同体声明的嵌套类型(裸名)。 */
sema_push_scope(sema);
spl_type_member_vec_t members;
vec_init(members);
spl_lang_method_vec_t methods;
vec_init(methods);
/* 第一遍:登记嵌套类型/函数的 def,挂进 methods 与聚合作用域。成员类型可能引用它们,
必须早于成员类型推断,否则限定名(经 methods)与裸名(经作用域)都解析不到。 */
for (usize i = 0; i < vec_size(te->type_aggregate.members); ++i) {
spl_ast_node_ref_t mref = vec_at(te->type_aggregate.members, i);
spl_ast_node_t *mn = spl_ast_node(sema->ast, mref);
if (!mn)
continue;
if (mn->kind == SPL_AST_MEMBER_DECL) {
spl_lang_type_id_t mtid = 0;
if (mn->member_decl.type_expr)
mtid = sema_infer(sema, mn->member_decl.type_expr);
spl_type_member_t m = {.name = mn->member_decl.name,
.type_id = spl_lang_type_get_ir_type(sema->type, mtid),
.ast_node_ref = mref};
vec_push(members, m);
} else if (mn->kind == SPL_AST_FN_DECL) {
if (mn->kind == SPL_AST_FN_DECL) {
spl_def_id_t fn_def = mn->resolved_def_id;
if (!fn_def) {
fn_def = spl_def_alloc(sema->type, SPL_DEF_FN, mn->fn_decl.name, mn->dbg, sema->ast,
@@ -334,6 +330,9 @@ static spl_lang_type_id_t sema_build_aggregate(spl_sema_t *sema, spl_ast_node_t
fn_d->owner_def = owner_def_id;
spl_lang_method_t meth = {.name = mn->fn_decl.name, .def_id = fn_def};
vec_push(methods, meth);
spl_symbol_t fsym = {.name = mn->fn_decl.name, .kind = SPL_SYMBOL_KIND_FN};
fsym.node = fn_def;
spl_scope_insert(sema->scope, sema->scope->current_scope, fsym);
} else if (mn->kind == SPL_AST_TYPE_DECL) {
spl_ast_node_t *tpat = spl_ast_node(sema->ast, mn->type_decl.pattern);
if (!tpat || tpat->kind != SPL_AST_PATTERN_IDENT)
@@ -352,9 +351,37 @@ static spl_lang_type_id_t sema_build_aggregate(spl_sema_t *sema, spl_ast_node_t
}
spl_lang_method_t meth = {.name = tname, .def_id = tdef};
vec_push(methods, meth);
spl_symbol_t tsym = {.name = tname, .kind = SPL_SYMBOL_KIND_TYPE};
tsym.node = tdef;
spl_scope_insert(sema->scope, sema->scope->current_scope, tsym);
}
}
spl_lang_type_node_t *lslot = spl_lang_type_node(sema->type, agg_lang);
if (lslot) {
vec_free(lslot->methods);
lslot->methods = methods;
vec_init(methods);
}
/* 第二遍:成员(字段/变体)类型推断;此时嵌套名字已可解析。 */
for (usize i = 0; i < vec_size(te->type_aggregate.members); ++i) {
spl_ast_node_ref_t mref = vec_at(te->type_aggregate.members, i);
spl_ast_node_t *mn = spl_ast_node(sema->ast, mref);
if (!mn)
continue;
if (mn->kind == SPL_AST_MEMBER_DECL) {
spl_lang_type_id_t mtid = 0;
if (mn->member_decl.type_expr)
mtid = sema_infer(sema, mn->member_decl.type_expr);
spl_type_member_t m = {.name = mn->member_decl.name,
.type_id = spl_lang_type_get_ir_type(sema->type, mtid),
.ast_node_ref = mref};
vec_push(members, m);
}
}
sema_pop_scope(sema);
sema->current_aggregate_lang = saved_agg;
spl_type_node_t tn = {0};
@@ -366,13 +393,6 @@ static spl_lang_type_id_t sema_build_aggregate(spl_sema_t *sema, spl_ast_node_t
vec_init(members);
spl_lang_define_ir(sema->type, agg_ir, &tn);
spl_lang_type_node_t *lslot = spl_lang_type_node(sema->type, agg_lang);
if (lslot) {
vec_free(lslot->methods);
lslot->methods = methods;
vec_init(methods);
}
return agg_lang;
}
@@ -1136,6 +1156,18 @@ static void sema_bind_pattern(spl_sema_t *sema, spl_ast_node_ref_t pat_ref,
case SPL_AST_PATTERN_UNDERSCORE:
return;
case SPL_AST_PATTERN_REF: {
if (!matched_tid) {
spl_diag_error(sema->diag, SPL_DIAG_KIND_TYPE_MISMATCH, &pat->dbg,
"ref pattern requires a concrete type");
return;
}
spl_lang_type_id_t ptr = spl_lang_make_ptr(sema->type, matched_tid);
sema_bind_pattern(sema, pat->pattern_ref.pat, ptr);
pat->resolved_lang_tid = ptr;
return;
}
case SPL_AST_PATTERN_LIST: {
for (usize i = 0; i < vec_size(pat->pattern_list.patterns); ++i)
sema_bind_pattern(sema, vec_at(pat->pattern_list.patterns, i), matched_tid);
+8 -10
View File
@@ -1,9 +1,7 @@
// Expect retcode = 0
// AST:用 ADT(enum 带载荷)表达节点,节点引用是 arena 序号 usize。
// stage1 的 C 结构只是「手写 union 模拟 ADT」;这里直接用 SPL 的 enum 载荷,
// 不照抄 union 布局,只要求最终 dump / 语义与 stage1 一致。
// 索引 0 为 NONE 哨兵(与 stage1 一致)。
// AST:节点为带载荷 ADT,节点引用是 arena 序号(0 为 NONE 哨兵)。最终 dump/语义须与
// splc0 一致。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
@@ -18,7 +16,6 @@ type .{ .Sources, .Source, .set_at } = @import("utils/source.spl");
// 算子不另立 enum:AST 直接存词法 Punct。一元/二元由节点 kind 区分
// (一元:Sub=负 / Not=! / BitNot=~ / And=& / Mul=.*;二元即对应 Punct)。
// ---- 节点体(ADT;variant 名 = stage1 的 kind 名;载荷用内联匿名 struct)----
type Body = enum {
None,
@@ -45,7 +42,7 @@ type Body = enum {
type_expr: usize,
init_expr: usize,
},
ParamDecl: struct { attr_list: Vec, name: ByteView, type_expr: usize },
ParamDecl: struct { attr_list: Vec, is_comptime: bool, name: ByteView, type_expr: usize },
StatementRet: struct { expr: usize },
StatementBreak: struct { label: usize, expr: usize },
StatementContinue: struct { label: usize },
@@ -124,6 +121,7 @@ type Body = enum {
PatternList: struct { items: Vec },
PatternAggregate: struct { items: Vec },
PatternField: struct { name: ByteView, pattern: usize },
PatternRef: struct { pat: usize },
ExprComptime: struct { body: usize },
ExprComptimeInit: struct { name: ByteView, args: Vec, fields: Vec },
}
@@ -201,6 +199,7 @@ fn kind_name(body: Body): []u8 {
.PatternList(_) => { ret "pattern_list"; },
.PatternAggregate(_) => { ret "pattern_aggregate"; },
.PatternField(_) => { ret "pattern_field"; },
.PatternRef(_) => { ret "pattern_ref"; },
}
ret "?";
}
@@ -300,11 +299,11 @@ fn alloc(self: *Ast, body: Body, span: Span): usize {
}
// 注册一段已解码的字符串字节(Ast 拥有;ByteView 指向其中,生命周期同 Ast)。
// 空字符串也保证非空 data 指针(镜像 stage1:空字面量仍有稳定的非空字节地址)。
// 空字符串也保证非空 data 指针(空字面量仍有稳定非空地址)。
fn push_string(self: *Ast, bytes: ByteBuffer): ByteView {
var b = bytes;
if b.storage.len == 0 {
match ByteBuffer.reserve(&b, 1) { .Ok => {}, .Err(error) => {} }
ByteBuffer.reserve(&b, 1);
}
@assert(b.storage.data != null, "ast string pool must be non-null");
// 直接构造,避免 from_slice 把空串规范成 null 视图。
@@ -327,7 +326,6 @@ fn ref_vec(): Vec {
ret Vec.blank(@sizeof(usize), @alignof(usize));
}
// ---- dump(镜像 stage1 spl_ast_dump)----
//
// AST:
// <indent>`-/|-kind #ref [line:col]
@@ -590,6 +588,7 @@ fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool):
.PatternList(v) => { ok = dump_list(ast, buf, stack, v.items); },
.PatternAggregate(v) => { ok = dump_list(ast, buf, stack, v.items); },
.PatternField(p) => { ok = dump_opt(ast, buf, stack, p.pattern, true); },
.PatternRef(p) => { ok = dump_opt(ast, buf, stack, p.pat, true); },
}
stack.len = stack.len - 1;
@@ -604,7 +603,6 @@ fn dump(ast: *Ast, out: *ByteBuffer): bool {
ret dump_node(ast, out, &stack, ast.root, true);
}
// ---- 测试 ----
fn test_kind_names() {
@assert(ByteView.eq(ByteView.from_slice(kind_name(.None)), ByteView.from_slice("none")),
+324 -232
View File
File diff suppressed because it is too large. Load diff
+5 -10
View File
@@ -1,8 +1,7 @@
// Expect retcode = 0
// 属性注册表与属性节点(移植自 stage1/spl_attr.c)。注册表是数据:内置属性
// 在 register_builtins 里登记,查找按 (ns, name)。节点记录命中信息 + 实参。
// 新增属性只加注册项,不改 sema 逻辑(对应 SPL.md 的 @/# 扩展点)。
// 属性注册表:内置属性在 register_builtins 登记,按 (ns, name) 查找。新增属性只加
// 注册项,不改 sema 逻辑(SPL.md 的 @/# 扩展点)。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
@@ -163,10 +162,7 @@ fn alloc(self: *Attr, info_index: usize, args: Vec): usize {
}
fn registry_add(self: *Attr, info: AttrInfo) {
match Vec.push(&self.registry, &info as *u8) {
.Ok => {},
.Err(error) => {},
}
Vec.push(&self.registry, &info as *u8);
}
// 返回注册表下标(>=1)或 0。
@@ -202,9 +198,9 @@ fn register_builtins(self: *Attr) {
registry_add(self, make_info("", "align", .Layout, .Type, .Required, 1, 1));
registry_add(self, make_info("", "volatile", .Ir, .Expr, .Required, 0, 0));
registry_add(self, make_info("", "atomic", .Ir, .Expr, .Required, 0, 1));
registry_add(self, make_info("", "export", .Ir, .Decl, .Optional, 1, 1));
}
// ---- dump(镜像 stage1 spl_attr_dump / spl_attr_dump_id)----
fn push_out(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
@@ -340,7 +336,6 @@ fn dump(self: *Attr, out: *ByteBuffer): bool {
ret true;
}
// ---- 测试 ----
fn expect_text(buf: ByteBuffer, expected: []u8) {
var got = ByteBuffer.as_slice(buf);
@@ -360,7 +355,7 @@ fn test_registry() {
}
defer { drop(&at); }
@assert(at.registry.len == 7, "1 sentinel + 6 builtins");
@assert(at.registry.len == 8, "1 sentinel + 7 builtins");
var i = lookup(&at, ByteView.empty(), ByteView.from_slice("extern"));
@assert(i != 0, "extern found");
+4 -12
View File
@@ -1,12 +1,7 @@
// Expect retcode = 0
// 声明句柄表(移植自 stage1/spl_lang_type.h 的 spl_def_node_t 部分)。
// DefId 是「声明」的稳定身份:作用域符号、AST 节点 resolved_def_id、以及将来
// comptime 生成的声明都用它。前向引用/环形引用由 state 状态机表达。
//
// 与 stage1 的差异:owner_ast 改为不透明 `*any`(借用),使本表不依赖具体 AST
// 表示,便于将来 comptime/序列化复用;sema 侧自行 cast 回 *Ast。
// 名称是 ByteView(借用源/AST),本表不做拥有。
// 声明句柄表。DefId 是声明的稳定身份:作用域符号、节点 resolved_def_id、comptime
// 生成的声明都用它;前向/环形引用由 state 状态机表达。owner_ast 为不透明 *any。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
@@ -84,7 +79,7 @@ fn drop(self: *DefTable) {
Vec.drop(&self.table);
}
// id 0 与越界均返回 null(对应 stage1 spl_def_node)。
// id 0 与越界均返回 null。
fn node(self: *DefTable, id: usize): *DefNode {
if id == 0 || id >= self.table.len { ret null; }
ret (self.table.data as *DefNode) + id;
@@ -129,7 +124,6 @@ fn get_lang_id(self: *DefTable, id: usize): usize {
ret d.lang_id;
}
// ---- 分类 ----
fn kind_name(kind: DefKind): []u8 {
match kind {
@@ -156,7 +150,7 @@ fn state_name(state: DeclState): []u8 {
ret "unknown";
}
// 能作为类型使用的 def(对应 stage1 sema_def_is_type)。
// 能作为类型使用的 def。
fn is_type_kind(kind: DefKind): bool {
match kind {
.Scalar => { ret true; },
@@ -169,7 +163,6 @@ fn is_type_kind(kind: DefKind): bool {
ret false;
}
// ---- dump(镜像 stage1 spl_type_def_dump 的文本)----
fn push_out(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
@@ -203,7 +196,6 @@ fn dump(self: *DefTable, id: usize, out: *ByteBuffer): bool {
ret push_out(out, ByteView.as_slice(d.name));
}
// ---- 测试 ----
fn test_alloc_and_state() {
var dt: DefTable = undefined;
+2 -15
View File
@@ -1,14 +1,7 @@
// Expect retcode = 0
// 丰富诊断(参考 rustc / Clang / Swift 的设计,不照搬 stage1 C 实现):
// Severity Note/Help/Warning/Error/Fatal
// Code 固定语义枚举 + 稳定 E 码;集中管理,利于 diff
// Span 字节区间 {file,start,end};file 是 Sources 的下标,NO_FILE 表示无位置
// Label 主/次标签(span + 文本),可多个
// Child 子诊断(note/help,可带 span),挂在条目上
// 渲染:人类可读(源码行 + caret 下划线)与 JSON(字段稳定)双格式。
// 位置只存下标,渲染时经 Sources 解析行列/取行,避免复制文件名。
// 消息按拥有型 Str 保存;条目拥有其 labels/children;clear/drop 释放全部内部资源。
// 丰富诊断:Severity / 稳定 E 码 / Span / Label / Child,渲染为人类可读或 JSON。
// 位置只存下标,渲染时经 Sources 解析行列;条目拥有其字符串与 labels/children。
type .{ .Error, .Status, .make } = @import("./utils/error.spl");
type .{ .Vec } = @import("./utils/vec.spl");
@@ -181,7 +174,6 @@ fn has_error(self: Diag): bool { ret self.errors > 0; }
fn has_fatal(self: Diag): bool { ret self.fatals > 0; }
// ---- 采集 ----
// 追加一条诊断,返回其下标(失败返回 no_file())。span 为主位置。
fn emit(self: *Diag, severity: Severity, stage: Stage, code: Code, span: Span,
@@ -265,7 +257,6 @@ fn attach_child(self: *Diag, severity: Severity, span: Span, msg: []u8): Status
ret .Ok;
}
// ---- 名称 ----
fn severity_name(severity: Severity): []u8 {
match severity {
@@ -370,7 +361,6 @@ fn code_name(code: Code): []u8 {
ret "none";
}
// ---- 渲染:公共小工具 ----
fn append_num(out: *ByteBuffer, value: usize): Status {
ret append_usize(out, value, 10, false);
@@ -519,7 +509,6 @@ fn render_human(self: *Diag, out: *ByteBuffer): Status {
ret .Ok;
}
// ---- JSON 渲染(字段稳定,供 LSP / diff 工具)----
fn append_json_hex4(out: *ByteBuffer, b: u8): Status {
var hex: []u8 = "0123456789abcdef";
@@ -661,7 +650,6 @@ fn render_json(self: *Diag, out: *ByteBuffer): Status {
ret ByteBuffer.append_byte(out, ']');
}
// ---- 生命周期 ----
fn drop_item(it: *Item) {
Str.drop(&it.message);
@@ -700,7 +688,6 @@ fn drop(self: *Diag) {
self.sources = null;
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
+9 -18
View File
@@ -1,22 +1,16 @@
// Expect retcode = 0
// comptime / const 求值的**接口 seam**(本轮只占位,不实现求值)。
//
// 目标:把「编译期求值」从 sema 主体里隔离出来,将来接一个解释器(可直接复用
// VM 或 AST 求值器)时不动 sema 结构。sema 只在 comptime 语句 / const 初始化 /
// @import 等点调用这里;未实现时统一返回 NotConst(= 放弃折叠,不报错)。
//
// 分块编译相关:eval 未来的产物是「编译期生成的声明」,统一经 DeclSink 登记,
// 由驱动在固定点循环里插入并触发重跑;eval 自己不直接改 sema 表,避免重入。
// comptime/const 求值的接口 seam:sema 只在此调用,未实现时返回 NotConst(放弃折叠、
// 不报错)。编译期生成的声明经 DeclSink 登记,不改 sema 表。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
type Ast = @import("./ast.spl");
type Diag = @import("./diag.spl");
// 编译期值:占位。未来扩展为 BigInt / 聚合 / 类型句柄等。
// 编译期值(当前仅标量)。
type EvalValue = enum {
Int: usize, // TODO: BigInt
Int: usize,
Bool: bool,
}
@@ -36,14 +30,13 @@ type DeclSinkResult = enum {
Err: Error,
}
// 求值上下文(借用 sink 与 diag;本轮不持有所有权)。
// 求值上下文:sink/diag 均借用,不持有所有权。
type Eval = @self;
sink: *DeclSink, // 借用,可为 null
diag: *Diag, // 借用,可为 null
enabled: bool, // false = 完全不求值(等价旧行为)
enabled: bool, // false = 完全不求值
// ---- DeclSink ----
fn sink_new(): DeclSinkResult {
var s = DeclSink { .items = Vec.blank(@sizeof(usize), @alignof(usize)) };
@@ -66,7 +59,6 @@ fn sink_len(self: *DeclSink): usize {
ret self.items.len;
}
// ---- Eval ----
fn new(sink: *DeclSink, diag: *Diag, enabled: bool): Eval {
ret Eval {
@@ -80,25 +72,24 @@ fn is_enabled(self: *Eval): bool {
ret self.enabled;
}
// 求值一个表达式。本轮一律 NotConst(可由调用方作为「放弃折叠」处理)。
// 求值表达式:当前一律 NotConst(调用方按“放弃折叠”处理)。
fn eval_expr(self: *Eval, ast: *Ast, ref: usize): EvalOutcome {
if !self.enabled { ret .NotConst; }
ret .NotConst;
}
// 执行一个 comptime 块(可能产生声明,登记到 sink)。本轮不做。
// 执行 comptime 块;当前不实现,直接 NotConst。
fn run_block(self: *Eval, ast: *Ast, ref: usize): EvalOutcome {
if !self.enabled { ret .NotConst; }
ret .NotConst;
}
// 顶层 const 初始化求值。本轮不做。
// 顶层 const 初始化求值;当前不实现。
fn eval_const_init(self: *Eval, ast: *Ast, ref: usize): EvalOutcome {
if !self.enabled { ret .NotConst; }
ret .NotConst;
}
// ---- 测试 ----
fn test_sink() {
var sink: DeclSink = undefined;
+3 -5
View File
@@ -1,8 +1,7 @@
// Expect retcode = 0
// 内建(intrinsic)注册表(移植自 stage1/spl_intrin.c)。表是数据:按 kind 查
// 描述信息,按名字/字段/`as` 转换规则反查 kind。新增内建只改 info_at,
// 不改 sema 逻辑(对应 SPL.md 的 @/# 扩展点)。
// 内建注册表:按 Intrin 查描述信息,按名字/字段/`as` 规则反查 Intrin。新增内建只改
// info_at,不改 sema 逻辑(SPL.md 的 @/# 扩展点)。
type .{ .ByteView } = @import("utils/byte_view.spl");
type TypeTable = @import("./type_table.spl");
@@ -63,7 +62,7 @@ fn kind_is(a: LangKind, b: LangKind): bool {
ret @enum2int(a) == @enum2int(b);
}
// 与 stage1 表逐项对应(枚举顺序即 kind 数值)。
// 枚举顺序即 kind 数值(与 splc0 表一致)。
fn info_at(index: usize): IntrinInfo {
match index {
1 => {
@@ -250,7 +249,6 @@ fn lookup_cast(ir: *TypeTable, ft: usize, tt: usize): Intrin {
ret .None;
}
// ---- 测试 ----
fn test_info_table() {
var d = info(.Sizeof);
+9 -16
View File
@@ -1,10 +1,7 @@
// Expect retcode = 0
// SIR 中间表示(移植自 stage1/spl_ir.c/.h)。节点用 arena 序号引用(0 = error),
// 按函数分桶。节点公共字段(kind/dbg/attrs)在外层 entry,kind 专属载荷在 ADT
// IrBody;kind 与载荷变体一一对应(多种 kind 可共享同一载荷形状)。
//
// builder 维护当前函数/基本块/fixup 表,负责发射节点与回填跳转。
// SIR 中间表示:节点用 arena 序号引用(0=error),按函数分桶;公共字段在 IrEntry,
// kind 专属载荷在 IrBody ADT(kind 与载荷一一对应)。builder 负责发射与跳转回填。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
@@ -138,7 +135,6 @@ type Ir = @self;
funcs: Vec, // IrFunc
globals: Vec, // Global
// ---- 生命周期 ----
fn new_entry(): IrEntry {
ret IrEntry {
@@ -159,8 +155,8 @@ fn new(): Ir {
.nodes = Vec.blank(@sizeof(IrEntry), @alignof(IrEntry)),
};
var sn = new_entry();
match Vec.push(&sentinel.nodes, &sn as *u8) { .Ok => {}, .Err(error) => {} }
match Vec.push(&ir.funcs, &sentinel as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&sentinel.nodes, &sn as *u8);
Vec.push(&ir.funcs, &sentinel as *u8);
ret ir;
}
@@ -307,7 +303,6 @@ fn kind_name(kind: IrKind): []u8 {
ret "?";
}
// ---- dump ----
fn out_str(out: *ByteBuffer, s: []u8): bool {
match ByteBuffer.append(out, s) { .Ok => { ret true; }, .Err(error) => { ret false; } }
@@ -360,11 +355,10 @@ fn dump_body(out: *ByteBuffer, ty: *TypeTable, e: *IrEntry): bool {
.Arith(a) => {
if !dump_type(out, ty, a.tid) { ret false; }
if !dump_ref(out, a.left) { ret false; }
// 一元 arith(neg/abs/not)不打印 right(镜像 stage1)。
if @enum2int(e.kind) == @enum2int(IrKind.ArithNeg) ||
@enum2int(e.kind) == @enum2int(IrKind.ArithAbs) ||
@enum2int(e.kind) == @enum2int(IrKind.ArithNot) {
ret true;
// 一元 arith(neg/abs/not)不打印 right。
match e.kind {
.ArithNeg, .ArithAbs, .ArithNot => { ret true; },
_ => {},
}
ret dump_ref(out, a.right);
},
@@ -465,7 +459,7 @@ fn dump_body(out: *ByteBuffer, ty: *TypeTable, e: *IrEntry): bool {
match ByteBuffer.append_byte(out, cv as u8) { .Ok => {}, .Err(error) => { ret false; } }
ret out_str(out, "'");
}
// stage1 对其他常量统一按 int_lit 打印(union 别名)。
// 其他常量统一按 int_lit 打印(union 别名)。
var iv: usize = 0;
match c.lit {
.Int(v) => { iv = v; },
@@ -582,7 +576,6 @@ fn dump(self: *Ir, ty: *TypeTable, attr: *Attr, out: *ByteBuffer): bool {
ret true;
}
// ---- 测试 ----
fn test_kinds() {
@assert(ByteView.eq(ByteView.from_slice(kind_name(.ArithAdd)), ByteView.from_slice("arith.add")),
+2 -42
View File
@@ -1,12 +1,7 @@
// Expect retcode = 0
// IR -> C99 后端(P1a 子集)。
//
// 设计:每个 IR ref 一个 C 局部变量(C 编译器 -O2 会做 mem2reg),标签用 goto;
// 类型直接由 IR 的 tid 决定,生成期无运行时分发。
//
// 每个非 extern 函数的 C 名为 `spl_f<fid>`;extern 函数直接用其 SPL 名
// (由 runtime 提供)。暂不支持聚合/切片/全局数据。
// IR -> C99。每个 IR ref 生成一个 C 局部变量(交给 C 编译器 mem2reg),标签用 goto;
// 类型由 IR tid 决定,生成期无运行时分发。非 extern 函数名为 `spl_f<fid>`。
type .{ .Vec } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
@@ -83,7 +78,6 @@ fn put_unsupported(self: *Ir2C, what: []u8) {
put(self, " */\n");
}
// ---- 类型查询 ----
fn info_of(self: *Ir2C, tid: usize): *LayoutM.LayoutInfo {
ret LayoutM.info_of(self.layout, tid);
@@ -168,7 +162,6 @@ fn fn_ret_type(self: *Ir2C, fn_tid: usize): usize {
ret 0;
}
// ---- C 类型 ----
fn put_type(self: *Ir2C, tid: usize): bool {
var te = TypeTable.node(self.ty, tid);
@@ -231,7 +224,6 @@ fn c_fn_name(self: *Ir2C, fid: usize) {
put_u(self, fid);
}
// ---- 常量解析 ----
fn const_node(self: *Ir2C, f: *IrFunc, ref: usize): usize {
if ref == 0 || ref >= f.nodes.len { ret 0; }
@@ -250,7 +242,6 @@ fn const_node(self: *Ir2C, f: *IrFunc, ref: usize): usize {
ret 0;
}
// ---- 聚合字段 ----
fn field_tid(self: *Ir2C, tid: usize, idx: usize): usize {
var te = TypeTable.node(self.ty, tid);
@@ -436,7 +427,6 @@ fn emit_agg_insert(self: *Ir2C, ref: usize, n: *IrEntry) {
}
}
// ---- 节点发射 ----
fn emit_arith(self: *Ir2C, ref: usize, n: *IrEntry) {
match n.body {
@@ -1224,7 +1214,6 @@ fn emit_def(self: *Ir2C, fid: usize) {
put(self, "spl_trap();\n}\n");
}
// ---- driver ----
fn find_main(self: *Ir2C): usize {
var i: usize = 1;
@@ -1283,7 +1272,6 @@ fn run(self: *Ir2C) {
}
i = i + 1;
}
emit_ct_table(self);
var m = find_main(self);
if m != 0 {
var f = IrM.func(self.ir, m);
@@ -1311,34 +1299,6 @@ fn run(self: *Ir2C) {
}
}
// compiler function(`ct_` 前缀)回调表:供 native 端 vm_set_foreign 按名分发。
fn emit_ct_table(self: *Ir2C) {
put(self, "static const struct { const char *name; void *fn; } spl_ct_tab[] = {\n");
var n: usize = 0;
var i: usize = 1;
while i < self.ir.funcs.len {
var f = IrM.func(self.ir, i);
if f != null && !fn_is_extern(self, f) &&
ByteView.starts_with(f.name, ByteView.from_slice("ct_")) {
put(self, " {\"");
put_bv(self, f.name);
put(self, "\", (void*)f");
put_u(self, i);
put(self, "},\n");
n = n + 1;
}
i = i + 1;
}
if n == 0 { put(self, " {0, 0},\n"); }
put(self, "};\n");
put(self, "void *spl_ct_lookup(const char *name) {\n");
put(self, " unsigned long i;\n");
put(self, " for (i = 0; i < sizeof(spl_ct_tab)/sizeof(spl_ct_tab[0]); i++)\n");
put(self, " if (spl_ct_tab[i].name && strcmp(spl_ct_tab[i].name, name) == 0) return spl_ct_tab[i].fn;\n");
put(self, " return 0;\n");
put(self, "}\n");
}
fn new(ir: *Ir, ty: *TypeTable, layout: *Layout, attr: *Attr, out: *ByteBuffer): Ir2C {
ret Ir2C {
.ir = ir,
+35 -56
View File
@@ -1,11 +1,7 @@
// Expect retcode = 0
// IR -> VM 机器码(移植自 stage1/spl_ir2vm.c)。
// 依赖:IR(ir.spl)、IR 类型表(type_table.spl)、布局(layout.spl)、
// 属性(attr.spl)、字节码容器(mcode.spl)。
//
// extern_native 用「按函数 ref 下标的 isize 数组」代替 stage1 的 map:
// 默认 -1 表示非 extern,>=0 表示 native 索引(语义等价)。
// IR -> VM 字节码。extern_native 是按函数 ref 下标的 isize 数组:-1 非 extern,
// >=0 为 native 索引。
type .{ .Vec } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
@@ -19,7 +15,7 @@ type IrM = @import("./ir.spl");
type .{ .Ir, .IrFunc, .IrEntry, .Global } = @import("./ir.spl");
type Mcode = @import("./mcode.spl");
type .{ .Prog, .Op, .VmKind, .VmIns, .VmFunc } = @import("./mcode.spl");
type Mem = @import("sys/mem.spl");
type Mem = @import("utils/memory.spl");
type Ir2Vm = @self;
@@ -31,7 +27,6 @@ extern_native: Vec, // isize
global_gaddr: Vec, // usize:每个全局变量在 prog.gdata 的下标
prog: Prog,
// ---- 类型/布局查询 ----
fn info_of(ctx: *Ir2Vm, tid: usize): *LayoutM.LayoutInfo {
ret LayoutM.info_of(ctx.layout, tid);
@@ -187,7 +182,6 @@ fn ir_result_tid(ctx: *Ir2Vm, n: *IrEntry): usize {
ret 0;
}
// ---- 小工具 ----
// 内部热路径:假定索引有效,直接取址(省去 Vec.get/valid)。
fn usize_at(v: *Vec, i: usize): usize {
@@ -195,7 +189,7 @@ fn usize_at(v: *Vec, i: usize): usize {
}
fn push_usize(v: *Vec, x: usize) {
ignore_bool(Vec.push_raw(v, &x as *u8));
Vec.push_raw(v, &x as *u8);
}
fn fnode(f: *IrFunc, i: usize): *IrEntry {
@@ -239,7 +233,6 @@ fn const_fn(n: *IrEntry): usize {
ret 0;
}
// ---- extern ----
fn fn_check_extern(ctx: *Ir2Vm, f: *IrFunc): bool {
if ctx.attr == null || f == null { ret false; }
@@ -275,7 +268,6 @@ fn extern_set(ctx: *Ir2Vm, ref: usize, value: isize) {
}
}
// ---- 帧布局 ----
type Slot = struct {
result_off: usize,
@@ -363,7 +355,7 @@ fn frame_build(fl: *FrameLayout, ctx: *Ir2Vm, fid: usize) {
var i: usize = 0;
while i < n {
var blank: Slot = .{ .result_off = 0, .data_off = 0 };
ignore_bool(Vec.push_raw(&fl.slots, &blank as *u8));
Vec.push_raw(&fl.slots, &blank as *u8);
i = i + 1;
}
@@ -397,7 +389,6 @@ fn frame_drop(fl: *FrameLayout) {
Vec.drop(&fl.slots);
}
// ---- cgen ----
type FixKind = enum {
Jmp,
@@ -432,7 +423,7 @@ fn emit(cg: *Cgen, op: Op, ty: VmKind, imm: usize) {
prog.insns.len = i + 1;
ret;
}
ignore_usize(Mcode.add_instr(prog, op, ty, imm));
Mcode.add_instr(prog, op, ty, imm);
}
fn ip_of(cg: *Cgen): usize {
@@ -456,20 +447,20 @@ fn cg_swap(cg: *Cgen) { emit(cg, .Swap, .Void, 0); }
fn cg_gaddr(cg: *Cgen, idx: usize) { emit(cg, .Gaddr, .Void, idx); }
fn cg_load_slot(cg: *Cgen, ref: usize, k: VmKind) {
cg_laddr(cg, slot_result(&cg.frame, ref));
cg_load(cg, k);
emit(cg, .Laddr, .Void, slot_result(&cg.frame, ref));
emit(cg, .Load, k, 0);
}
fn cg_store_slot(cg: *Cgen, ref: usize, k: VmKind) {
cg_laddr(cg, slot_result(&cg.frame, ref));
cg_swap(cg);
cg_store(cg, k);
emit(cg, .Laddr, .Void, slot_result(&cg.frame, ref));
emit(cg, .Swap, .Void, 0);
emit(cg, .Store, k, 0);
}
fn cg_store_at(cg: *Cgen, addr: usize, k: VmKind) {
cg_laddr(cg, addr);
cg_swap(cg);
cg_store(cg, k);
emit(cg, .Laddr, .Void, addr);
emit(cg, .Swap, .Void, 0);
emit(cg, .Store, k, 0);
}
type DataLoc = struct {
@@ -534,7 +525,7 @@ fn cg_add_fix(cg: *Cgen, ins_idx: usize, kind: FixKind, node_target: usize, fn_t
.node_target = node_target,
.fn_target = fn_target,
};
match Vec.push(cg.fixups, &fx as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(cg.fixups, &fx as *u8);
}
fn arith_tid(n: *IrEntry): usize {
@@ -638,6 +629,7 @@ fn cg_const(cg: *Cgen, ref: usize, n: *IrEntry) {
}
},
.Int(x) => { imm = const_usize(n); },
.Any => { imm = const_usize(n); },
.Float => {
var fv: f64 = 0.0;
match n.body {
@@ -695,7 +687,7 @@ fn cg_cast(cg: *Cgen, ref: usize, n: *IrEntry) {
} else if f_bool && t_int {
emit(cg, .Zext, .Void, 1);
}
ignore_bool(t_bool);
t_bool;
cg_store_slot(cg, ref, tk);
},
_ => {},
@@ -915,10 +907,7 @@ fn cg_control(cg: *Cgen, ref: usize, n: *IrEntry) {
cg_load(cg, .Ptr);
cg_load_slot(cg, r.val, .Ptr);
cg_push(cg, .U64, sz);
var nat = Mcode.get_or_add_native(&ctx.prog, ByteView.from_slice("vm_memcpy"));
cg_push(cg, .U64, nat as usize);
emit(cg, .Ncall, .Void, 3);
emit(cg, .Drop, .Void, 0);
emit(cg, .Memcpy, .Void, 0);
}
emit(cg, .Ret, .Void, 0);
} else {
@@ -1150,7 +1139,6 @@ fn cmp_tid(n: *IrEntry): usize {
ret 0;
}
// ---- 翻译 ----
fn translate_function(ctx: *Ir2Vm, fid: usize, all_fixups: *Vec): usize {
var irf = IrM.func(ctx.ir, fid);
@@ -1174,7 +1162,7 @@ fn translate_function(ctx: *Ir2Vm, fid: usize, all_fixups: *Vec): usize {
var func_ip = ip_of(&cg);
ignore_usize(Mcode.add_func(&ctx.prog, irf.name, fn_nargs(ctx, irf.fn_tid), func_ip));
Mcode.add_func(&ctx.prog, irf.name, fn_nargs(ctx, irf.fn_tid), func_ip);
var local_slots = (cg.frame.frame_bytes - cg.frame.args_bytes + 7) / 8;
emit(&cg, .Alloc, .Void, local_slots);
@@ -1195,23 +1183,19 @@ fn translate_function(ctx: *Ir2Vm, fid: usize, all_fixups: *Vec): usize {
i = 0;
while i < local_fixups.len {
match Vec.get(&local_fixups, i) {
.Ok(ptr) => {
var fx = ptr as *Fix;
if @enum2int(fx.kind) == @enum2int(FixKind.Jmp) {
var ins = ins_ptr(&ctx.prog, fx.ins_idx);
if ins != null {
var target_ip: usize = 0;
if fx.node_target < nnodes {
target_ip = usize_at(&cg.node_ip, fx.node_target);
}
ins.imm = target_ip - fx.ins_idx - 1;
var fx = (local_fixups.data as *Fix) + i;
match fx.kind {
.Jmp => {
var ins = ins_ptr(&ctx.prog, fx.ins_idx);
if ins != null {
var target_ip: usize = 0;
if fx.node_target < nnodes {
target_ip = usize_at(&cg.node_ip, fx.node_target);
}
} else if @enum2int(fx.kind) == @enum2int(FixKind.Fnaddr) {
match Vec.push(all_fixups, ptr as *u8) { .Ok => {}, .Err(error) => {} }
ins.imm = target_ip - fx.ins_idx - 1;
}
},
.Err(error) => {},
.Fnaddr => { Vec.push(all_fixups, fx as *u8); },
}
i = i + 1;
}
@@ -1222,9 +1206,8 @@ fn translate_function(ctx: *Ir2Vm, fid: usize, all_fixups: *Vec): usize {
ret func_ip;
}
// ---- 生命周期 / 入口 ----
// 就地初始化(避免返回含 Prog 的大聚合;对应 stage1 spl_ir2vm_init)。
// 就地初始化,避免返回含 Prog 的大聚合。
fn init(ctx: *Ir2Vm, ir: *Ir, ty: *TypeTable, layout: *Layout, attr: *Attr) {
ctx.ir = ir;
ctx.ty = ty;
@@ -1248,7 +1231,7 @@ fn drop(ctx: *Ir2Vm) {
fn run_func(ctx: *Ir2Vm, ref: usize): i32 {
var all_fixups = Vec.blank(@sizeof(Fix), @alignof(Fix));
defer { Vec.drop(&all_fixups); }
ignore_usize(translate_function(ctx, ref, &all_fixups));
translate_function(ctx, ref, &all_fixups);
ret 0;
}
@@ -1260,7 +1243,7 @@ fn run(ctx: *Ir2Vm): i32 {
var i: usize = 0;
while i < n {
var v: isize = -1;
match Vec.push(&ctx.extern_native, &v as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&ctx.extern_native, &v as *u8);
i = i + 1;
}
i = 1;
@@ -1285,12 +1268,12 @@ fn run(ctx: *Ir2Vm): i32 {
didx = Mcode.add_data(&ctx.prog, g.data.data as usize, gsize);
}
var dv = didx;
match Vec.push(&ctx.global_gaddr, &dv as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&ctx.global_gaddr, &dv as *u8);
gi = gi + 1;
}
// 哨兵:保证真实函数入口地址非零。
ignore_usize(Mcode.add_instr(&ctx.prog, .Halt, .Void, 0));
Mcode.add_instr(&ctx.prog, .Halt, .Void, 0);
// 预分配指令容量(按 IR 节点数粗略估计),减少逐条 append 的扩容/拷贝。
var est: usize = 16;
@@ -1300,7 +1283,7 @@ fn run(ctx: *Ir2Vm): i32 {
if irf != null { est = est + irf.nodes.len * 8 + 32; }
i = i + 1;
}
match Vec.reserve(&ctx.prog.insns, est) { .Ok => {}, .Err(error) => {} }
Vec.reserve(&ctx.prog.insns, est);
// Pass 2:翻译非 extern 函数。
var fid_ip = Vec.blank(@sizeof(usize), @alignof(usize));
@@ -1384,12 +1367,8 @@ fn store(ctx: *Ir2Vm, path: ByteView): bool {
ret false;
}
// ---- 工具 ----
fn ignore_usize(v: usize) {}
fn ignore_bool(b: bool) {}
// ---- 测试 ----
fn main() {
var ir = IrM.new();
+22 -50
View File
@@ -1,7 +1,6 @@
// Expect retcode = 0
// SIR builder (IrBuilder). Split from ir.spl: stage1 ast2ir
// infinitely recurses on same-file @self nesting; cross-file is fine.
// IR 构建器:单独成文件,以免 ast2ir 在同文件 @self 嵌套时无限递归。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
@@ -18,8 +17,6 @@ fn list_at(v: Vec, i: usize): usize {
ret ((v.data as *usize) + i).*;
}
// ---- builder ----
type FixKind = enum { BrTrue, BrFalse, Jmp }
type Fix = struct {
@@ -46,13 +43,9 @@ fn builder_alloc(self: *IrBuilder, kind: IrKind): usize {
e.kind = kind;
e.dbg = self.dbg;
}
if self.current_block >= self.blocks.len { ret ref; }
match Vec.get(&self.blocks, self.current_block) {
.Ok(p) => {
var slot = p as *usize;
if slot.* == 0 { slot.* = ref; }
},
.Err(error) => {},
if self.current_block < self.blocks.len {
var slot = (self.blocks.data as *usize) + self.current_block;
if slot.* == 0 { slot.* = ref; }
}
ret ref;
}
@@ -113,25 +106,18 @@ fn fn_begin_at(self: *IrBuilder, fid: usize) {
fn fn_end(self: *IrBuilder) {
var k: usize = 0;
while k < self.fixups.len {
match Vec.get(&self.fixups, k) {
.Ok(fp) => {
var fx = fp as *Fix;
var e = Ir.node(&self.ir, self.current_fn, fx.node);
if e != null {
var target: usize = 0;
if fx.block < self.blocks.len { target = list_at(self.blocks, fx.block); }
if target != 0 {
if @enum2int(fx.slot) == @enum2int(FixKind.BrTrue) {
match e.body { .Br(b) => { b.true_label = target; e.body = .Br(b); }, _ => {} }
} else if @enum2int(fx.slot) == @enum2int(FixKind.BrFalse) {
match e.body { .Br(b) => { b.false_label = target; e.body = .Br(b); }, _ => {} }
} else {
match e.body { .Jmp(j) => { j.label = target; e.body = .Jmp(j); }, _ => {} }
}
}
var fx = (self.fixups.data as *Fix) + k;
var e = Ir.node(&self.ir, self.current_fn, fx.node);
if e != null {
var target: usize = 0;
if fx.block < self.blocks.len { target = list_at(self.blocks, fx.block); }
if target != 0 {
match fx.slot {
.BrTrue => { match e.body { .Br(&b) => { b.true_label = target; }, _ => {} } },
.BrFalse => { match e.body { .Br(&b) => { b.false_label = target; }, _ => {} } },
.Jmp => { match e.body { .Jmp(&j) => { j.label = target; }, _ => {} } },
}
},
.Err(error) => {},
}
}
k = k + 1;
}
@@ -143,7 +129,7 @@ fn fn_end(self: *IrBuilder) {
fn block_begin(self: *IrBuilder): usize {
var zero: usize = 0;
match Vec.push(&self.blocks, &zero as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&self.blocks, &zero as *u8);
var block = self.blocks.len - 1;
self.current_block = block;
self.terminated = false;
@@ -151,10 +137,9 @@ fn block_begin(self: *IrBuilder): usize {
}
fn block_end(self: *IrBuilder) {
// terminated 与空块校验在 stage1 为 Panic;这里保持同样约束但不终止进程。
// 空实现:本实现不做 terminated/空块校验(不终止进程)。
}
// ---- arith / cmp / cast ----
fn set_arith(self: *IrBuilder, kind: IrKind, tid: usize, left: usize, right: usize): usize {
var ref = builder_alloc(self, kind);
@@ -211,7 +196,6 @@ fn cast_bool2int(self: *IrBuilder, f: usize, t: usize, v: usize): usize { ret se
fn case_int2float(self: *IrBuilder, f: usize, t: usize, v: usize): usize { ret set_cast(self, .CaseInt2float, f, t, v); }
fn case_float2int(self: *IrBuilder, f: usize, t: usize, v: usize): usize { ret set_cast(self, .CaseFloat2int, f, t, v); }
// ---- memory ----
fn mem_alloca(self: *IrBuilder, tid: usize, count: usize): usize {
var ref = builder_alloc(self, .MemAlloca);
@@ -269,7 +253,6 @@ fn mem_set(self: *IrBuilder, tid: usize, dst: usize, val: usize, size: usize): u
ret ref;
}
// ---- type const ----
fn const_node(self: *IrBuilder, tid: usize, lit: ConstLit): usize {
var ref = builder_alloc(self, .TypeConst);
@@ -292,7 +275,6 @@ fn add_global(self: *IrBuilder, tid: usize, zero: bool, bytes: Vec): usize {
ret Ir.add_global(&self.ir, tid, zero, bytes);
}
// ---- type ops ----
fn type_bitsizeof(self: *IrBuilder, tid: usize): usize {
var ref = builder_alloc(self, .TypeBitsizeof);
@@ -329,7 +311,6 @@ fn type_field_count(self: *IrBuilder, tid: usize): usize {
ret ref;
}
// ---- agg ----
fn agg_construct(self: *IrBuilder, tid: usize): usize {
var ref = builder_alloc(self, .AggConstruct);
@@ -343,12 +324,8 @@ fn agg_construct(self: *IrBuilder, tid: usize): usize {
fn agg_construct_field(self: *IrBuilder, node_ref: usize, field: usize) {
var e = Ir.node(&self.ir, self.current_fn, node_ref);
if e == null { ret; }
// 载荷按值绑定:改副本后写回。
match e.body {
.AggConstruct(a) => {
match Vec.push(&a.fields, &field as *u8) { .Ok => {}, .Err(error) => {} }
e.body = .AggConstruct(a);
},
.AggConstruct(&a) => { Vec.push(&a.fields, &field as *u8); },
_ => {},
}
}
@@ -369,7 +346,6 @@ fn agg_insert(self: *IrBuilder, tid: usize, field_idx: usize, agg: usize, field:
ret ref;
}
// ---- control ----
fn control_select(self: *IrBuilder, tid: usize, cond: usize, tv: usize, fv: usize): usize {
var ref = builder_alloc(self, .ControlSelect);
@@ -388,9 +364,9 @@ fn control_br(self: *IrBuilder, cond: usize): usize {
fn control_br_fixup(self: *IrBuilder, ref: usize, true_block: usize, false_block: usize) {
var f1 = Fix { .node = ref, .slot = .BrTrue, .block = true_block };
match Vec.push(&self.fixups, &f1 as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&self.fixups, &f1 as *u8);
var f2 = Fix { .node = ref, .slot = .BrFalse, .block = false_block };
match Vec.push(&self.fixups, &f2 as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&self.fixups, &f2 as *u8);
}
fn control_jmp(self: *IrBuilder): usize {
@@ -403,7 +379,7 @@ fn control_jmp(self: *IrBuilder): usize {
fn control_jmp_fixup(self: *IrBuilder, ref: usize, target_block: usize) {
var fx = Fix { .node = ref, .slot = .Jmp, .block = target_block };
match Vec.push(&self.fixups, &fx as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&self.fixups, &fx as *u8);
}
fn control_call(self: *IrBuilder, tid: usize, fn_ref: usize): usize {
@@ -419,12 +395,8 @@ fn control_call(self: *IrBuilder, tid: usize, fn_ref: usize): usize {
fn control_call_param(self: *IrBuilder, call_node: usize, arg: usize) {
var e = Ir.node(&self.ir, self.current_fn, call_node);
if e == null { ret; }
// 载荷按值绑定:改副本后写回。
match e.body {
.Call(c) => {
match Vec.push(&c.params, &arg as *u8) { .Ok => {}, .Err(error) => {} }
e.body = .Call(c);
},
.Call(&c) => { Vec.push(&c.params, &arg as *u8); },
_ => {},
}
}
+11 -37
View File
@@ -1,11 +1,7 @@
// Expect retcode = 0
// 语言类型表(移植自 stage1/spl_lang_type.c):在 IR 类型表(type_table.spl)
// 之上,登记「语言层类型」= IR 类型 id + 语言种类 + 聚合方法表,同样 hash-consing。
// 另持有声明句柄表(def.spl)与语言类型子类型/求交/字面量适配。
//
// 语言类型是 sema 的主类型:AST 节点 resolved_lang_tid、def.lang_id 都指这里。
// 名称/方法名是 ByteView(借用);聚合方法表与 tuple/fn 的载荷 Vec 由本表拥有。
// 语言类型表:在 IR 类型表之上登记「语言层类型」(IR 类型 id + 种类 + 聚合成员),
// 按结构 hash-consing。sema 的 resolved_lang_tid / def.lang_id 都指向这里。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
@@ -77,7 +73,6 @@ type LangTypeResult = enum {
Err: Error,
}
// ---- 小工具 ----
fn seed(): usize {
ret 14695981039346656037;
@@ -142,7 +137,6 @@ fn elem_of(entry: LangEntry): usize {
ret 0;
}
// ---- 生命周期 ----
fn new_entry(kind: LangKind, ir_type_id: usize): LangEntry {
ret LangEntry {
@@ -215,7 +209,7 @@ fn drop(self: *LangType) {
TypeTable.drop(&self.ir);
}
// id 0 与越界返回 null(对应 stage1 spl_lang_type_node)。
// id 0 与越界返回 null。
fn lang_node(self: *LangType, id: usize): *LangEntry {
if id == 0 || id >= self.lang_table.len { ret null; }
ret (self.lang_table.data as *LangEntry) + id;
@@ -231,7 +225,6 @@ fn get_ir_type(self: *LangType, lang_id: usize): usize {
ret ir_type(self, lang_id);
}
// ---- IR 类型槽位预留(自引用聚合)----
fn reserve_ir(self: *LangType): usize {
ret TypeTable.reserve(&self.ir);
@@ -241,7 +234,6 @@ fn define_ir(self: *LangType, id: usize, src: *TypeNode) {
TypeTable.define(&self.ir, id, src);
}
// ---- def 便捷封装(sema 侧只用 LangType)----
fn alloc_def(self: *LangType, kind: DefKind, name: ByteView, span: Span, owner: *any,
ast_node_ref: usize): usize {
@@ -266,7 +258,6 @@ fn def_is_type(self: *LangType, id: usize): bool {
ret DefTable.is_type_kind(d.kind);
}
// ---- intern ----
fn free_extra(e: *LangEntry) {
match e.extra {
@@ -423,10 +414,7 @@ fn fold_insert(self: *LangType, hash: usize, id: usize) {
var e = lang_node(self, id);
if e == null { ret; }
e.hash_next = old;
match Map.put(&self.fold, &hash as *u8, &id as *u8) {
.Ok => {},
.Err(error) => {},
}
Map.put(&self.fold, &hash as *u8, &id as *u8);
}
// intern 一个 probe:命中释放载荷并返回已有 id;否则复制入表。probe 返回后失效。
@@ -460,7 +448,6 @@ fn push_simple(self: *LangType, kind: LangKind, ir: usize): usize {
ret push(self, &e);
}
// ---- builders ----
fn make_error(self: *LangType): usize {
ret push_simple(self, .Error, TypeTable.make_error(&self.ir));
@@ -560,13 +547,10 @@ fn make_range(self: *LangType, elem_lang: usize): usize {
ret push(self, &e);
}
// 为 tuple 字段生成稳定的十进制名字("0"/"1"/...),镜像 stage1。
// tuple 字段用稳定的十进制名("0"/"1"/...)。
fn intern_index_name(self: *LangType, value: usize): ByteView {
var b = ByteBuffer.new();
match append_usize(&b, value, 10, false) {
.Ok => {},
.Err(error) => {},
}
append_usize(&b, value, 10, false);
var view = ByteView.from_slice(ByteBuffer.as_slice(b));
match Vec.push(&self.owned_names, &b as *u8) {
.Ok => {},
@@ -646,7 +630,7 @@ fn parse_bits(rest: []u8): usize {
ret value;
}
// 内置类型名:bool/void/isize/usize/any/iN/uN/fN(对应 stage1 spl_type_lookup_builtin)。
// 内置类型名:bool/void/isize/usize/any/iN/uN/fN。
fn lookup_builtin(self: *LangType, name: ByteView): usize {
if name.len == 0 { ret 0; }
if ByteView.eq(name, ByteView.from_slice("bool")) { ret make_bool(self); }
@@ -675,7 +659,6 @@ fn lookup_builtin(self: *LangType, name: ByteView): usize {
ret 0;
}
// ---- IR 位宽读取 ----
fn int_bits(self: *LangType, ir_id: usize): usize {
var te = TypeTable.node(&self.ir, ir_id);
@@ -707,7 +690,6 @@ fn float_bits(self: *LangType, ir_id: usize): usize {
ret 0;
}
// ---- 语言层子类型 / 求交 / 字面量适配 ----
fn is_subtype(self: *LangType, sub: usize, super: usize): bool {
if sub == 0 || super == 0 { ret false; }
@@ -838,7 +820,7 @@ fn int_fits(self: *LangType, target: usize, value: BigInt): bool {
.Err(error) => { ret false; },
}
// 镜像 stage1:目标位宽 >= 64 时不做边界检查(其 mpa 只存低 64 位)。
// 目标位宽 >= 64 时不做边界检查(mpa 只存低 64 位)。
if bits >= 64 { ret true; }
var u: u64 = 0;
@@ -860,7 +842,6 @@ fn int_fits(self: *LangType, target: usize, value: BigInt): bool {
ret false;
}
// ---- dump(镜像 stage1 spl_lang_type_dump)----
fn push_out(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
@@ -898,10 +879,7 @@ fn dump_rec(self: *LangType, id: usize, out: *ByteBuffer, stack: *Vec): bool {
if e == null {
if !push_out(out, "none") { ret false; }
var dropped: usize = 0;
match Vec.pop(stack, &dropped as *u8) {
.Ok => {},
.Err(error) => {},
}
Vec.pop(stack, &dropped as *u8);
ret true;
}
@@ -941,7 +919,7 @@ fn dump_rec(self: *LangType, id: usize, out: *ByteBuffer, stack: *Vec): bool {
if !push_out(out, "[") { ok = false; }
if ok && !push_usize(out, len) { ok = false; }
if ok && !push_out(out, "]") { ok = false; }
// 镜像 stage1:数组直接 dump IR 类型(会重复一次 [N])。
// 数组直接 dump IR 类型(会重复一次 [N])。
if ok { ok = TypeTable.pure_dump(&self.ir, e.ir_type_id, out); }
},
.Slice => {
@@ -995,10 +973,7 @@ fn dump_rec(self: *LangType, id: usize, out: *ByteBuffer, stack: *Vec): bool {
}
var dropped2: usize = 0;
match Vec.pop(stack, &dropped2 as *u8) {
.Ok => {},
.Err(error) => {},
}
Vec.pop(stack, &dropped2 as *u8);
ret ok;
}
@@ -1008,7 +983,6 @@ fn dump(self: *LangType, id: usize, out: *ByteBuffer): bool {
ret dump_rec(self, id, out, &stack);
}
// ---- 测试 ----
fn expect_text(buf: ByteBuffer, expected: []u8) {
var got = ByteBuffer.as_slice(buf);
+4 -9
View File
@@ -1,9 +1,7 @@
// Expect retcode = 0
// 目标布局(移植自 stage1/spl_layout.c)。输入是 IR 类型表 TypeTable;
// 为每个类型计算 size_bits / align_bits / 字段位偏移,供 ir2vm 使用。
// 默认 64 位平台:标量按 1/2/4/8 字节对齐,指针 = usize,聚合按最大字段对齐
// 且不允许重排(与 stage1 的默认策略一致)。
// 目标布局:由 IR 类型表计算 size/align/字段位偏移,供 ir2vm 使用。默认 64 位平台,
// 聚合按最大字段对齐且不重排。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
@@ -47,7 +45,7 @@ fn info_at(self: *Layout, id: usize): *LayoutInfo {
ret (self.infos.data as *LayoutInfo) + id;
}
// 未解析或越界返回 null(对应 stage1 spl_layout_info_of)。
// 未解析或越界返回 null。
fn info_of(self: *Layout, id: usize): *LayoutInfo {
var info = info_at(self, id);
if info == null || !info.resolved { ret null; }
@@ -84,10 +82,7 @@ fn ensure(self: *Layout, n: usize) {
}
fn push_usize(v: *Vec, x: usize) {
match Vec.push(v, &x as *u8) {
.Ok => {},
.Err(error) => {},
}
Vec.push(v, &x as *u8);
}
fn usize_at(v: *Vec, i: usize): usize {
+2 -7
View File
@@ -1,9 +1,7 @@
// Expect retcode = 0
// 词法分析器:字节流 -> Vec<Token>。镜像 stage1/spl_lexer.c 的行为:
// 行注释作为 token 产出;块注释(可嵌套)整体跳过;换行产出 Endline;EOF 产出 Eof。
// 复用 utils/ascii 做字符分类;整型/字符在词法期解码后放进 TokenKind 载荷。
// Token.text 借用输入字节,不复制。
// 字节流 -> Vec<Token>。行为镜像 splc0(保证 diff):行注释作为 token 产出,块注释
//(可嵌套)跳过,换行产 Endline,EOF 产 Eof。Token.text 借用输入,不复制。
type .{ .Vec, .VecResult } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
@@ -80,7 +78,6 @@ fn decode_char(text: ByteView): u8 {
ret e;
}
// ---- 读取辅助 ----
fn has2(self: *Lexer, ch: u8): bool {
ret self.pos + 1 < self.src.len && self.src.ptr[self.pos + 1] == ch;
@@ -120,7 +117,6 @@ fn op3(self: *Lexer, out: *Vec, punct: Punct, start: usize, line: usize, col: us
emit_to(self, out, .Punct(punct), start, start + 3, line, col);
}
// ---- 复合扫描 ----
fn scan_int(self: *Lexer, out: *Vec, start: usize, line: usize, col: usize) {
var p = self.pos;
@@ -453,7 +449,6 @@ fn lex(src: ByteView, diag: *Diag, file: usize): VecResult {
ret .Ok(out);
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
+65 -74
View File
@@ -1,28 +1,15 @@
// Expect retcode = 0
// SPL VM 机器码容器(移植自 stage0/spl_mcode.c 的构建/序列化/dump 部分)。
// 只负责「内存中的 prog」与「写入 .sir」,不包含反序列化(由 C 侧 spl_cli 读)。
//
// 字符串一律是 ByteView(借用上层 IR/attr 的名称,本模块不复制、不释放);
// gdata 条目是 ByteBuffer,由本模块拥有并释放。
//
// 二进制格式(元数据字段均为 u64 小端):
// [HEADER] magic(8) nfuncs(8) ninsns(8) nnatives(8) nstrs(8) ndata(8)
// [FUNCS] 每项: name_len(8) name(pad8, 含结尾 NUL) idx_of_strtab(8)
// nargs(8) ninsns(8) address(8)
// [INSTRS] 每项: opcode(2) type(2) imm(8) = 12 字节
// [NATIVES] 每项: name_len(8) name(pad8, 含结尾 NUL) idx_of_strtab(8)
// [STRTAB] 每项: slen(8) str(pad8)
// [GDATA] 每项: dsize(8) data(pad8)
// VM 字节码容器:内存中的 Prog 与 .sir 序列化(反序列化在 C 侧 spl_cli)。
// 字符串用 ByteView 借用、不拥有;gdata 条目为 ByteBuffer,由本模块拥有释放。
type .{ .Error, .Status, .make } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
type .{ .ByteBuffer } = @import("utils/byte_buffer.spl");
type .{ .append_usize, .append_i64 } = @import("utils/fmt.spl");
type Mem = @import("sys/mem.spl");
type File = @import("sys/file.spl");
type .{ .open_cstr, .write_all, .read_all } = @import("utils/io.spl");
type Mem = @import("utils/memory.spl");
type .{ .open_cstr, .write_all, .read_all, .File } = @import("utils/io.spl");
type Op = enum {
Error,
@@ -72,6 +59,7 @@ type Op = enum {
Gaddr,
Load,
Store,
Memcpy,
Ncall,
Nlib,
Bk,
@@ -177,6 +165,7 @@ fn op_name(op: Op): []u8 {
.Gaddr => { ret "gaddr"; },
.Load => { ret "load"; },
.Store => { ret "store"; },
.Memcpy => { ret "memcpy"; },
.Ncall => { ret "ncall"; },
.Nlib => { ret "nlib"; },
.Bk => { ret "breakpoint"; },
@@ -206,7 +195,6 @@ fn kind_name(k: VmKind): []u8 {
ret "???";
}
// ---- 生命周期 ----
fn new(): ProgResult {
var prog = Prog {
@@ -262,7 +250,6 @@ fn drop(self: *Prog) {
Vec.drop(&self.insns);
}
// ---- 构建 ----
fn add_instr(self: *Prog, op: Op, ty: VmKind, imm: usize): usize {
var i = self.insns.len;
@@ -304,7 +291,7 @@ fn add_data(self: *Prog, ptr: usize, size: usize): usize {
}
if size != 0 {
if ptr == 0 { ByteBuffer.drop(&entry); ret 0; }
ignore_ptr(Mem.copy(entry.storage.data as *any, ptr as *any, size));
Mem.copy(entry.storage.data as *any, ptr as *any, size);
entry.storage.len = size;
}
match Vec.push(&self.gdata, &entry as *u8) {
@@ -351,7 +338,6 @@ fn get_or_add_native(self: *Prog, name: ByteView): isize {
ret (self.natives.len - 1) as isize;
}
// ---- dump(输出必须与 stage0 spl_prog_dump 逐字节一致)----
fn out_s(out: *ByteBuffer, s: []u8): bool {
match ByteBuffer.append(out, s) { .Ok => { ret true; }, .Err(error) => { ret false; } }
@@ -468,21 +454,23 @@ fn dump(self: *Prog, out: *ByteBuffer): bool {
if !out_s(out, " ") { ret false; }
if !out_i(out, ins.imm as i64) { ret false; }
if @enum2int(ins.opcode) == @enum2int(Op.Jmp) ||
@enum2int(ins.opcode) == @enum2int(Op.Bz) ||
@enum2int(ins.opcode) == @enum2int(Op.Bnz) {
if !out_s(out, " ; -> ") { ret false; }
if !out_u(out, i + 1 + ins.imm) { ret false; }
} else if @enum2int(ins.opcode) == @enum2int(Op.Call) {
if !out_s(out, " ; nargs=") { ret false; }
if !out_u(out, ins.imm) { ret false; }
if !out_s(out, ", from stack") { ret false; }
} else if @enum2int(ins.opcode) == @enum2int(Op.Calli) {
if !out_s(out, " ; indirect call") { ret false; }
} else if @enum2int(ins.opcode) == @enum2int(Op.Gaddr) {
if !out_s(out, " ; gdata[") { ret false; }
if !out_u(out, ins.imm) { ret false; }
if !out_s(out, "]") { ret false; }
match ins.opcode {
.Jmp, .Bz, .Bnz => {
if !out_s(out, " ; -> ") { ret false; }
if !out_u(out, i + 1 + ins.imm) { ret false; }
},
.Call => {
if !out_s(out, " ; nargs=") { ret false; }
if !out_u(out, ins.imm) { ret false; }
if !out_s(out, ", from stack") { ret false; }
},
.Calli => { if !out_s(out, " ; indirect call") { ret false; } },
.Gaddr => {
if !out_s(out, " ; gdata[") { ret false; }
if !out_u(out, ins.imm) { ret false; }
if !out_s(out, "]") { ret false; }
},
_ => {},
}
if !out_s(out, "\n") { ret false; }
i = i + 1;
@@ -511,14 +499,13 @@ fn str_at(self: *Prog, i: usize): ByteView {
ret ByteView.empty();
}
// ---- 序列化 ----
fn align8(n: usize): usize {
ret (n + 7) & (~(7 as usize));
}
// 说明:以下 put_* 直接写入已预留容量的 ByteBuffer 存储(store 已按精确总大小 reserve),
// 跳过 ByteBuffer.append → Vec.append 的校验/拷贝路径。若容量不足会越界,故 store 先校验容量。
// put_* 直接写入已预留容量的 ByteBuffer 存储(store 已按精确总大小 reserve),跳过
// append 的校验/拷贝;容量不足会越界,故 store 先校验容量。
fn put_u8(out: *ByteBuffer, b: u8): bool {
out.storage.data[out.storage.len] = b;
@@ -543,7 +530,7 @@ fn put_u64(out: *ByteBuffer, v: usize): bool {
fn put_zeros(out: *ByteBuffer, n: usize): bool {
if n != 0 {
ignore_ptr(Mem.set((out.storage.data + out.storage.len) as *any, 0, n));
Mem.set((out.storage.data + out.storage.len) as *any, 0, n);
out.storage.len = out.storage.len + n;
}
ret true;
@@ -570,36 +557,37 @@ fn encode(self: *Prog, out: *ByteBuffer): Status {
// 精确预估输出大小并一次性预留,避免大文件逐字节增长导致的重复拷贝。
var total: usize = 48;
var fi: usize = 0;
var func_base = self.funcs.data as *VmFunc;
var nat_base = self.natives.data as *VmNative;
var str_base = self.strtab.data as *ByteView;
var gd_base = self.gdata.data as *ByteBuffer;
while fi < self.funcs.len {
var f = func_at(self, fi);
if f != null {
var nlen = f.name.len + 1;
total = total + 8 + align8(nlen) + 32;
}
var f = func_base + fi;
var nlen = f.name.len + 1;
total = total + 8 + align8(nlen) + 32;
fi = fi + 1;
}
total = total + self.insns.len * 12;
fi = 0;
while fi < self.natives.len {
var n = native_at(self, fi);
if n != null {
var nlen = n.name.len + 1;
total = total + 8 + align8(nlen) + 8;
}
var n = nat_base + fi;
var nlen = n.name.len + 1;
total = total + 8 + align8(nlen) + 8;
fi = fi + 1;
}
fi = 0;
while fi < self.strtab.len {
total = total + 8 + align8(str_at(self, fi).len);
var s = str_base + fi;
total = total + 8 + align8(s.len);
fi = fi + 1;
}
fi = 1;
while fi < self.gdata.len {
var e = gdata_at(self, fi);
if e != null { total = total + 8 + align8(e.storage.len); }
var e = gd_base + fi;
total = total + 8 + align8(e.storage.len);
fi = fi + 1;
}
match ByteBuffer.reserve(out, total) { .Ok => {}, .Err(error) => {} }
ByteBuffer.reserve(out, total);
if out.storage.cap < total || out.storage.data == null { ret .Err(make(.Io)); }
if !put_view(out, ByteView.from_slice("SPLBIN")) { ret .Err(make(.Io)); }
@@ -620,8 +608,7 @@ fn encode(self: *Prog, out: *ByteBuffer): Status {
var i: usize = 0;
while i < nfuncs {
var f = func_at(self, i);
if f == null { ret .Err(make(.Io)); }
var f = func_base + i;
if !put_name_field(out, f.name) { ret .Err(make(.Io)); }
if !put_u64(out, f.idx_of_strtab) { ret .Err(make(.Io)); }
if !put_u64(out, f.nargs) { ret .Err(make(.Io)); }
@@ -631,20 +618,23 @@ fn encode(self: *Prog, out: *ByteBuffer): Status {
}
i = 0;
var ins_base = self.insns.data as *VmIns;
var out_base = out.storage.data;
var out_len = out.storage.len;
while i < ninsns {
var ins = ins_at(self, i);
var d = out.storage.data + out.storage.len;
(d as *u16).* = @enum2int(ins.opcode) as u16;
((d + 2) as *u16).* = @enum2int(ins.ty) as u16;
((d + 4) as *u64).* = ins.imm as u64;
out.storage.len = out.storage.len + 12;
var p = ins_base + i;
var d = out_base + out_len;
(d as *u16).* = @enum2int(p.opcode) as u16;
((d + 2) as *u16).* = @enum2int(p.ty) as u16;
((d + 4) as *u64).* = p.imm as u64;
out_len = out_len + 12;
i = i + 1;
}
out.storage.len = out_len;
i = 0;
while i < nnatives {
var n = native_at(self, i);
if n == null { ret .Err(make(.Io)); }
var n = nat_base + i;
if !put_name_field(out, n.name) { ret .Err(make(.Io)); }
if !put_u64(out, n.idx_of_strtab) { ret .Err(make(.Io)); }
i = i + 1;
@@ -652,17 +642,16 @@ fn encode(self: *Prog, out: *ByteBuffer): Status {
i = 0;
while i < nstrs {
var s = str_at(self, i);
var s = str_base + i;
if !put_u64(out, s.len) { ret .Err(make(.Io)); }
if !put_view(out, s) { ret .Err(make(.Io)); }
if !put_view(out, s.*) { ret .Err(make(.Io)); }
if !put_zeros(out, align8(s.len) - s.len) { ret .Err(make(.Io)); }
i = i + 1;
}
i = 1;
while i < self.gdata.len {
var e = gdata_at(self, i);
if e == null { ret .Err(make(.Io)); }
var e = gd_base + i;
var dsize = e.storage.len;
if !put_u64(out, dsize) { ret .Err(make(.Io)); }
if !put_view(out, ByteView.from_slice(ByteBuffer.as_slice(e.*))) { ret .Err(make(.Io)); }
@@ -693,10 +682,12 @@ fn store(self: *Prog, path: ByteView): Status {
ret .Ok;
}
fn ignore_ptr(p: *any) {}
fn ignore_usize(v: usize) {}
// 序列化到内存缓冲(供内嵌 VM 直接装载)。
fn serialize(self: *Prog, out: *ByteBuffer): Status {
ret encode(self, out);
}
// ---- 测试 ----
fn test_dump_basic() {
var pr: Prog = undefined;
@@ -706,7 +697,7 @@ fn test_dump_basic() {
}
defer { drop(&pr); }
ignore_usize(add_instr(&pr, .Halt, .Void, 0));
add_instr(&pr, .Halt, .Void, 0);
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
@@ -754,8 +745,8 @@ fn test_store_roundtrip() {
}
defer { drop(&pr); }
ignore_usize(add_func(&pr, ByteView.from_slice("main"), 0, 0));
ignore_usize(add_instr(&pr, .Halt, .Void, 0));
add_func(&pr, ByteView.from_slice("main"), 0, 0);
add_instr(&pr, .Halt, .Void, 0);
var path = ByteView.from_slice("build/_mcode_roundtrip.tmp");
match store(&pr, path) {
+242 -235
View File
@@ -1,7 +1,6 @@
// Expect retcode = 0
// Parser:token 流 -> Ast(ADT 节点)。C 版只作控制流参考,节点分配顺序需与 stage1
// 一致,以保证 dump 的 #ref 可对比。pos 在 token 向量上移动,自动跳过 trivia。
// token 流 -> Ast。节点分配顺序必须与 splc0 一致,否则 dump 的 #ref 无法逐字节对比。
type .{ .Vec } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
@@ -41,7 +40,6 @@ fn new(ast: *Ast, toks: Vec, diag: *Diag): Parser {
};
}
// ---- token 访问 ----
fn token_ptr(self: *Parser, index: usize): *Token {
if index >= self.toks.len { ret null; }
@@ -138,7 +136,6 @@ fn at_eof(self: *Parser): bool {
ret false;
}
// ---- 错误 ----
fn span_of(self: *Parser, tok: *Token): Span {
if tok == null { ret span_none(); }
@@ -151,7 +148,7 @@ fn parse_error(self: *Parser, tok: *Token, what: []u8) {
Diag.err(self.diag, span_of(self, tok), .ParseExpected, what);
}
// 转义解码(镜像 stage1 spl_decode_escape):去掉引号,处理 \n \t \r \0 \\ \' \" \xHH。
// 转义解码:去掉引号,处理 \n \t \r \0 \\ \' \" \xHH。
fn hex_digit(c: u8): u8 {
if c >= '0' && c <= '9' { ret c - '0'; }
if c >= 'a' && c <= 'f' { ret (c - 'a') + 10; }
@@ -172,9 +169,7 @@ fn decode_str(t: ByteView): ByteBuffer {
if e == 'x' && i + 3 < end {
var hi = hex_digit(t.ptr[i + 2]);
var lo = hex_digit(t.ptr[i + 3]);
match ByteBuffer.append_byte(&out, (hi * 16 + lo) as u8) {
.Ok => {}, .Err(error) => {},
}
ByteBuffer.append_byte(&out, (hi * 16 + lo) as u8);
i = i + 4;
} else {
var d: u8 = e;
@@ -182,11 +177,11 @@ fn decode_str(t: ByteView): ByteBuffer {
else if e == 't' { d = '\t'; }
else if e == 'r' { d = '\r'; }
else if e == '0' { d = 0; }
match ByteBuffer.append_byte(&out, d) { .Ok => {}, .Err(error) => {} }
ByteBuffer.append_byte(&out, d);
i = i + 2;
}
} else {
match ByteBuffer.append_byte(&out, c) { .Ok => {}, .Err(error) => {} }
ByteBuffer.append_byte(&out, c);
i = i + 1;
}
}
@@ -203,7 +198,6 @@ fn expect_punct(self: *Parser, punct: Punct, what: []u8): bool {
ret true;
}
// ---- 节点 ----
fn new_node(self: *Parser, body: Body, tok: *Token): usize {
ret Ast.alloc(self.ast, body, span_of(self, tok));
@@ -262,7 +256,6 @@ fn int_token_u64(self: *Parser, tok: *Token, radix: Radix): u64 {
ret v;
}
// ---- 判定(stage1 can_start_*)----
fn can_start_expr(kind: TokenKind): bool {
match kind {
@@ -335,11 +328,10 @@ fn can_start_statement(kind: TokenKind): bool {
ret false;
}
// ---- 模式(M3.2 子集:ident / _ / .variant / tuple / .{ } )----
fn parse_pattern_aggregate(self: *Parser, start: *Token): usize {
if !expect_punct(self, .LBrace, "'{' after '.'") { ret 0; }
// stage1 先分配 PATTERN_AGGREGATE,再解析字段。
// 先分配 PATTERN_AGGREGATE,再解析字段。
var ref = new_node(self, .PatternAggregate(.{ .items = ref_vec() }), start);
var fields = ref_vec();
while !self.failed {
@@ -354,7 +346,7 @@ fn parse_pattern_aggregate(self: *Parser, start: *Token): usize {
if name == null { break; }
match name.kind { .Ident => {}, _ => { break; } }
advance(self);
// stage1 先分配 PATTERN_FIELD,再解析可选子模式。
// 先分配 PATTERN_FIELD,再解析可选子模式。
var fre = new_node(self, .PatternField(.{
.name = name.text,
.pattern = 0,
@@ -449,7 +441,7 @@ fn parse_pattern_atom(self: *Parser): usize {
if nx == null { ret 0; }
match nx.kind { .Ident => {}, _ => { ret 0; } }
advance(self);
// stage1 先分配 PATTERN_DOT,再解析子模式。
// 先分配 PATTERN_DOT,再解析子模式。
var ref = new_node(self, .PatternDot(.{
.name = nx.text,
.sub_pattern = 0,
@@ -460,9 +452,8 @@ fn parse_pattern_atom(self: *Parser): usize {
var sub = parse_pattern(self);
var pn = Ast.node(self.ast, ref);
match pn.body {
.PatternDot(pd) => {
.PatternDot(&pd) => {
pd.sub_pattern = sub;
pn.body = .PatternDot(pd);
},
_ => {},
}
@@ -473,7 +464,7 @@ fn parse_pattern_atom(self: *Parser): usize {
},
.LParen => {
advance(self);
// stage1 先分配 PATTERN_TUPLE,再解析内部模式。
// 先分配 PATTERN_TUPLE,再解析内部模式。
var ref = new_node(self, .PatternTuple(.{ .items = ref_vec() }), t);
if at_punct(self, .RParen) {
advance(self);
@@ -508,6 +499,24 @@ fn parse_pattern_atom(self: *Parser): usize {
}
ret ref;
},
.And => {
// `&name`:解包左值引用绑定。仅允许作用于绑定名。
advance(self);
var nx = peek(self);
if nx == null {
parse_error(self, nx, "expected binding name after '&'");
ret 0;
}
match nx.kind {
.Ident => {},
_ => {
parse_error(self, nx, "expected binding name after '&'");
ret 0;
},
}
var inner = parse_pattern_atom(self);
ret new_node(self, .PatternRef(.{ .pat = inner }), t);
},
_ => {},
}
},
@@ -545,9 +554,8 @@ fn parse_pattern(self: *Parser): usize {
ret new_node(self, .PatternList(.{ .items = atoms }), peek(self));
}
// ---- 声明 ----
fn parse_tag_list(self: *Parser, out: *Vec, is_external: bool, allow_at: bool) {
fn parse_tag_list(self: *Parser, out: *Vec, is_external: bool, allow_at: bool, bang_only: bool) {
while !self.failed {
var t = peek(self);
if t == null { ret; }
@@ -556,30 +564,37 @@ fn parse_tag_list(self: *Parser, out: *Vec, is_external: bool, allow_at: bool) {
else if kind_is_punct(t.kind, .Sharp) { is_at = false; }
else { ret; }
if !allow_at && is_at { ret; }
advance(self);
if is_external {
t = peek(self);
if t == null || !kind_is_punct(t.kind, .Not) {
parse_error(self, t, "expected '!' in external tag");
ret;
}
if bang_only {
// 仅消费 `#!`/`@!` 形式的当前层 tag;遇到普通 `#name` 即停。
var save = self.pos;
advance(self);
var nt = peek(self);
var has_bang = nt != null && kind_is_punct(nt.kind, .Not);
self.pos = save;
if !has_bang { ret; }
}
advance(self);
t = peek(self);
var ext_here = is_external;
if t != null && kind_is_punct(t.kind, .Not) {
advance(self);
ext_here = true;
}
t = peek(self);
if t == null { ret; }
match t.kind { .Ident => {}, _ => { parse_error(self, t, "expected tag name"); ret; } }
advance(self);
// stage1 先分配 tag 节点,再解析参数。
// 先分配 tag 节点,再解析参数。
var body: Body = .TagItem(.{
.is_at = is_at,
.is_external = is_external,
.is_external = ext_here,
.name = t.text,
.args = ref_vec(),
});
if is_external {
if ext_here {
body = .ExternalTagItem(.{
.is_at = is_at,
.is_external = is_external,
.is_external = ext_here,
.name = t.text,
.args = ref_vec(),
});
@@ -608,7 +623,13 @@ fn parse_tag_list(self: *Parser, out: *Vec, is_external: bool, allow_at: bool) {
fn parse_param_decl_impl(self: *Parser): usize {
var attrs = ref_vec();
parse_tag_list(self, &attrs, false, true);
var is_comptime = false;
var c0 = peek(self);
if c0 != null && kind_is_keyword(c0.kind, .Comptime) {
advance(self);
is_comptime = true;
}
parse_tag_list(self, &attrs, false, true, false);
var name = peek(self);
if name == null { ret 0; }
var ok = false;
@@ -620,10 +641,10 @@ fn parse_param_decl_impl(self: *Parser): usize {
if !ok { ret 0; }
advance(self);
if !expect_punct(self, .Colon, "':' in parameter declaration") { ret 0; }
parse_tag_list(self, &attrs, false, false);
parse_tag_list(self, &attrs, false, false, false);
var ty = parse_type_expr(self);
ret new_node(self,
.ParamDecl(.{ .attr_list = attrs, .name = name.text, .type_expr = ty }),
.ParamDecl(.{ .attr_list = attrs, .is_comptime = is_comptime, .name = name.text, .type_expr = ty }),
name);
}
@@ -651,11 +672,24 @@ fn parse_param_list(self: *Parser): Vec {
if at_punct(self, .Comma) { advance(self); continue; }
break;
},
.Keyword(k) => {
if @enum2int(k) == @enum2int(Keyword.Comptime) {
var pd2 = parse_param_decl_impl(self);
if pd2 != 0 {
match Vec.push(&out, &pd2 as *u8) { .Ok => {}, .Err(e) => { ret out; } }
}
if at_punct(self, .Comma) { advance(self); continue; }
break;
}
parse_error(self, t, "unexpected token in parameter list");
break;
},
.Punct(p) => {
if @enum2int(p) == @enum2int(Punct.Ellipsis) {
advance(self);
var pd = new_node(self, .ParamDecl(.{
.attr_list = ref_vec(),
.is_comptime = false,
.name = ByteView.empty(),
.type_expr = 0,
}), t);
@@ -681,20 +715,16 @@ fn token_starts_type(t: *Token): bool {
match t.kind {
.Ident => { ret true; },
.Keyword(k) => {
if @enum2int(k) == @enum2int(Keyword.Type) { ret true; }
if @enum2int(k) == @enum2int(Keyword.Bool) { ret true; }
if @enum2int(k) == @enum2int(Keyword.Any) { ret true; }
if @enum2int(k) == @enum2int(Keyword.Fn) { ret true; }
if @enum2int(k) == @enum2int(Keyword.Struct) { ret true; }
if @enum2int(k) == @enum2int(Keyword.Union) { ret true; }
if @enum2int(k) == @enum2int(Keyword.Enum) { ret true; }
if @enum2int(k) == @enum2int(Keyword.Shape) { ret true; }
match k {
.Type, .Bool, .Any, .Fn, .Struct, .Union, .Enum, .Shape => { ret true; },
_ => {},
}
},
.Punct(p) => {
if @enum2int(p) == @enum2int(Punct.Mul) { ret true; }
if @enum2int(p) == @enum2int(Punct.LBracket) { ret true; }
if @enum2int(p) == @enum2int(Punct.At) { ret true; }
if @enum2int(p) == @enum2int(Punct.Sharp) { ret true; }
match p {
.Mul, .LBracket, .At, .Sharp => { ret true; },
_ => {},
}
},
_ => {},
}
@@ -752,7 +782,7 @@ fn parse_type_decl(self: *Parser, tags: Vec): usize {
var pattern = parse_pattern(self);
if pattern == 0 { ret 0; }
if !expect_punct(self, .Assign, "'=' in type declaration") { ret 0; }
// stage1 先分配 TYPE_DECL 再解析 type_expr(影响 #ref 顺序)。
// 先分配 TYPE_DECL 再解析 type_expr(影响 #ref 顺序)。
var ref = new_node(self, .TypeDecl(.{
.attr_list = tags,
.pattern = pattern,
@@ -825,7 +855,7 @@ fn parse_member_decl(self: *Parser, tags: Vec): usize {
var t = peek(self);
if t != null && kind_is_punct(t.kind, .Colon) {
advance(self);
parse_tag_list(self, &tags, false, false);
parse_tag_list(self, &tags, false, false, false);
te = parse_type_expr(self);
t = peek(self);
if t != null && kind_is_punct(t.kind, .Assign) {
@@ -864,38 +894,39 @@ fn parse_comptime_decl(self: *Parser): usize {
fn parse_container_declaration(self: *Parser): usize {
var tags = ref_vec();
parse_tag_list(self, &tags, false, false);
parse_tag_list(self, &tags, false, false, false);
var t = peek(self);
if t == null { ret 0; }
match t.kind {
.Eof => { ret 0; },
.Keyword(k) => {
if @enum2int(k) == @enum2int(Keyword.Fn) { ret parse_fn_decl(self, tags, false); }
if @enum2int(k) == @enum2int(Keyword.Type) { ret parse_type_decl(self, tags); }
if @enum2int(k) == @enum2int(Keyword.Var) {
ret parse_var_const_decl(self, tags, false);
}
if @enum2int(k) == @enum2int(Keyword.Const) {
ret parse_var_const_decl(self, tags, true);
}
if @enum2int(k) == @enum2int(Keyword.Comptime) {
// `comptime fn ...` -> 标记为编译期函数;否则 `comptime { }` 声明。
var nxt = peek_next(self);
if nxt != null && kind_is_keyword(nxt.kind, .Fn) {
advance(self);
ret parse_fn_decl(self, tags, true);
}
ret parse_comptime_decl(self);
match k {
.Fn => { ret parse_fn_decl(self, tags, false); },
.Type => { ret parse_type_decl(self, tags); },
.Var => { ret parse_var_const_decl(self, tags, false); },
.Const => { ret parse_var_const_decl(self, tags, true); },
.Comptime => {
var nxt = peek_next(self);
if nxt != null && kind_is_keyword(nxt.kind, .Fn) {
advance(self);
ret parse_fn_decl(self, tags, true);
}
ret parse_comptime_decl(self);
},
_ => {},
}
},
.Ident => { ret parse_member_decl(self, tags); },
.Punct(p) => {
if @enum2int(p) == @enum2int(Punct.LBrace) {
var block = parse_block(self);
ret new_node(self, .TopLevelBlock(.{
.tag_list = tags,
.block = block,
}), t);
match p {
.LBrace => {
var block = parse_block(self);
ret new_node(self, .TopLevelBlock(.{
.tag_list = tags,
.block = block,
}), t);
},
_ => {},
}
},
_ => {},
@@ -905,7 +936,6 @@ fn parse_container_declaration(self: *Parser): usize {
ret 0;
}
// ---- 类型 ----
fn parse_type_comptime_call(self: *Parser): usize {
var start = peek(self);
@@ -934,7 +964,7 @@ fn parse_type_base(self: *Parser): usize {
if kind_is_keyword(bt.kind, .Fn) {
advance(self);
if !expect_punct(self, .LParen, "'(' in function type") { ret 0; }
// stage1 先分配 TYPE_FN,再解析参数与返回类型。
// 先分配 TYPE_FN,再解析参数与返回类型。
var ref = new_node(self, .TypeFn(.{
.is_comptime = false,
.params = ref_vec(),
@@ -968,10 +998,13 @@ fn parse_type_base(self: *Parser): usize {
match bt.kind {
.Keyword(k) => {
var kind_name: []u8 = "";
if @enum2int(k) == @enum2int(Keyword.Struct) { kind_name = "struct"; }
else if @enum2int(k) == @enum2int(Keyword.Union) { kind_name = "union"; }
else if @enum2int(k) == @enum2int(Keyword.Enum) { kind_name = "enum"; }
else if @enum2int(k) == @enum2int(Keyword.Shape) { kind_name = "shape"; }
match k {
.Struct => { kind_name = "struct"; },
.Union => { kind_name = "union"; },
.Enum => { kind_name = "enum"; },
.Shape => { kind_name = "shape"; },
_ => {},
}
if kind_name.len != 0 {
advance(self);
if !expect_punct(self, .LBrace, "'{' in aggregate type") { ret 0; }
@@ -1045,20 +1078,21 @@ fn parse_type_base(self: *Parser): usize {
}), bt);
},
.Keyword(k) => {
// stage1 is_builtin_type_kw:bool / any 作为类型路径;stage3 增加 `type`。
if @enum2int(k) == @enum2int(Keyword.Bool) ||
@enum2int(k) == @enum2int(Keyword.Any) ||
@enum2int(k) == @enum2int(Keyword.Type) {
advance(self);
ret new_node(self, .TypePath(.{
.name = bt.text,
.generic_args = ref_vec(),
}), bt);
match k {
.Bool, .Any, .Type => {
advance(self);
ret new_node(self, .TypePath(.{
.name = bt.text,
.generic_args = ref_vec(),
}), bt);
},
_ => {},
}
},
.Punct(p) => {
if @enum2int(p) == @enum2int(Punct.At) || @enum2int(p) == @enum2int(Punct.Sharp) {
ret parse_type_comptime_call(self);
match p {
.At, .Sharp => { ret parse_type_comptime_call(self); },
_ => {},
}
},
_ => {},
@@ -1073,7 +1107,7 @@ fn parse_type_expr(self: *Parser): usize {
if kind_is_punct(t.kind, .Mul) {
advance(self);
// stage1 先分配 POINTER,再解析 pointee。
// 先分配 POINTER,再解析 pointee。
var ref = new_node(self, .TypePointer(.{ .pointee = 0 }), t);
var pointee = parse_type_expr(self);
var pn = Ast.node(self.ast, ref);
@@ -1157,7 +1191,6 @@ fn parse_type_expr(self: *Parser): usize {
ret base;
}
// ---- 表达式 ----
type BinInfo = struct { op: Punct, prec: i32, right: bool }
type BinResult = enum { No, Yes: BinInfo }
@@ -1282,9 +1315,9 @@ fn parse_prefix(self: *Parser): usize {
if ref == 0 { ret 0; }
var n = Ast.node(self.ast, ref);
match n.body {
.ExprWhile(w) => { w.label = label; n.body = .ExprWhile(w); },
.ExprLoop(l) => { l.label = label; n.body = .ExprLoop(l); },
.ExprFor(f) => { f.label = label; n.body = .ExprFor(f); },
.ExprWhile(&w) => { w.label = label; },
.ExprLoop(&l) => { l.label = label; },
.ExprFor(&f) => { f.label = label; },
_ => {},
}
ret ref;
@@ -1324,7 +1357,7 @@ fn parse_postfix(self: *Parser): usize {
if kind_is_punct(t.kind, .LParen) {
advance(self);
// stage1 先分配 CALL,再解析实参(影响 #ref 顺序)。
// 先分配 CALL,再解析实参(影响 #ref 顺序)。
var ref = new_node(self, .ExprCall(.{ .callee = expr, .args = ref_vec() }), t);
var args = parse_expr_list(self);
var cn = Ast.node(self.ast, ref);
@@ -1437,47 +1470,31 @@ fn parse_primary(self: *Parser): usize {
ret new_node(self, .ExprStringLit(.{ .data = Ast.push_string(self.ast, decode_str(t.text)) }), t);
},
.Keyword(k) => {
if @enum2int(k) == @enum2int(Keyword.True) {
advance(self);
ret new_node(self, .ExprBoolLit(.{ .value = true }), t);
}
if @enum2int(k) == @enum2int(Keyword.False) {
advance(self);
ret new_node(self, .ExprBoolLit(.{ .value = false }), t);
}
if @enum2int(k) == @enum2int(Keyword.Null) {
advance(self);
ret new_node(self, .ExprNullLit, t);
}
if @enum2int(k) == @enum2int(Keyword.Undefined) {
advance(self);
ret new_node(self, .ExprUndefinedLit, t);
}
if @enum2int(k) == @enum2int(Keyword.If) { ret parse_if_expr(self); }
if @enum2int(k) == @enum2int(Keyword.While) { ret parse_while_expr(self); }
if @enum2int(k) == @enum2int(Keyword.Loop) { ret parse_loop_expr(self); }
if @enum2int(k) == @enum2int(Keyword.For) { ret parse_for_expr(self); }
if @enum2int(k) == @enum2int(Keyword.Match) { ret parse_match_expr(self); }
// `try <expr>`:错误上抛前缀。
if @enum2int(k) == @enum2int(Keyword.Try) {
advance(self);
var tv = parse_expr(self);
ret new_node(self, .ExprTry(.{ .value = tv }), t);
}
// `comptime <expr>`:编译期表达式(可调用普通函数、返回类型等)。
if @enum2int(k) == @enum2int(Keyword.Comptime) {
advance(self);
var cbody = parse_expr(self);
ret new_node(self, .ExprComptime(.{ .body = cbody }), t);
}
// 类型即表达式:仅在 comptime 上下文内允许 `struct { ... }` 等聚合类型。
if self.comptime_depth > 0 {
if @enum2int(k) == @enum2int(Keyword.Struct) ||
@enum2int(k) == @enum2int(Keyword.Union) ||
@enum2int(k) == @enum2int(Keyword.Enum) ||
@enum2int(k) == @enum2int(Keyword.Shape) {
ret parse_type_base(self);
}
match k {
.True => { advance(self); ret new_node(self, .ExprBoolLit(.{ .value = true }), t); },
.False => { advance(self); ret new_node(self, .ExprBoolLit(.{ .value = false }), t); },
.Null => { advance(self); ret new_node(self, .ExprNullLit, t); },
.Undefined => { advance(self); ret new_node(self, .ExprUndefinedLit, t); },
.If => { ret parse_if_expr(self); },
.While => { ret parse_while_expr(self); },
.Loop => { ret parse_loop_expr(self); },
.For => { ret parse_for_expr(self); },
.Match => { ret parse_match_expr(self); },
.Try => {
advance(self);
var tv = parse_expr(self);
ret new_node(self, .ExprTry(.{ .value = tv }), t);
},
.Comptime => {
advance(self);
var cbody = parse_expr(self);
ret new_node(self, .ExprComptime(.{ .body = cbody }), t);
},
.Struct, .Union, .Enum, .Shape => {
// 类型即表达式仅限 comptime 上下文。
if self.comptime_depth > 0 { ret parse_type_base(self); }
},
_ => {},
}
parse_error(self, t, "unrecognized expression");
ret 0;
@@ -1485,7 +1502,7 @@ fn parse_primary(self: *Parser): usize {
.Ident => {
advance(self);
if at_punct(self, .LBrace) && self.stop_agg == 0 {
// stage1 先分配 AGGREGATE_LIT,再解析字段。
// 先分配 AGGREGATE_LIT,再解析字段。
var ref = new_node(self, .ExprAggregateLit(.{
.name = t.text,
.fields = ref_vec(),
@@ -1493,10 +1510,7 @@ fn parse_primary(self: *Parser): usize {
var fields = parse_aggregate_fields(self);
var an = Ast.node(self.ast, ref);
match an.body {
.ExprAggregateLit(a) => {
a.fields = fields;
an.body = .ExprAggregateLit(a);
},
.ExprAggregateLit(&a) => { a.fields = fields; },
_ => {},
}
ret ref;
@@ -1504,71 +1518,69 @@ fn parse_primary(self: *Parser): usize {
ret new_node(self, .ExprIdent(.{ .name = t.text }), t);
},
.Punct(p) => {
if @enum2int(p) == @enum2int(Punct.Dot) {
advance(self);
var nx = peek(self);
if nx == null { parse_error(self, t, "unexpected '.'"); ret 0; }
if kind_is_punct(nx.kind, .LBrace) && self.stop_agg == 0 {
var ref = new_node(self, .ExprAggregateLit(.{
.name = ByteView.empty(),
.fields = ref_vec(),
}), t);
var fields = parse_aggregate_fields(self);
var an = Ast.node(self.ast, ref);
match an.body {
.ExprAggregateLit(a) => {
a.fields = fields;
an.body = .ExprAggregateLit(a);
},
_ => {},
match p {
.Dot => {
advance(self);
var nx = peek(self);
if nx == null { parse_error(self, t, "unexpected '.'"); ret 0; }
if kind_is_punct(nx.kind, .LBrace) && self.stop_agg == 0 {
var ref = new_node(self, .ExprAggregateLit(.{
.name = ByteView.empty(),
.fields = ref_vec(),
}), t);
var fields = parse_aggregate_fields(self);
var an = Ast.node(self.ast, ref);
match an.body {
.ExprAggregateLit(&a) => { a.fields = fields; },
_ => {},
}
ret ref;
}
ret ref;
}
if kind_is_punct(nx.kind, .LBracket) {
advance(self);
var elems = parse_expr_list(self);
if !expect_punct(self, .RBracket, "']' in array literal") { ret 0; }
ret new_node(self, .ExprArrayLit(.{
.has_len = false,
.len = 0,
.is_underscore_len = false,
.elem_type = 0,
.elems = elems,
}), t);
}
var is_ident = false;
match nx.kind { .Ident => { is_ident = true; }, _ => {} }
if is_ident { ret parse_variant_construct(self, t); }
parse_error(self, nx, "expected '{', '[' or identifier after '.'");
ret 0;
}
if @enum2int(p) == @enum2int(Punct.LBracket) { ret parse_array_literal(self); }
if @enum2int(p) == @enum2int(Punct.LBrace) { ret parse_block(self); }
if @enum2int(p) == @enum2int(Punct.At) || @enum2int(p) == @enum2int(Punct.Sharp) {
ret parse_comptime_call(self);
}
if @enum2int(p) == @enum2int(Punct.LParen) {
advance(self);
var elems = ref_vec();
if at_punct(self, .RParen) {
advance(self);
ret new_node(self, .ExprTuple(.{ .items = elems }), t);
}
var first = parse_expr(self);
if at_punct(self, .Comma) {
match Vec.push(&elems, &first as *u8) { .Ok => {}, .Err(e) => { ret 0; } }
while at_punct(self, .Comma) {
if kind_is_punct(nx.kind, .LBracket) {
advance(self);
if at_punct(self, .RParen) { break; }
var nx = parse_expr(self);
match Vec.push(&elems, &nx as *u8) { .Ok => {}, .Err(e) => { ret 0; } }
var elems = parse_expr_list(self);
if !expect_punct(self, .RBracket, "']' in array literal") { ret 0; }
ret new_node(self, .ExprArrayLit(.{
.has_len = false,
.len = 0,
.is_underscore_len = false,
.elem_type = 0,
.elems = elems,
}), t);
}
expect_punct(self, .RParen, "')' in tuple literal");
ret new_node(self, .ExprTuple(.{ .items = elems }), t);
}
expect_punct(self, .RParen, "')' in paren expression");
Vec.drop(&elems);
ret first;
var is_ident = false;
match nx.kind { .Ident => { is_ident = true; }, _ => {} }
if is_ident { ret parse_variant_construct(self, t); }
parse_error(self, nx, "expected '{', '[' or identifier after '.'");
ret 0;
},
.LBracket => { ret parse_array_literal(self); },
.LBrace => { ret parse_block(self); },
.At, .Sharp => { ret parse_comptime_call(self); },
.LParen => {
advance(self);
var elems = ref_vec();
if at_punct(self, .RParen) {
advance(self);
ret new_node(self, .ExprTuple(.{ .items = elems }), t);
}
var first = parse_expr(self);
if at_punct(self, .Comma) {
Vec.push(&elems, &first as *u8);
while at_punct(self, .Comma) {
advance(self);
if at_punct(self, .RParen) { break; }
var nx = parse_expr(self);
Vec.push(&elems, &nx as *u8);
}
expect_punct(self, .RParen, "')' in tuple literal");
ret new_node(self, .ExprTuple(.{ .items = elems }), t);
}
expect_punct(self, .RParen, "')' in paren expression");
Vec.drop(&elems);
ret first;
},
_ => {},
}
},
_ => {},
@@ -1718,7 +1730,6 @@ fn parse_expr_list(self: *Parser): Vec {
ret vec;
}
// ---- if / while / loop / for / match ----
fn parse_if_expr(self: *Parser): usize {
var kw = peek(self);
@@ -1885,7 +1896,7 @@ fn parse_match_expr(self: *Parser): usize {
if at_punct(self, .Comma) { advance(self); }
}
if !expect_punct(self, .RBrace, "'}' in match") { ret 0; }
// stage1 先分配 MATCH_EXPR,再逐个分配 MATCH_ARM。
// 先分配 MATCH_EXPR,再逐个分配 MATCH_ARM。
var ref = new_node(self, .ExprMatch(.{
.matched_expr = matched,
.arms = ref_vec(),
@@ -1914,7 +1925,6 @@ fn parse_match_expr(self: *Parser): usize {
ret ref;
}
// ---- 语句 ----
fn parse_ret_stmt(self: *Parser): usize {
var kw = peek(self);
@@ -2011,27 +2021,26 @@ fn parse_statement(self: *Parser): usize {
match t.kind {
.Keyword(k) => {
if @enum2int(k) == @enum2int(Keyword.Ret) { ret parse_ret_stmt(self); }
if @enum2int(k) == @enum2int(Keyword.Break) { ret parse_break_stmt(self); }
if @enum2int(k) == @enum2int(Keyword.Continue) { ret parse_continue_stmt(self); }
if @enum2int(k) == @enum2int(Keyword.Defer) { ret parse_defer_stmt(self); }
if @enum2int(k) == @enum2int(Keyword.Errdefer) { ret parse_errdefer_stmt(self); }
if @enum2int(k) == @enum2int(Keyword.Comptime) { ret parse_comptime_stmt(self); }
if @enum2int(k) == @enum2int(Keyword.Var) ||
@enum2int(k) == @enum2int(Keyword.Const) ||
@enum2int(k) == @enum2int(Keyword.Type) {
var tags = ref_vec();
parse_tag_list(self, &tags, false, false);
var decl: usize = 0;
if @enum2int(k) == @enum2int(Keyword.Var) {
decl = parse_var_const_decl(self, tags, false);
} else if @enum2int(k) == @enum2int(Keyword.Const) {
decl = parse_var_const_decl(self, tags, true);
} else {
decl = parse_type_decl(self, tags);
}
if decl == 0 { ret 0; }
ret new_node(self, .StatementDecl(.{ .decl = decl }), t);
match k {
.Ret => { ret parse_ret_stmt(self); },
.Break => { ret parse_break_stmt(self); },
.Continue => { ret parse_continue_stmt(self); },
.Defer => { ret parse_defer_stmt(self); },
.Errdefer => { ret parse_errdefer_stmt(self); },
.Comptime => { ret parse_comptime_stmt(self); },
.Var, .Const, .Type => {
var tags = ref_vec();
parse_tag_list(self, &tags, false, false, false);
var decl: usize = 0;
match k {
.Var => { decl = parse_var_const_decl(self, tags, false); },
.Const => { decl = parse_var_const_decl(self, tags, true); },
_ => { decl = parse_type_decl(self, tags); },
}
if decl == 0 { ret 0; }
ret new_node(self, .StatementDecl(.{ .decl = decl }), t);
},
_ => {},
}
},
_ => {},
@@ -2136,7 +2145,7 @@ fn block_push_stmt(self: *Parser, ref: usize, stmt: usize) {
var n = Ast.node(self.ast, ref);
match n.body {
.ExprBlock(b) => {
match Vec.push(&b.stmts, &stmt as *u8) { .Ok => {}, .Err(e) => {} }
Vec.push(&b.stmts, &stmt as *u8);
n.body = .ExprBlock(b);
},
_ => {},
@@ -2157,7 +2166,6 @@ fn block_set_tail(self: *Parser, ref: usize, expr: usize) {
}
}
// ---- 入口 ----
fn skip_to_sync(self: *Parser) {
while !self.failed {
@@ -2172,7 +2180,7 @@ fn skip_to_sync(self: *Parser) {
}
}
// 解析整个文件;Root/ContainerMembers 最后分配(与 stage1 一致)。
// 解析整个文件;Root/ContainerMembers 最后分配(#ref 顺序须与 splc0 一致)。
fn parse(self: *Parser) {
var external_tags = ref_vec();
var declarations = ref_vec();
@@ -2188,7 +2196,7 @@ fn parse(self: *Parser) {
var t2 = peek(self);
self.pos = save;
if t2 != null && kind_is_punct(t2.kind, .Not) {
parse_tag_list(self, &external_tags, true, true);
parse_tag_list(self, &external_tags, true, true, true);
continue;
}
}
@@ -2215,7 +2223,6 @@ fn parse(self: *Parser) {
self.ast.root = root;
}
// ---- 测试 ----
fn lex_tokens(src: []u8): Vec {
var out = Vec.blank(@sizeof(Token), @alignof(Token));
@@ -2279,7 +2286,7 @@ fn expect_text(buf: *ByteBuffer, expected: []u8) {
}
}
// 与 stage1 `splc0 --dump ast` 输出逐字节一致(含 #ref 与 [line:col])。
// 与 splc0 --dump ast 逐字节一致(含 #ref 与 [line:col])。
fn test_parse_decls() {
var src: []u8 = "type Point = struct { x: i32, y: i32 };\nfn f(a: i32): i32;\n";
var toks = lex_tokens(src);
@@ -2311,7 +2318,7 @@ fn test_parse_decls() {
"AST:\n`-root #13\n `-container_members #12\n |-type_decl #2 [1:1]\n | |-pattern_ident #1 [1:6]\n | `-type_aggregate #3 [1:14]\n | |-member_decl #5 [1:23]\n | | |-type_path #4 [1:26]\n | `-member_decl #7 [1:31]\n | |-type_path #6 [1:34]\n `-fn_decl #11 [2:1]\n `-param_decl #9 [2:6]\n `-type_path #8 [2:9]\n |-type_path #10 [2:15]\n");
}
// 表达式/语句/块:与 001_main.spl 的 stage1 dump 逐字节一致。
// 表达式/语句/块:与 splc0 dump 逐字节一致。
fn test_parse_main() {
var src: []u8 = "// Expect retcode = 0\n\nfn main(): i32 {\n ret 0;\n}\n";
var toks = lex_tokens(src);
@@ -2343,7 +2350,7 @@ fn test_parse_main() {
"AST:\n`-root #7\n `-container_members #6\n `-fn_decl #5 [3:1]\n |-type_path #1 [3:12]\n `-block #2 [3:16]\n `-statement_ret #4 [4:5]\n `-int_lit #3 [4:9]\n");
}
// 任意宽度整数:2^64 也能正确解析(stage1 u64 之外);含分隔符与多进制。
// 任意宽度整数:2^64 也能正确解析;含分隔符与多进制。
fn check_int(src: []u8, expected: []u8) {
var toks = lex_tokens(src);
defer { Vec.drop(&toks); }
+2 -5
View File
@@ -1,9 +1,7 @@
// Expect retcode = 0
// 作用域树(移植自 stage1/spl_scope.c)。每个作用域是一张名字 -> Symbol 表,
// 节点用 parent 指向父作用域;查找从 current_scope 沿父链上溯(支持遮蔽)。
// 名字是 ByteView(借用源/AST);Map 复制键值字节,但 ByteView 指向的字节由
// 调用方保证存活。node 字段是 def.spl 的 DefId。
// 作用域树:名字 -> Symbol,节点经 parent 上溯查找(支持遮蔽)。名字借用源字节,
// 存活由调用方保证;node 为 def.spl 的 DefId。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
@@ -134,7 +132,6 @@ fn find(self: *Scope, name: ByteView, out: *Symbol): bool {
ret false;
}
// ---- 测试 ----
fn sym(name: []u8, kind: SymbolKind, node: usize): Symbol {
ret Symbol {
+247 -245
View File
File diff suppressed because it is too large. Load diff
+25 -42
View File
@@ -1,8 +1,7 @@
// Expect retcode = 0
// splc1 (stage2 自举编译器入口)。
// 当前实现 `--dump <lex|ast|sema|ir|vm> <file> [out]`:读取源文件,按与 stage1
// splc0 完全一致的格式打印各阶段产物,供 diff 测试逐字节比对。
// splc1:自举编译器入口。`splc1 <in> <out>` 编译;`--dump <mode> <file>` 打印各阶段
// 产物,格式必须与 splc0 逐字节一致以通过 diff。
type .{ .ByteView } = @import("./utils/byte_view.spl");
type .{ .ByteBuffer } = @import("./utils/byte_buffer.spl");
@@ -13,8 +12,7 @@ type Ast = @import("./ast.spl");
type Parser = @import("./parser.spl");
type Sema = @import("./sema.spl");
type .{ .append_usize } = @import("./utils/fmt.spl");
type .{ .read_all, .print, .eprint, .open_cstr, .write_all } = @import("./utils/io.spl");
type File = @import("./sys/file.spl");
type .{ .read_all, .print, .eprint, .open_cstr, .write_all, .File } = @import("./utils/io.spl");
type .{ .Sources, .Source, .set_new, .set_add, .set_at, .set_drop } = @import("./utils/source.spl");
type .{ .Diag, .Code, .span_none } = @import("./diag.spl");
type Logger = @import("./utils/log.spl");
@@ -27,7 +25,7 @@ type .{ .Layout } = @import("./layout.spl");
type Ir2VmM = @import("./ir2vm.spl");
type .{ .Ir2Vm } = @import("./ir2vm.spl");
type Ir2CM = @import("./ir2c.spl");
type .{ .alloc, .free } = @import("./sys/mem.spl");
type .{ .alloc, .free } = @import("./utils/memory.spl");
fn token_at(tokens: *Vec, index: usize): Token {
match Vec.get(tokens, index) {
@@ -131,14 +129,11 @@ fn dump_lex(log: *Logger, path: ByteView): i32 {
}
defer { Vec.drop(&tokens); }
// 非法输入:走诊断(stage1 在此处是宽容无视,stage2 显式报错)。
// 非法输入:走诊断(显式报错,不静默)。
if Diag.has_error(diag) {
var rendered = ByteBuffer.new();
defer { ByteBuffer.drop(&rendered); }
match Diag.render_human(&diag, &rendered) {
.Ok => {},
.Err(error) => {},
}
Diag.render_human(&diag, &rendered);
eprint(ByteBuffer.as_slice(rendered));
ret 1;
}
@@ -200,10 +195,7 @@ fn dump_ast(log: *Logger, path: ByteView): i32 {
if Diag.has_error(diag) || p.failed {
var rendered = ByteBuffer.new();
defer { ByteBuffer.drop(&rendered); }
match Diag.render_human(&diag, &rendered) {
.Ok => {},
.Err(error) => {},
}
Diag.render_human(&diag, &rendered);
eprint(ByteBuffer.as_slice(rendered));
ret 1;
}
@@ -221,7 +213,6 @@ fn dump_ast(log: *Logger, path: ByteView): i32 {
ret 0;
}
// ---- @import 模块加载器(driver 侧)----
type ModEntry = struct {
path: ByteView,
@@ -236,7 +227,6 @@ type LoaderCtx = struct {
diag: *Diag,
}
fn ignore_bool(b: bool) {}
fn append_bytes(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
@@ -263,7 +253,7 @@ fn sub(p: ByteView, a: usize, b: usize): []u8 {
fn normalize_pop(out: *ByteBuffer) {
var cur = ByteBuffer.as_slice(out.*);
if cur.len == 0 {
ignore_bool(append_bytes(out, ".."));
append_bytes(out, "..");
ret;
}
var end = cur.len;
@@ -274,7 +264,7 @@ fn normalize_pop(out: *ByteBuffer) {
var start = end;
while start > 0 && cur.ptr[start - 1] != '/' { start = start - 1; }
if end - start == 2 && cur.ptr[start] == '.' && cur.ptr[start + 1] == '.' {
ignore_bool(append_bytes(out, ".."));
append_bytes(out, "..");
ret;
}
var new_len: usize = 0;
@@ -286,7 +276,7 @@ fn normalize_pop(out: *ByteBuffer) {
// 折叠重复分隔符、解析 "." 与 ".."、'\' 统一成 '/'。
fn normalize_into(out: *ByteBuffer, p: ByteView) {
if p.len > 0 && (p.ptr[0] == '/' || p.ptr[0] == '\\') {
ignore_bool(append_byte(out, '/'));
append_byte(out, '/');
}
var i: usize = 0;
while i < p.len {
@@ -302,9 +292,9 @@ fn normalize_into(out: *ByteBuffer, p: ByteView) {
}
var cur = ByteBuffer.as_slice(out.*);
if cur.len > 0 && cur.ptr[cur.len - 1] != '/' {
ignore_bool(append_byte(out, '/'));
append_byte(out, '/');
}
ignore_bool(append_bytes(out, seg));
append_bytes(out, seg);
}
}
@@ -325,9 +315,9 @@ fn resolve_path(from: ByteView, path: ByteView): ByteBuffer {
i = i + 1;
}
if last >= 0 {
ignore_bool(append_bytes(&out, sub(from, 0, (last as usize) + 1)));
append_bytes(&out, sub(from, 0, (last as usize) + 1));
}
ignore_bool(append_bytes(&out, ByteView.as_slice(path)));
append_bytes(&out, ByteView.as_slice(path));
var norm = ByteBuffer.new();
normalize_into(&norm, ByteView.from_slice(ByteBuffer.as_slice(out)));
ByteBuffer.drop(&out);
@@ -504,10 +494,7 @@ fn dump_sema(log: *Logger, path: ByteView): i32 {
if Diag.has_error(diag) || p.failed {
var rendered = ByteBuffer.new();
defer { ByteBuffer.drop(&rendered); }
match Diag.render_human(&diag, &rendered) {
.Ok => {},
.Err(error) => {},
}
Diag.render_human(&diag, &rendered);
eprint(ByteBuffer.as_slice(rendered));
ret 1;
}
@@ -538,10 +525,7 @@ fn dump_sema(log: *Logger, path: ByteView): i32 {
if Diag.has_error(diag) {
var rendered = ByteBuffer.new();
defer { ByteBuffer.drop(&rendered); }
match Diag.render_human(&diag, &rendered) {
.Ok => {},
.Err(error) => {},
}
Diag.render_human(&diag, &rendered);
eprint(ByteBuffer.as_slice(rendered));
ret 1;
}
@@ -573,7 +557,7 @@ type PipeMode = enum {
fn step(mode: PipeMode, s: []u8) {
if @enum2int(mode) == @enum2int(PipeMode.State) {
match eprint(s) { .Ok => {}, .Err(error) => {} }
eprint(s);
}
}
@@ -631,7 +615,7 @@ fn run_pipeline(log: *Logger, path: ByteView, mode: PipeMode, outpath: ByteView)
if Diag.has_error(diag) || p.failed {
var rendered = ByteBuffer.new();
defer { ByteBuffer.drop(&rendered); }
match Diag.render_human(&diag, &rendered) { .Ok => {}, .Err(error) => {} }
Diag.render_human(&diag, &rendered);
eprint(ByteBuffer.as_slice(rendered));
ret 1;
}
@@ -662,7 +646,7 @@ fn run_pipeline(log: *Logger, path: ByteView, mode: PipeMode, outpath: ByteView)
if Diag.has_error(diag) {
var rendered = ByteBuffer.new();
defer { ByteBuffer.drop(&rendered); }
match Diag.render_human(&diag, &rendered) { .Ok => {}, .Err(error) => {} }
Diag.render_human(&diag, &rendered);
eprint(ByteBuffer.as_slice(rendered));
ret 1;
}
@@ -677,13 +661,13 @@ fn run_pipeline(log: *Logger, path: ByteView, mode: PipeMode, outpath: ByteView)
var asts = Vec.blank(@sizeof(usize), @alignof(usize));
defer { Vec.drop(&asts); }
var ap: *Ast = &ast;
match Vec.push(&asts, &ap as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&asts, &ap as *u8);
var mi: usize = 0;
while mi < ctx.mods.len {
var m = mod_at(&ctx, mi);
if m != null && m.ok && m.ast != null {
var mp: *Ast = m.ast;
match Vec.push(&asts, &mp as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&asts, &mp as *u8);
}
mi = mi + 1;
}
@@ -692,7 +676,7 @@ fn run_pipeline(log: *Logger, path: ByteView, mode: PipeMode, outpath: ByteView)
if Diag.has_error(diag) {
var rendered = ByteBuffer.new();
defer { ByteBuffer.drop(&rendered); }
match Diag.render_human(&diag, &rendered) { .Ok => {}, .Err(error) => {} }
Diag.render_human(&diag, &rendered);
eprint(ByteBuffer.as_slice(rendered));
ret 1;
}
@@ -736,8 +720,8 @@ fn run_pipeline(log: *Logger, path: ByteView, mode: PipeMode, outpath: ByteView)
Logger.error(log, "cannot open C output file");
ret 1;
}
match write_all(&f, ByteBuffer.as_slice(cout)) { .Ok => {}, .Err(error) => {} }
ignore_i32(File.close(&f));
write_all(&f, ByteBuffer.as_slice(cout));
File.close(&f);
} else {
match print(ByteBuffer.as_slice(cout)) {
.Ok => {},
@@ -754,7 +738,7 @@ fn run_pipeline(log: *Logger, path: ByteView, mode: PipeMode, outpath: ByteView)
var ir2vm: Ir2Vm = undefined;
Ir2VmM.init(&ir2vm, &builder.ir, &sema.types.ir, &layout, &sema.attr);
defer { Ir2VmM.drop(&ir2vm); }
ignore_i32(Ir2VmM.run(&ir2vm));
Ir2VmM.run(&ir2vm);
step(mode, "state: ir2vm ok\n");
if @enum2int(mode) == @enum2int(PipeMode.Vm) {
@@ -782,7 +766,6 @@ fn run_pipeline(log: *Logger, path: ByteView, mode: PipeMode, outpath: ByteView)
ret 0;
}
fn ignore_i32(v: i32) {}
fn main(argc: i32, argv: **u8): i32 {
// 无参数:自测运行(`nob test stage2`)视为成功。
+8 -1
View File
@@ -8,6 +8,13 @@ type spl_vm_val_t = u64; // usize
#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;
// TODO
#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: u64): i32;
fn main() {}
+2 -4
View File
@@ -1,7 +1,7 @@
// Expect retcode = 0
// 词法单元:用带载荷 ADT 表达 TokenKind;关键词/算符各自独立 enum。
// 整型与字符在词法期解码并随载荷携带;文本一律借用源切片(不复制)。
// 词法单元:TokenKind 为带载荷 ADT,关键词/算符各自独立 enum;整型/字符在词法期
// 解码,文本一律借用源切片。
type .{ .ByteView } = @import("utils/byte_view.spl");
@@ -128,7 +128,6 @@ fn keyword_of(text: ByteView): KeywordResult {
ret .No;
}
// ---- token 类型名(与 stage1 spl_tok_type_name 逐字一致,供 dump/diff 使用)----
fn keyword_name(kw: Keyword): []u8 {
match kw {
@@ -242,7 +241,6 @@ fn kind_name(kind: TokenKind): []u8 {
ret "?";
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
+7 -28
View File
@@ -1,11 +1,7 @@
// Expect retcode = 0
// IR 类型表(移植自 stage1/spl_type.c)。类型按结构 hash-consing(intern),
// id 0 为保留哨兵(Error)。节点借用式持有:名称是 ByteView(指向源/AST),
// 不复制字符串;聚合成员与函数参数的 Vec 由本表拥有,drop 时统一释放。
//
// hash 只用于选桶;相等永远由结构比较决定。桶以「完整 hash -> 链头 id」的
// Map 存储,节点自带 hash_next 串链(对应 stage1 的 spl_fold)。
// IR 类型表:按结构 hash-consing。id 0 为保留哨兵(Error)。成员/参数 Vec 由本表
// 拥有;hash 仅用于选桶,相等始终由结构比较决定。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
@@ -41,7 +37,7 @@ type AggKind = enum {
Shape,
}
// 与 stage1 spl_type_node_kind_t 一一对应;Forall/Exists 保留(暂打印 quant)。
// 变体顺序即 kind 数值;Forall/Exists 暂按 quant 打印。
type TypeNode = enum {
Error,
Never,
@@ -78,7 +74,6 @@ type TypeTableResult = enum {
Err: Error,
}
// ---- hash(FNV 风格;值不必与 stage1 相同,只要结构一致即可)----
fn seed(): usize {
ret 14695981039346656037;
@@ -290,7 +285,6 @@ fn free_payload(n: *TypeNode) {
}
}
// ---- 底层访问 ----
fn usize_at(v: Vec, i: usize): usize {
match Vec.get(&v, i) {
@@ -317,13 +311,12 @@ fn push_member(v: *Vec, name: []u8, type_id: usize) {
}
}
// id 0 与越界均返回 null(对应 stage1 spl_type_node)。
// id 0 与越界均返回 null。
fn node(self: *TypeTable, id: usize): *TypeEntry {
if id == 0 || id >= self.table.len { ret null; }
ret (self.table.data as *TypeEntry) + id;
}
// ---- 生命周期 ----
fn new(): TypeTableResult {
var tt = TypeTable {
@@ -376,7 +369,6 @@ fn define(self: *TypeTable, id: usize, src: *TypeNode) {
src.* = .Error;
}
// ---- intern ----
fn fold_find(self: *TypeTable, hash: usize, probe: *TypeNode): usize {
var head: usize = 0;
@@ -403,10 +395,7 @@ fn fold_insert(self: *TypeTable, hash: usize, id: usize) {
var n = node(self, id);
if n == null { ret; }
n.hash_next = old;
match Map.put(&self.fold, &hash as *u8, &id as *u8) {
.Ok => {},
.Err(error) => {},
}
Map.put(&self.fold, &hash as *u8, &id as *u8);
}
// intern 一个 probe:命中则释放 probe 载荷并返回已有 id;否则复制入表。
@@ -433,7 +422,6 @@ fn push(self: *TypeTable, probe: *TypeNode): usize {
ret id;
}
// ---- builders ----
fn make_error(self: *TypeTable): usize {
var n: TypeNode = .Error;
@@ -513,7 +501,6 @@ fn make_agg(self: *TypeTable, kind: AggKind, agg: Agg): usize {
ret push(self, &n);
}
// ---- 查询 ----
fn is_subtype(self: *TypeTable, sub: usize, super: usize): bool {
if sub == 0 || super == 0 { ret false; }
@@ -597,7 +584,6 @@ fn agg_member_idx(self: *TypeTable, tid: usize, name: ByteView, out_idx: *usize)
ret false;
}
// ---- dump(镜像 stage1 spl_type_pure_dump)----
fn push_out(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
@@ -637,10 +623,7 @@ fn dump_rec(self: *TypeTable, id: usize, out: *ByteBuffer, stack: *Vec): bool {
if n == null {
if !push_out(out, "none") { ret false; }
var popped: usize = 0;
match Vec.pop(stack, &popped as *u8) {
.Ok => {},
.Err(error) => {},
}
Vec.pop(stack, &popped as *u8);
ret true;
}
@@ -698,10 +681,7 @@ fn dump_rec(self: *TypeTable, id: usize, out: *ByteBuffer, stack: *Vec): bool {
}
var dropped: usize = 0;
match Vec.pop(stack, &dropped as *u8) {
.Ok => {},
.Err(error) => {},
}
Vec.pop(stack, &dropped as *u8);
ret ok;
}
@@ -739,7 +719,6 @@ fn pure_dump_text(self: *TypeTable, id: usize): ByteBuffer {
ret out;
}
// ---- 测试 ----
fn test_intern_simple() {
var tt: TypeTable = undefined;
-1
View File
@@ -155,7 +155,6 @@ fn stable_sort(data: *u8, len: usize, elem_size: usize,
ret .Ok;
}
// ---- 测试 ----
type Item = struct {
key: i32,
-1
View File
@@ -127,7 +127,6 @@ fn drop(self: *Arena) {
self.current = 0;
}
// ---- 测试辅助 ----
fn is_aligned(p: *u8, align: usize): bool {
ret ((p as usize) & (align - 1)) == 0;
+1 -1
View File
@@ -26,7 +26,7 @@ fn new(): ByteBuffer {
fn with_capacity(cap: usize): ByteBuffer {
var b = new();
match reserve(&b, cap) { .Ok => {}, .Err(error) => {} }
reserve(&b, cap);
ret b;
}
+2 -4
View File
@@ -9,8 +9,8 @@ type .{ .ByteView } = @import("byte_view.spl");
type .{ .Value, .int, .uint, .char, .str, .addr } = @import("value.spl");
type .{ .BigInt, .Bits } = @import("mp.spl");
// 注意:radix 边界直接用字面量。stage1 刻意不做常量求值/折叠,
// 顶层 const 不应用于运行时表达式。
// radix 边界直接用字面量:顶层 const 不参与运行时常量折叠。
fn valid_radix(radix: u8): bool {
ret radix >= 2 && radix <= 36;
}
@@ -71,7 +71,6 @@ fn append_bool(out: *ByteBuffer, value: bool): Status {
ret ByteBuffer.append(out, "false");
}
// ---- 显式装箱值格式化 ----
// Int/Uint 落到整数;signed 仅对 Int 的十进制生效,其余按无符号位模式输出。
fn append_value_int(out: *ByteBuffer, value: Value, radix: u8, uppercase: bool,
@@ -223,7 +222,6 @@ fn format(out: *ByteBuffer, fmt: []u8, args: []Value): Status {
ret ByteBuffer.append(out, ByteBuffer.as_slice(temp));
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
-2
View File
@@ -34,7 +34,6 @@ fn hash_usize_value(value: usize): usize {
ret h;
}
// ---- map 回调 ----
// 键按 usize 解释。
fn hash_usize(key: *u8): usize {
@@ -55,7 +54,6 @@ fn eq_view(a: *u8, b: *u8): bool {
ret ByteView.eq((a as *ByteView).*, (b as *ByteView).*);
}
// ---- 测试辅助 ----
fn expect_hash(view: []u8, expected: usize) {
var got = hash_bytes(view.ptr, view.len);
+2 -7
View File
@@ -1,11 +1,7 @@
// Expect retcode = 0
// I/O 便利层(构建在 sys/file 之上):
// - C 字符串路径/模式的 open 包装
// - 精确读取、完整写入和普通文件整读
// - stdout/stderr 打印
// 说明:read_all 会按文件大小一次性读入 ByteBuffer;不处理增长中的文件。
// 短读、短写后的零进展及关闭失败返回 Err(.Io);文件写入不承诺回滚。
// sys/file 之上的 I/O 便利层:C 字符串路径 open、精确读取/完整写入、整读、stdout/stderr 打印。
// 短读/短写零进展与关闭失败返回 Err(.Io);写入失败不承诺回滚。
type .{ .Error, .Status, .make } = @import("error.spl");
type .{ .ByteView } = @import("byte_view.spl");
@@ -130,7 +126,6 @@ fn read_all(path: ByteView, out: *ByteBuffer): Status {
ret .Ok;
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
+3 -9
View File
@@ -1,10 +1,6 @@
// Expect retcode = 0
// 轻量 JSON 解析 / 输出器(递归下降 + 节点池),用于验证底层库的拼装,未来服务 LSP。
// 设计:
// - 输入 ByteView,字符串/数字以“源切片”借用,不做解码,round-trip 保真;
// - 节点池 Vec[JsonNode];数组/对象子项存 Vec[JsonChild],保留插入顺序;
// - 错误带字节位置(error.spl);输出写 ByteBuffer;缩进/数字用 ByteBuffer/fmt。
// 限制:不做字符串转义解码、数字不做数值化(原样保存);递归/输出深度上限见 max_depth()。
// 轻量 JSON 解析/输出器:输入按源切片借用、不解码(round-trip 保真),数字不做数值化。
// 节点/子项存 Vec 保留插入顺序;输出写 ByteBuffer。递归/输出深度上限见 max_depth()。
type .{ .Error, .Status, .make, .at } = @import("error.spl");
type .{ .ByteView, .ViewResult, .FindResult } = @import("byte_view.spl");
@@ -393,7 +389,7 @@ fn root_index(doc: *Json): usize {
ret doc.root;
}
// 枚举 tag 取整(stage1 枚举 == 有缺陷,用 @enum2int 比较更稳妥)。
// 枚举 tag 取整:枚举 == 不可靠,用 @enum2int 比较。
fn kind_code(kind: JsonKind): usize {
ret @enum2int(kind) as usize;
}
@@ -578,7 +574,6 @@ fn emit_pretty(out: *ByteBuffer, doc: *Json, indent: usize): Status {
ret emit(out, doc, doc.root, indent, 0);
}
// ---- 构造辅助(写 JSON 片段;字符串需由调用方保证已转义)----
fn write_int(out: *ByteBuffer, value: i64): Status {
ret append_i64(out, value, 10, false);
@@ -588,7 +583,6 @@ fn write_u64(out: *ByteBuffer, value: u64): Status {
ret append_u64(out, value, 10, false);
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
-2
View File
@@ -89,7 +89,6 @@ fn fatal(self: *Logger, message: []u8) {
Exit.fail();
}
// ---- 格式化入口(显式装箱,见 value.spl / fmt.format)----
// 先格式化到临时缓冲;格式错误在写出前返回 Err(.InvalidFormat)。
fn logf(self: *Logger, level: Level, fmt: []u8, args: []Value): Status {
@@ -125,7 +124,6 @@ fn fatalf(self: *Logger, fmt: []u8, args: []Value) {
Exit.fail();
}
// ---- 测试 ----
fn expect_name(level: Level, expected: []u8) {
@assert(ByteView.eq(ByteView.from_slice(level_name(level)),
-1
View File
@@ -99,7 +99,6 @@ fn parse_frame(input: ByteView, body_out: *ByteBuffer): FrameResult {
ret .Ok(body_start + content_len);
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
-1
View File
@@ -155,7 +155,6 @@ fn take(source: *Map): Map {
ret result;
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
+13 -3
View File
@@ -1,13 +1,23 @@
// Expect retcode = 0
// 尺寸计算和字节移动;不分配、不释放内存,不改变任何资源的所有权。
// 尺寸计算、字节移动与内存分配统一门面(分配/释放转发自 sys/mem)。
// 本模块不改变任何资源的所有权。
type .{ .Error, .Status, .make } = @import("error.spl");
type SysMem = @import("../sys/mem.spl");
// 分配/释放/字节操作转发(core 只经本模块使用内存,不直接依赖 sys)。
fn alloc(sz: usize): *any { ret SysMem.alloc(sz); }
fn free(p: *any) { SysMem.free(p); }
fn realloc(p: *any, sz: usize): *any { ret SysMem.realloc(p, sz); }
fn copy(dst: *any, src: *any, n: usize): *any { ret SysMem.copy(dst, src, n); }
fn cmp(a: *any, b: *any, n: usize): isize { ret SysMem.cmp(a, b, n); }
fn set(dst: *any, byte: u8, n: usize): *any { ret SysMem.set(dst, byte, n); }
fn zero(dst: *any, n: usize): *any { ret SysMem.zero(dst, n); }
#extern(vm) fn vm_memcpy(dst: *any, src: *any, n: usize): *any;
#extern(vm) fn vm_memmove(dst: *any, src: *any, n: usize): *any;
fn ignore_ptr(p: *any) {}
type SizeResult = enum {
Ok: usize,
@@ -75,7 +85,7 @@ fn move(dst: []u8, src: []u8): Status {
if dst_addr == src_addr { ret .Ok; }
// 重叠安全,统一走原生 memmove。
ignore_ptr(vm_memmove(dst.ptr as *any, src.ptr as *any, count));
vm_memmove(dst.ptr as *any, src.ptr as *any, count);
ret .Ok;
}
-1
View File
@@ -297,7 +297,6 @@ fn normalize_into(out: *ByteBuffer, path: ByteView, style: PathStyle): Status {
ret .Ok;
}
// ---- 测试 ----
fn expect_ok(result: Status) {
match result { .Ok => {}, .Err(error) => { @assert(false, "unexpected path error"); }, }
}
+6 -12
View File
@@ -1,10 +1,7 @@
// Expect retcode = 0
// 全量热点/耗时记录器(配合 @file_name()/@line()/@col() 与 sys/time.spl)。
// 每个调用点聚合:count、独占(self)与包含(total)的 steps/ns。
// - total_* 含被调用者(嵌套会重复,跨站点求和会超过墙钟)
// - self_* = total_* - 子区间之和,用于定位真正的热点
// 用法(严格 LIFO,defer 正好满足):
// 采样热点记录器:每个调用点聚合 count 与 self/total 的 steps/ns(self = total 减子区间)。
// 严格 LIFO,用 defer 配对:
// var tok = Profile.begin(&prof, @file_name(), @line(), @col());
// defer { Profile.end(&prof, tok); }
@@ -139,7 +136,7 @@ fn begin(self: *Profile, fname: []u8, line: usize, col: usize): usize {
.Err(error) => { ret 0; },
}
var token = self.spans.len - 1;
match Vec.push(&self.stack, &token as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&self.stack, &token as *u8);
ret token;
}
@@ -164,7 +161,7 @@ fn end(self: *Profile, token: usize) {
// 弹栈并把区间计入父 span(LIFO)。
var popped: usize = 0;
match Vec.pop(&self.stack, &popped as *u8) { .Ok => {}, .Err(error) => {} }
Vec.pop(&self.stack, &popped as *u8);
var n = self.stack.len;
if n > 0 {
var p = span_at(self, usize_at(&self.stack, n - 1));
@@ -175,7 +172,6 @@ fn end(self: *Profile, token: usize) {
}
}
// ---- dump / save ----
fn out_s(out: *ByteBuffer, s: []u8): bool {
match ByteBuffer.append(out, s) { .Ok => { ret true; }, .Err(error) => { ret false; } }
@@ -202,7 +198,7 @@ fn dump(self: *Profile, out: *ByteBuffer): bool {
defer { Vec.drop(&idx); }
var i: usize = 0;
while i < self.sites.len {
match Vec.push(&idx, &i as *u8) { .Ok => {}, .Err(error) => {} }
Vec.push(&idx, &i as *u8);
i = i + 1;
}
@@ -271,7 +267,6 @@ fn save(self: *Profile, path: ByteView): bool {
ret true;
}
// ---- 测试 ----
fn spin(n: usize): usize {
var i: usize = 0;
@@ -293,10 +288,9 @@ fn test_profile() {
@assert(s != null && s.count >= 1, "count");
@assert(s.total_steps > 0, "steps");
@assert(s.self_steps > 0, "self steps");
if v == 0 { ignore_usize(v + 1); }
if v == 0 { v + 1; }
}
fn ignore_usize(v: usize) {}
fn main() {
test_profile();
-1
View File
@@ -74,7 +74,6 @@ fn drop(self: *Set) {
Map.drop(&self.map);
}
// ---- 测试 ----
fn expect_ok(result: Status) {
match result {
-2
View File
@@ -123,7 +123,6 @@ fn drop(self: *Source) {
Vec.drop(&self.line_starts);
}
// ---- 多文件集合 ----
type Sources = struct {
items: Vec, // Source
@@ -191,7 +190,6 @@ fn set_drop(set: *Sources) {
Map.drop(&set.by_name);
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
-1
View File
@@ -122,7 +122,6 @@ fn drop(self: *Str) {
ByteBuffer.drop(&self.storage);
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
-1
View File
@@ -181,7 +181,6 @@ fn utf16_to_byte(data: *u8, len: usize, utf16_off: usize): usize {
ret i;
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
-1
View File
@@ -43,7 +43,6 @@ fn addr(value: *any): Value {
ret .Ptr(value);
}
// ---- 测试 ----
fn test_int_and_uint() {
match int(-5) {
+155
View File
@@ -0,0 +1,155 @@
// Expect retcode = 0
type Pair = struct {
x: i32,
y: i32,
}
type Option = enum {
None,
Some: i32,
}
type Nested = struct {
inner: Pair,
tag: i32,
}
// 对照:无 & 的值绑定是拷贝,写回不作用于源。
fn test_value_binding_is_copy() {
var p: Pair = .{ .x = 1, .y = 2 };
var .{ .x = a, .y = b } = p;
a = 10;
b = 20;
@assert(a == 10, "value binding a is local copy");
@assert(p.x == 1, "value binding does not write back x");
@assert(p.y == 2, "value binding does not write back y");
}
// 普通结构体解构:& 引用绑定。
fn test_struct_ref_binding() {
var p: Pair = .{ .x = 1, .y = 2 };
var .{ .x = &a, .y = &b } = p;
@assert(a.* == 1, "struct ref reads x");
@assert(b.* == 2, "struct ref reads y");
a.* = 10;
b.* = 20;
@assert(p.x == 10, "struct ref writes back x");
@assert(p.y == 20, "struct ref writes back y");
}
// 混合:值绑定 + 引用绑定。
fn test_struct_mixed_binding() {
var p: Pair = .{ .x = 1, .y = 2 };
var .{ .x = val, .y = &ref } = p;
@assert(val == 1, "mixed value reads x");
val = 100;
ref.* = 200;
@assert(p.x == 1, "mixed value does not write back");
@assert(p.y == 200, "mixed ref writes back");
}
// 部分字段 & 引用绑定。
fn test_struct_partial_ref() {
var p: Pair = .{ .x = 1, .y = 2 };
var .{ .y = &b } = p;
b.* = 99;
@assert(p.y == 99, "partial ref writes back y");
@assert(p.x == 1, "partial ref leaves x untouched");
}
// 嵌套结构体解构:& 引用绑定。
fn test_nested_ref() {
var n: Nested = .{ .inner = .{ .x = 1, .y = 2 }, .tag = 3 };
var .{ .inner = .{ .x = &a, .y = &b }, .tag = &t } = n;
a.* = 7;
b.* = 8;
t.* = 9;
@assert(n.inner.x == 7, "nested ref writes back inner.x");
@assert(n.inner.y == 8, "nested ref writes back inner.y");
@assert(n.tag == 9, "nested ref writes back tag");
}
// 源本身是左值子表达式(字段):& 引用绑定。
fn test_field_source_ref() {
var n: Nested = .{ .inner = .{ .x = 1, .y = 2 }, .tag = 3 };
var .{ .x = &a, .y = &b } = n.inner;
a.* = 11;
b.* = 12;
@assert(n.inner.x == 11, "field source ref writes back x");
@assert(n.inner.y == 12, "field source ref writes back y");
}
// 枚举解构:& 引用绑定。
fn test_enum_ref() {
var o: Option = .Some(1);
var .Some(&n) = o;
@assert(n.* == 1, "enum ref reads payload");
n.* = 42;
match o {
.None => { @assert(false, "enum ref: expected Some"); },
.Some(m) => { @assert(m == 42, "enum ref writes back payload"); },
}
}
// 元组解构:& 引用绑定。
fn test_tuple_ref() {
var t: (i32, i32) = (1, 2);
var (&a, &b) = t;
@assert(a.* == 1, "tuple ref reads [0]");
@assert(b.* == 2, "tuple ref reads [1]");
a.* = 10;
b.* = 20;
@assert(t[0] == 10, "tuple ref writes back [0]");
@assert(t[1] == 20, "tuple ref writes back [1]");
}
// if var:& 引用绑定(枚举)。
fn test_ifvar_enum_ref() {
var o: Option = .Some(1);
if var .Some(&n) = o {
n.* = 77;
}
match o {
.None => { @assert(false, "if var ref: expected Some"); },
.Some(m) => { @assert(m == 77, "if var ref writes back payload"); },
}
}
// if var:& 引用绑定(元组)。
fn test_ifvar_tuple_ref() {
var t: (i32, i32) = (1, 2);
if var (&a, &b) = t {
a.* = 5;
b.* = 6;
}
@assert(t[0] == 5, "if var tuple ref writes back [0]");
@assert(t[1] == 6, "if var tuple ref writes back [1]");
}
// match arm:& 引用绑定。
fn test_match_enum_ref() {
var o: Option = .Some(1);
match o {
.None => { @assert(false, "match ref: expected Some"); },
.Some(&n) => { n.* = 55; },
}
match o {
.None => { @assert(false, "match ref: expected Some after"); },
.Some(m) => { @assert(m == 55, "match arm ref writes back payload"); },
}
}
fn main() {
test_value_binding_is_copy();
test_struct_ref_binding();
test_struct_mixed_binding();
test_struct_partial_ref();
test_nested_ref();
test_field_source_ref();
test_enum_ref();
test_tuple_ref();
test_ifvar_enum_ref();
test_ifvar_tuple_ref();
test_match_enum_ref();
}