bundling: fs/process stdlib + post-link callback + Apple .app in sx

Campaign Weeks 3-6 of /Users/agra/.claude/plans/lets-plan-to-move-splendid-pumpkin.md
land in one push: the bundling pipeline that used to live in
src/target.zig (createBundle, embedFramework, extractEntitlements,
buildInfoPlist, codesign) now lives in
library/modules/platform/bundle.sx and runs in the IR interpreter
after target.link() returns.

New language-side surface:
- library/modules/fs.sx — POSIX libc bindings (open/read/write/close,
  mkdir/unlink/rmdir, chmod, rename, access, basename/dirname). Variadic
  open() lowers to C's varargs via the new args: ..T form. Direct libc
  calls bypass *File method dispatch so they work from the post-link
  IR interpreter.
- library/modules/process.sx — popen-based run(cmd) returning
  ProcessResult{ exit_code, stdout }, plus env() and find_executable().
- library/modules/std.sx — xml_escape(s) and variadic path_join(parts).
- library/modules/compiler.sx — BuildOptions grows
  set_post_link_callback / set_post_link_module / binary_path
  accessors; bundle_path/bundle_id/codesign_identity/provisioning_profile
  setters + accessors; per-target predicates is_macos/is_ios/
  is_ios_device/is_ios_simulator + target_triple; framework_count /
  framework_at(i) / framework_path_count / framework_path_at(i);
  add_asset_dir(src, dest) + asset_dir_count / src_at / dest_at.

Compiler-side wiring:
- src/ir/compiler_hooks.zig — BuildConfig now carries post_link_callback_fn,
  post_link_module, binary_path, bundle_*, target_triple,
  target_frameworks, target_framework_paths, asset_dirs. Hook registry
  exposes every accessor; getters return "" / 0 for unset fields so
  bundle.sx can treat absent values uniformly.
- src/ir/host_ffi.zig (new) — dlsym(RTLD_DEFAULT) + arity-switched cdecl
  trampolines so #foreign("c") declarations resolve through the host
  libc during #run / post-link interpretation.
- src/ir/interp.zig — callForeign dispatch; build_config pointer
  injection so accessor hooks see live state during re-entry.
- src/core.zig — keeps the IR module alive past generateCode; exposes
  invokeByName / invokeByFuncId so main.zig can re-enter the
  interpreter after linking.
- src/main.zig — wires bundle/codesign/provisioning CLI flags +
  target_triple + framework lists into BuildConfig; invokes the
  post-link callback (by FuncId or by <module>.bundle_main lookup) once
  target.link() returns. When --bundle is set but no callback is
  registered, auto-falls-back to post_link_module = "platform.bundle"
  so the legacy --bundle CLI keeps working for any program that imports
  modules/platform/bundle.sx.

Apple .app bundler (library/modules/platform/bundle.sx):
- Single bundle_main entry covers macOS, iOS simulator, iOS device.
  Per-target Info.plist switch keys off is_ios()/is_ios_simulator() —
  iOS emits UIDeviceFamily / LSRequiresIPhoneOS /
  UIApplicationSceneManifest / DTPlatformName (iPhoneOS or
  iPhoneSimulator); macOS emits the minimal CFBundle* set.
- iOS-only steps:
  - Provisioning embed: fs.read_file + fs.write_file to
    <bundle>/embedded.mobileprovision.
  - Framework embed: recursive cp -R per -F search path into
    <bundle>/Frameworks/<Name>.framework/ (until fs.sx grows list_dir).
  - Entitlements extraction: four process.run calls (security cms -D,
    plutil -extract Entitlements xml1, plutil -extract
    ApplicationIdentifierPrefix.0, plutil -replace application-identifier)
    resolving the wildcard <TEAM>.* -> <TEAM>.<bundle_id>.
  - Real codesign with --entitlements when present.
- Asset dirs (add_asset_dir): recursive cp -R src/. into <bundle>/dest/.
  Missing src is treated as "nothing to do" so projects can register
  add_asset_dir("assets", "assets") unconditionally.

