ffi 2.11 green: DSL call sites on #jni_class-typed receivers lower to JNI dispatch
`inst.method(args)` on a value typed as a foreign-class alias
(`Activity :: #jni_class("android/app/Activity") { getWindow ::
(self: *Self) -> *Window; }` etc.) now lowers to `jni_msg_send`
with descriptor auto-derived from the sx signature, env from the
enclosing `#jni_env` scope (lexical-direct via 2.16b), and slot
interning re-used from Phase 1C.
Touch surface:
- `Lowering` gains `foreign_class_map: StringHashMap(*const
ForeignClassDecl)` populated in `scanDecls` + `lowerDecls`.
- New `registerForeignClassDecl` records each declared alias; the
type-bridge fallback already interns the alias as a 0-field
struct, so `*Activity` resolves cleanly through `getStructTypeName`.
- New `lowerForeignMethodCall` looks up the method in
`ForeignClassDecl.members`, derives the descriptor via
`jni_descriptor.deriveMethod` (with a `ClassRegistry` built from
`foreign_class_map`), and emits `jni_msg_send` directly. Filters
by runtime — `jni_class`/`jni_interface` lower; `objc_class` etc.
surface a clear "not yet supported" diagnostic until Phase 3/4.
- `lowerCall`'s method-dispatch arm inserts the foreign-class
check before the standard struct-method resolution.
JNI descriptor derivation gains `*void → Ljava/lang/Object;` (the
opaque-jobject convention) — common when sx code doesn't have a
precise Java type for the value. Locked in with a unit test.
IR snapshot at `tests/expected/ffi-jni-class-08-call.ir` shows the
full lowering: env from the enclosing fn param, target from the
foreign-class arg, slot-interned `(class, method, sig)` cache
pair, jni_msg_send to `CallObjectMethod` (slot 34). Mangled slot
names `@SX_JNI_CLS_getWindow____Ljava_lang_Object_` confirm the
derived descriptor.
129/129 examples + 16 jni_descriptor unit tests green.
This commit is contained in:
@@ -69,6 +69,21 @@ test "void return is V (null type_node)" {
|
||||
try std.testing.expectEqualStrings("V", buf.items);
|
||||
}
|
||||
|
||||
test "*void resolves to java/lang/Object (opaque jobject)" {
|
||||
const a = std.testing.allocator;
|
||||
var arena = std.heap.ArenaAllocator.init(a);
|
||||
defer arena.deinit();
|
||||
const aa = arena.allocator();
|
||||
|
||||
const void_te = try makeTypeExpr(aa, "void");
|
||||
const ptr = try makePointer(aa, void_te);
|
||||
|
||||
var buf: std.ArrayList(u8) = .empty;
|
||||
defer buf.deinit(a);
|
||||
try desc.writeType(a, &buf, .{ .enclosing_path = "anything" }, ptr);
|
||||
try std.testing.expectEqualStrings("Ljava/lang/Object;", buf.items);
|
||||
}
|
||||
|
||||
test "*Self resolves to enclosing class L-form" {
|
||||
const a = std.testing.allocator;
|
||||
var arena = std.heap.ArenaAllocator.init(a);
|
||||
|
||||
@@ -79,12 +79,16 @@ pub fn writeType(
|
||||
try writeType(allocator, buf, ctx, arr.element_type);
|
||||
},
|
||||
.pointer_type_expr => |ptr| {
|
||||
// *Self → L<enclosing>;, *Foo → L<Foo's foreign path>;
|
||||
// *Self → L<enclosing>;, *Foo → L<Foo's foreign path>;,
|
||||
// *void → Ljava/lang/Object; (opaque jobject — common when
|
||||
// users don't have a precise Java type for the value).
|
||||
const inner = ptr.pointee_type;
|
||||
if (inner.data != .type_expr) return DeriveError.UnsupportedType;
|
||||
const target_name = inner.data.type_expr.name;
|
||||
const target_path: []const u8 = if (std.mem.eql(u8, target_name, "Self"))
|
||||
ctx.enclosing_path
|
||||
else if (std.mem.eql(u8, target_name, "void"))
|
||||
"java/lang/Object"
|
||||
else if (ctx.classes) |reg|
|
||||
reg.get(target_name) orelse return DeriveError.UnknownClassAlias
|
||||
else
|
||||
|
||||
119
src/ir/lower.zig
119
src/ir/lower.zig
@@ -10,6 +10,7 @@ const unescape = @import("../unescape.zig");
|
||||
const parser_mod = @import("../parser.zig");
|
||||
const interp_mod = @import("interp.zig");
|
||||
const errors = @import("../errors.zig");
|
||||
const jni_descriptor = @import("jni_descriptor.zig");
|
||||
|
||||
const TypeId = types.TypeId;
|
||||
const StringId = types.StringId;
|
||||
@@ -97,6 +98,7 @@ pub const Lowering = struct {
|
||||
current_source_file: ?[]const u8 = null, // source file of function currently being lowered
|
||||
sel_register_name_fid: ?FuncId = null, // lazily-declared `sel_registerName` extern (non-literal selector fallback)
|
||||
jni_env_stack: std.ArrayList(Ref) = std.ArrayList(Ref).empty, // lexical `#jni_env(env)` Ref stack — top is current scope's env for omitted-env `#jni_call`
|
||||
foreign_class_map: std.StringHashMap(*const ast.ForeignClassDecl) = std.StringHashMap(*const ast.ForeignClassDecl).init(std.heap.page_allocator), // sx alias → ForeignClassDecl (jni_class / objc_class / swift_class / ... — registered in scan pass)
|
||||
type_bindings: ?std.StringHashMap(TypeId) = null, // generic type param bindings ($T → concrete TypeId)
|
||||
current_match_tags: ?[]const u64 = null, // type tags for current match arm (for runtime dispatch)
|
||||
force_block_value: bool = false, // set by lowerBlockValue to extract if-else values
|
||||
@@ -361,6 +363,9 @@ pub const Lowering = struct {
|
||||
.impl_block => {
|
||||
self.registerImplBlock(&decl.data.impl_block, is_imported, decl);
|
||||
},
|
||||
.foreign_class_decl => {
|
||||
self.registerForeignClassDecl(&decl.data.foreign_class_decl);
|
||||
},
|
||||
.namespace_decl => |ns| {
|
||||
if (self.main_file != null) {
|
||||
self.lowerDecls(ns.decls);
|
||||
@@ -498,6 +503,9 @@ pub const Lowering = struct {
|
||||
.impl_block => {
|
||||
self.registerImplBlock(&decl.data.impl_block, is_imported, decl);
|
||||
},
|
||||
.foreign_class_decl => {
|
||||
self.registerForeignClassDecl(&decl.data.foreign_class_decl);
|
||||
},
|
||||
.namespace_decl => |ns| {
|
||||
if (self.main_file != null) {
|
||||
self.scanDecls(ns.decls);
|
||||
@@ -3930,6 +3938,96 @@ pub const Lowering = struct {
|
||||
} }, ret_ty);
|
||||
}
|
||||
|
||||
/// Lower an `inst.method(args)` call where `inst`'s type is a foreign-class
|
||||
/// alias declared by `#jni_class("...") { ... }` (or its parallel forms).
|
||||
/// JNI runtimes lower directly to `jni_msg_send` with a descriptor derived
|
||||
/// from the method's sx signature; Obj-C / Swift runtimes are deferred to
|
||||
/// Phase 3/4 and currently surface a clear diagnostic.
|
||||
fn lowerForeignMethodCall(
|
||||
self: *Lowering,
|
||||
fcd: *const ast.ForeignClassDecl,
|
||||
method_name: []const u8,
|
||||
target: Ref,
|
||||
method_args: []const Ref,
|
||||
span: ast.Span,
|
||||
) Ref {
|
||||
var found_method: ?ast.ForeignMethodDecl = null;
|
||||
for (fcd.members) |m| {
|
||||
switch (m) {
|
||||
.method => |md| {
|
||||
if (std.mem.eql(u8, md.name, method_name)) {
|
||||
found_method = md;
|
||||
break;
|
||||
}
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
const method = found_method orelse {
|
||||
if (self.diagnostics) |d| {
|
||||
d.addFmt(.err, span, "no method '{s}' on foreign class '{s}'", .{ method_name, fcd.name });
|
||||
}
|
||||
return Ref.none;
|
||||
};
|
||||
|
||||
if (fcd.runtime != .jni_class and fcd.runtime != .jni_interface) {
|
||||
if (self.diagnostics) |d| {
|
||||
d.addFmt(.err, span, "method calls on '{s}' runtime not yet supported (Phase 3/4)", .{@tagName(fcd.runtime)});
|
||||
}
|
||||
return Ref.none;
|
||||
}
|
||||
|
||||
if (self.jni_env_stack.items.len == 0) {
|
||||
if (self.diagnostics) |d| {
|
||||
d.addFmt(.err, span, "method call on '{s}' requires an enclosing '#jni_env' scope", .{fcd.name});
|
||||
}
|
||||
return Ref.none;
|
||||
}
|
||||
const env_ref = self.jni_env_stack.items[self.jni_env_stack.items.len - 1];
|
||||
|
||||
// Build a ClassRegistry snapshot so descriptor derivation can
|
||||
// resolve `*Foo` cross-class refs to their foreign paths.
|
||||
var registry = jni_descriptor.ClassRegistry.init(self.alloc);
|
||||
defer registry.deinit();
|
||||
var it = self.foreign_class_map.iterator();
|
||||
while (it.next()) |entry| {
|
||||
registry.put(entry.key_ptr.*, entry.value_ptr.*.foreign_path) catch {};
|
||||
}
|
||||
|
||||
const desc_str = jni_descriptor.deriveMethod(self.alloc, .{
|
||||
.enclosing_path = fcd.foreign_path,
|
||||
.classes = ®istry,
|
||||
}, method) catch |err| {
|
||||
if (self.diagnostics) |d| {
|
||||
d.addFmt(.err, span, "JNI descriptor derivation failed for '{s}.{s}': {s}", .{ fcd.name, method.name, @errorName(err) });
|
||||
}
|
||||
return Ref.none;
|
||||
};
|
||||
|
||||
const name_sid = self.module.types.internString(method_name);
|
||||
const name_ref = self.builder.constString(name_sid);
|
||||
const sig_sid = self.module.types.internString(desc_str);
|
||||
const sig_ref = self.builder.constString(sig_sid);
|
||||
|
||||
const ret_ty = if (method.return_type) |rt| self.resolveType(rt) else .void;
|
||||
|
||||
const cache_key: inst_mod.CacheKey = .{
|
||||
.name_str = method_name,
|
||||
.sig_str = desc_str,
|
||||
};
|
||||
|
||||
const args_owned = self.alloc.dupe(Ref, method_args) catch unreachable;
|
||||
return self.builder.emit(.{ .jni_msg_send = .{
|
||||
.env = env_ref,
|
||||
.target = target,
|
||||
.name = name_ref,
|
||||
.sig = sig_ref,
|
||||
.args = args_owned,
|
||||
.is_static = method.is_static,
|
||||
.cache_key = cache_key,
|
||||
} }, ret_ty);
|
||||
}
|
||||
|
||||
// ── Calls ───────────────────────────────────────────────────────
|
||||
|
||||
fn lowerCall(self: *Lowering, c: *const ast.Call) Ref {
|
||||
@@ -4494,8 +4592,18 @@ pub const Lowering = struct {
|
||||
method_args.append(self.alloc, a) catch unreachable;
|
||||
}
|
||||
|
||||
// Try to resolve the method by struct type name
|
||||
// Foreign-class DSL: `inst.method(args)` where `inst`'s
|
||||
// type is an alias declared by `#jni_class("...") { ... }`
|
||||
// (or its parallel forms). Routes to the JNI dispatch
|
||||
// shape, descriptor derived from the sx signature.
|
||||
const struct_name = self.getStructTypeName(obj_ty);
|
||||
if (struct_name) |sname_for_foreign| {
|
||||
if (self.foreign_class_map.get(sname_for_foreign)) |fcd| {
|
||||
return self.lowerForeignMethodCall(fcd, fa.field, obj, args.items, c.callee.span);
|
||||
}
|
||||
}
|
||||
|
||||
// Try to resolve the method by struct type name
|
||||
if (struct_name) |sname| {
|
||||
// Try direct qualified name: StructName.method
|
||||
const qualified = std.fmt.allocPrint(self.alloc, "{s}.{s}", .{ sname, fa.field }) catch fa.field;
|
||||
@@ -8004,6 +8112,15 @@ pub const Lowering = struct {
|
||||
}
|
||||
}
|
||||
|
||||
/// Register a foreign-class declaration. The alias goes into
|
||||
/// `foreign_class_map` for method-dispatch lookup. The underlying
|
||||
/// type (e.g. `*Activity`) is resolved via the existing struct
|
||||
/// fallback in `type_bridge.resolveTypeName` (which interns unknown
|
||||
/// named types as 0-field structs).
|
||||
fn registerForeignClassDecl(self: *Lowering, fcd: *const ast.ForeignClassDecl) void {
|
||||
self.foreign_class_map.put(fcd.name, fcd) catch {};
|
||||
}
|
||||
|
||||
/// Register an impl block: register its methods as TypeName.method in fn_ast_map.
|
||||
fn registerImplBlock(self: *Lowering, ib: *const ast.ImplBlock, is_imported: bool, decl: *const Node) void {
|
||||
// Parameterised-protocol impl (e.g. `impl Into(Block) for Closure() -> void`):
|
||||
|
||||
Reference in New Issue
Block a user