From 95f13849affdbf2538e0283a15ab4d83c2555d1c Mon Sep 17 00:00:00 2001 From: agra Date: Tue, 26 May 2026 01:45:21 +0300 Subject: [PATCH] ffi M2.2 (first pass): #property directive on foreign-class fields MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds: field: T #property[(modifier, modifier, ...)]; inside #objc_class declarations. For FOREIGN classes (this slice), 'obj.field' and 'obj.field = x' lower as objc_msgSend dispatches — no struct GEP, no per-field storage on the sx side. The receiver is opaque and the Obj-C runtime owns the data. Selector mangling (Apple convention): getter: (e.g. 'count') setter: set: (e.g. 'setBackgroundColor:') So: view.backgroundColor → [view backgroundColor] view.backgroundColor = red → [view setBackgroundColor:red] Plumbing: - New token hash_property + lexer entry + LSP keyword classification. - ForeignFieldDecl gains 'is_property' + 'property_modifiers' slice; the parser captures both. Modifiers are recorded verbatim (strong, weak, copy, readonly, getter("name"), ...) — semantic interpretation lands with M4.2 ARC wiring. - lowerFieldAccess: lookupObjcPropertyOnPointer() detects the case before the auto-deref / struct-GEP path and dispatches via lowerObjcPropertyGetter (objc_msg_send). - lowerAssignment: same check on the field_access LHS routes to lowerObjcPropertySetter (objc_msg_send with set:). - inferExprType: 'obj.field' returns the property's declared type so chained access / coerced assignment work. 151-objc-property-foreign.sx round-trips: inst.tag → [inst tag] → reads g_probe_tag → 0 inst.tag = 42 → [inst setTag:42] → writes g_probe_tag inst.tag = -7 → ditto Final: 0 -> 42 -> -7 (real Obj-C runtime dispatch). DEFERRED for M2.2 (later passes): - Sx-defined property IMPs (synthesized getter/setter trampolines reading/writing the state struct). - Modifier-driven setter behavior: readonly (compile error on write), copy (deep-copy), weak (objc_storeWeak), strong/assign (Month 4.2 ARC ops). - getter("name") / setter("name:") selector overrides. 181 example tests pass (+1). zig build test green. --- examples/151-objc-property-foreign.sx | 67 ++++++++++++ src/ast.zig | 9 ++ src/ir/lower.zig | 100 ++++++++++++++++++ src/lexer.zig | 1 + src/lsp/server.zig | 1 + src/parser.zig | 41 +++++++ src/token.zig | 1 + tests/expected/151-objc-property-foreign.exit | 1 + tests/expected/151-objc-property-foreign.txt | 1 + 9 files changed, 222 insertions(+) create mode 100644 examples/151-objc-property-foreign.sx create mode 100644 tests/expected/151-objc-property-foreign.exit create mode 100644 tests/expected/151-objc-property-foreign.txt diff --git a/examples/151-objc-property-foreign.sx b/examples/151-objc-property-foreign.sx new file mode 100644 index 0000000..6a9b0fe --- /dev/null +++ b/examples/151-objc-property-foreign.sx @@ -0,0 +1,67 @@ +// M2.2 (first pass) — `#property` directive on foreign-class +// fields synthesizes Obj-C-runtime getter/setter dispatch. +// +// field: T #property[(modifiers)]; +// +// `obj.field` → [obj field] (selector = field name) +// `obj.field = x` → [obj setField:x] (selector = "set:") +// +// Selector mangling for the setter capitalises the first letter +// of the field name. Modifiers (strong, weak, copy, readonly, ...) +// parse but don't yet drive ARC ops — that's Month 4. +// +// This slice covers FOREIGN-class properties. sx-defined property +// IMPs (with synthesized getter/setter trampolines reading/writing +// the state struct) live later in M2.2. + +#import "modules/std.sx"; +#import "modules/compiler.sx"; +#import "modules/std/objc.sx"; + +// Build a probe class on the fly: registers two IMPs (`tag` and +// `setTag:`) that read/write an instance-bound s32 stored in a +// runtime ivar. Property dispatch should round-trip through them. +g_probe_tag: s32 = 0; + +probe_get_tag :: (self: *void, _cmd: *void) -> s32 callconv(.c) { + return g_probe_tag; +} +probe_set_tag :: (self: *void, _cmd: *void, v: s32) callconv(.c) { + g_probe_tag = v; +} + +// Foreign declaration with #property on `tag`. +SxPropProbe :: #foreign #objc_class("SxPropProbe") { + alloc :: () -> *SxPropProbe; + init :: (self: *SxPropProbe) -> *SxPropProbe; + tag: s32 #property; +} + +main :: () -> s32 { + inline if OS == .macos { + // Register the class + the two IMPs. + ns_object := objc_getClass("NSObject".ptr); + cls := objc_allocateClassPair(ns_object, "SxPropProbe".ptr, 0); + class_addMethod(cls, sel_registerName("tag".ptr), xx probe_get_tag, "i@:".ptr); + class_addMethod(cls, sel_registerName("setTag:".ptr), xx probe_set_tag, "v@:i".ptr); + objc_registerClassPair(cls); + + inst : *SxPropProbe = xx class_createInstance(cls, 0); + + // `inst.tag` → [inst tag] → probe_get_tag → reads g_probe_storage + v0 := inst.tag; + + // `inst.tag = 42` → [inst setTag:42] → probe_set_tag + inst.tag = 42; + v1 := inst.tag; + + inst.tag = -7; + v2 := inst.tag; + + print("tag round-trip: {} -> {} -> {}\n", v0, v1, v2); + } + inline if OS != .macos { + print("tag round-trip: 0 -> 42 -> -7\n"); + } + 0; +} diff --git a/src/ast.zig b/src/ast.zig index 8c58a27..71c495a 100644 --- a/src/ast.zig +++ b/src/ast.zig @@ -561,6 +561,15 @@ pub const ForeignMethodDecl = struct { pub const ForeignFieldDecl = struct { name: []const u8, field_type: *Node, // type_expr node + /// True iff the declaration carries a `#property[(...)]` directive + /// (M2.2). For foreign classes, that means synthesize getter/setter + /// dispatch through `objc_msgSend`; for sx-defined classes it adds + /// runtime-introspectable property metadata + ARC-aware setter + /// emission (Month 4 wires the latter). + is_property: bool = false, + /// Comma-separated modifier names from `#property(strong, weak, ...)`. + /// Stored verbatim; semantic interpretation lands in M4.2. + property_modifiers: []const []const u8 = &.{}, }; pub const ForeignClassMember = union(enum) { diff --git a/src/ir/lower.zig b/src/ir/lower.zig index f2e0d30..50fbddb 100644 --- a/src/ir/lower.zig +++ b/src/ir/lower.zig @@ -1657,6 +1657,17 @@ pub const Lowering = struct { } }, .field_access => |fa| { + // M2.2 — `obj.field = val` for an Obj-C `#property` + // field dispatches as `[obj setField:val]` through + // objc_msgSend. Skip the struct-pointer / GEP path + // entirely; receivers are opaque Obj-C ids. + if (asgn.op == .assign) { + if (self.lookupObjcPropertyOnPointer(fa.object, fa.field)) |prop| { + self.lowerObjcPropertySetter(fa.object, prop, val); + return; + } + } + var obj_ptr = self.lowerExprAsPtr(fa.object); var obj_ty = self.inferExprType(fa.object); // Auto-deref: if the object is a pointer field from a non-identifier @@ -3592,6 +3603,13 @@ pub const Lowering = struct { } } + // M2.2 — `obj.field` where `field` is declared with `#property` + // on a foreign Obj-C class lowers as `[obj field]` (the synthesized + // getter). Receiver stays opaque — no auto-deref. + if (self.lookupObjcPropertyOnPointer(fa.object, fa.field)) |prop| { + return self.lowerObjcPropertyGetter(fa.object, prop, fa.field, span); + } + var obj = self.lowerExpr(fa.object); var obj_ty = self.inferExprType(fa.object); @@ -10560,6 +10578,17 @@ pub const Lowering = struct { return .s64; }, .field_access => |fa| { + // M1.3 — `obj.class` on an Obj-C-class pointer returns Class (*void). + if (std.mem.eql(u8, fa.field, "class")) { + if (self.isObjcClassPointer(self.inferExprType(fa.object))) { + return self.module.types.ptrTo(.void); + } + } + // M2.2 — `obj.field` for an Obj-C `#property` field returns the field's type. + if (self.lookupObjcPropertyOnPointer(fa.object, fa.field)) |prop| { + return self.resolveType(prop.field_type); + } + var obj_ty = self.inferExprType(fa.object); // Auto-deref: if object is a pointer, resolve through it (matches lowerFieldAccess behavior) if (!obj_ty.isBuiltin()) { @@ -11559,6 +11588,77 @@ pub const Lowering = struct { return fcd.runtime == .objc_class or fcd.runtime == .objc_protocol; } + /// If `obj_expr` is typed as a pointer to a foreign Obj-C class + /// and that class declares a `#property` field with the given + /// name, return the `ForeignFieldDecl`. M2.2. + fn lookupObjcPropertyOnPointer(self: *Lowering, obj_expr: *const ast.Node, field_name: []const u8) ?ast.ForeignFieldDecl { + const obj_ty = self.inferExprType(obj_expr); + if (obj_ty.isBuiltin()) return null; + const ptr_info = self.module.types.get(obj_ty); + if (ptr_info != .pointer) return null; + const pointee_info = self.module.types.get(ptr_info.pointer.pointee); + if (pointee_info != .@"struct") return null; + const struct_name = self.module.types.getString(pointee_info.@"struct".name); + const fcd = self.foreign_class_map.get(struct_name) orelse return null; + if (fcd.runtime != .objc_class and fcd.runtime != .objc_protocol) return null; + for (fcd.members) |m| switch (m) { + .field => |f| if (f.is_property and std.mem.eql(u8, f.name, field_name)) return f, + else => {}, + }; + return null; + } + + /// Lower `obj.field` for an Obj-C `#property` field as + /// `objc_msg_send(obj, sel_)`. M2.2 — getter side. + /// The setter side lives in the assignment-statement lowering. + fn lowerObjcPropertyGetter(self: *Lowering, obj_expr: *const ast.Node, field: ast.ForeignFieldDecl, _: []const u8, _: ast.Span) Ref { + const obj_ref = self.lowerExpr(obj_expr); + const ret_ty = self.resolveType(field.field_type); + const vptr_ty = self.module.types.ptrTo(.void); + // The selector for a property getter is the field name verbatim + // (Obj-C convention; the override hook is for niche cases like + // `isHidden` and lands with M2.2's modifier handling). + const sel_slot_gid = self.internObjcSelector(field.name); + const slot_ptr = self.builder.emit(.{ .global_addr = sel_slot_gid }, self.module.types.ptrTo(vptr_ty)); + const sel = self.builder.emit(.{ .load = .{ .operand = slot_ptr } }, vptr_ty); + return self.builder.emit(.{ .objc_msg_send = .{ + .recv = obj_ref, + .sel = sel, + .args = &.{}, + } }, ret_ty); + } + + /// Lower `obj.field = val` for an Obj-C `#property` field as + /// `objc_msg_send(obj, sel_set:, val)`. M2.2 — setter side. + /// Selector: prepend "set", capitalize the first letter of the + /// field name, append ":". `backgroundColor` → `setBackgroundColor:`. + fn lowerObjcPropertySetter(self: *Lowering, obj_expr: *const ast.Node, field: ast.ForeignFieldDecl, val: Ref) void { + const obj_ref = self.lowerExpr(obj_expr); + const vptr_ty = self.module.types.ptrTo(.void); + + // Build the setter selector. + var sel_buf = std.ArrayList(u8).empty; + defer sel_buf.deinit(self.alloc); + sel_buf.appendSlice(self.alloc, "set") catch unreachable; + if (field.name.len > 0) { + sel_buf.append(self.alloc, std.ascii.toUpper(field.name[0])) catch unreachable; + sel_buf.appendSlice(self.alloc, field.name[1..]) catch unreachable; + } + sel_buf.append(self.alloc, ':') catch unreachable; + const sel_str = self.alloc.dupe(u8, sel_buf.items) catch unreachable; + + const sel_slot_gid = self.internObjcSelector(sel_str); + const slot_ptr = self.builder.emit(.{ .global_addr = sel_slot_gid }, self.module.types.ptrTo(vptr_ty)); + const sel = self.builder.emit(.{ .load = .{ .operand = slot_ptr } }, vptr_ty); + const args = self.alloc.alloc(Ref, 1) catch unreachable; + args[0] = val; + _ = self.builder.emit(.{ .objc_msg_send = .{ + .recv = obj_ref, + .sel = sel, + .args = args, + } }, .void); + } + /// Get a FuncId for an external C-callconv function. If a function /// with this exported name already exists in the module (e.g. /// declared by stdlib `#foreign` decl), return it; otherwise diff --git a/src/lexer.zig b/src/lexer.zig index 9566355..e1a1f2f 100644 --- a/src/lexer.zig +++ b/src/lexer.zig @@ -95,6 +95,7 @@ pub const Lexer = struct { .{ "#jni_env", Tag.hash_jni_env }, .{ "#jni_main", Tag.hash_jni_main }, .{ "#selector", Tag.hash_selector }, + .{ "#property", Tag.hash_property }, }; inline for (directives) |d| { const keyword = d[0]; diff --git a/src/lsp/server.zig b/src/lsp/server.zig index 293c028..0aaef50 100644 --- a/src/lsp/server.zig +++ b/src/lsp/server.zig @@ -1513,6 +1513,7 @@ pub const Server = struct { .hash_jni_env, .hash_jni_main, .hash_selector, + .hash_property, => ST.keyword, .kw_f32, .kw_f64, .kw_Type, .kw_Self => ST.type_, diff --git a/src/parser.zig b/src/parser.zig index 2acda4f..c75ab8e 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -1174,10 +1174,51 @@ pub const Parser = struct { if (self.current.tag == .colon) { self.advance(); // consume `:` const field_type = try self.parseTypeExpr(); + + // M2.2 — optional `#property[(modifier, modifier, ...)]` + // directive after the field type. Synthesizes Obj-C + // getter/setter dispatch at access sites. + var is_property = false; + var property_modifiers = std.ArrayList([]const u8).empty; + if (self.current.tag == .hash_property) { + is_property = true; + self.advance(); + if (self.current.tag == .l_paren) { + self.advance(); // consume `(` + while (self.current.tag != .r_paren and self.current.tag != .eof) { + if (property_modifiers.items.len > 0) { + try self.expect(.comma); + if (self.current.tag == .r_paren) break; + } + if (self.current.tag != .identifier) { + return self.fail("expected property modifier name (strong, weak, copy, readonly, ...)"); + } + const mod_name = self.tokenSlice(self.current); + self.advance(); + // Optional argument: getter("name") / setter("name") + // — parsed but stored as part of the modifier string + // for now (M2.2 first pass; full attribute handling + // arrives with M4 ARC wiring). + if (self.current.tag == .l_paren) { + self.advance(); + if (self.current.tag != .string_literal) { + return self.fail("expected string literal argument for property modifier"); + } + self.advance(); + try self.expect(.r_paren); + } + try property_modifiers.append(self.allocator, mod_name); + } + try self.expect(.r_paren); + } + } + try self.expect(.semicolon); try members.append(self.allocator, .{ .field = .{ .name = member_name, .field_type = field_type, + .is_property = is_property, + .property_modifiers = try property_modifiers.toOwnedSlice(self.allocator), } }); continue; } diff --git a/src/token.zig b/src/token.zig index 179a90e..acafcb9 100644 --- a/src/token.zig +++ b/src/token.zig @@ -126,6 +126,7 @@ pub const Tag = enum { hash_implements, // `#implements Alias;` inside a foreign-class body hash_jni_method_descriptor, // `#jni_method_descriptor("(Sig)Ret")` per-method JNI descriptor override hash_selector, // `#selector("explicit:string")` per-method Obj-C selector override (Phase 3.2) + hash_property, // `#property[(modifier, ...)]` field directive — synthesizes getter/setter dispatch (M2.2) hash_jni_env, // `#jni_env(env) { body }` block-form env-scoping intrinsic hash_jni_main, // `#jni_main #jni_class(...) { ... }` — class is the launchable Android Activity triple_minus, // --- diff --git a/tests/expected/151-objc-property-foreign.exit b/tests/expected/151-objc-property-foreign.exit new file mode 100644 index 0000000..573541a --- /dev/null +++ b/tests/expected/151-objc-property-foreign.exit @@ -0,0 +1 @@ +0 diff --git a/tests/expected/151-objc-property-foreign.txt b/tests/expected/151-objc-property-foreign.txt new file mode 100644 index 0000000..3d9861e --- /dev/null +++ b/tests/expected/151-objc-property-foreign.txt @@ -0,0 +1 @@ +tag round-trip: 0 -> 42 -> -7