Parser:
- parseStmt() now accepts #import \"path\"; and #framework \"Name\"; as
  statement-position tokens. Needed for top-level
  inline if OS == .android { #import \"modules/platform/android.sx\"; }
  blocks (issue-0042 flatten pass surfaces them); chess's
  inline-if-with-#import was rejected at parse time before this fix.

Removals from src/target.zig:
- createBundle, embedFramework, extractEntitlements, buildInfoPlist,
  codesign (~210 lines). main.zig no longer calls createBundle after
  link(); the sx callback is the single entry point.

Tests / regression markers (all run under sx run host JIT):
- examples/115-post-link-callback.sx — callback registration round-trip.
- examples/116-fs-roundtrip.sx — fs.write_file -> fs.read_file -> exists.
- examples/117-process-roundtrip.sx — process.run + env + find_executable.
- examples/118-macos-bundle.sx — macOS .app via bundle_main callback.
- examples/119-interp-cast-ptr-cmp.sx — cast(T) val under interpreter.
- examples/120-interp-variadic-any.sx — variadic ..Any indexing in IR
  interpreter.
- examples/121-ios-sim-bundle.sx — iOS-sim cross-compile + .app with
  iOS-shaped Info.plist (added to tests/cross_compile.sh as the
  ios-sim tuple).
- examples/122-ios-device-bundle.sx — iOS device cross-compile +
  full codesign pipeline (provisioning embed + entitlements
  extraction + --entitlements codesign). Manually verified end-to-end:
  installed via xcrun devicectl device install app + launched
  successfully on iPhone 17 Pro.
- examples/123-inline-if-import-in-body.sx — locks in the parser fix.

zig build && zig build test && bash tests/run_examples.sh => 141 passed,
0 failed; bash tests/cross_compile.sh => 7 passed, 0 failed.
This commit is contained in:
agra
2026-05-22 19:03:31 +03:00
parent 30fed66616
commit 5cc62e63c3
50 changed files with 2827 additions and 589 deletions

View File

@@ -125,6 +125,9 @@ pub const Param = struct {
type_expr: *Node,
is_variadic: bool = false,
is_comptime: bool = false,
/// Optional default value expression. When the caller omits this
/// parameter, lowering substitutes this expression in its place.
default_expr: ?*Node = null,
};
pub const Block = struct {

View File

@@ -29,6 +29,10 @@ pub const Compilation = struct {
import_graph: std.StringHashMap(std.StringHashMap(void)),
sema_result: ?sema.SemaResult = null,
ir_emitter: ?ir.LLVMEmitter = null,
/// Lowered IR module, kept alive past `generateCode` so post-link
/// callbacks can re-enter the interpreter to invoke sx functions
/// (e.g. `platform.bundle.bundle_main` after `target.link`).
ir_module: ?*ir.Module = null,
/// C sources requested by the lowering pass (not in the user's AST).
/// E.g. the JNI env TL runtime when `#jni_env` is used. Merged with
/// AST sources in `collectCImportSources`.
@@ -55,6 +59,10 @@ pub const Compilation = struct {
pub fn deinit(self: *Compilation) void {
if (self.ir_emitter) |*e| e.deinit();
if (self.ir_module) |m| {
m.deinit();
self.allocator.destroy(m);
}
self.diagnostics.deinit();
}
@@ -124,12 +132,43 @@ pub const Compilation = struct {
ir_mod_ptr.* = try self.lowerToIR();
var emitter = ir.LLVMEmitter.init(self.allocator, ir_mod_ptr, "sx_module", self.target_config);
emitter.emit();
// IR module is no longer needed after LLVM IR has been generated
ir_mod_ptr.deinit();
self.allocator.destroy(ir_mod_ptr);
// Keep the IR module alive past LLVM emission so post-link
// callbacks can re-enter the interpreter via `invokeByName`.
self.ir_module = ir_mod_ptr;
self.ir_emitter = emitter;
}
/// Re-enter the IR interpreter after `generateCode` (and after linking,
/// if applicable) to invoke a named sx function. Used for the post-link
/// bundling callback. Returns the function's return value, or null if the
/// name doesn't resolve to a function in the lowered module.
pub fn invokeByName(self: *Compilation, name: []const u8, args: []const ir.Value) !?ir.Value {
const mod = self.ir_module orelse return null;
var found_id: ?ir.FuncId = null;
for (mod.functions.items, 0..) |func, i| {
const fname = mod.types.getString(func.name);
if (std.mem.eql(u8, fname, name)) {
found_id = ir.FuncId.fromIndex(@intCast(i));
break;
}
}
const fid = found_id orelse return null;
return try self.invokeByFuncId(fid, args);
}
/// Re-enter the IR interpreter and call a previously-resolved function
/// id. Companion to `invokeByName` — used when the FuncId was captured
/// at `#run` time (e.g. by `set_post_link_callback`) and we want to
/// invoke it later without name lookup.
pub fn invokeByFuncId(self: *Compilation, id: ir.FuncId, args: []const ir.Value) !ir.Value {
const mod = self.ir_module orelse return error.NoIRModule;
var interp = ir.Interpreter.init(mod, self.allocator);
defer interp.deinit();
if (self.ir_emitter) |*e| interp.build_config = &e.build_config;
ir.Interpreter.last_bail_op = null;
return try interp.call(id, args);
}
/// Get link flags accumulated from #run build blocks.
pub fn getBuildLinkFlags(self: *Compilation) []const []const u8 {
if (self.ir_emitter) |*e| return e.build_config.link_flags.items;
@@ -154,6 +193,20 @@ pub const Compilation = struct {
return null;
}
/// Get the post-link callback function id (set via
/// `BuildOptions.set_post_link_callback(fn)`), if any.
pub fn getPostLinkCallback(self: *Compilation) ?ir.FuncId {
if (self.ir_emitter) |*e| return e.build_config.post_link_callback_fn;
return null;
}
/// Get the post-link module name (set via
/// `BuildOptions.set_post_link_module("name")`), if any.
pub fn getPostLinkModule(self: *Compilation) ?[]const u8 {
if (self.ir_emitter) |*e| return e.build_config.post_link_module;
return null;
}
/// Collect C import source info — both from user-written `#import c { ... }`
/// blocks in the AST AND from lowering-time auto-injections (currently:
/// the JNI env TL runtime when `#jni_env` / `#jni_call`-with-omitted-env

View File

@@ -3,19 +3,71 @@ const Allocator = std.mem.Allocator;
const interp_mod = @import("interp.zig");
const Value = interp_mod.Value;
const Interpreter = interp_mod.Interpreter;
const inst = @import("inst.zig");
const FuncId = inst.FuncId;
// ── BuildConfig ─────────────────────────────────────────────────────────
// Mutable build configuration accumulated by #run blocks via #compiler methods.
/// `(src_dir, dest_in_bundle)` pair recorded by
/// `BuildOptions.add_asset_dir(src, dest)`. The sx bundler walks the
/// list and recursively copies each `src` directory into the bundle
/// at the relative `dest` path (e.g. `("assets", "assets")` copies
/// `./assets/` to `<bundle>/assets/`). Android's Week-7 APK path will
/// zip the same pairs into the unaligned APK.
pub const AssetDir = struct {
src: []const u8,
dest: []const u8,
};
pub const BuildConfig = struct {
link_flags: std.ArrayList([]const u8) = .empty,
frameworks: std.ArrayList([]const u8) = .empty,
asset_dirs: std.ArrayList(AssetDir) = .empty,
output_path: ?[]const u8 = null,
wasm_shell_path: ?[]const u8 = null,
/// Post-link callback registered via
/// `BuildOptions.set_post_link_callback(fn)`. When set, the
/// compiler re-enters the IR interpreter after `target.link()`
/// and invokes this function with no args. A `false` return is
/// treated as a build failure.
post_link_callback_fn: ?FuncId = null,
/// Alternative to `post_link_callback_fn`: the qualified name of
/// a module whose `bundle_main` function should be called
/// post-link.
post_link_module: ?[]const u8 = null,
/// Path of the freshly-linked binary, populated by `main.zig`
/// right before the post-link callback runs. The sx-side bundler
/// reads this via `binary_path()` to know what file to wrap.
binary_path: ?[]const u8 = null,
// Apple `.app` / Android `.apk` bundling parameters. Set either
// by the sx-side `BuildOptions.set_bundle_*` methods (preferred)
// or by main.zig from CLI flags (transitional fallback). The sx
// bundler reads them via the matching accessor methods.
bundle_path: ?[]const u8 = null,
bundle_id: ?[]const u8 = null,
codesign_identity: ?[]const u8 = null,
provisioning_profile: ?[]const u8 = null,
/// Target triple as supplied to `--target` (canonicalized).
/// Populated by main.zig before the post-link callback runs so the
/// sx bundler can switch on iOS vs. macOS vs. simulator.
target_triple: ?[]const u8 = null,
/// Frameworks the binary links against (`-framework` names) and
/// the search paths to look them up in (`-F` directories), forwarded
/// from the link step so the sx bundler can embed them into
/// `<bundle>/Frameworks/`.
target_frameworks: []const []const u8 = &.{},
target_framework_paths: []const []const u8 = &.{},
pub fn deinit(self: *BuildConfig, alloc: Allocator) void {
self.link_flags.deinit(alloc);
self.frameworks.deinit(alloc);
self.asset_dirs.deinit(alloc);
}
};
@@ -55,8 +107,36 @@ pub const Registry = struct {
self.hooks.put("build_options", &hookBuildOptions) catch {};
self.hooks.put("BuildOptions.add_link_flag", &hookAddLinkFlag) catch {};
self.hooks.put("BuildOptions.add_framework", &hookAddFramework) catch {};
self.hooks.put("BuildOptions.add_asset_dir", &hookAddAssetDir) catch {};
self.hooks.put("BuildOptions.asset_dir_count", &hookAssetDirCount) catch {};
self.hooks.put("BuildOptions.asset_dir_src_at", &hookAssetDirSrcAt) catch {};
self.hooks.put("BuildOptions.asset_dir_dest_at", &hookAssetDirDestAt) catch {};
self.hooks.put("BuildOptions.set_output_path", &hookSetOutputPath) catch {};
self.hooks.put("BuildOptions.set_wasm_shell", &hookSetWasmShell) catch {};
self.hooks.put("BuildOptions.set_post_link_callback", &hookSetPostLinkCallback) catch {};
self.hooks.put("BuildOptions.set_post_link_module", &hookSetPostLinkModule) catch {};
self.hooks.put("BuildOptions.binary_path", &hookGetBinaryPath) catch {};
// Bundling setters
self.hooks.put("BuildOptions.set_bundle_path", &hookSetBundlePath) catch {};
self.hooks.put("BuildOptions.set_bundle_id", &hookSetBundleId) catch {};
self.hooks.put("BuildOptions.set_codesign_identity", &hookSetCodesignIdentity) catch {};
self.hooks.put("BuildOptions.set_provisioning_profile", &hookSetProvisioningProfile) catch {};
// Bundling accessors
self.hooks.put("BuildOptions.bundle_path", &hookGetBundlePath) catch {};
self.hooks.put("BuildOptions.bundle_id", &hookGetBundleId) catch {};
self.hooks.put("BuildOptions.codesign_identity", &hookGetCodesignIdentity) catch {};
self.hooks.put("BuildOptions.provisioning_profile", &hookGetProvisioningProfile) catch {};
// Target accessors — mirror TargetConfig.is{MacOS,IOS,IOSDevice,IOSSimulator}()
self.hooks.put("BuildOptions.target_triple", &hookGetTargetTriple) catch {};
self.hooks.put("BuildOptions.is_macos", &hookIsMacOS) catch {};
self.hooks.put("BuildOptions.is_ios", &hookIsIOS) catch {};
self.hooks.put("BuildOptions.is_ios_device", &hookIsIOSDevice) catch {};
self.hooks.put("BuildOptions.is_ios_simulator", &hookIsIOSSimulator) catch {};
// Framework list accessors (for `.app/Frameworks/` embedding)
self.hooks.put("BuildOptions.framework_count", &hookFrameworkCount) catch {};
self.hooks.put("BuildOptions.framework_at", &hookFrameworkAt) catch {};
self.hooks.put("BuildOptions.framework_path_count", &hookFrameworkPathCount) catch {};
self.hooks.put("BuildOptions.framework_path_at", &hookFrameworkPathAt) catch {};
}
};
@@ -105,6 +185,40 @@ fn hookAddFramework(
return .void_val;
}
fn hookAddAssetDir(
interp: *const Interpreter,
args: []const Value,
bc: *BuildConfig,
alloc: Allocator,
) HookError!Value {
// args: [self (BuildOptions value), src_path, dest_path_in_bundle]
if (args.len < 3) return .void_val;
const src = args[1].asString(interp) orelse return error.TypeError;
const dest = args[2].asString(interp) orelse return error.TypeError;
const src_dup = alloc.dupe(u8, src) catch return error.CannotEvalComptime;
const dest_dup = alloc.dupe(u8, dest) catch return error.CannotEvalComptime;
bc.asset_dirs.append(alloc, .{ .src = src_dup, .dest = dest_dup }) catch return error.CannotEvalComptime;
return .void_val;
}
fn hookAssetDirCount(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
return Value{ .int = @intCast(bc.asset_dirs.items.len) };
}
fn hookAssetDirSrcAt(_: *const Interpreter, args: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
if (args.len < 2) return Value{ .string = "" };
const idx = args[1].asInt() orelse return error.TypeError;
if (idx < 0 or @as(usize, @intCast(idx)) >= bc.asset_dirs.items.len) return Value{ .string = "" };
return Value{ .string = bc.asset_dirs.items[@intCast(idx)].src };
}
fn hookAssetDirDestAt(_: *const Interpreter, args: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
if (args.len < 2) return Value{ .string = "" };
const idx = args[1].asInt() orelse return error.TypeError;
if (idx < 0 or @as(usize, @intCast(idx)) >= bc.asset_dirs.items.len) return Value{ .string = "" };
return Value{ .string = bc.asset_dirs.items[@intCast(idx)].dest };
}
fn hookSetOutputPath(
interp: *const Interpreter,
args: []const Value,
@@ -134,3 +248,199 @@ fn hookSetWasmShell(
}
return .void_val;
}
fn hookSetPostLinkCallback(
_: *const Interpreter,
args: []const Value,
bc: *BuildConfig,
_: Allocator,
) HookError!Value {
// args: [self (BuildOptions value), fn_value]. We accept a function
// value (.func_ref) and stash the FuncId so `main.zig` can re-enter
// the interpreter after linking.
if (args.len < 2) return .void_val;
switch (args[1]) {
.func_ref => |id| bc.post_link_callback_fn = id,
else => return error.TypeError,
}
return .void_val;
}
fn hookSetPostLinkModule(
interp: *const Interpreter,
args: []const Value,
bc: *BuildConfig,
alloc: Allocator,
) HookError!Value {
if (args.len < 2) return .void_val;
if (args[1].asString(interp)) |s| {
bc.post_link_module = alloc.dupe(u8, s) catch return error.CannotEvalComptime;
}
return .void_val;
}
/// Read the linked-binary path that main.zig populated right before
/// invoking the post-link callback. Returns the fat-string aggregate
/// the interpreter normally hands out for sx `string` values.
fn hookGetBinaryPath(
interp: *const Interpreter,
_: []const Value,
bc: *BuildConfig,
_: Allocator,
) HookError!Value {
_ = interp;
const path = bc.binary_path orelse "";
return Value{ .string = path };
}
// ── Bundling setters & accessors ─────────────────────────────────────
// Same pattern as set_output_path: take a string arg, dupe into the
// long-lived allocator, store on BuildConfig. The companion accessor
// reads back the same field; empty string when unset.
fn hookSetBundlePath(
interp: *const Interpreter,
args: []const Value,
bc: *BuildConfig,
alloc: Allocator,
) HookError!Value {
if (args.len < 2) return .void_val;
if (args[1].asString(interp)) |s| {
bc.bundle_path = alloc.dupe(u8, s) catch return error.CannotEvalComptime;
}
return .void_val;
}
fn hookSetBundleId(
interp: *const Interpreter,
args: []const Value,
bc: *BuildConfig,
alloc: Allocator,
) HookError!Value {
if (args.len < 2) return .void_val;
if (args[1].asString(interp)) |s| {
bc.bundle_id = alloc.dupe(u8, s) catch return error.CannotEvalComptime;
}
return .void_val;
}
fn hookSetCodesignIdentity(
interp: *const Interpreter,
args: []const Value,
bc: *BuildConfig,
alloc: Allocator,
) HookError!Value {
if (args.len < 2) return .void_val;
if (args[1].asString(interp)) |s| {
bc.codesign_identity = alloc.dupe(u8, s) catch return error.CannotEvalComptime;
}
return .void_val;
}
fn hookSetProvisioningProfile(
interp: *const Interpreter,
args: []const Value,
bc: *BuildConfig,
alloc: Allocator,
) HookError!Value {
if (args.len < 2) return .void_val;
if (args[1].asString(interp)) |s| {
bc.provisioning_profile = alloc.dupe(u8, s) catch return error.CannotEvalComptime;
}
return .void_val;
}
fn hookGetBundlePath(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
return Value{ .string = bc.bundle_path orelse "" };
}
fn hookGetBundleId(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
return Value{ .string = bc.bundle_id orelse "" };
}
fn hookGetCodesignIdentity(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
return Value{ .string = bc.codesign_identity orelse "" };
}
fn hookGetProvisioningProfile(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
return Value{ .string = bc.provisioning_profile orelse "" };
}
// ── Target accessors ──────────────────────────────────────────────────
// These look at the target_triple that main.zig populates and answer
// the same questions TargetConfig's helpers do for Zig callers.
fn tripleContains(triple: ?[]const u8, needle: []const u8) bool {
const t = triple orelse return false;
return std.mem.indexOf(u8, t, needle) != null;
}
fn isIOSTriple(triple: ?[]const u8) bool {
return tripleContains(triple, "apple-ios");
}
fn hookGetTargetTriple(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
return Value{ .string = bc.target_triple orelse "" };
}
fn hookIsMacOS(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
if (isIOSTriple(bc.target_triple)) return Value{ .boolean = false };
const t = bc.target_triple orelse "";
const is_mac = std.mem.indexOf(u8, t, "apple-macosx") != null or
std.mem.indexOf(u8, t, "apple-macos") != null or
std.mem.indexOf(u8, t, "apple-darwin") != null;
return Value{ .boolean = is_mac };
}
fn hookIsIOS(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
return Value{ .boolean = isIOSTriple(bc.target_triple) };
}
fn hookIsIOSDevice(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
const ios = isIOSTriple(bc.target_triple);
const sim = tripleContains(bc.target_triple, "simulator");
return Value{ .boolean = ios and !sim };
}
fn hookIsIOSSimulator(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
const ios = isIOSTriple(bc.target_triple);
const sim = tripleContains(bc.target_triple, "simulator");
return Value{ .boolean = ios and sim };
}
// ── Framework list accessors ──────────────────────────────────────────
// The Apple .app bundler in `library/modules/platform/bundle.sx` walks
// the framework list to recursively copy each `<Name>.framework`
// directory from the user's -F search paths into `<bundle>/Frameworks/`.
// Slice-of-string returns aren't natively expressible as a Value, so we
// expose count + indexed lookups instead.
fn intValue(n: i64) Value {
return Value{ .int = n };
}
fn hookFrameworkCount(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
return intValue(@intCast(bc.target_frameworks.len));
}
fn hookFrameworkAt(_: *const Interpreter, args: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
if (args.len < 2) return Value{ .string = "" };
const idx_i64 = args[1].asInt() orelse return error.TypeError;
if (idx_i64 < 0 or @as(usize, @intCast(idx_i64)) >= bc.target_frameworks.len) {
return Value{ .string = "" };
}
return Value{ .string = bc.target_frameworks[@intCast(idx_i64)] };
}
fn hookFrameworkPathCount(_: *const Interpreter, _: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
return intValue(@intCast(bc.target_framework_paths.len));
}
fn hookFrameworkPathAt(_: *const Interpreter, args: []const Value, bc: *BuildConfig, _: Allocator) HookError!Value {
if (args.len < 2) return Value{ .string = "" };
const idx_i64 = args[1].asInt() orelse return error.TypeError;
if (idx_i64 < 0 or @as(usize, @intCast(idx_i64)) >= bc.target_framework_paths.len) {
return Value{ .string = "" };
}
return Value{ .string = bc.target_framework_paths[@intCast(idx_i64)] };
}

155
src/ir/host_ffi.zig Normal file
View File

@@ -0,0 +1,155 @@
//! Host FFI dispatch for the IR interpreter.
//!
//! When the interpreter encounters a call to an extern function during `#run`
//! (or post-link interpretation), it has no body to walk. This module
//! `dlsym`s the symbol from the host's already-loaded dylibs (libc, libSystem,
//! kernel32, whatever the OS provides) and calls it via an arity-switched
//! cdecl function pointer.
//!
//! Limits:
//! * Up to 8 cdecl-passed arguments. Beyond that, return error.
//! * All arguments are marshalled to / from `usize`. Pointer-sized integers,
//! pointers, null-terminated strings, and booleans are supported; floats,
//! aggregates passed by value, and varargs are not.
//! * Return value can be void, integer (i64), pointer (usize), or boolean.
const std = @import("std");
const RTLD_DEFAULT: ?*anyopaque = @ptrFromInt(@as(usize, @bitCast(@as(isize, -2))));
extern "c" fn dlsym(handle: ?*anyopaque, name: [*:0]const u8) ?*anyopaque;
/// Look up an extern symbol in the host's loaded image. Returns null if not
/// found.
pub fn lookupSymbol(allocator: std.mem.Allocator, name: []const u8) !?*anyopaque {
const name_z = try allocator.allocSentinel(u8, name.len, 0);
defer allocator.free(name_z);
@memcpy(name_z[0..name.len], name);
return dlsym(RTLD_DEFAULT, name_z.ptr);
}
/// Call a cdecl symbol that returns `i64`. Args are pre-marshalled to `usize`.
pub fn callIntRet(symbol: *anyopaque, args: []const usize) !i64 {
return switch (args.len) {
0 => @as(*const fn () callconv(.c) i64, @ptrCast(@alignCast(symbol)))(),
1 => @as(*const fn (usize) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0]),
2 => @as(*const fn (usize, usize) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1]),
3 => @as(*const fn (usize, usize, usize) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2]),
4 => @as(*const fn (usize, usize, usize, usize) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3]),
5 => @as(*const fn (usize, usize, usize, usize, usize) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4]),
6 => @as(*const fn (usize, usize, usize, usize, usize, usize) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4], args[5]),
7 => @as(*const fn (usize, usize, usize, usize, usize, usize, usize) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4], args[5], args[6]),
8 => @as(*const fn (usize, usize, usize, usize, usize, usize, usize, usize) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]),
else => return error.TooManyArgs,
};
}
/// Call a cdecl symbol that returns a pointer (or any pointer-sized value).
pub fn callPtrRet(symbol: *anyopaque, args: []const usize) !usize {
return switch (args.len) {
0 => @as(*const fn () callconv(.c) usize, @ptrCast(@alignCast(symbol)))(),
1 => @as(*const fn (usize) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0]),
2 => @as(*const fn (usize, usize) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1]),
3 => @as(*const fn (usize, usize, usize) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2]),
4 => @as(*const fn (usize, usize, usize, usize) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3]),
5 => @as(*const fn (usize, usize, usize, usize, usize) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4]),
6 => @as(*const fn (usize, usize, usize, usize, usize, usize) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4], args[5]),
7 => @as(*const fn (usize, usize, usize, usize, usize, usize, usize) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4], args[5], args[6]),
8 => @as(*const fn (usize, usize, usize, usize, usize, usize, usize, usize) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]),
else => return error.TooManyArgs,
};
}
/// Call a cdecl symbol with void return.
pub fn callVoidRet(symbol: *anyopaque, args: []const usize) !void {
switch (args.len) {
0 => @as(*const fn () callconv(.c) void, @ptrCast(@alignCast(symbol)))(),
1 => @as(*const fn (usize) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0]),
2 => @as(*const fn (usize, usize) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1]),
3 => @as(*const fn (usize, usize, usize) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2]),
4 => @as(*const fn (usize, usize, usize, usize) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3]),
5 => @as(*const fn (usize, usize, usize, usize, usize) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4]),
6 => @as(*const fn (usize, usize, usize, usize, usize, usize) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4], args[5]),
7 => @as(*const fn (usize, usize, usize, usize, usize, usize, usize) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4], args[5], args[6]),
8 => @as(*const fn (usize, usize, usize, usize, usize, usize, usize, usize) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]),
else => return error.TooManyArgs,
}
}
// ── Variadic cdecl dispatch ─────────────────────────────────────────
// For foreign functions declared with `args: ..T` (C-variadic, e.g.
// libc `open(path, flags, ...)`). The trailing args must be passed
// through the C-variadic ABI — arm64 places them on the stack rather
// than in argument registers. Calling a variadic function as if it
// were fixed-arity puts the mode/etc. in the wrong register and the
// callee reads garbage.
//
// The dispatch is keyed by (fixed_count, total_args). `fixed_count`
// is the number of declared (non-variadic) params; trailing
// `total_args - fixed_count` slots are the variadic tail. The Zig
// function-pointer types use `...` so the compiler emits
// proper-variadic calls.
pub fn callIntRetVar(symbol: *anyopaque, fixed: usize, args: []const usize) !i64 {
if (args.len < fixed) return error.TooFewArgs;
// Special-case the shapes we actually use today; extend as
// needed. fixed_count > total is impossible.
return switch (fixed) {
2 => switch (args.len) {
2 => @as(*const fn (usize, usize, ...) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1]),
3 => @as(*const fn (usize, usize, ...) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2]),
4 => @as(*const fn (usize, usize, ...) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3]),
5 => @as(*const fn (usize, usize, ...) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4]),
else => return error.TooManyArgs,
},
1 => switch (args.len) {
1 => @as(*const fn (usize, ...) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0]),
2 => @as(*const fn (usize, ...) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1]),
3 => @as(*const fn (usize, ...) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2]),
4 => @as(*const fn (usize, ...) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3]),
5 => @as(*const fn (usize, ...) callconv(.c) i64, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3], args[4]),
else => return error.TooManyArgs,
},
else => return error.UnsupportedVariadicArity,
};
}
pub fn callPtrRetVar(symbol: *anyopaque, fixed: usize, args: []const usize) !usize {
if (args.len < fixed) return error.TooFewArgs;
return switch (fixed) {
2 => switch (args.len) {
2 => @as(*const fn (usize, usize, ...) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1]),
3 => @as(*const fn (usize, usize, ...) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2]),
4 => @as(*const fn (usize, usize, ...) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3]),
else => return error.TooManyArgs,
},
1 => switch (args.len) {
1 => @as(*const fn (usize, ...) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0]),
2 => @as(*const fn (usize, ...) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1]),
3 => @as(*const fn (usize, ...) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2]),
4 => @as(*const fn (usize, ...) callconv(.c) usize, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3]),
else => return error.TooManyArgs,
},
else => return error.UnsupportedVariadicArity,
};
}
pub fn callVoidRetVar(symbol: *anyopaque, fixed: usize, args: []const usize) !void {
if (args.len < fixed) return error.TooFewArgs;
switch (fixed) {
2 => switch (args.len) {
2 => @as(*const fn (usize, usize, ...) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1]),
3 => @as(*const fn (usize, usize, ...) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2]),
4 => @as(*const fn (usize, usize, ...) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3]),
else => return error.TooManyArgs,
},
1 => switch (args.len) {
1 => @as(*const fn (usize, ...) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0]),
2 => @as(*const fn (usize, ...) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1]),
3 => @as(*const fn (usize, ...) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2]),
4 => @as(*const fn (usize, ...) callconv(.c) void, @ptrCast(@alignCast(symbol)))(args[0], args[1], args[2], args[3]),
else => return error.TooManyArgs,
},
else => return error.UnsupportedVariadicArity,
}
}

