Files
sx/src/ir/jni_java_emit.zig
agra 8ae4e0c653 ffi #jni_main R.1: manifest synthesis + default parent → android.app.Activity
When `Compilation.lowering_jni_main_decls` is non-empty, `createApk`
synthesises a manifest whose `<activity android:name>` points at the
user's `#jni_main` class (dotted form of the foreign path), sets
`android:hasCode="true"` so Android loads the bundled classes.dex, and
drops the `android.app.lib_name` meta-data (that's the NativeActivity-
specific autoload mechanism — Java-driven Activities load the .so via
`System.loadLibrary` from a Java static initializer slice R.3 will
emit). The legacy NativeActivity path stays as the fallback when no
`#jni_main` decl is present.

`jni_java_emit.zig`'s default superclass moves from
`android.app.NativeActivity` to `android.app.Activity` — the former
requires native_app_glue's `ANativeActivity_onCreate` to be in the .so,
which the next slice (R.2) will stop linking by default.

Verified end-to-end on the slice 2 smoke APK: `aapt2 dump xmltree`
shows `android:name="co.swipelab.sxjnimain.SxApp"` + `hasCode="true"`,
and `dexdump -l plain` confirms SxApp now extends `Landroid/app/Activity;`.
99-android-egl-clear's APK still uses the NativeActivity manifest as
before (legacy path intact for R.2-R.5).
2026-05-20 14:55:26 +03:00

271 lines
9.2 KiB
Zig

