ffi 2.8: JNI descriptor derivation + table-driven Zig unit tests

New `src/ir/jni_descriptor.zig`:
  - `writeType(allocator, buf, ctx, type_node)` appends one JNI
    descriptor for an sx type AST node.
  - `deriveMethod(allocator, ctx, method)` returns the full
    `(args)ret` descriptor for a `ForeignMethodDecl`, skipping the
    implicit `self` for instance methods.
  - `Context.enclosing_path` resolves `*Self` to its `L<path>;` form.

Primitive table: void→V, bool→Z, s8/u8→B, s16→S, u16→C, s32→I,
s64→J, f32→F, f64→D. Arrays: `[]T` / `[*]T` / `[N]T` → `[<elem>`.
`*Self` → `L<enclosing>;`. Cross-class `*Foo` → explicit
`CrossClassRefNotYetSupported` error (lands in step 2.9 with the
ForeignClassDecl registry lookup).

Tests in `src/ir/jni_descriptor.test.zig`: primitive table coverage,
void-on-null, *Self, slice, cross-class-fail-fast, plus three
deriveMethod scenarios (instance, static, multi-param, slice param).

Step 2.8 is internal compiler work — derivation isn't observable at
the sx surface until call-site lowering at step 2.11. The cadence
rule's xfail-then-green pattern presupposes a snapshot harness that
doesn't apply to internal-only functions; the rule re-applies at
2.11 where end-to-end observation returns.

zig build test passes; 126/126 examples still green.
This commit is contained in:
agra
2026-05-20 10:24:12 +03:00
parent 5fd8e0fbbe
commit 21c49066e5
3 changed files with 339 additions and 0 deletions

View File

