ffi M1.2 A.1 follow-up: struct args/returns in Obj-C type encoding

`appendObjcEncoding` previously bailed on `.@"struct"`, which blocked
sx-defined `#objc_class` methods from declaring CGPoint / CGRect /
NSRange-shape signatures — the `class_addMethod` registration path
would emit a "type kind not yet supported by Obj-C encoding"
diagnostic. The helper now emits Apple's `{Name=field0field1...}`
form recursively, with a small `ObjcEncodingStack` (cap 16) that
breaks transitive struct→struct cycles by emitting the abbreviated
`{Name}` form instead of recursing forever.

`{Point=dd}`, `{_NSRange=QQ}`, `{CGRect={CGPoint=dd}{CGSize=dd}}`
all flow through the existing `objc_msg_send` + `class_addMethod`
path with no further plumbing.

Tests:
- `lower.test.zig` gains four cases: optional unwrap (single + nested),
  flat struct (CGPoint, NSRange shape), nested struct (CGRect with
  CGPoint+CGSize), bringing the helper's test coverage from
  primitives + pointers to the full encoding table.
- `examples/ffi-objc-defined-class-02-struct-encoding.sx` exercises
  a sx-defined `SxMover` class with `goto(p: Point)` setter and
  `here() -> Point` getter end-to-end on macOS; the IR snapshot
  confirms `v@:{Point=dd}` and `{Point=dd}@:` land in
  `OBJC_METH_VAR_TYPE_` constants wired to `class_addMethod`.

Checkpoint cleanup: the "Next step (M1.2 A.1 — type-encoding
derivation table)" header in CHECKPOINT-FFI.md was stale (A.1
shipped in 6cc016c; A.0–A.7 all done; commit list now linked).
The encoding table stays as reference material.

224/224 example tests pass; zig build test green.
This commit is contained in:
agra
2026-05-28 14:24:02 +03:00
parent 3ac13b7442
commit 6d258ad82b
6 changed files with 275 additions and 22 deletions

View File

@@ -5011,9 +5011,12 @@ pub const Lowering = struct {
///
/// Foreign-class pointers (`*UIView` etc.) encode as `@` (object
/// pointer). Other pointers fall to `^v` — the encoding is metadata,
/// not ABI, so being conservative here is safe. Struct returns and
/// other complex shapes BAIL loudly via diagnostics rather than
/// silently mis-encoding (per CLAUDE.md rejected-patterns rule).
/// not ABI, so being conservative here is safe. Pass-by-value
/// structs encode as `{Name=field0field1...}`; nested structs
/// recurse with cycle-break via `ObjcEncodingStack`. Tagged-union /
/// array / vector / function shapes BAIL loudly via diagnostics
/// rather than silently mis-encoding (per CLAUDE.md rejected-
/// patterns rule).
///
/// Returns an allocator-owned slice; caller frees via `self.alloc`.
fn objcTypeEncodingFromSignature(
@@ -5025,17 +5028,54 @@ pub const Lowering = struct {
var out = std.ArrayList(u8).empty;
errdefer out.deinit(self.alloc);
try self.appendObjcEncoding(&out, return_ty, span);
var stack: ObjcEncodingStack = .{};
try self.appendObjcEncoding(&out, return_ty, span, &stack);
try out.append(self.alloc, '@'); // self
try out.append(self.alloc, ':'); // _cmd
for (param_tys) |pty| {
try self.appendObjcEncoding(&out, pty, span);
try self.appendObjcEncoding(&out, pty, span, &stack);
}
return try out.toOwnedSlice(self.alloc);
}
fn appendObjcEncoding(self: *Lowering, out: *std.ArrayList(u8), ty: TypeId, span: ?ast.Span) !void {
/// Tracks struct TypeIds currently being emitted so a struct field of
/// `*Self` (or a transitive pointee that cycles back) emits the
/// abbreviated `{Name}` form instead of recursing forever. Bounded to
/// `cap` — well above any realistic Obj-C struct nesting depth.
const ObjcEncodingStack = struct {
const cap = 16;
items: [cap]TypeId = undefined,
len: u8 = 0,
fn push(self: *ObjcEncodingStack, tid: TypeId) bool {
if (self.len >= cap) return false;
self.items[self.len] = tid;
self.len += 1;
return true;
}
fn pop(self: *ObjcEncodingStack) void {
std.debug.assert(self.len > 0);
self.len -= 1;
}
fn contains(self: *const ObjcEncodingStack, tid: TypeId) bool {
var i: usize = 0;
while (i < self.len) : (i += 1) {
if (self.items[i] == tid) return true;
}
return false;
}
};
fn appendObjcEncoding(
self: *Lowering,
out: *std.ArrayList(u8),
ty: TypeId,
span: ?ast.Span,
stack: *ObjcEncodingStack,
) !void {
const info = self.module.types.get(ty);
switch (info) {
.void => try out.append(self.alloc, 'v'),
@@ -5097,7 +5137,33 @@ pub const Lowering = struct {
// wire-level encoding is the same as T. Unwrap and
// recurse. (Same goes for `?*UIView` etc. — the
// underlying pointer kind drives the encoding char.)
return self.appendObjcEncoding(out, o.child, span);
return self.appendObjcEncoding(out, o.child, span, stack);
},
.@"struct" => |s| {
// Pass-by-value struct argument or return: Apple's
// encoding is `{Name=field0field1...}`. A struct
// already on the encoding stack (i.e. transitively
// referenced through a struct field — extremely rare
// since sx structs don't recurse by value) gets the
// abbreviated `{Name}` form. Recursion through
// POINTERS is fine because `.pointer` collapses to
// `^v` regardless of pointee shape.
const name = self.module.types.getString(s.name);
try out.append(self.alloc, '{');
try out.appendSlice(self.alloc, name);
if (stack.contains(ty)) {
try out.append(self.alloc, '}');
return;
}
if (!stack.push(ty)) {
return self.bailObjcEncoding(span, "Obj-C struct encoding nested deeper than supported", ObjcEncodingStack.cap);
}
defer stack.pop();
try out.append(self.alloc, '=');
for (s.fields) |f| {
try self.appendObjcEncoding(out, f.ty, span, stack);
}
try out.append(self.alloc, '}');
},
else => return self.bailObjcEncoding(span, "type kind not yet supported by Obj-C encoding", @intFromEnum(std.meta.activeTag(info))),
}