View File

@@ -108,6 +108,7 @@ pub const InterpError = error{
const compiler_hooks = @import("compiler_hooks.zig");
pub const BuildConfig = compiler_hooks.BuildConfig;
const host_ffi = @import("host_ffi.zig");
// ── Interpreter ─────────────────────────────────────────────────────────
@@ -130,6 +131,14 @@ pub const Interpreter = struct {
// Compiler hook registry for #compiler methods
hooks: compiler_hooks.Registry,
// First op tag that bailed with InterpError, captured the first
// time the interpreter unwinds so callers can surface "op=foo at
// <file>:<offset>" alongside the bare error name. Static so it
// survives Interpreter teardown (lifetime: program global).
pub var last_bail_op: ?[]const u8 = null;
pub var last_bail_file: ?[]const u8 = null;
pub var last_bail_offset: u32 = 0;
pub fn init(module: *const Module, alloc: Allocator) Interpreter {
var hooks = compiler_hooks.Registry.init(alloc);
hooks.registerDefaults();
@@ -217,6 +226,121 @@ pub const Interpreter = struct {
return .undef;
}
/// Marshal a single sx Value into a `usize` slot for a cdecl host call.
/// Strings are made null-terminated; pointer-like values pass their
/// underlying address. The returned `usize` is only valid for the
/// duration of this call — caller-allocated buffers are tracked in
/// `tmp` so they get freed once the call returns.
fn marshalForeignArg(self: *Interpreter, v: Value, tmp: *std.ArrayList([]u8)) !usize {
return switch (v) {
.int => |i| @bitCast(i),
.boolean => |b| @intFromBool(b),
.null_val => 0,
.heap_ptr => |hp| blk: {
const mem = self.heapSlice(hp) orelse return error.TypeError;
break :blk @intFromPtr(mem.ptr) + hp.offset;
},
.string => |s| blk: {
const buf = try self.alloc.alloc(u8, s.len + 1);
@memcpy(buf[0..s.len], s);
buf[s.len] = 0;
tmp.append(self.alloc, buf) catch return error.TypeError;
break :blk @intFromPtr(buf.ptr);
},
.aggregate => |fields| blk: {
// Fat string pointer: { ptr, len }. Pass the raw bytes
// null-terminated so libc string APIs work.
if (fields.len == 2) {
const len: usize = @intCast(fields[1].asInt() orelse return error.TypeError);
switch (fields[0]) {
.heap_ptr => |hp| {
const mem = self.heapSlice(hp) orelse return error.TypeError;
const start = hp.offset;
const slice = mem[start .. start + len];
const buf = try self.alloc.alloc(u8, len + 1);
@memcpy(buf[0..len], slice);
buf[len] = 0;
tmp.append(self.alloc, buf) catch return error.TypeError;
break :blk @intFromPtr(buf.ptr);
},
.string => |s| {
const slice = if (len <= s.len) s[0..len] else s;
const buf = try self.alloc.alloc(u8, slice.len + 1);
@memcpy(buf[0..slice.len], slice);
buf[slice.len] = 0;
tmp.append(self.alloc, buf) catch return error.TypeError;
break :blk @intFromPtr(buf.ptr);
},
else => return error.TypeError,
}
}
return error.TypeError;
},
else => error.TypeError,
};
}
fn callForeign(self: *Interpreter, func: *const inst_mod.Function, args: []const Value) InterpError!Value {
const name = self.module.types.getString(func.name);
const symbol = (host_ffi.lookupSymbol(self.alloc, name) catch return error.CannotEvalComptime) orelse {
return error.CannotEvalComptime;
};
var packed_args: [8]usize = undefined;
if (args.len > packed_args.len) return error.CannotEvalComptime;
var tmp = std.ArrayList([]u8).empty;
defer {
for (tmp.items) |buf| self.alloc.free(buf);
tmp.deinit(self.alloc);
}
for (args, 0..) |a, i| {
packed_args[i] = self.marshalForeignArg(a, &tmp) catch return error.TypeError;
}
const argv = packed_args[0..args.len];
// Variadic foreign functions (declared `args: ..T`) must be
// dispatched through C-variadic trampolines so the trailing
// args land in the right place per the target's variadic
// ABI. The fixed-arity trampolines would put them in arg
// registers, and the callee would read garbage from the
// stack.
const fixed = func.params.len;
const variadic = func.is_variadic and args.len > fixed;
const ret = func.ret;
if (ret == .void) {
if (variadic) {
host_ffi.callVoidRetVar(symbol, fixed, argv) catch return error.CannotEvalComptime;
} else {
host_ffi.callVoidRet(symbol, argv) catch return error.CannotEvalComptime;
}
return .void_val;
}
if (ret == .s8 or ret == .s16 or ret == .s32 or ret == .s64 or
ret == .u8 or ret == .u16 or ret == .u32 or ret == .u64 or
ret == .usize or ret == .isize)
{
const r = if (variadic)
host_ffi.callIntRetVar(symbol, fixed, argv) catch return error.CannotEvalComptime
else
host_ffi.callIntRet(symbol, argv) catch return error.CannotEvalComptime;
return Value{ .int = r };
}
if (ret == .bool) {
const r = if (variadic)
host_ffi.callIntRetVar(symbol, fixed, argv) catch return error.CannotEvalComptime
else
host_ffi.callIntRet(symbol, argv) catch return error.CannotEvalComptime;
return Value{ .boolean = r != 0 };
}
const r = if (variadic)
host_ffi.callPtrRetVar(symbol, fixed, argv) catch return error.CannotEvalComptime
else
host_ffi.callPtrRet(symbol, argv) catch return error.CannotEvalComptime;
return Value{ .int = @bitCast(@as(u64, r)) };
}
pub fn call(self: *Interpreter, func_id: FuncId, args: []const Value) InterpError!Value {
if (self.call_depth >= self.max_call_depth) return error.StackOverflow;
self.call_depth += 1;
@@ -224,7 +348,10 @@ pub const Interpreter = struct {
const func = self.module.getFunction(func_id);
if (func.is_extern or func.blocks.items.len == 0) {
return error.CannotEvalComptime;
// Dispatch to host libc via dlsym. Lets `#run` (and the
// post-link bundler) call ordinary foreign symbols like
// `puts`, `getenv`, `posix_spawn`, etc.
return self.callForeign(func, args);
}
// Compute total refs: params + all instructions across all blocks
@@ -269,6 +396,11 @@ pub const Interpreter = struct {
}
const result = self.execInst(instruction, &frame, &current_block, &block_args) catch |err| {
if (last_bail_op == null) {
last_bail_op = @tagName(instruction.op);
last_bail_file = func.source_file;
last_bail_offset = instruction.span.start;
}
return err;
};
switch (result) {
@@ -982,8 +1114,14 @@ pub const Interpreter = struct {
}
},
// Type-as-value sentinel emitted for the type arg of
// `cast(T) val`. Result is never read (the cast lowering
// consumes the type from the AST, not the IR Ref), so an
// undef value is sufficient — matches the LLVM emitter.
.placeholder => return .{ .value = .undef },
// ── Not yet evaluable at comptime ──────────────────
.call_closure, .protocol_call_dynamic, .protocol_erase, .closure_create, .context_load, .context_store, .context_save, .context_restore, .union_get, .union_gep, .vec_splat, .vec_extract, .vec_insert, .placeholder => {
.call_closure, .protocol_call_dynamic, .protocol_erase, .closure_create, .context_load, .context_store, .context_save, .context_restore, .union_get, .union_gep, .vec_splat, .vec_extract, .vec_insert => {
return error.CannotEvalComptime;
},
}
@@ -1187,14 +1325,13 @@ pub const Interpreter = struct {
const parent = frame.loadSlot(parent_slot);
switch (parent) {
.aggregate => |parent_fields| {
if (field_idx < parent_fields.len) {
// Clone the aggregate and update the field
const new_fields = self.alloc.alloc(Value, parent_fields.len) catch return false;
@memcpy(new_fields, parent_fields);
new_fields[field_idx] = new_val;
frame.storeSlot(parent_slot, .{ .aggregate = new_fields });
return true;
}
const new_len = @max(field_idx + 1, parent_fields.len);
const new_fields = self.alloc.alloc(Value, new_len) catch return false;
@memcpy(new_fields[0..parent_fields.len], parent_fields);
for (new_fields[parent_fields.len..]) |*f| f.* = .undef;
new_fields[field_idx] = new_val;
frame.storeSlot(parent_slot, .{ .aggregate = new_fields });
return true;
},
.undef => {
// Initialize a new aggregate from undef

View File

@@ -4381,7 +4381,12 @@ pub const Lowering = struct {
// ── Calls ───────────────────────────────────────────────────────
fn lowerCall(self: *Lowering, c: *const ast.Call) Ref {
fn lowerCall(self: *Lowering, c_in: *const ast.Call) Ref {
// Expand default parameter values for bare identifier callees:
// when the caller omits trailing positional args, fill them in
// from the callee's `param: T = expr` declarations.
var c = c_in;
if (self.expandCallDefaults(c)) |expanded| c = expanded;
// Check reflection builtins first (before lowering args — some args are type names, not values)
if (c.callee.data == .identifier) {
if (self.tryLowerReflectionCall(c.callee.data.identifier.name, c)) |ref| return ref;
@@ -4991,7 +4996,11 @@ pub const Lowering = struct {
// Generic #compiler method dispatch
if (self.fn_ast_map.get(qualified)) |method_fd| {
if (method_fd.body.data == .compiler_expr) {
return self.builder.compilerCall(qualified, method_args.items, .void);
const ret_ty = if (method_fd.return_type) |rt|
type_bridge.resolveAstType(rt, &self.module.types)
else
.void;
return self.builder.compilerCall(qualified, method_args.items, ret_ty);
}
}
@@ -7436,6 +7445,39 @@ pub const Lowering = struct {
return false;
}
/// When a bare-identifier call omits trailing positional args and the
/// callee's signature provides defaults for them, return a fresh Call
/// node with the defaults filled in. Returns null when no expansion is
/// needed (callee unknown, all args provided, or no defaults available).
fn expandCallDefaults(self: *Lowering, c: *const ast.Call) ?*ast.Call {
if (c.callee.data != .identifier) return null;
const id_name = c.callee.data.identifier.name;
const eff_name = blk: {
const scoped = if (self.scope) |scope| scope.lookupFn(id_name) orelse id_name else id_name;
if (self.ufcs_alias_map.get(id_name)) |target| {
break :blk if (self.scope) |scope| scope.lookupFn(target) orelse target else target;
}
break :blk scoped;
};
const fd = self.fn_ast_map.get(eff_name) orelse return null;
if (c.args.len >= fd.params.len) return null;
var end: usize = c.args.len;
while (end < fd.params.len) : (end += 1) {
if (fd.params[end].default_expr == null) break;
}
if (end == c.args.len) return null;
var new_args = self.alloc.alloc(*ast.Node, end) catch return null;
for (c.args, 0..) |arg, i| new_args[i] = arg;
var i: usize = c.args.len;
while (i < end) : (i += 1) {
new_args[i] = fd.params[i].default_expr.?;
}
const new_call = self.alloc.create(ast.Call) catch return null;
new_call.* = .{ .callee = c.callee, .args = new_args };
return new_call;
}
/// Resolve parameter types for a call expression (for target_type context).
/// Returns empty slice if the function can't be resolved.
fn resolveCallParamTypes(self: *Lowering, c: *const ast.Call) []const TypeId {

View File

@@ -401,6 +401,25 @@ fn deriveOutputName(input_path: []const u8) []const u8 {
}
/// Format the "interpreter bailed during X" message, attaching the IR op
/// and the source location (line:col) when the interpreter captured them.
fn printInterpBailDiag(comp: *const sx.core.Compilation, label: []const u8, err: anyerror) void {
const op = sx.ir.Interpreter.last_bail_op orelse {
std.debug.print("error: {s} failed: {s}\n", .{ label, @errorName(err) });
return;
};
if (sx.ir.Interpreter.last_bail_file) |file| {
if (comp.import_sources.get(file)) |source| {
const loc = sx.errors.SourceLoc.compute(source, sx.ir.Interpreter.last_bail_offset);
std.debug.print("error: {s} failed: {s} (op={s}) at {s}:{d}:{d}\n", .{ label, @errorName(err), op, file, loc.line, loc.col });
return;
}
std.debug.print("error: {s} failed: {s} (op={s}) at {s}:+{d}\n", .{ label, @errorName(err), op, file, sx.ir.Interpreter.last_bail_offset });
return;
}
std.debug.print("error: {s} failed: {s} (op={s})\n", .{ label, @errorName(err), op });
}
fn readSource(allocator: std.mem.Allocator, io: std.Io, input_path: []const u8) ![:0]const u8 {
const source_bytes = std.Io.Dir.readFileAlloc(.cwd(), io, input_path, allocator, .limited(10 * 1024 * 1024)) catch |err| {
std.debug.print("error: cannot read '{s}': {}\n", .{ input_path, err });
@@ -601,14 +620,6 @@ fn compileWithTimer(allocator: std.mem.Allocator, io: std.Io, input_path: []cons
};
timer.record("link");
// Wrap into a .app bundle if requested (iOS/macOS).
if (merged_config.bundle_path) |bp| {
timer.mark();
sx.target.createBundle(allocator, io, final_output, merged_config, fws) catch std.process.exit(1);
timer.record("bundle");
std.debug.print("bundled: {s}\n", .{bp});
}
// Wrap into an .apk if requested (Android).
if (merged_config.apk_path) |ap| {
timer.mark();
@@ -617,6 +628,77 @@ fn compileWithTimer(allocator: std.mem.Allocator, io: std.Io, input_path: []cons
std.debug.print("apk: {s}\n", .{ap});
}
// Make the linked binary's path + bundling config visible to the
// post-link callback via `BuildOptions.binary_path()`,
// `BuildOptions.bundle_path()`, etc. CLI flags
// (`--bundle Foo.app`, `--bundle-id`, ...) feed in here so the sx
// bundler doesn't need a separate code path.
if (comp.ir_emitter) |*e| {
e.build_config.binary_path = final_output;
if (e.build_config.bundle_path == null) e.build_config.bundle_path = merged_config.bundle_path;
if (e.build_config.bundle_id == null) e.build_config.bundle_id = merged_config.bundle_id;
if (e.build_config.codesign_identity == null) e.build_config.codesign_identity = merged_config.codesign_identity;
if (e.build_config.provisioning_profile == null) e.build_config.provisioning_profile = merged_config.provisioning_profile;
// Target triple + framework lists drive the sx bundler's per-platform
// branching (iOS device vs simulator vs macOS) and `Frameworks/`
// embedding. Slice fields point into the long-lived target_config /
// CLI argv buffers, which outlive the post-link callback.
if (merged_config.triple) |t| e.build_config.target_triple = std.mem.span(t);
e.build_config.target_frameworks = fws;
e.build_config.target_framework_paths = merged_config.framework_paths;
}
// CLI `--bundle <path>` migration shim. The legacy Zig bundler
// path (target.createBundle) has been retired; the equivalent
// logic now lives in `library/modules/platform/bundle.sx`. If the
// user passed `--bundle` on the command line but did NOT register
// a post-link callback themselves, point the resolver at
// `platform.bundle.bundle_main`. The lookup is best-effort: if the
// source doesn't `#import "modules/platform/bundle.sx"`,
// `invokeByName` returns null and the existing "not found" branch
// prints a clear migration message.
if (comp.ir_emitter) |*e| {
if (e.build_config.bundle_path != null and
e.build_config.post_link_callback_fn == null and
e.build_config.post_link_module == null)
{
e.build_config.post_link_module = "platform.bundle";
}
}
// Post-link callback: if the user registered one via
// `BuildOptions.set_post_link_callback(fn)` or
// `set_post_link_module("name")`, re-enter the IR interpreter and
// invoke that sx function now. A `false` return fails the build.
if (comp.getPostLinkCallback()) |fid| {
const ret = comp.invokeByFuncId(fid, &.{}) catch |err| {
printInterpBailDiag(&comp, "post-link callback", err);
return error.CompileError;
};
if (ret.asBool() == false) {
std.debug.print("error: post-link callback returned false\n", .{});
return error.CompileError;
}
} else if (comp.getPostLinkModule()) |mod_name| {
const qualified = try std.fmt.allocPrint(allocator, "{s}.bundle_main", .{mod_name});
defer allocator.free(qualified);
const ret_opt = comp.invokeByName(qualified, &.{}) catch |err| {
const label = try std.fmt.allocPrint(allocator, "post-link module '{s}.bundle_main'", .{mod_name});
defer allocator.free(label);
printInterpBailDiag(&comp, label, err);
return error.CompileError;
};
if (ret_opt) |ret| {
if (ret.asBool() == false) {
std.debug.print("error: post-link module '{s}.bundle_main' returned false\n", .{mod_name});
return error.CompileError;
}
} else {
std.debug.print("error: post-link module '{s}.bundle_main' not found\n", .{mod_name});
return error.CompileError;
}
}
// Post-process wasm HTML: inject content hash for cache busting
if (merged_config.isEmscripten() and std.mem.endsWith(u8, final_output, ".html")) {
sx.target.postProcessWasmHtml(allocator, io, final_output);

View File

@@ -18,6 +18,11 @@ pub const Parser = struct {
diagnostics: ?*errors.DiagnosticList = null,
/// Type param names from enclosing generic struct (set while parsing methods)
struct_type_params: []const []const u8 = &.{},
/// When true (set while parsing methods inside `struct #compiler { ... }`),
/// a missing function body (just `name :: (params);`) is synthesized as
/// a `.compiler_expr` body so the per-method `#compiler` suffix can be
/// omitted.
struct_default_compiler: bool = false,
pub fn init(allocator: std.mem.Allocator, source: [:0]const u8) Parser {
var lexer = Lexer.init(source);
@@ -760,6 +765,15 @@ pub const Parser = struct {
fn parseStructDecl(self: *Parser, name: []const u8, start_pos: u32) anyerror!*Node {
self.advance(); // skip 'struct'
// Optional `#compiler` attribute: all methods inside this struct are
// implicitly compiler hooks (no per-method `#compiler` suffix needed).
// Mirrors `protocol #inline { ... }` shape.
var is_compiler_struct = false;
if (self.current.tag == .hash_compiler) {
is_compiler_struct = true;
self.advance();
}
// Optional type params: struct($N: u32, $T: Type) { ... }
var type_params = std.ArrayList(ast.StructTypeParam).empty;
if (self.current.tag == .l_paren) {
@@ -805,6 +819,13 @@ pub const Parser = struct {
self.struct_type_params = tp_names.items;
defer self.struct_type_params = saved_struct_type_params;
// Propagate the struct-level `#compiler` flag to nested method
// parsing so a bodyless `name :: (params);` synthesizes a
// `.compiler_expr` body.
const saved_struct_default_compiler = self.struct_default_compiler;
self.struct_default_compiler = is_compiler_struct;
defer self.struct_default_compiler = saved_struct_default_compiler;
var field_names = std.ArrayList([]const u8).empty;
var field_types = std.ArrayList(*Node).empty;
var field_defaults = std.ArrayList(?*Node).empty;
@@ -1486,7 +1507,14 @@ pub const Parser = struct {
is_comptime_param = true;
}
}
try params.append(self.allocator, .{ .name = param_name, .name_span = param_name_span, .type_expr = param_type, .is_variadic = is_variadic, .is_comptime = is_comptime_param });
// Optional default value: `param: T = expr`. Stored on the Param
// node; lowering fills it in for callers that omit this positional arg.
var default_expr: ?*Node = null;
if (self.current.tag == .equal) {
self.advance(); // consume '='
default_expr = try self.parseExpr();
}
try params.append(self.allocator, .{ .name = param_name, .name_span = param_name_span, .type_expr = param_type, .is_variadic = is_variadic, .is_comptime = is_comptime_param, .default_expr = default_expr });
}
for (params.items, 0..) |param, i| {
if (param.is_variadic and i != params.items.len - 1) {
@@ -1570,6 +1598,12 @@ pub const Parser = struct {
self.advance();
try self.expect(.semicolon);
break :blk try self.createNode(ci_start, .{ .compiler_expr = {} });
} else if (self.struct_default_compiler and self.current.tag == .semicolon) blk: {
// Inside `struct #compiler { ... }`: a bodyless method is
// implicitly a `#compiler` hook.
const ci_start = self.current.loc.start;
self.advance();
break :blk try self.createNode(ci_start, .{ .compiler_expr = {} });
} else if (self.current.tag == .hash_foreign) blk: {
const fi_start = self.current.loc.start;
self.advance();
@@ -1741,6 +1775,36 @@ pub const Parser = struct {
return try self.createNode(start, .{ .insert_expr = .{ .expr = inner } });
}
// `#import "path";` / `#framework "Name";` inside a block body.
// Only meaningful inside an `inline if OS == ... { ... }` arm —
// the imports.zig flatten pass (issue-0042) surfaces those
// declarations to the top level before resolution. Anywhere else
// these nodes survive into lowering and produce a clear error.
if (self.current.tag == .hash_import) {
const start = self.current.loc.start;
self.advance();
if (self.current.tag != .string_literal) {
return self.fail("expected string path after '#import'");
}
const raw = self.tokenSlice(self.current);
const path = raw[1 .. raw.len - 1];
self.advance();
try self.expect(.semicolon);
return try self.createNode(start, .{ .import_decl = .{ .path = path, .name = null } });
}
if (self.current.tag == .hash_framework) {
const start = self.current.loc.start;
self.advance();
if (self.current.tag != .string_literal) {
return self.fail("expected string after '#framework'");
}
const raw = self.tokenSlice(self.current);
const fw_name = raw[1 .. raw.len - 1];
self.advance();
try self.expect(.semicolon);
return try self.createNode(start, .{ .framework_decl = .{ .name = fw_name } });
}
// inline if — compile-time conditional
if (self.current.tag == .kw_inline) {
if (self.peekNext() == .kw_if) {
@@ -2777,6 +2841,10 @@ pub const Parser = struct {
fn isFunctionDef(self: *Parser) bool {
const tag = self.peekPastParens() orelse return false;
// Inside `struct #compiler { ... }`, a bodyless method declaration
// ends with `;` directly after the param list — recognise it as a
// function def (not a constant) so it goes through parseFnDecl.
if (self.struct_default_compiler and tag == .semicolon) return true;
return tag == .l_brace or tag == .arrow or tag == .hash_builtin or tag == .hash_compiler or tag == .hash_foreign or tag == .fat_arrow or tag == .kw_callconv;
}

View File

@@ -926,243 +926,10 @@ pub fn link(allocator: std.mem.Allocator, io: std.Io, output_obj: []const u8, ex
if (result.exited != 0) return error.LinkError;
}
/// Move `binary_path` into a freshly-created `<bundle_path>` directory,
/// write a minimal Info.plist, and ad-hoc codesign for simulator runs.
/// The executable inside the bundle is named after the basename of
/// `binary_path` (also used as CFBundleExecutable).
pub fn createBundle(allocator: std.mem.Allocator, io: std.Io, binary_path: []const u8, target_config: TargetConfig, frameworks: []const []const u8) !void {
const bundle_path = target_config.bundle_path orelse return error.NoBundlePath;
const bundle_id = target_config.bundle_id orelse {
std.debug.print("error: --bundle requires --bundle-id (e.g. co.swipelab.app)\n", .{});
return error.MissingBundleId;
};
// Device builds without a real identity will be rejected by the device,
// so fail fast with a clear hint.
if (target_config.isIOSDevice() and target_config.codesign_identity == null) {
std.debug.print("error: --target ios requires --codesign-identity (e.g. \"Apple Development: ...\") and --provisioning-profile <path>\n", .{});
return error.MissingCodesignIdentity;
}
const cwd = std.Io.Dir.cwd();
cwd.deleteTree(io, bundle_path) catch {};
try cwd.createDirPath(io, bundle_path);
const exe_name = std.fs.path.basename(binary_path);
const exe_dest = try std.fs.path.join(allocator, &.{ bundle_path, exe_name });
cwd.rename(binary_path, cwd, exe_dest, io) catch return error.BundleMoveFailed;
// Info.plist
const plist = try buildInfoPlist(allocator, exe_name, bundle_id, target_config);
const plist_path = try std.fs.path.join(allocator, &.{ bundle_path, "Info.plist" });
try cwd.writeFile(io, .{ .sub_path = plist_path, .data = plist });
// Embed provisioning profile if supplied. Required for device installs.
if (target_config.provisioning_profile) |pp| {
const profile_data = std.Io.Dir.readFileAlloc(.cwd(), io, pp, allocator, .limited(1 * 1024 * 1024)) catch {
std.debug.print("error: cannot read provisioning profile: {s}\n", .{pp});
return error.ProvisioningProfileNotFound;
};
const embedded_path = try std.fs.path.join(allocator, &.{ bundle_path, "embedded.mobileprovision" });
try cwd.writeFile(io, .{ .sub_path = embedded_path, .data = profile_data });
}
// Embed any dynamic frameworks the binary links against. iOS apps load
// frameworks from `<bundle>.app/Frameworks/<Name>.framework/<Name>` via
// the `@executable_path/Frameworks` rpath we set at link time. For each
// framework, look it up in `framework_paths` and copy the bundle in.
if (target_config.isIOS() and frameworks.len > 0) {
const fw_dir = try std.fs.path.join(allocator, &.{ bundle_path, "Frameworks" });
try cwd.createDirPath(io, fw_dir);
for (frameworks) |fw| {
try embedFramework(allocator, io, fw, target_config.framework_paths, fw_dir);
}
}
// Codesign: real identity for device, ad-hoc otherwise.
const identity: []const u8 = target_config.codesign_identity orelse "-";
const ent_path: ?[]const u8 = if (target_config.entitlements_path) |e| e else blk: {
if (target_config.provisioning_profile) |pp| {
break :blk try extractEntitlements(allocator, io, pp, bundle_id);
}
break :blk null;
};
try codesign(allocator, io, bundle_path, identity, ent_path);
}
/// Find `<name>.framework` in one of `framework_paths` and copy it into
/// `<dest_dir>/<name>.framework`. Shells out to `cp -R` because Zig's std
/// doesn't expose a recursive-copy primitive on `Io.Dir` yet.
fn embedFramework(allocator: std.mem.Allocator, io: std.Io, name: []const u8, framework_paths: []const []const u8, dest_dir: []const u8) !void {
const cwd = std.Io.Dir.cwd();
const subdir = try std.fmt.allocPrint(allocator, "{s}.framework", .{name});
for (framework_paths) |fp| {
const candidate = try std.fs.path.join(allocator, &.{ fp, subdir });
if (cwd.openDir(io, candidate, .{})) |d| {
d.close(io);
const dest = try std.fs.path.join(allocator, &.{ dest_dir, subdir });
const r = std.process.run(allocator, io, .{
.argv = &.{ "cp", "-R", candidate, dest },
}) catch return error.FrameworkCopyFailed;
defer allocator.free(r.stdout);
defer allocator.free(r.stderr);
if (r.term != .exited or r.term.exited != 0) {
std.debug.print("error: cp -R {s} -> {s} failed: {s}\n", .{ candidate, dest, r.stderr });
return error.FrameworkCopyFailed;
}
return;
} else |_| {}
}
std.debug.print("warning: framework '{s}' not found in any -F path; runtime load will fail\n", .{name});
}
/// Extract entitlements XML from a `.mobileprovision` and resolve the
/// `application-identifier` wildcard (`<TEAM>.*`) to the concrete bundle ID
/// (`<TEAM>.<bundle_id>`). Without this substitution the device installer
/// rejects the app with `MIInstallerErrorDomain error 13` /
/// `0xe8008015 (A valid provisioning profile ... was not found)`.
/// Writes the resolved entitlements to `.sx-tmp/entitlements.plist`.
fn extractEntitlements(allocator: std.mem.Allocator, io: std.Io, profile_path: []const u8, bundle_id: []const u8) ![]const u8 {
const cwd = std.Io.Dir.cwd();
cwd.createDirPath(io, ".sx-tmp") catch {};
const profile_plist_path = ".sx-tmp/profile.plist";
const ent_path = ".sx-tmp/entitlements.plist";
// 1. security cms -D -i <profile> -o profile.plist (decode CMS to plist)
const r1 = std.process.run(allocator, io, .{
.argv = &.{ "security", "cms", "-D", "-i", profile_path, "-o", profile_plist_path },
}) catch return error.SecurityCommandFailed;
defer allocator.free(r1.stdout);
defer allocator.free(r1.stderr);
if (r1.term != .exited or r1.term.exited != 0) {
std.debug.print("error: failed to decode provisioning profile: {s}\n", .{r1.stderr});
return error.SecurityCommandFailed;
}
// 2. plutil -extract Entitlements xml1 -o entitlements.plist profile.plist
const r2 = std.process.run(allocator, io, .{
.argv = &.{ "plutil", "-extract", "Entitlements", "xml1", "-o", ent_path, profile_plist_path },
}) catch return error.PlutilCommandFailed;
defer allocator.free(r2.stdout);
defer allocator.free(r2.stderr);
if (r2.term != .exited or r2.term.exited != 0) {
std.debug.print("error: failed to extract entitlements: {s}\n", .{r2.stderr});
return error.PlutilCommandFailed;
}
// 3. Read the team identifier so we can resolve the wildcard. The profile
// stores it as `ApplicationIdentifierPrefix.0` (an array). We use that
// path because `com.apple.developer.team-identifier` would confuse
// plutil — dots in plutil paths are interpreted as path separators.
const r3 = std.process.run(allocator, io, .{
.argv = &.{ "plutil", "-extract", "ApplicationIdentifierPrefix.0", "raw", "-o", "-", profile_plist_path },
}) catch return error.PlutilCommandFailed;
defer allocator.free(r3.stdout);
defer allocator.free(r3.stderr);
if (r3.term != .exited or r3.term.exited != 0) {
std.debug.print("error: profile missing ApplicationIdentifierPrefix: {s}\n", .{r3.stderr});
return error.PlutilCommandFailed;
}
const team = std.mem.trimEnd(u8, r3.stdout, " \t\r\n");
const resolved_app_id = try std.fmt.allocPrint(allocator, "{s}.{s}", .{ team, bundle_id });
defer allocator.free(resolved_app_id);
// 4. plutil -replace application-identifier -string "<team>.<bundle_id>" entitlements.plist
const r4 = std.process.run(allocator, io, .{
.argv = &.{ "plutil", "-replace", "application-identifier", "-string", resolved_app_id, ent_path },
}) catch return error.PlutilCommandFailed;
defer allocator.free(r4.stdout);
defer allocator.free(r4.stderr);
if (r4.term != .exited or r4.term.exited != 0) {
std.debug.print("error: failed to resolve application-identifier: {s}\n", .{r4.stderr});
return error.PlutilCommandFailed;
}
return try allocator.dupe(u8, ent_path);
}
fn buildInfoPlist(allocator: std.mem.Allocator, exe_name: []const u8, bundle_id: []const u8, target_config: TargetConfig) ![]const u8 {
const min_os: []const u8 = "14.0";
const is_sim = target_config.isIOSSimulator();
const platform_key: []const u8 = if (is_sim) "iPhoneSimulator" else "iPhoneOS";
// UIApplicationSceneManifest opts the app into the iOS 13+ scene-based
// lifecycle. Without it, iOS 26 boots the app in `[rb-legacy]` mode and
// the CAMetalLayer never reaches the compositor. With the manifest
// declared (no UISceneDelegate listed), iOS auto-connects an implicit
// scene that our SxAppDelegate can find via `[app connectedScenes]`.
return std.fmt.allocPrint(allocator,
\\<?xml version="1.0" encoding="UTF-8"?>
\\<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
\\<plist version="1.0">
\\<dict>
\\ <key>CFBundleIdentifier</key>
\\ <string>{s}</string>
\\ <key>CFBundleName</key>
\\ <string>{s}</string>
\\ <key>CFBundleExecutable</key>
\\ <string>{s}</string>
\\ <key>CFBundlePackageType</key>
\\ <string>APPL</string>
\\ <key>CFBundleVersion</key>
\\ <string>1</string>
\\ <key>CFBundleShortVersionString</key>
\\ <string>0.1</string>
\\ <key>MinimumOSVersion</key>
\\ <string>{s}</string>
\\ <key>UIDeviceFamily</key>
\\ <array>
\\ <integer>1</integer>
\\ </array>
\\ <key>LSRequiresIPhoneOS</key>
\\ <true/>
\\ <key>UILaunchScreen</key>
\\ <dict/>
\\ <key>UIApplicationSceneManifest</key>
\\ <dict>
\\ <key>UIApplicationSupportsMultipleScenes</key>
\\ <false/>
\\ <key>UISceneConfigurations</key>
\\ <dict>
\\ <key>UIWindowSceneSessionRoleApplication</key>
\\ <array>
\\ <dict>
\\ <key>UISceneConfigurationName</key>
\\ <string>Default Configuration</string>
\\ <key>UISceneDelegateClassName</key>
\\ <string>SxSceneDelegate</string>
\\ </dict>
\\ </array>
\\ </dict>
\\ </dict>
\\ <key>DTPlatformName</key>
\\ <string>{s}</string>
\\</dict>
\\</plist>
\\
, .{ bundle_id, exe_name, exe_name, min_os, platform_key });
}
fn codesign(allocator: std.mem.Allocator, io: std.Io, bundle_path: []const u8, identity: []const u8, entitlements: ?[]const u8) !void {
var argv = std.ArrayList([]const u8).empty;
defer argv.deinit(allocator);
try argv.appendSlice(allocator, &.{ "codesign", "--force", "--sign", identity, "--timestamp=none" });
if (entitlements) |ep| {
try argv.appendSlice(allocator, &.{ "--entitlements", ep });
}
try argv.append(allocator, bundle_path);
const r = std.process.run(allocator, io, .{ .argv = argv.items }) catch |e| {
std.debug.print("error: failed to run codesign: {}\n", .{e});
return error.CodesignFailed;
};
defer allocator.free(r.stdout);
defer allocator.free(r.stderr);
if (r.term != .exited or r.term.exited != 0) {
std.debug.print("codesign failed: {s}\n", .{r.stderr});
return error.CodesignFailed;
}
}
// Apple .app bundling (createBundle, embedFramework, extractEntitlements,
// buildInfoPlist, codesign) has moved to
// `library/modules/platform/bundle.sx`. `src/main.zig` invokes it
// post-link via the BuildOptions callback registered from sx code.
/// After emcc produces HTML output, inject cache-busting hashes into the
/// generated <script> tag and add Module.locateFile for .wasm/.data files.