@@ -39,6 +39,8 @@ pub const type_bridge = @import("type_bridge.zig");
pub const resolveAstType = type_bridge.resolveAstType;
pub const bridgeType = type_bridge.bridgeType;
pub const jni_descriptor = @import("jni_descriptor.zig");
pub const types_tests = @import("types.test.zig");
pub const inst_tests = @import("inst.test.zig");
pub const module_tests = @import("module.test.zig");
@@ -47,6 +49,7 @@ pub const interp_tests = @import("interp.test.zig");
pub const lower_tests = @import("lower.test.zig");
pub const type_bridge_tests = @import("type_bridge.test.zig");
pub const emit_llvm_tests = @import("emit_llvm.test.zig");
pub const jni_descriptor_tests = @import("jni_descriptor.test.zig");
test {
@import("std").testing.refAllDecls(@This());

View File

@@ -0,0 +1,208 @@
// Tests for jni_descriptor.zig — Phase 2 step 2.8.
// Table-driven golden test for the primitive / array / *Self JNI
// signature alphabet. Cross-class references land in 2.9.
const std = @import("std");
const ast = @import("../ast.zig");
const desc = @import("jni_descriptor.zig");
const Node = ast.Node;
fn makeTypeExpr(allocator: std.mem.Allocator, name: []const u8) !*Node {
const node = try allocator.create(Node);
node.* = .{
.span = .{ .start = 0, .end = 0 },
.data = .{ .type_expr = .{ .name = name } },
};
return node;
}
fn makePointer(allocator: std.mem.Allocator, pointee: *Node) !*Node {
const node = try allocator.create(Node);
node.* = .{
.span = .{ .start = 0, .end = 0 },
.data = .{ .pointer_type_expr = .{ .pointee_type = pointee } },
};
return node;
}
fn makeSlice(allocator: std.mem.Allocator, element: *Node) !*Node {
const node = try allocator.create(Node);
node.* = .{
.span = .{ .start = 0, .end = 0 },
.data = .{ .slice_type_expr = .{ .element_type = element } },
};
return node;
}
fn expectType(name: []const u8, expected: []const u8) !void {
const a = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const aa = arena.allocator();
const tn = try makeTypeExpr(aa, name);
var buf: std.ArrayList(u8) = .empty;
defer buf.deinit(a);
try desc.writeType(a, &buf, .{ .enclosing_path = "" }, tn);
try std.testing.expectEqualStrings(expected, buf.items);
}
test "primitive descriptors" {
try expectType("void", "V");
try expectType("bool", "Z");
try expectType("s8", "B");
try expectType("u8", "B");
try expectType("s16", "S");
try expectType("u16", "C");
try expectType("s32", "I");
try expectType("s64", "J");
try expectType("f32", "F");
try expectType("f64", "D");
}
test "void return is V (null type_node)" {
const a = std.testing.allocator;
var buf: std.ArrayList(u8) = .empty;
defer buf.deinit(a);
try desc.writeType(a, &buf, .{ .enclosing_path = "" }, null);
try std.testing.expectEqualStrings("V", buf.items);
}
test "*Self resolves to enclosing class L-form" {
const a = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const aa = arena.allocator();
const self_te = try makeTypeExpr(aa, "Self");
const ptr = try makePointer(aa, self_te);
var buf: std.ArrayList(u8) = .empty;
defer buf.deinit(a);
try desc.writeType(a, &buf, .{ .enclosing_path = "android/view/View" }, ptr);
try std.testing.expectEqualStrings("Landroid/view/View;", buf.items);
}
test "slice of primitive is array descriptor" {
const a = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const aa = arena.allocator();
const s32 = try makeTypeExpr(aa, "s32");
const slice = try makeSlice(aa, s32);
var buf: std.ArrayList(u8) = .empty;
defer buf.deinit(a);
try desc.writeType(a, &buf, .{ .enclosing_path = "" }, slice);
try std.testing.expectEqualStrings("[I", buf.items);
}
test "cross-class *Foo is not yet supported (2.9)" {
const a = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const aa = arena.allocator();
const foo = try makeTypeExpr(aa, "Window");
const ptr = try makePointer(aa, foo);
var buf: std.ArrayList(u8) = .empty;
defer buf.deinit(a);
const result = desc.writeType(a, &buf, .{ .enclosing_path = "android/view/View" }, ptr);
try std.testing.expectError(desc.DeriveError.CrossClassRefNotYetSupported, result);
}
test "deriveMethod skips implicit self for instance methods" {
const a = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const aa = arena.allocator();
// method: getId :: (self: *Self) -> s32 → ()I
const self_te = try makeTypeExpr(aa, "Self");
const self_ptr = try makePointer(aa, self_te);
const ret = try makeTypeExpr(aa, "s32");
const method: ast.ForeignMethodDecl = .{
.name = "getId",
.params = &.{self_ptr},
.param_names = &.{"self"},
.return_type = ret,
.is_static = false,
};
const out = try desc.deriveMethod(a, .{ .enclosing_path = "android/view/View" }, method);
defer a.free(out);
try std.testing.expectEqualStrings("()I", out);
}
test "deriveMethod for static method emits all params" {
const a = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const aa = arena.allocator();
// static abs :: (n: s32) -> s32 → (I)I
const n_ty = try makeTypeExpr(aa, "s32");
const ret = try makeTypeExpr(aa, "s32");
const method: ast.ForeignMethodDecl = .{
.name = "abs",
.params = &.{n_ty},
.param_names = &.{"n"},
.return_type = ret,
.is_static = true,
};
const out = try desc.deriveMethod(a, .{ .enclosing_path = "java/lang/Math" }, method);
defer a.free(out);
try std.testing.expectEqualStrings("(I)I", out);
}
test "deriveMethod with multiple primitive params and void return" {
const a = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const aa = arena.allocator();
// setBounds :: (self: *Self, x: s32, y: s32, w: s32, h: s32) -> void → (IIII)V
const self_te = try makeTypeExpr(aa, "Self");
const self_ptr = try makePointer(aa, self_te);
const s = try makeTypeExpr(aa, "s32");
const method: ast.ForeignMethodDecl = .{
.name = "setBounds",
.params = &.{ self_ptr, s, s, s, s },
.param_names = &.{ "self", "x", "y", "w", "h" },
.return_type = null,
.is_static = false,
};
const out = try desc.deriveMethod(a, .{ .enclosing_path = "android/graphics/Rect" }, method);
defer a.free(out);
try std.testing.expectEqualStrings("(IIII)V", out);
}
test "deriveMethod with slice param" {
const a = std.testing.allocator;
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const aa = arena.allocator();
// copy :: (self: *Self, src: []s8) -> s32 → ([B)I
const self_te = try makeTypeExpr(aa, "Self");
const self_ptr = try makePointer(aa, self_te);
const s8 = try makeTypeExpr(aa, "s8");
const src_slice = try makeSlice(aa, s8);
const ret = try makeTypeExpr(aa, "s32");
const method: ast.ForeignMethodDecl = .{
.name = "copy",
.params = &.{ self_ptr, src_slice },
.param_names = &.{ "self", "src" },
.return_type = ret,
.is_static = false,
};
const out = try desc.deriveMethod(a, .{ .enclosing_path = "java/nio/ByteBuffer" }, method);
defer a.free(out);
try std.testing.expectEqualStrings("([B)I", out);
}

128
src/ir/jni_descriptor.zig Normal file
View File

@@ -0,0 +1,128 @@
// JNI descriptor derivation for #jni_class methods (Phase 2 step 2.8).
//
// Walks sx parameter / return type AST nodes through the standard JNI
// signature alphabet (JLS §4.3.3 and JNI spec §3.3) to produce the
// descriptor string consumed by `GetMethodID` / `GetStaticMethodID`.
//
// void → V
// bool → Z (jboolean)
// s8 → B (jbyte)
// s16 → S (jshort)
// s32 → I (jint)
// s64 → J (jlong)
// u8 → B (jbyte — JNI bytes are signed; sx u8 still bridges via B)
// u16 → C (jchar — unsigned 16-bit)
// f32 → F (jfloat)
// f64 → D (jdouble)
// []T → [<elem>
// [*]T → [<elem> (sx many-pointer treated as array for now)
// *Self → L<enclosing-foreign-path>;
// *Foo → L<Foo's foreign path>; (cross-class — step 2.9)
//
// `#jni_method_descriptor("...")` (step 2.6) overrides this whole walk
// when set; sema/lowering use the override verbatim.
const std = @import("std");
const ast = @import("../ast.zig");
const Node = ast.Node;
pub const DeriveError = error{
UnknownPrimitive,
UnsupportedType,
CrossClassRefNotYetSupported, // *Foo for non-Self — lands in step 2.9
OutOfMemory,
};
pub const Context = struct {
/// Foreign path of the enclosing #jni_class — used to resolve `*Self`.
/// e.g. "android/view/View".
enclosing_path: []const u8,
};
/// Appends a single JNI type-descriptor to `buf` for `type_node`.
/// A null type_node represents a void return ('V').
pub fn writeType(
allocator: std.mem.Allocator,
buf: *std.ArrayList(u8),
ctx: Context,
type_node: ?*const Node,
) DeriveError!void {
if (type_node == null) {
try buf.append(allocator, 'V');
return;
}
const tn = type_node.?;
switch (tn.data) {
.type_expr => |te| {
const ch = primitiveChar(te.name) orelse return DeriveError.UnknownPrimitive;
try buf.append(allocator, ch);
},
.slice_type_expr => |sl| {
try buf.append(allocator, '[');
try writeType(allocator, buf, ctx, sl.element_type);
},
.many_pointer_type_expr => |mp| {
try buf.append(allocator, '[');
try writeType(allocator, buf, ctx, mp.element_type);
},
.array_type_expr => |arr| {
try buf.append(allocator, '[');
try writeType(allocator, buf, ctx, arr.element_type);
},
.pointer_type_expr => |ptr| {
// *Self → L<enclosing-foreign-path>;
const inner = ptr.pointee_type;
if (inner.data == .type_expr and std.mem.eql(u8, inner.data.type_expr.name, "Self")) {
try buf.append(allocator, 'L');
try buf.appendSlice(allocator, ctx.enclosing_path);
try buf.append(allocator, ';');
return;
}
return DeriveError.CrossClassRefNotYetSupported;
},
else => return DeriveError.UnsupportedType,
}
}
/// Derives the full `(args)ret` method descriptor for a `ForeignMethodDecl`.
/// The first param is skipped when `is_static == false` (it's the implicit
/// `self: *Self` receiver, which doesn't appear in the JNI descriptor).
pub fn deriveMethod(
allocator: std.mem.Allocator,
ctx: Context,
method: ast.ForeignMethodDecl,
) DeriveError![]u8 {
var buf: std.ArrayList(u8) = .empty;
errdefer buf.deinit(allocator);
try buf.append(allocator, '(');
const start: usize = if (method.is_static) 0 else 1;
if (method.params.len < start) return DeriveError.UnsupportedType;
for (method.params[start..]) |param| {
try writeType(allocator, &buf, ctx, param);
}
try buf.append(allocator, ')');
try writeType(allocator, &buf, ctx, method.return_type);
return buf.toOwnedSlice(allocator);
}
fn primitiveChar(name: []const u8) ?u8 {
const table = [_]struct { name: []const u8, ch: u8 }{
.{ .name = "void", .ch = 'V' },
.{ .name = "bool", .ch = 'Z' },
.{ .name = "s8", .ch = 'B' },
.{ .name = "u8", .ch = 'B' },
.{ .name = "s16", .ch = 'S' },
.{ .name = "u16", .ch = 'C' },
.{ .name = "s32", .ch = 'I' },
.{ .name = "s64", .ch = 'J' },
.{ .name = "f32", .ch = 'F' },
.{ .name = "f64", .ch = 'D' },
};
for (table) |entry| {
if (std.mem.eql(u8, name, entry.name)) return entry.ch;
}
return null;
}