// Java source emission for `#jni_main #jni_class("...") { ... }` decls
// (FFI plan, #jni_main pipeline slice 1).
//
// Given a `ForeignClassDecl` whose `is_main` flag is set, emit a `.java`
// source file that:
//
// - declares a `public class` at the foreign_path's package + simple
// name (e.g. `co/swipelab/Test/SxTestActivity` →
// `package co.swipelab.Test; public class SxTestActivity`);
// - extends the parent specified by `#extends Alias` (or
// `android.app.NativeActivity` by default for a #jni_main class);
// - for each method with a body, emits an `@Override` Java method
// that calls `super` then a private native delegate `sx_<method>`;
// - emits the matching `private native ... sx_<method>(...)` decls.
//
// The downstream pipeline (slice 2+) feeds this through `javac` + `d8`
// and bundles the resulting `.dex` into the APK. Slice 3 wires the
// manifest's `<activity android:name="...">` to point at this class.
// Slice 4 emits a synthetic `JNI_OnLoad` that calls `RegisterNatives`
// to bind the `sx_<method>` symbols.
//
// Type matrix covered today:
// - void return + primitive returns (s8/s16/s32/s64, u8/u16, bool,
// f32/f64)
// - `(self: *Self)` plus primitive params
// - cross-class refs (`*Foo` where Foo is another declared
// `#foreign #jni_class`) lower to Foo's foreign path → Java
// fully-qualified type
// - `*void` → `Object` (opaque jobject)
const std = @import("std");
const ast = @import("../ast.zig");
const Allocator = std.mem.Allocator;
pub const EmitError = error{
OutOfMemory,
UnsupportedType,
NotAJniMainClass,
};
pub const Options = struct {
/// Map from sx alias → foreign path of declared `#jni_class` decls.
/// Used to resolve `*Foo` cross-class refs in method signatures.
classes: ?*const std.StringHashMap([]const u8) = null,
/// Default superclass when the user doesn't write `#extends ...;`.
/// `android.app.Activity` is the standard base for Java-driven
/// Activities — `NativeActivity` is the legacy NDK path that
/// requires native_app_glue's `ANativeActivity_onCreate`.
default_extends: []const u8 = "android.app.Activity",
};
/// Emit a `.java` source for the given foreign-class decl. Result is
/// heap-allocated through `allocator`; caller owns it.
pub fn emitJavaSource(
allocator: Allocator,
fcd: *const ast.ForeignClassDecl,
opts: Options,
) EmitError![]u8 {
if (!fcd.is_main) return EmitError.NotAJniMainClass;
var buf: std.ArrayList(u8) = .empty;
errdefer buf.deinit(allocator);
const parts = splitForeignPath(fcd.foreign_path);
if (parts.pkg.len > 0) {
try buf.appendSlice(allocator, "package ");
try appendDotted(allocator, &buf, parts.pkg);
try buf.appendSlice(allocator, ";\n\n");
}
var parent: []const u8 = opts.default_extends;
var parent_owned = false;
for (fcd.members) |m| switch (m) {
.extends => |alias| {
if (opts.classes) |reg| {
if (reg.get(alias)) |path| {
parent = try foreignPathToJavaName(allocator, path);
parent_owned = true;
break;
}
}
parent = alias;
break;
},
else => {},
};
defer if (parent_owned) allocator.free(parent);
try buf.appendSlice(allocator, "public class ");
try buf.appendSlice(allocator, parts.cls);
try buf.appendSlice(allocator, " extends ");
try buf.appendSlice(allocator, parent);
try buf.appendSlice(allocator, " {\n");
// Two passes: @Override stubs that call super + native delegate,
// then the native declarations.
for (fcd.members) |m| switch (m) {
.method => |md| {
if (md.body == null) continue;
if (md.is_static) continue; // TODO: static native handling
try emitOverride(allocator, &buf, md, opts);
},
else => {},
};
for (fcd.members) |m| switch (m) {
.method => |md| {
if (md.body == null) continue;
if (md.is_static) continue;
try emitNativeDecl(allocator, &buf, md, opts);
},
else => {},
};
try buf.appendSlice(allocator, "}\n");
return buf.toOwnedSlice(allocator);
}
const PathParts = struct { pkg: []const u8, cls: []const u8 };
fn splitForeignPath(foreign_path: []const u8) PathParts {
const last_slash = std.mem.lastIndexOfScalar(u8, foreign_path, '/') orelse {
return .{ .pkg = "", .cls = foreign_path };
};
return .{
.pkg = foreign_path[0..last_slash],
.cls = foreign_path[last_slash + 1 ..],
};
}
fn appendDotted(
allocator: Allocator,
buf: *std.ArrayList(u8),
slash_path: []const u8,
) EmitError!void {
for (slash_path) |c| {
try buf.append(allocator, if (c == '/') '.' else c);
}
}
fn foreignPathToJavaName(allocator: Allocator, slash_path: []const u8) EmitError![]u8 {
var buf: std.ArrayList(u8) = .empty;
try appendDotted(allocator, &buf, slash_path);
return buf.toOwnedSlice(allocator);
}
fn emitOverride(
allocator: Allocator,
buf: *std.ArrayList(u8),
md: ast.ForeignMethodDecl,
opts: Options,
) EmitError!void {
try buf.appendSlice(allocator, " @Override\n public ");
try emitJavaReturnType(allocator, buf, md.return_type, opts);
try buf.append(allocator, ' ');
try buf.appendSlice(allocator, md.name);
try buf.append(allocator, '(');
try emitJavaParamList(allocator, buf, md, opts);
try buf.appendSlice(allocator, ") {\n super.");
try buf.appendSlice(allocator, md.name);
try buf.append(allocator, '(');
try emitJavaArgList(allocator, buf, md);
try buf.appendSlice(allocator, ");\n sx_");
try buf.appendSlice(allocator, md.name);
try buf.append(allocator, '(');
try emitJavaArgList(allocator, buf, md);
try buf.appendSlice(allocator, ");\n }\n");
}
fn emitNativeDecl(
allocator: Allocator,
buf: *std.ArrayList(u8),
md: ast.ForeignMethodDecl,
opts: Options,
) EmitError!void {
try buf.appendSlice(allocator, " private native ");
try emitJavaReturnType(allocator, buf, md.return_type, opts);
try buf.appendSlice(allocator, " sx_");
try buf.appendSlice(allocator, md.name);
try buf.append(allocator, '(');
try emitJavaParamList(allocator, buf, md, opts);
try buf.appendSlice(allocator, ");\n");
}
fn emitJavaReturnType(
allocator: Allocator,
buf: *std.ArrayList(u8),
ret: ?*ast.Node,
opts: Options,
) EmitError!void {
if (ret == null) {
try buf.appendSlice(allocator, "void");
return;
}
try emitJavaType(allocator, buf, ret.?, opts);
}
fn emitJavaParamList(
allocator: Allocator,
buf: *std.ArrayList(u8),
md: ast.ForeignMethodDecl,
opts: Options,
) EmitError!void {
const start: usize = if (md.is_static) 0 else 1; // skip self
for (md.params[start..], 0..) |p, i| {
if (i > 0) try buf.appendSlice(allocator, ", ");
try emitJavaType(allocator, buf, p, opts);
try buf.append(allocator, ' ');
try buf.appendSlice(allocator, md.param_names[start + i]);
}
}
fn emitJavaArgList(
allocator: Allocator,
buf: *std.ArrayList(u8),
md: ast.ForeignMethodDecl,
) EmitError!void {
const start: usize = if (md.is_static) 0 else 1;
for (md.param_names[start..], 0..) |name, i| {
if (i > 0) try buf.appendSlice(allocator, ", ");
try buf.appendSlice(allocator, name);
}
}
fn emitJavaType(
allocator: Allocator,
buf: *std.ArrayList(u8),
type_node: *ast.Node,
opts: Options,
) EmitError!void {
switch (type_node.data) {
.type_expr => |te| {
const name = javaPrimitiveName(te.name) orelse return EmitError.UnsupportedType;
try buf.appendSlice(allocator, name);
},
.pointer_type_expr => |ptr| {
const inner = ptr.pointee_type;
if (inner.data != .type_expr) return EmitError.UnsupportedType;
const target_name = inner.data.type_expr.name;
if (std.mem.eql(u8, target_name, "void")) {
try buf.appendSlice(allocator, "Object");
return;
}
if (opts.classes) |reg| {
if (reg.get(target_name)) |path| {
try appendDotted(allocator, buf, path);
return;
}
}
// Unknown alias — pass through dotted as best-effort. Sema
// should catch this earlier; tolerate for now.
try appendDotted(allocator, buf, target_name);
},
else => return EmitError.UnsupportedType,
}
}
fn javaPrimitiveName(name: []const u8) ?[]const u8 {
if (std.mem.eql(u8, name, "void")) return "void";
if (std.mem.eql(u8, name, "bool")) return "boolean";
if (std.mem.eql(u8, name, "s8")) return "byte";
if (std.mem.eql(u8, name, "u8")) return "byte";
if (std.mem.eql(u8, name, "s16")) return "short";
if (std.mem.eql(u8, name, "u16")) return "char";
if (std.mem.eql(u8, name, "s32")) return "int";
if (std.mem.eql(u8, name, "s64")) return "long";
if (std.mem.eql(u8, name, "f32")) return "float";
if (std.mem.eql(u8, name, "f64")) return "double";
return null;
}