// shape 子系统:声明期绑定 adapter,调用点校验并生成实例。 // 通过 Sema 的 ShapeHooks 从 sema 反向调用,避免两个模块互相 import。 type .{ .Vec } = @import("../stage2/utils/vec.spl"); type .{ .ByteBuffer } = @import("../stage2/utils/byte_buffer.spl"); type .{ .append_usize } = @import("../stage2/utils/fmt.spl"); type LangType = @import("./lang_type.spl"); type Bld = @import("./spl_ir_builder.spl"); type NodeClone = @import("./node_clone.spl"); type .{ .Ref } = @import("./builtins/spl_ir.spl"); type .{ .ErrorCode } = @import("./builtins/error_code.spl"); type SemaM = @import("./sema.spl"); type Sema = SemaM.Sema; type ShapeParam = SemaM.ShapeParam; type ShapeInstance = SemaM.ShapeInstance; type ShapeUse = SemaM.ShapeUse; type ShapeAdapterResult = SemaM.ShapeAdapterResult; type ShapeAdapterEval = SemaM.ShapeAdapterEval; type ShapeTypeBind = SemaM.ShapeTypeBind; type CtFnRef = SemaM.CtFnRef; type Decl = SemaM.Decl; type ShapeCallResult = SemaM.ShapeCallResult; type ShapeHooks = SemaM.ShapeHooks; type ShapeComp = SemaM.ShapeComp; type ShapeBind = SemaM.ShapeBind; fn shape_bind_find(binds: *Vec, name: []u8): usize { var i: usize = 0; while i < binds.len { var b = (binds.data as *ShapeBind) + i; if SemaM.eq(b.name, name) { ret b.lang; } i = i + 1; } ret 0; } fn shape_bind_put(self: *Sema, binds: *Vec, name: []u8, lang: usize): bool { var old = shape_bind_find(binds, name); if old != 0 { if old == lang { ret true; } SemaM.sema_error_code(self, ErrorCode.ShapeAssocMismatch, "associated type binding mismatch", name); ret false; } var b = ShapeBind { .name = name, .lang = lang }; match Vec.push(binds, &b as *u8) { .Ok => { ret true; }, .Err(error) => { ret false; }, } ret false; } fn shape_use_shape_count(self: *Sema, ref: Ref): usize { var n = Bld.node_ptr(&self.hir, ref); if n == null { ret 0; } match n.kind { .ShapeUse(x) => { ret x.shapes.len; }, _ => {}, } ret 1; } fn shape_use_shape_at(self: *Sema, ref: Ref, i: usize): Ref { var n = Bld.node_ptr(&self.hir, ref); if n == null { ret 0; } match n.kind { .ShapeUse(x) => { if i < x.shapes.len { ret x.shapes[i]; } ret 0; }, _ => {}, } if i == 0 { ret ref; } ret 0; } fn shape_apply_binds(self: *Sema, shape_ref: Ref, binds: *Vec): bool { var n = Bld.node_ptr(&self.hir, shape_ref); if n == null { ret true; } match n.kind { .ShapeApply(x) => { var i: usize = 0; while i < x.binds.len { var bn = Bld.node_ptr(&self.hir, x.binds[i]); if bn != null { match bn.kind { .AssocBind(b) => { var l = SemaM.resolve_type(self, b.ty); if !shape_bind_put(self, binds, b.name, l) { ret false; } }, _ => {}, } } i = i + 1; } }, _ => {}, } ret true; } // shape 声明上的 marker 绑定作为默认值;使用点显式绑定优先后合并。 fn shape_marker_binds(self: *Sema, value_lang: usize, shape_lang: usize, binds: *Vec): bool { if SemaM.lang_conform_binds(self, value_lang, shape_lang, binds) { ret true; } var cont = LangType.container_of(&self.types, value_lang); if cont == 0 { ret true; } var n = Bld.node_ptr(&self.hir, cont); if n == null { ret true; } var ok = true; match n.kind { .AggType(a) => { var i: usize = 0; while i < a.conforms.len { var cref = a.conforms[i]; var sl = SemaM.resolve_type(self, cref); if sl == shape_lang { if !shape_apply_binds(self, cref, binds) { ok = false; } } i = i + 1; } }, _ => {}, } ret ok; } fn shape_assoc_names_bound(self: *Sema, shape_lang: usize, binds: *Vec): bool { var cont = LangType.container_of(&self.types, shape_lang); if cont == 0 { ret true; } var n = Bld.node_ptr(&self.hir, cont); if n == null { ret true; } var ok = true; match n.kind { .AggType(a) => { var i: usize = 0; while i < a.decls.len { var dn = Bld.node_ptr(&self.hir, a.decls[i]); if dn != null { match dn.kind { .AssocDecl(x) => { if shape_bind_find(binds, x.name) == 0 { SemaM.sema_error_code(self, ErrorCode.ShapeAssocUnbound, "associated type is not bound", x.name); ok = false; } }, _ => {}, } } i = i + 1; } }, _ => {}, } ret ok; } // ---- shape:声明期绑定 adapter、调用点生成实例 ---- fn shape_param_at(self: *Sema, fn_ref: Ref, param_index: usize): usize { var i: usize = 0; while i < self.shape_state.params.len { var p = (self.shape_state.params.data as *ShapeParam) + i; if p.fn_ref == fn_ref && p.param_index == param_index { ret i + 1; } i = i + 1; } ret 0; } fn is_shape_lang(self: *Sema, lang: usize): bool { var cont = LangType.container_of(&self.types, lang); if cont == 0 { ret false; } var m = LangType.container_mod_of(&self.types, lang); var saved = self.cur_mod; if m != saved { SemaM.switch_mod(self, m); } var n = Bld.node_ptr(&self.hir, cont); var is_shape = false; if n != null { match n.kind { .AggType(a) => { match a.kind { .Shape => { is_shape = true; }, _ => {}, } }, _ => {}, } } if m != saved { SemaM.switch_mod(self, saved); } ret is_shape; } // 找到该 shape 参数显式挂载的 adapter 名,例如 `@alloc[Allocator]` 的 `alloc`。 fn at_tag_name(self: *Sema, ref: Ref): []u8 { var n = Bld.node_ptr(&self.hir, ref); if n == null { ret ""; } var i: usize = 0; while i < n.tags.len { var tn = Bld.node_ptr(&self.hir, n.tags[i]); if tn != null { match tn.kind { .Tag(x) => { if x.is_at { ret x.name; } }, _ => {}, } } i = i + 1; } ret ""; } // `@name[Shape]` 只按 name 查找 adapter hook;不再扫描模块里的唯一候选。 fn find_shape_adapter(self: *Sema, name: []u8): usize { var d = SemaM.find_decl(self, name); if d == 0 { SemaM.sema_error_code(self, ErrorCode.ImplHookNotFound, "shape adapter not found", name); ret 0; } var di = d - 1; var is_fn = false; match SemaM.decl_at(self, di).kind { .Fn => { is_fn = true; }, _ => {} } if !is_fn { SemaM.sema_error_code(self, ErrorCode.ImplHookNotFound, "shape adapter not found", name); ret 0; } SemaM.ensure_decl(self, di); var node = SemaM.decl_at(self, di).node; var n = Bld.node_ptr(&self.hir, node); if n == null { ret 0; } var params_len: usize = 0; match n.kind { .FnDecl(f) => { params_len = f.params.len; }, _ => {}, } if !SemaM.has_tag(self, node, "macro") { SemaM.sema_error_code(self, ErrorCode.ImplHookNotMacro, "shape adapter must be macro", name); ret 0; } if params_len != 2 || !SemaM.is_impl_hook(self, node) { SemaM.sema_error_code(self, ErrorCode.ImplHookArgCount, "shape adapter expects two type parameters", name); ret 0; } ret d; } // `@name[Shape]` 是 type-only shape 使用点;这里解析显式 adapter 名和 shape 类型。 // 组合 shape 的同名方法必须兼容;不同签名直接报 E0320。 fn compose_conflicts(self: *Sema, use_ref: Ref): bool { var count = shape_use_shape_count(self, use_ref); var i: usize = 0; while i < count { var si = SemaM.resolve_type(self, shape_use_shape_at(self, use_ref, i)); var ci = LangType.container_of(&self.types, si); var ni = Bld.node_ptr(&self.hir, ci); if ni != null { var j: usize = i + 1; while j < count { var sj = SemaM.resolve_type(self, shape_use_shape_at(self, use_ref, j)); var cj = LangType.container_of(&self.types, sj); var nj = Bld.node_ptr(&self.hir, cj); if nj != null { match ni.kind { .AggType(ai) => { var k: usize = 0; while k < ai.decls.len { var dn = Bld.node_ptr(&self.hir, ai.decls[k]); if dn != null { match dn.kind { .FnDecl(f) => { var other = SemaM.method_sym(self, sj, f.name); var own = SemaM.method_sym(self, si, f.name); if other != 0 && own != 0 { var binds = Vec.blank(@sizeof(ShapeBind), @alignof(ShapeBind)); var reported = false; var same = shape_type_match(self, SemaM.sym_at(self, own - 1).fn_tid, SemaM.sym_at(self, other - 1).fn_tid, si, sj, &binds, &reported); Vec.drop(&binds); if !same { SemaM.sema_error_code(self, ErrorCode.ShapeMethodConflict, "shape method conflict", f.name); ret true; } } }, _ => {}, } } k = k + 1; } }, _ => {}, } } j = j + 1; } } i = i + 1; } ret false; } // `A + B` 在原始函数体里需要一个合并方法集的临时 shape;实例化后仍按真实类型替换。 fn compose_shapes(self: *Sema, use_ref: Ref): usize { var count = shape_use_shape_count(self, use_ref); if count <= 1 { ret 0; } if compose_conflicts(self, use_ref) { ret 0; } var parts = Vec.blank(@sizeof(usize), @alignof(usize)); var i: usize = 0; while i < count { var sr = shape_use_shape_at(self, use_ref, i); var sl = SemaM.resolve_type(self, sr); match Vec.push(&parts, &sl as *u8) { .Ok => {}, .Err(error) => { Vec.drop(&parts); ret 0; }, } i = i + 1; } var empty: [1]Ref = .[0]; var agg = Bld.construct(&self.hir, .{ .kind = .AggType(.{ .kind = .Shape, .conforms = empty[0..0], .fields = empty[0..0], .decls = empty[0..0], .injected = empty[0..0], }) }); if agg == 0 { Vec.drop(&parts); ret 0; } self.shape_state.seq = self.shape_state.seq + 1; var lang = LangType.declare_struct(&self.types); LangType.set_container(&self.types, lang, self.cur_mod, agg); LangType.set_name(&self.types, lang, "__shape_comp"); var rec = ShapeComp { .lang = lang, .parts = parts }; match Vec.push(&self.shape_state.composed, &rec as *u8) { .Ok => {}, .Err(error) => { Vec.drop(&parts); ret 0; }, } ret lang; } fn shape_use_of(self: *Sema, ty_ref: Ref): ShapeUse { var out = ShapeUse { .is_shape = false, .adapter_decl = 0, .shape_lang = 0, .shape_ref = 0 }; if ty_ref == 0 { ret out; } var n = Bld.node_ptr(&self.hir, ty_ref); if n == null { ret out; } var adapter_name: []u8 = ""; match n.kind { .ShapeUse(x) => { adapter_name = x.adapter; }, _ => { var old = at_tag_name(self, ty_ref); if old.len != 0 { SemaM.sema_error_code(self, ErrorCode.Syntax, "shape use requires @adapter[Shape]", old); } ret out; }, } if shape_use_shape_count(self, ty_ref) == 0 { ret out; } var first = shape_use_shape_at(self, ty_ref, 0); var shape_lang = SemaM.type_arg_lang(self, first); if shape_lang != 0 && !is_shape_lang(self, shape_lang) { SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape, "shape parameter type is not a shape", adapter_name); ret out; } if shape_lang == 0 { ret out; } if shape_use_shape_count(self, ty_ref) > 1 { var composed = compose_shapes(self, ty_ref); if composed == 0 { ret out; } shape_lang = composed; } var d = find_shape_adapter(self, adapter_name); if d == 0 { ret out; } out = ShapeUse { .is_shape = true, .adapter_decl = d - 1, .shape_lang = shape_lang, .shape_ref = ty_ref }; ret out; } // 声明期:把每个 shape 形参的 adapter/shape 固定下来;原函数体按 shape 做类型检查。 fn bind_shape_params(self: *Sema, fn_ref: Ref, params: []Ref) { var j: usize = 0; while j < params.len { var pn = Bld.node_ptr(&self.hir, params[j]); if pn != null { match pn.kind { .ParamDecl(p) => { var su = shape_use_of(self, p.ty); if su.is_shape { SemaM.set_tid(self, p.ty, su.shape_lang); if shape_param_at(self, fn_ref, j) == 0 { var sp = ShapeParam { .fn_ref = fn_ref, .param_index = j, .adapter_decl = su.adapter_decl, .shape_lang = su.shape_lang, .shape_ref = su.shape_ref }; match Vec.push(&self.shape_state.params, &sp as *u8) { .Ok => {}, .Err(e) => {} } } } }, _ => {}, } } j = j + 1; } } fn clear_ct_fn_refs(self: *Sema) { self.ct.fn_refs.len = 0; } fn ct_sym_for_ref(self: *Sema, ref: Ref): usize { var i: usize = 0; while i < self.ct.fn_refs.len { var e = (self.ct.fn_refs.data as *CtFnRef) + i; if e.ref == ref { ret e.sym; } i = i + 1; } ret 0; } fn shape_type_value(self: *Sema, lang: usize): usize { var h = SemaM.ct_handle(self, lang); var r = Bld.construct(&self.hir, .{ .kind = .LitInt(SemaM.itext(self, h)) }); SemaM.set_tid(self, r, LangType.make_type(&self.types)); ret r; } // 真实执行 adapter(called_type, shape_type),从返回聚合读回 type 和 wrapper 符号。 fn shape_adapter_eval_type(self: *Sema, adi: usize, arg_lang: usize, shape_lang: usize): ShapeAdapterEval { var out = ShapeAdapterEval { .lang = 0, .wrapper_sym = 0, .adapter_ref = 0 }; var name = SemaM.decl_at(self, adi).name; var callee = Bld.construct(&self.hir, .{ .kind = .Global(name) }); var av = Vec.blank(@sizeof(usize), @alignof(usize)); defer { Vec.drop(&av); } var a0 = shape_type_value(self, arg_lang); var a1 = shape_type_value(self, shape_lang); match Vec.push(&av, &a0 as *u8) { .Ok => {}, .Err(e) => { ret out; } } match Vec.push(&av, &a1 as *u8) { .Ok => {}, .Err(e) => { ret out; } } // 编译器生成的 adapter 调用也必须显式走 comptime 入口;源码里对应的是 // `@adapter(...)`,这里不能依赖普通调用自动升级。 var call = Bld.construct(&self.hir, .{ .kind = .Call(.{ .is_comptime = true, .callee = callee, .args = (av.data as *Ref)[0..av.len], }) }); var call_node = Bld.node_ptr(&self.hir, call); if call_node != null { var tag = Bld.construct(&self.hir, .{ .kind = .Tag(.{ .is_at = false, .name = "adapter_call", .args = (av.data as *Ref)[0..0], }) }); var tags: [1]Ref = .[tag]; call_node.tags = Bld.dup_refs(&self.hir, tags[0..1]); } clear_ct_fn_refs(self); var before = Bld.count(&self.hir); SemaM.sema_expr(self, call, 0); var n = Bld.node_ptr(&self.hir, call); if n == null { ret out; } var adapter_ref: Ref = 0; match n.kind { .LitInt(s) => { adapter_ref = SemaM.parse_u(s); }, _ => {}, } if adapter_ref == 0 { // Ref 0 表示 identity:不生成 wrapper,装箱类型就是实参类型。 out.lang = arg_lang; ret out; } // 非 0 的包装函数必须由本次 hook 执行生成;旧节点或任意小整数 Ref 不是 wrapper。 if adapter_ref <= before { SemaM.sema_error_code(self, ErrorCode.ImplHookBadReturn, "shape adapter must return a fresh wrapper Ref", ""); ret out; } var wn = Bld.node_ptr(&self.hir, adapter_ref); if wn == null { SemaM.sema_error_code(self, ErrorCode.ImplHookBadReturn, "shape adapter must return a wrapper Ref", ""); ret out; } match wn.kind { .FnDecl(f) => { var boxed = SemaM.resolve_type(self, f.ret_ty); if boxed == 0 { SemaM.sema_error_code(self, ErrorCode.ImplHookBadReturn, "shape adapter wrapper has no return type", ""); ret out; } if f.params.len != 1 { SemaM.sema_error_code(self, ErrorCode.ImplHookBadWrapper, "shape wrapper must take one argument", ""); ret out; } var pn = Bld.node_ptr(&self.hir, f.params[0]); if pn == null { SemaM.sema_error_code(self, ErrorCode.ImplHookBadWrapper, "shape wrapper parameter is invalid", ""); ret out; } match pn.kind { .ParamDecl(p) => { var pt = SemaM.resolve_type(self, p.ty); if pt == 0 || LangType.ir_of(&self.types, pt) != LangType.ir_of(&self.types, arg_lang) { SemaM.sema_error_code(self, ErrorCode.ImplHookBadWrapper, "shape wrapper parameter type mismatch", ""); ret out; } }, _ => {}, } out.lang = boxed; out.adapter_ref = adapter_ref; }, _ => { SemaM.sema_error_code(self, ErrorCode.ImplHookBadReturn, "shape adapter must return a wrapper Ref", ""); }, } ret out; } // 适配器返回 `(type, wrapper)`:执行 comptime 调用,读取真实结果。 fn shape_adapter_result(self: *Sema, sp_i: usize, arg_lang: usize): ShapeAdapterResult { var out = ShapeAdapterResult { .lang = 0, .wrapper_sym = 0, .adapter_ref = 0, .adapter_mod = 0 }; if sp_i == 0 || sp_i > self.shape_state.params.len { ret out; } var sp = (self.shape_state.params.data as *ShapeParam) + (sp_i - 1); var saved = self.cur_mod; var adi = sp.adapter_decl; var amod = SemaM.decl_at(self, adi).mod; if amod != saved { SemaM.switch_mod(self, amod); } SemaM.ensure_decl(self, adi); var ev = shape_adapter_eval_type(self, adi, arg_lang, sp.shape_lang); out = ShapeAdapterResult { .lang = ev.lang, .wrapper_sym = ev.wrapper_sym, .adapter_ref = ev.adapter_ref, .adapter_mod = amod }; if amod != saved { SemaM.switch_mod(self, saved); } ret out; } // shape 类型与目标方法的签名匹配;关联类型从 binds 取,不做推断。 fn shape_type_match(self: *Sema, a: usize, b: usize, shape_lang: usize, value_lang: usize, binds: *Vec, reported: *bool): bool { if a == 0 || b == 0 { ret a == b; } if LangType.is_assoc(&self.types, a) { var name = LangType.name_of(&self.types, a); var bound = shape_bind_find(binds, name); if bound == 0 { SemaM.sema_error_code(self, ErrorCode.ShapeAssocUnbound, "associated type is not bound", name); reported.* = true; ret false; } if bound == b { ret true; } if shape_type_match(self, bound, b, shape_lang, value_lang, binds, reported) { ret true; } if !reported.* { SemaM.sema_error_code(self, ErrorCode.ShapeAssocMismatch, "associated type does not match", name); reported.* = true; } ret false; } if a == shape_lang { ret b == value_lang; } var ka = LangType.kind_of(&self.types, a); var kb = LangType.kind_of(&self.types, b); if !LangType.kind_eq(ka, kb) { ret false; } match ka { .Ptr, .Slice => { ret shape_type_match(self, LangType.elem_of(&self.types, a), LangType.elem_of(&self.types, b), shape_lang, value_lang, binds, reported); }, .Array => { if LangType.array_len_of(&self.types, a) != LangType.array_len_of(&self.types, b) { ret false; } ret shape_type_match(self, LangType.elem_of(&self.types, a), LangType.elem_of(&self.types, b), shape_lang, value_lang, binds, reported); }, .Fn => { if LangType.fn_param_count(&self.types, a) != LangType.fn_param_count(&self.types, b) { ret false; } var i: usize = 0; while i < LangType.fn_param_count(&self.types, a) { if !shape_type_match(self, LangType.fn_param_of(&self.types, a, i), LangType.fn_param_of(&self.types, b, i), shape_lang, value_lang, binds, reported) { ret false; } i = i + 1; } ret shape_type_match(self, LangType.fn_ret_of(&self.types, a), LangType.fn_ret_of(&self.types, b), shape_lang, value_lang, binds, reported); }, .Struct, .Union, .Enum => { if LangType.member_count(&self.types, a) != LangType.member_count(&self.types, b) { ret false; } var i: usize = 0; while i < LangType.member_count(&self.types, a) { if !SemaM.eq(LangType.member_name(&self.types, a, i), LangType.member_name(&self.types, b, i)) { ret false; } if !shape_type_match(self, LangType.member_lang(&self.types, a, i), LangType.member_lang(&self.types, b, i), shape_lang, value_lang, binds, reported) { ret false; } i = i + 1; } if LangType.kind_eq(ka, .Enum) { if LangType.enum_tag(&self.types, a) != LangType.enum_tag(&self.types, b) { ret false; } if LangType.enum_ok_index(&self.types, a) != LangType.enum_ok_index(&self.types, b) { ret false; } if LangType.enum_error_count(&self.types, a) != LangType.enum_error_count(&self.types, b) { ret false; } } ret true; }, .Int, .Float => { ret LangType.ir_of(&self.types, a) == LangType.ir_of(&self.types, b); }, .Shape => { ret a == b; }, .Bool, .Unit, .Any, .Type, .Never, .Error => { ret true; }, .Assoc => { ret false; }, } ret false; } fn shape_marker_has(self: *Sema, value_lang: usize, shape_lang: usize): bool { var cont = LangType.container_of(&self.types, value_lang); if cont == 0 { ret false; } var n = Bld.node_ptr(&self.hir, cont); if n == null { ret false; } match n.kind { .AggType(a) => { var i: usize = 0; while i < a.conforms.len { if SemaM.resolve_type(self, a.conforms[i]) == shape_lang { ret true; } i = i + 1; } }, _ => {}, } ret false; } fn shape_conforms_use(self: *Sema, use_ref: Ref, value_lang: usize): bool { var count = shape_use_shape_count(self, use_ref); var i: usize = 0; while i < count { var sref = shape_use_shape_at(self, use_ref, i); var sn = Bld.node_ptr(&self.hir, sref); var simple = false; if sn != null { match sn.kind { .NamedType(_) => { simple = true; }, _ => {} } } // 类型声明上的 marker 已经完整检查过;无名绑定时使用点不重复检查。 if simple && shape_marker_has(self, value_lang, SemaM.resolve_type(self, sref)) { i = i + 1; continue; } if !shape_conforms(self, sref, value_lang) { ret false; } i = i + 1; } ret true; } // 目标类型是否具备 shape 声明里的方法名与签名;方法体在实例化后继续分析。 fn shape_conforms(self: *Sema, shape_ref: Ref, value_lang: usize): bool { var shape_lang = SemaM.resolve_type(self, shape_ref); if shape_lang == 0 || !is_shape_lang(self, shape_lang) { SemaM.sema_error_code(self, ErrorCode.ShapeParamNotShape, "shape parameter type is not a shape", ""); ret false; } var binds = Vec.blank(@sizeof(ShapeBind), @alignof(ShapeBind)); defer { Vec.drop(&binds); } if !shape_apply_binds(self, shape_ref, &binds) { ret false; } if !shape_marker_binds(self, value_lang, shape_lang, &binds) { ret false; } if !shape_assoc_names_bound(self, shape_lang, &binds) { ret false; } ret shape_conforms_with(self, shape_lang, value_lang, &binds); } fn shape_conforms_with(self: *Sema, shape_lang: usize, value_lang: usize, binds: *Vec): bool { var cont = LangType.container_of(&self.types, shape_lang); if cont == 0 { ret true; } var n = Bld.node_ptr(&self.hir, cont); if n == null { ret true; } var ok = true; match n.kind { .AggType(a) => { var i: usize = 0; while i < a.decls.len { var dn = Bld.node_ptr(&self.hir, a.decls[i]); if dn != null { match dn.kind { .FnDecl(f) => { var want = SemaM.method_sym(self, shape_lang, f.name); if want == 0 { SemaM.sema_error_code(self, ErrorCode.ShapeMethodMissing, "shape method declaration is missing", f.name); ok = false; break; } var want_tid = SemaM.sym_at(self, want - 1).fn_tid; var reported = false; var got = SemaM.method_sym(self, value_lang, f.name); var got_tid: usize = 0; if got != 0 { got_tid = SemaM.sym_at(self, got - 1).fn_tid; } var matched = false; if got != 0 { matched = shape_type_match(self, want_tid, SemaM.sym_at(self, got - 1).fn_tid, shape_lang, value_lang, binds, &reported); } else { // dyn 表允许用同名字段承载方法类型。 var field_idx = LangType.member_idx(&self.types, value_lang, f.name); if field_idx < 0 { SemaM.sema_error_code(self, ErrorCode.ShapeMethodMissing, "shape method is missing", f.name); ok = false; break; } matched = shape_type_match(self, want_tid, LangType.member_lang(&self.types, value_lang, field_idx as usize), shape_lang, value_lang, binds, &reported); } if !matched { if !reported { SemaM.sema_error_code(self, ErrorCode.ShapeMismatch, "shape method signature mismatch", f.name); } ok = false; break; } }, _ => {}, } } i = i + 1; } }, _ => {}, } if ok && value_lang != shape_lang { match n.kind { .AggType(a) => { var pi: usize = 0; while pi < a.conforms.len { if !shape_conforms(self, a.conforms[pi], value_lang) { ok = false; break; } pi = pi + 1; } }, _ => {}, } } ret ok; } fn for_item_hook(): fn(*any, usize, usize): usize { ret for_item; } fn for_item(user: *any, value_lang: usize, shape_lang: usize): usize { var self = user as *Sema; var binds = Vec.blank(@sizeof(ShapeBind), @alignof(ShapeBind)); if !shape_marker_binds(self, value_lang, shape_lang, &binds) { Vec.drop(&binds); ret 0; } if !shape_assoc_names_bound(self, shape_lang, &binds) { Vec.drop(&binds); ret 0; } var ok = shape_conforms_with(self, shape_lang, value_lang, &binds); var item: usize = 0; if ok { item = shape_bind_find(&binds, "Item"); } Vec.drop(&binds); if !ok { ret 0; } if item == 0 { SemaM.sema_error_code(self, ErrorCode.ShapeAssocUnbound, "iterator Item is not bound", "Item"); } ret item; } fn check_conforms(user: *any, agg_ref: Ref, value_lang: usize) { var self = user as *Sema; var n = Bld.node_ptr(&self.hir, agg_ref); if n == null { ret; } match n.kind { .AggType(a) => { // shape 继承在具体类型 conformance 时展开,shape 自身不按结构实现父 shape。 if SemaM.agg_is_shape(a.kind) { ret; } var i: usize = 0; while i < a.conforms.len { if !shape_conforms(self, a.conforms[i], value_lang) { ret; } i = i + 1; } }, _ => {}, } } fn shape_type_node(self: *Sema, lang: usize): usize { var r = Bld.construct(&self.hir, .{ .kind = .NamedType("__shape_ty") }); SemaM.grow_tables(self); SemaM.set_tid(self, r, lang); ret r; } fn shape_instance_name(self: *Sema): []u8 { self.shape_state.seq = self.shape_state.seq + 1; var b = ByteBuffer.new(); defer { ByteBuffer.drop(&b); } ByteBuffer.append(&b, "__shape$"); append_usize(&b, self.shape_state.seq, 10, false); ret Bld.dup_bytes(&self.hir, ByteBuffer.as_slice(b)); } // adapter 返回动态 FnDecl Ref 时,先把它登记成普通函数声明并分析体。 fn ensure_adapter_fn(self: *Sema, ref: Ref, mod: usize): usize { var sym = SemaM.fn_sym_for_ref(self, ref); if sym != 0 { ret sym; } var p = Bld.node_ptr(&self.hir, ref); if p == null { ret 0; } var saved = self.cur_mod; if mod != saved { SemaM.switch_mod(self, mod); } var nm = shape_instance_name(self); match p.kind { .FnDecl(f) => { f.name = nm; p.kind = .FnDecl(f); }, _ => { if mod != saved { SemaM.switch_mod(self, saved); } ret 0; }, } var d = Decl { .name = nm, .kind = .Fn, .node = ref, .container = 0, .mod = mod, .state = .Unresolved, .lang = 0, .ret_lang = 0, .sym = 0, .gidx = 0, .init = 0, .def = 0, .body_done = false }; var di = self.decls.len; match Vec.push(&self.decls, &d as *u8) { .Ok => {}, .Err(e) => {} } SemaM.ensure_decl(self, di); SemaM.analyze_fn_body(self, di); sym = SemaM.decl_at(self, di).sym; if mod != saved { SemaM.switch_mod(self, saved); } ret sym; } // 把调用点实参替换为 adapter 调用;恒等包装(0)不生成代码。 fn insert_shape_box(self: *Sema, arg: usize, ret_lang: usize, wrapper_sym: usize, adapter_ref: Ref, adapter_mod: usize): usize { var sym = wrapper_sym; if adapter_ref != 0 { sym = ensure_adapter_fn(self, adapter_ref, adapter_mod); } if sym == 0 { ret arg; } var name = SemaM.sym_at(self, sym - 1).name; var ws = SemaM.sym_at(self, sym - 1); var callee = Bld.construct(&self.hir, .{ .kind = .Global(name) }); SemaM.set_node_fn(self, callee, sym); SemaM.set_tid(self, callee, ws.fn_tid); var av = Vec.blank(@sizeof(usize), @alignof(usize)); defer { Vec.drop(&av); } match Vec.push(&av, &arg as *u8) { .Ok => {}, .Err(e) => { ret arg; } } var call = Bld.construct(&self.hir, .{ .kind = .Call(.{ .is_comptime = false, .callee = callee, .args = (av.data as *Ref)[0..av.len], }) }); // 包装函数的真实返回类型必须与 adapter 声明的装箱类型布局一致。 var want_ir = LangType.ir_of(&self.types, ret_lang); var got_ir = LangType.ir_of(&self.types, ws.ret_tid); if ret_lang == 0 || want_ir == 0 || want_ir != got_ir { SemaM.sema_error_code(self, ErrorCode.ImplHookBadWrapper, "shape wrapper return type mismatch", name); } SemaM.set_tid(self, call, ws.ret_tid); SemaM.record_call(self, sym); ret call; } fn shape_instance_matches(self: *Sema, si: *ShapeInstance, fn_ref: Ref, args: []usize): bool { if si.fn_ref != fn_ref || si.args.len != args.len { ret false; } var i: usize = 0; while i < args.len { if (si.args.data as *usize)[i] != args[i] { ret false; } i = i + 1; } ret true; } fn shape_instance_for(self: *Sema, fn_ref: Ref, args: []usize): usize { var i: usize = 0; while i < self.shape_state.instances.len { var si = (self.shape_state.instances.data as *ShapeInstance) + i; if shape_instance_matches(self, si, fn_ref, args) { ret si.sym; } i = i + 1; } var orig = SemaM.fn_sym_for_ref(self, fn_ref); if orig == 0 { ret 0; } var saved = self.cur_mod; var m = SemaM.sym_at(self, orig - 1).mod; if m != saved { SemaM.switch_mod(self, m); } var od = SemaM.find_decl_by_node(self, m, fn_ref); if od == 0 { if m != saved { SemaM.switch_mod(self, saved); } ret 0; } // 先分析原函数体:生成方法里的 @sizeof(t) 等类型查询会折成常量, // 克隆后的 shape 实例才不会丢掉 gen_binds 的求值结果。 SemaM.analyze_fn_body(self, od - 1); var clone_state = NodeClone.new(); var clone = NodeClone.clone_ref(&self.hir, &clone_state, fn_ref); NodeClone.drop(&clone_state); SemaM.grow_tables(self); var nm = shape_instance_name(self); var cn = Bld.node_ptr(&self.hir, clone); if cn != null { match cn.kind { .FnDecl(f) => { f.name = nm; cn.kind = .FnDecl(f); }, _ => {}, } } var cn2 = Bld.node_ptr(&self.hir, clone); if cn2 != null { match cn2.kind { .FnDecl(f) => { var k: usize = 0; var pi: usize = 0; while pi < self.shape_state.params.len { var sp = (self.shape_state.params.data as *ShapeParam) + pi; if sp.fn_ref == fn_ref { if k >= args.len { break; } var pref = f.params[sp.param_index]; var pn = Bld.node_ptr(&self.hir, pref); if pn != null { match pn.kind { .ParamDecl(p) => { p.ty = shape_type_node(self, args[k]); pn.kind = .ParamDecl(p); }, _ => {}, } set_shape_type_bind(self, pref, args[k]); } k = k + 1; } pi = pi + 1; } }, _ => {}, } } var odi = (od - 1); var d = Decl { .name = nm, .kind = .Fn, .node = clone, .container = SemaM.decl_at(self, odi).container, .mod = m, .state = .Unresolved, .lang = 0, .ret_lang = 0, .sym = 0, .gidx = 0, .init = 0, .def = 0, .body_done = false }; var di = self.decls.len; match Vec.push(&self.decls, &d as *u8) { .Ok => {}, .Err(e) => {} } SemaM.ensure_decl(self, di); SemaM.analyze_fn_body(self, di); var inst = SemaM.decl_at(self, di).sym; if m != saved { SemaM.switch_mod(self, saved); } if inst != 0 { var av = Vec.blank(@sizeof(usize), @alignof(usize)); var ai: usize = 0; while ai < args.len { match Vec.push(&av, &args[ai] as *u8) { .Ok => {}, .Err(e) => {} } ai = ai + 1; } var rec = ShapeInstance { .fn_ref = fn_ref, .args = av, .sym = inst }; match Vec.push(&self.shape_state.instances, &rec as *u8) { .Ok => {}, .Err(e) => {} } } ret inst; } fn shape_type_bind_of(self: *Sema, ref: Ref): usize { var i: usize = 0; while i < self.shape_state.type_binds.len { var b = (self.shape_state.type_binds.data as *ShapeTypeBind) + i; if b.ref == ref { ret b.lang; } i = i + 1; } ret 0; } fn set_shape_type_bind(self: *Sema, ref: Ref, lang: usize) { var b = ShapeTypeBind { .ref = ref, .lang = lang }; match Vec.push(&self.shape_state.type_binds, &b as *u8) { .Ok => {}, .Err(e) => {} } } // ---- 注入 sema 的入口 ---- fn bind_params(user: *any, fn_ref: Ref, params: []Ref) { var self = user as *Sema; bind_shape_params(self, fn_ref, params); } fn type_bind_of(user: *any, ref: Ref): usize { var self = user as *Sema; ret shape_type_bind_of(self, ref); } fn prepare_call(user: *any, callee_ref: Ref, callee: Ref, args: []usize, out: *ShapeCallResult) { var self = user as *Sema; var shape_args = Vec.blank(@sizeof(usize), @alignof(usize)); defer { Vec.drop(&shape_args); } var shape_ok = true; var need_report = false; var pi: usize = 0; while pi < self.shape_state.params.len { var sp = (self.shape_state.params.data as *ShapeParam) + pi; if sp.fn_ref == callee_ref { if sp.param_index >= args.len { shape_ok = false; need_report = true; } else { var a = args[sp.param_index]; var al = SemaM.tid_of(self, a); if al == 0 { shape_ok = false; need_report = true; } else if !shape_conforms_use(self, sp.shape_ref, al) { shape_ok = false; } else { var sr = shape_adapter_result(self, pi + 1, al); if sr.lang == 0 || !shape_conforms_use(self, sp.shape_ref, sr.lang) { shape_ok = false; } else { var boxed = insert_shape_box(self, a, sr.lang, sr.wrapper_sym, sr.adapter_ref, sr.adapter_mod); if boxed != a { args.ptr[sp.param_index] = boxed; } match Vec.push(&shape_args, &sr.lang as *u8) { .Ok => {}, .Err(e) => { shape_ok = false; }, } } } } } pi = pi + 1; } if !shape_ok && need_report { SemaM.sema_error_code(self, ErrorCode.ShapeMismatch, "shape argument does not conform", ""); } out.ok = shape_ok; if shape_ok && shape_args.len > 0 { var inst = shape_instance_for(self, callee_ref, (shape_args.data as *usize)[0..shape_args.len]); if inst != 0 { var si2 = SemaM.sym_at(self, inst - 1); SemaM.set_node_fn(self, callee, inst); SemaM.set_tid(self, callee, si2.fn_tid); out.fn_tid = si2.fn_tid; out.ret_tid = si2.ret_tid; SemaM.record_call(self, inst); } } } fn op_method(user: *any, value_lang: usize, shape_lang: usize, method: []u8): usize { var self = user as *Sema; if !shape_marker_has(self, value_lang, shape_lang) { ret 0; } var binds = Vec.blank(@sizeof(ShapeBind), @alignof(ShapeBind)); defer { Vec.drop(&binds); } if !shape_marker_binds(self, value_lang, shape_lang, &binds) { ret 0; } if !shape_assoc_names_bound(self, shape_lang, &binds) { ret 0; } if !shape_conforms_with(self, shape_lang, value_lang, &binds) { ret 0; } ret SemaM.method_sym(self, value_lang, method); } fn marker_has_hook(user: *any, value_lang: usize, shape_lang: usize): bool { ret shape_marker_has(user as *Sema, value_lang, shape_lang); } fn hooks(): ShapeHooks { ret ShapeHooks { .bind_params = bind_params, .type_bind_of = type_bind_of, .prepare_call = prepare_call, .check_conforms = check_conforms, .op_method = op_method, .has_conformance = marker_has_hook, }; } fn main() {}