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:
@@ -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
155
src/ir/host_ffi.zig
Normal 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,
|
||||
}
|
||||
}
|
||||
@@ -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, ¤t_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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user