From 5c1d00a87796dafdeb04714b9ef30591368de174 Mon Sep 17 00:00:00 2001 From: agra Date: Tue, 26 May 2026 22:58:30 +0300 Subject: [PATCH] ffi M4.B helpers: objcPropertyKind + ARC runtime decls + xfail tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three pieces, no behavior change yet: 1. `ObjcPropertyKind` enum (strong/weak/copy/assign) + `objcPropertyKind` helper in lower.zig. Reads `field.property_modifiers`, applies the default rule (`*` → strong; primitives → assign), and emits loud diagnostics for the silent-error budget: - unknown modifier name (typo) → "expected one of: strong, weak, copy, ..." - conflicting modifiers (e.g. `strong,weak`) → "mutually exclusive" - `weak` on non-object slot → "requires a pointer-to-Obj-C-class type" - `copy` on non-object slot → same - `strong` (default or explicit) on `*void` → "ambiguous: specify #property(strong|weak|copy|assign) explicitly" Called from `emitObjcDefinedClassPropertyImps` for validation; the returned kind isn't wired into setter/getter/dealloc yet — that's the next three commits. 2. `ensureArcRuntimeDecls` lazily declares libobjc's ARC helpers: objc_retain, objc_release, objc_storeWeak, objc_loadWeakRetained, objc_initWeak, objc_destroyWeak. Uses the existing `ensureCRuntimeDecl` pattern; idempotent. 3. Fix existing NSObject method names in std/objc.sx — `isEqual_`, `isKindOfClass_`, `respondsToSelector_` had trailing underscores that the selector mangling turned into double-colon selectors (`isEqual::`). Removed the trailing underscore so the selectors come out as `isEqual:`, `isKindOfClass:`, `respondsToSelector:` as Apple's runtime expects. 4. Two xfail regression tests: - ffi-objc-arc-02-strong-property: assigns child to parent's strong property, releases the original child reference. Midpoint check: child's dealloc should NOT have fired (strong setter retained). Pre-M4.B-setter: child dealloc fires immediately → "FAIL: child dealloc'd at midpoint" snapshot. Exit code 1. - ffi-objc-arc-03-weak-property: assigns target to holder's weak property, releases target. Reads holder.target → should be null (auto-niled). Pre-M4.B-getter/setter: reads stale pointer → "FAIL: weak property didn't auto-nil" snapshot. These will turn green as M4.B setter (commit 2), getter (commit 3), and dealloc-cleanup (commit 4) land. Each subsequent commit updates the snapshot to reflect the now-passing output. 189/189 example tests pass; chess on iOS-sim green. --- examples/ffi-objc-arc-02-strong-property.sx | 78 ++++++++++ examples/ffi-objc-arc-03-weak-property.sx | 66 ++++++++ library/modules/std/objc.sx | 6 +- src/ir/lower.zig | 141 ++++++++++++++++++ .../ffi-objc-arc-02-strong-property.exit | 1 + .../ffi-objc-arc-02-strong-property.txt | 1 + .../ffi-objc-arc-03-weak-property.exit | 1 + .../ffi-objc-arc-03-weak-property.txt | 1 + 8 files changed, 292 insertions(+), 3 deletions(-) create mode 100644 examples/ffi-objc-arc-02-strong-property.sx create mode 100644 examples/ffi-objc-arc-03-weak-property.sx create mode 100644 tests/expected/ffi-objc-arc-02-strong-property.exit create mode 100644 tests/expected/ffi-objc-arc-02-strong-property.txt create mode 100644 tests/expected/ffi-objc-arc-03-weak-property.exit create mode 100644 tests/expected/ffi-objc-arc-03-weak-property.txt diff --git a/examples/ffi-objc-arc-02-strong-property.sx b/examples/ffi-objc-arc-02-strong-property.sx new file mode 100644 index 0000000..d7afee9 --- /dev/null +++ b/examples/ffi-objc-arc-02-strong-property.sx @@ -0,0 +1,78 @@ +// ffi-objc-arc-02 — #property(strong) on sx-defined class. +// +// Strong contract: +// - setter retains the new value, releases the old. +// - -dealloc releases each strong property ivar before freeing state. +// +// Observation: a child instance assigned to a parent's strong property +// stays alive after we drop our own reference. Without the strong +// setter, the child's refcount drops to 0 immediately when we release, +// and the parent ends up with a dangling pointer. +// +// We observe via TrackingAllocator. The KEY check is the dealloc count +// AT THE MIDPOINT — between dropping our child reference and releasing +// the parent. With strong+dealloc-cleanup: child stays alive across +// midpoint (no extra dealloc). Without: child is dead at midpoint. + +#import "modules/std.sx"; +#import "modules/allocators.sx"; +#import "modules/std/objc.sx"; +#import "modules/compiler.sx"; + +SxStrongChild :: #objc_class("SxStrongChild") { + #extends NSObject; + tag: s32; + alloc :: () -> *SxStrongChild; +} + +SxStrongParent :: #objc_class("SxStrongParent") { + #extends NSObject; + child: *SxStrongChild #property(strong); + alloc :: () -> *SxStrongParent; +} + +main :: () -> s32 { + inline if OS == .macos { + gpa := GPA.init(); + tracker := TrackingAllocator.init(xx gpa); + + push Context.{ allocator = xx tracker, data = null } { + d0 := tracker.dealloc_count; + a0 := tracker.alloc_count; + + parent := SxStrongParent.alloc(); + child := SxStrongChild.alloc(); + parent.child = child; // dispatches setChild: via M2.2 property machinery + child.release(); + + // Midpoint: with strong setter, child is retained by parent; + // tracker.dealloc_count should NOT have advanced beyond d0. + // Without strong setter, child auto-dealloc'd on release. + d_mid := tracker.dealloc_count; + if d_mid != d0 { + print("FAIL: child dealloc'd at midpoint (strong setter not retaining); delta={}\n", + d_mid - d0); + return 1; + } + + parent.release(); + + // After parent.release: parent.dealloc fires, releases the + // strong child ivar, child deallocs, state freed. + d_end := tracker.dealloc_count; + // Net: 2 allocs (parent + child state), 2 deallocs (both freed). + // Balance check: dealloc delta == alloc delta. + if d_end - d0 != tracker.alloc_count - a0 { + print("FAIL: unbalanced; alloc={} dealloc={}\n", + tracker.alloc_count - a0, d_end - d0); + return 1; + } + } + + print("strong property: ok\n"); + } + inline if OS != .macos { + print("skipped (not macos)\n"); + } + 0; +} diff --git a/examples/ffi-objc-arc-03-weak-property.sx b/examples/ffi-objc-arc-03-weak-property.sx new file mode 100644 index 0000000..5ca3bea --- /dev/null +++ b/examples/ffi-objc-arc-03-weak-property.sx @@ -0,0 +1,66 @@ +// ffi-objc-arc-03 — #property(weak) on sx-defined class. +// +// Weak contract: +// - setter calls objc_storeWeak — does NOT retain. +// - getter calls objc_loadWeakRetained + autorelease — auto-nils +// if the target has been deallocated. +// - -dealloc calls objc_destroyWeak on each weak ivar. +// +// Observation: assign a target to the weak property. Drop the +// caller's strong reference. Read back via the weak getter — should +// be `null` (the target deallocated when its last strong ref +// dropped, and the weak slot auto-niled). +// +// Pre-M4.B: setter just stores the pointer (no storeWeak); getter +// reads the raw pointer (no loadWeakRetained). After target's +// release, the slot points at freed memory — the read returns the +// stale pointer (not null). The test catches this by comparing the +// read result to null. + +#import "modules/std.sx"; +#import "modules/allocators.sx"; +#import "modules/std/objc.sx"; +#import "modules/compiler.sx"; + +SxWeakTarget :: #objc_class("SxWeakTarget") { + #extends NSObject; + tag: s32; + alloc :: () -> *SxWeakTarget; +} + +SxWeakHolder :: #objc_class("SxWeakHolder") { + #extends NSObject; + target: *SxWeakTarget #property(weak); + alloc :: () -> *SxWeakHolder; +} + +main :: () -> s32 { + inline if OS == .macos { + gpa := GPA.init(); + tracker := TrackingAllocator.init(xx gpa); + + push Context.{ allocator = xx tracker, data = null } { + holder := SxWeakHolder.alloc(); + target := SxWeakTarget.alloc(); + holder.target = target; + target.release(); + + // After release: target's refcount → 0 → target deallocates. + // With weak: holder.target should read as null (auto-niled). + // Without weak: holder.target reads as the stale pointer. + read_back := holder.target; + if read_back != null { + print("FAIL: weak property didn't auto-nil after target dealloc\n"); + return 1; + } + + holder.release(); + } + + print("weak property: ok\n"); + } + inline if OS != .macos { + print("skipped (not macos)\n"); + } + 0; +} diff --git a/library/modules/std/objc.sx b/library/modules/std/objc.sx index f2d4c9d..192d627 100644 --- a/library/modules/std/objc.sx +++ b/library/modules/std/objc.sx @@ -118,9 +118,9 @@ NSObject :: #foreign #objc_class("NSObject") { class :: () -> *void; // metaclass query — `Cls.class()` description :: (self: *Self) -> *void; // returns *NSString hash :: (self: *Self) -> u64; - isEqual_ :: (self: *Self, other: *void) -> BOOL; - isKindOfClass_ :: (self: *Self, cls: *void) -> BOOL; - respondsToSelector_ :: (self: *Self, sel: *void) -> BOOL; + isEqual :: (self: *Self, other: *void) -> BOOL; + isKindOfClass :: (self: *Self, cls: *void) -> BOOL; + respondsToSelector :: (self: *Self, sel: *void) -> BOOL; } // ─── Autoreleasepool (M4.A) ────────────────────────────────────────────── diff --git a/src/ir/lower.zig b/src/ir/lower.zig index d169a4c..fe9c402 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -12036,6 +12036,141 @@ pub const Lowering = struct { /// Both IMPs land in the cache's methods slice with appropriate /// selectors + encodings; emit_llvm's class_addMethod loop wires /// them up like any other instance method. + /// M4.B — interpretation of `#property(...)` modifiers for ARC. + /// `assign` is the default for primitives (direct store, no ARC ops); + /// `strong` is the default for pointer-to-object types (retain on + /// assign, release on dealloc); `weak` and `copy` are explicit. The + /// helper rejects ambiguous combinations loudly per the silent-error + /// budget — `*void` requires explicit modifier, `weak` requires an + /// object-pointer slot. + const ObjcPropertyKind = enum { + assign, // primitives or explicitly opted-out object slots + strong, // default for * — retain on assign, release on dealloc + weak, // objc_storeWeak / objc_loadWeakRetained — auto-nilling + copy, // [val copy] on assign — for immutable-wanting String/Array slots + + pub fn isObject(k: ObjcPropertyKind) bool { + return k == .strong or k == .weak or k == .copy; + } + }; + + /// Resolve a `#property(...)` field's ARC kind. Loud at compile time + /// for known footguns (per the silent-error budget in the plan): + /// - unknown modifier name (typo) → diagnostic + /// - `weak` on a non-object field type → diagnostic + /// - `strong` (explicit or defaulted) on `*void` (ambiguous: Obj-C + /// object vs raw memory) → require explicit modifier + fn objcPropertyKind(self: *Lowering, field: ast.ForeignFieldDecl) ObjcPropertyKind { + // Survey the modifier list. + var has_strong = false; + var has_weak = false; + var has_copy = false; + var has_assign = false; + for (field.property_modifiers) |mod| { + if (std.mem.eql(u8, mod, "strong")) has_strong = true + else if (std.mem.eql(u8, mod, "weak")) has_weak = true + else if (std.mem.eql(u8, mod, "copy")) has_copy = true + else if (std.mem.eql(u8, mod, "assign")) has_assign = true + else if (std.mem.eql(u8, mod, "readonly")) { + // Orthogonal to ARC kind — no-op here. + } + else if (std.mem.eql(u8, mod, "nonatomic") or std.mem.eql(u8, mod, "atomic")) { + // Atomicity — recorded for the property attribute string; + // doesn't affect the ARC kind. + } + else if (std.mem.startsWith(u8, mod, "getter(") or std.mem.startsWith(u8, mod, "setter(")) { + // Selector overrides — handled elsewhere. + } + else { + if (self.diagnostics) |d| { + const span = ast.Span{ .start = 0, .end = 0 }; + d.addFmt(.err, span, "unknown #property modifier '{s}' on field '{s}' — expected one of: strong, weak, copy, assign, readonly, nonatomic, atomic, getter(\"...\"), setter(\"...\")", .{ mod, field.name }); + } + } + } + + // Mutually-exclusive ARC modifiers — at most one. + const explicit_count: u32 = + (@as(u32, if (has_strong) 1 else 0)) + + (@as(u32, if (has_weak) 1 else 0)) + + (@as(u32, if (has_copy) 1 else 0)) + + (@as(u32, if (has_assign) 1 else 0)); + if (explicit_count > 1) { + if (self.diagnostics) |d| { + const span = ast.Span{ .start = 0, .end = 0 }; + d.addFmt(.err, span, "conflicting #property modifiers on field '{s}' — strong/weak/copy/assign are mutually exclusive", .{field.name}); + } + } + + // Resolve the field's type to decide defaults + validate. + const field_ty = self.resolveType(field.field_type); + const is_pointer = !field_ty.isBuiltin() and self.module.types.get(field_ty) == .pointer; + const is_object_ptr = is_pointer and blk: { + const pointee = self.module.types.get(field_ty).pointer.pointee; + // `*void` is NOT considered an object pointer — ambiguous. + if (pointee == .void) break :blk false; + // `*T` where T is a foreign-class struct (Obj-C class). + if (pointee.isBuiltin()) break :blk false; + const pointee_info = self.module.types.get(pointee); + if (pointee_info != .@"struct") break :blk false; + const struct_name = self.module.types.getString(pointee_info.@"struct".name); + const fcd = self.foreign_class_map.get(struct_name) orelse break :blk false; + break :blk fcd.runtime == .objc_class or fcd.runtime == .objc_protocol; + }; + + // `weak` requires an object pointer — `weak s32` is meaningless and + // would invoke objc_storeWeak on a non-object slot. + if (has_weak and !is_object_ptr) { + if (self.diagnostics) |d| { + const span = ast.Span{ .start = 0, .end = 0 }; + d.addFmt(.err, span, "#property(weak) on field '{s}' requires a pointer-to-Obj-C-class type; got '{s}'", .{ field.name, self.module.types.typeName(field_ty) }); + } + } + + // `copy` requires an object pointer — `copy s32` makes no sense. + if (has_copy and !is_object_ptr) { + if (self.diagnostics) |d| { + const span = ast.Span{ .start = 0, .end = 0 }; + d.addFmt(.err, span, "#property(copy) on field '{s}' requires a pointer-to-Obj-C-class type (typically NSString or NSArray)", .{field.name}); + } + } + + // `*void` is ambiguous (Obj-C object vs raw memory): require explicit + // modifier so the user opts into ARC semantics consciously. + if (is_pointer) { + const pointee = self.module.types.get(field_ty).pointer.pointee; + if (pointee == .void and explicit_count == 0) { + if (self.diagnostics) |d| { + const span = ast.Span{ .start = 0, .end = 0 }; + d.addFmt(.err, span, "#property on field '{s}' of type '*void' is ambiguous — specify `#property(strong|weak|copy|assign)` explicitly (Obj-C object vs raw memory)", .{field.name}); + } + return .assign; // assume safe default to keep compilation going + } + } + + // Apply explicit modifier or default. + if (has_weak) return .weak; + if (has_copy) return .copy; + if (has_strong) return .strong; + if (has_assign) return .assign; + // Default: object pointers → strong; everything else → assign. + return if (is_object_ptr) .strong else .assign; + } + + /// Lazily declare libobjc's ARC runtime helpers. Idempotent — uses + /// `ensureCRuntimeDecl` which skips already-declared symbols. Called + /// from the property setter/getter and -dealloc emission paths when + /// they need to emit a retain/release/storeWeak/etc. + fn ensureArcRuntimeDecls(self: *Lowering) void { + const ptr_void = self.module.types.ptrTo(.void); + _ = self.ensureCRuntimeDecl("objc_retain", &.{ptr_void}, ptr_void); + _ = self.ensureCRuntimeDecl("objc_release", &.{ptr_void}, .void); + _ = self.ensureCRuntimeDecl("objc_storeWeak", &.{ ptr_void, ptr_void }, ptr_void); + _ = self.ensureCRuntimeDecl("objc_loadWeakRetained", &.{ptr_void}, ptr_void); + _ = self.ensureCRuntimeDecl("objc_initWeak", &.{ ptr_void, ptr_void }, ptr_void); + _ = self.ensureCRuntimeDecl("objc_destroyWeak", &.{ptr_void}, .void); + } + fn emitObjcDefinedClassPropertyImps(self: *Lowering, fcd: *const ast.ForeignClassDecl, field: ast.ForeignFieldDecl) void { const state_ty = self.objcDefinedStateStructType(fcd); const state_info = self.module.types.get(state_ty); @@ -12052,6 +12187,12 @@ pub const Lowering = struct { const fidx = field_idx orelse return; const field_ty = self.resolveType(field.field_type); + // M4.B: validate modifiers + resolve ARC kind. Side-effect: emits + // diagnostics for typos, weak-on-non-object, ambiguous *void, etc. + // For now the setter/getter still emit bare load/store; subsequent + // M4.B commits wire the actual ARC ops keyed on this kind. + _ = self.objcPropertyKind(field); + // (1) Getter: ____imp self.emitObjcDefinedPropertyGetter(fcd, field, state_ty, fidx, field_ty); diff --git a/tests/expected/ffi-objc-arc-02-strong-property.exit b/tests/expected/ffi-objc-arc-02-strong-property.exit new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/tests/expected/ffi-objc-arc-02-strong-property.exit @@ -0,0 +1 @@ +1 diff --git a/tests/expected/ffi-objc-arc-02-strong-property.txt b/tests/expected/ffi-objc-arc-02-strong-property.txt new file mode 100644 index 0000000..ff29713 --- /dev/null +++ b/tests/expected/ffi-objc-arc-02-strong-property.txt @@ -0,0 +1 @@ +FAIL: child dealloc'd at midpoint (strong setter not retaining); delta=1 diff --git a/tests/expected/ffi-objc-arc-03-weak-property.exit b/tests/expected/ffi-objc-arc-03-weak-property.exit new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/tests/expected/ffi-objc-arc-03-weak-property.exit @@ -0,0 +1 @@ +1 diff --git a/tests/expected/ffi-objc-arc-03-weak-property.txt b/tests/expected/ffi-objc-arc-03-weak-property.txt new file mode 100644 index 0000000..73a890f --- /dev/null +++ b/tests/expected/ffi-objc-arc-03-weak-property.txt @@ -0,0 +1 @@ +FAIL: weak property didn't auto-nil after target dealloc