Skip to main content

js2zig_core/
project.rs

1/// Generate a complete Zig library project from translated JS code.
2use std::collections::HashSet;
3use std::fs;
4use std::path::Path;
5use std::process::Command;
6
7/// A single per-file Zig module with its dependency info.
8#[derive(Debug, Clone)]
9pub struct PerFileModule {
10    /// Sanitized module name (e.g. "math", "string_utils", "main")
11    pub mod_name: String,
12    /// Translated Zig source code for this file
13    pub zig_code: String,
14    /// Dependency imports: Vec<(imported_name, source_module_name)>
15    /// e.g. [("add", "math"), ("multiply", "math"), ("greet", "string_utils")]
16    pub dep_imports: Vec<(String, String)>,
17}
18
19/// Project generation options
20pub struct ProjectOptions {
21    /// Name of the Zig library (also the output directory name)
22    pub name: String,
23    /// Output directory (e.g. "out")
24    pub out_dir: String,
25    /// Per-file Zig modules. Each entry is written as `{mod_name}.zig`, and lib.zig
26    /// becomes a thin orchestrator that imports all per-file modules.
27    pub per_file_code: Vec<PerFileModule>,
28    /// Export names that should be re-exported from lib.zig.
29    /// Each entry: (export_name, source_module_name).
30    /// In multi-file mode, this should include ALL public exports from ALL modules.
31    pub external_exports: Vec<(String, String)>,
32    /// Pre-generated `pub export fn` wrapper code for C ABI exports.
33    /// Each wrapper calls a per-file module function and lives in the root lib.zig
34    /// so that Zig propagates the symbols into the final .lib.
35    pub cabi_wrapper_code: String,
36    /// Names that have C ABI wrappers — these are skipped in the re-export section
37    /// to avoid duplicate struct member errors.
38    pub cabi_names: std::collections::HashSet<String>,
39    /// Auto-generated test code (from testgen)
40    pub test_code: String,
41    /// Runtime source directory (relative to project root, e.g. "runtime")
42    pub runtime_dir: Option<String>,
43    /// Host function extern "c" declarations (from host::HostFnRegistry)
44    pub host_header: String,
45    /// Names of async host functions (used to generate aliases in per-file modules)
46    pub async_host_fn_names: Vec<String>,
47    /// Whether to include the Windows LdrRegisterDllNotification stub.
48    /// Must be `true` for exactly one group (the first one), because Zig's
49    /// standard library references this symbol and Windows COFF doesn't
50    /// support weak linkage across object files.
51    pub include_windows_stub: bool,
52}
53
54/// Generate the full Zig library project.
55pub fn generate(opts: &ProjectOptions) -> Result<(), String> {
56    let project_dir = Path::new(&opts.out_dir).join(&opts.name);
57    let src_dir = project_dir.join("src");
58
59    // Create directories
60    fs::create_dir_all(&src_dir).map_err(|e| format!("create {}: {}", project_dir.display(), e))?;
61
62    // 1. build.zig.zon - first pass without fingerprint
63    let zon_path = project_dir.join("build.zig.zon");
64    let zon_no_fp = generate_zon(&opts.name, None);
65    fs::write(&zon_path, &zon_no_fp).map_err(|e| format!("write build.zig.zon: {}", e))?;
66
67    // 2. build.zig
68    let build_zig = generate_build_zig(&opts.name);
69    fs::write(project_dir.join("build.zig"), build_zig)
70        .map_err(|e| format!("write build.zig: {}", e))?;
71
72    // 3. Write per-file .zig files + orchestrator lib.zig
73    for module in &opts.per_file_code {
74        let mod_zig = generate_module_zig(module, &opts.async_host_fn_names);
75        let mod_path = src_dir.join(format!("{}.zig", module.mod_name));
76        fs::write(&mod_path, mod_zig)
77            .map_err(|e| format!("write {}.zig: {}", mod_path.display(), e))?;
78    }
79
80    // Generate orchestrator lib.zig
81    let lib_zig = generate_orchestrator_lib(opts);
82    fs::write(src_dir.join("lib.zig"), lib_zig).map_err(|e| format!("write lib.zig: {}", e))?;
83
84    // 3.5 src/host.zig — host function extern "c" declarations.
85    // Always write it (even empty) — some generated modules import it for
86    // builtin transpilation that references host.* functions (e.g. host.regex_test).
87    let host_content = if opts.host_header.is_empty() {
88        // Minimum: always include regex_test and regex_search declarations
89        // since the Emitter may reference them.
90        r#"// Auto-generated host.zig — minimum declarations for builtin transpilation
91// These symbols are defined in Rust with #[no_mangle] pub extern "C".
92pub extern fn host_regex_test(
93    pattern_ptr: [*]const u8, pattern_len: usize,
94    subject_ptr: [*]const u8, subject_len: usize,
95) callconv(.c) bool;
96pub extern fn host_regex_search(
97    pattern_ptr: [*]const u8, pattern_len: usize,
98    subject_ptr: [*]const u8, subject_len: usize,
99) callconv(.c) i64;
100
101// Wrapper functions: the Emitter generates host.regex_test(pattern, subject) (dot
102// notation, 2 args as []const u8 slices), but extern declarations use
103// host_regex_test with ptr+len pairs. These wrappers bridge the gap.
104pub fn regex_test(pattern: []const u8, subject: []const u8) bool {
105    return host_regex_test(pattern.ptr, pattern.len, subject.ptr, subject.len);
106}
107pub fn regex_search(pattern: []const u8, subject: []const u8) i64 {
108    return host_regex_search(pattern.ptr, pattern.len, subject.ptr, subject.len);
109}
110"#
111        .to_string()
112    } else {
113        let mut content = opts.host_header.clone();
114        // Ensure regex_test/regex_search are declared even if not in registered host fns
115        if !content.contains("host_regex_test") {
116            content.push_str(
117                r#"
118pub extern fn host_regex_test(
119    pattern_ptr: [*]const u8, pattern_len: usize,
120    subject_ptr: [*]const u8, subject_len: usize,
121) callconv(.c) bool;
122"#,
123            );
124        }
125        if !content.contains("host_regex_search") {
126            content.push_str(
127                r#"pub extern fn host_regex_search(
128    pattern_ptr: [*]const u8, pattern_len: usize,
129    subject_ptr: [*]const u8, subject_len: usize,
130) callconv(.c) i64;
131"#,
132            );
133        }
134        // Add wrapper functions so the Emitter's host.regex_test(...) (dot notation)
135        // resolves to the extern host_regex_test (underscore naming).
136        if !content.contains("pub fn regex_test(") {
137            content.push_str(
138                r#"
139pub fn regex_test(pattern: []const u8, subject: []const u8) bool {
140    return host_regex_test(pattern.ptr, pattern.len, subject.ptr, subject.len);
141}
142"#,
143            );
144        }
145        if !content.contains("pub fn regex_search(") {
146            content.push_str(
147                r#"
148pub fn regex_search(pattern: []const u8, subject: []const u8) i64 {
149    return host_regex_search(pattern.ptr, pattern.len, subject.ptr, subject.len);
150}
151"#,
152            );
153        }
154        content
155    };
156    fs::write(src_dir.join("host.zig"), &host_content)
157        .map_err(|e| format!("write host.zig: {}", e))?;
158
159    // 4. Copy runtime/ if it exists (always overwrite to pick up runtime changes)
160    if let Some(ref rt_dir) = opts.runtime_dir {
161        let rt_src = Path::new(rt_dir);
162        if rt_src.exists() && rt_src.is_dir() {
163            let rt_dst = src_dir.join("js_runtime");
164            // Always re-copy runtime files to pick up changes (e.g. js_console.zig updates)
165            let _ = fs::remove_dir_all(&rt_dst);
166            if let Err(e) = copy_dir_recursive(rt_src, &rt_dst) {
167                // If copy fails (e.g. concurrent process has the file), check if
168                // another process already completed the copy.
169                if !rt_dst.join("js_runtime.zig").exists() {
170                    return Err(format!("copy {}: {}", rt_dst.display(), e));
171                }
172            }
173        }
174    }
175
176    // 5. Auto-compute fingerprint via zig build
177    if let Some(fp) = compute_fingerprint(&project_dir) {
178        let zon_with_fp = generate_zon(&opts.name, Some(&fp));
179        fs::write(&zon_path, zon_with_fp)
180            .map_err(|e| format!("write build.zig.zon (with fingerprint): {}", e))?;
181    }
182
183    Ok(())
184}
185
186/// Run `zig build` in the project directory to get the suggested fingerprint.
187fn compute_fingerprint(project_dir: &Path) -> Option<String> {
188    let output = Command::new("zig")
189        .arg("build")
190        .current_dir(project_dir)
191        .output()
192        .ok()?;
193
194    let stderr = String::from_utf8_lossy(&output.stderr);
195    // Parse: "suggested value: 0x8f0f7e479be9961b"
196    let prefix = "suggested value: ";
197    if let Some(pos) = stderr.find(prefix) {
198        let after = &stderr[pos + prefix.len()..];
199        let fp = after.split_whitespace().next()?;
200        // Validate it looks like 0xHEX (length varies: 16–18 chars)
201        if fp.starts_with("0x") && fp.len() >= 16 && fp[2..].chars().all(|c| c.is_ascii_hexdigit())
202        {
203            return Some(fp.to_string());
204        }
205    }
206    None
207}
208
209fn generate_zon(name: &str, fingerprint: Option<&str>) -> String {
210    let fp_line = match fingerprint {
211        Some(fp) => format!("    .fingerprint = {},\n", fp),
212        None => String::new(),
213    };
214    format!(
215        r#".{{
216    .name = .{name},
217{fp_line}    .version = "0.1.0",
218    .minimum_zig_version = "0.16.0",
219    .paths = .{{"src", "build.zig", "build.zig.zon"}},
220    .dependencies = .{{}},
221}}
222"#,
223        name = name,
224        fp_line = fp_line
225    )
226}
227
228pub fn generate_build_zig(lib_name: &str) -> String {
229    format!(
230        r#"const std = @import("std");
231
232pub fn build(b: *std.Build) void {{
233    const target = b.standardTargetOptions(.{{}});
234    const optimize = b.standardOptimizeOption(.{{}});
235
236    const lib_mod = b.createModule(.{{
237        .root_source_file = b.path("src/lib.zig"),
238        .target = target,
239        .optimize = optimize,
240        .link_libc = true,
241    }});
242
243    // Build as static library.
244    // bundle_compiler_rt = true: includes compiler-rt symbols in the .lib.
245    // MSVC link.exe cannot parse COMDAT sections in compiler_rt.obj (LNK1143),
246    // so users MUST use rust-lld as the linker:
247    //   .cargo/config.toml: [target.x86_64-pc-windows-msvc] linker = "rust-lld.exe"
248    const lib = b.addLibrary(.{{
249        .name = "{name}",
250        .linkage = .static,
251        .root_module = lib_mod,
252    }});
253    lib.bundle_compiler_rt = true;
254    b.installArtifact(lib);
255
256    // Test step
257    const tests = b.addTest(.{{
258        .root_module = lib_mod,
259    }});
260    const run_tests = b.addRunArtifact(tests);
261    const test_step = b.step("test", "Run all library tests");
262    test_step.dependOn(&run_tests.step);
263
264    // WASM target step: `zig build wasm` produces a .wasm module
265    const wasm_mod = b.createModule(.{{
266        .root_source_file = b.path("src/lib.zig"),
267        .target = b.resolveTargetQuery(.{{
268            .cpu_arch = .wasm32,
269            .os_tag = .wasi,
270        }}),
271        .optimize = optimize,
272    }});
273    const wasm_lib = b.addExecutable(.{{
274        .name = "{name}",
275        .root_module = wasm_mod,
276    }});
277    wasm_lib.entry = .disabled;
278    const wasm_install = b.addInstallArtifact(wasm_lib, .{{}});
279    const wasm_step = b.step("wasm", "Build WASM target (wasm32-wasi)");
280    wasm_step.dependOn(&wasm_install.step);
281}}
282"#,
283        name = lib_name
284    )
285}
286
287/// Generate a per-file Zig module with dependency imports and full runtime imports.
288///
289/// Produces:
290///   // Auto-generated from {mod_name}.js
291///   const std = ...
292///   const js_allocator = ...
293///   // --- Dependency module imports ---
294///   const math = @import("math.zig");
295///   const string_utils = @import("string_utils.zig");
296///   // --- Imported name aliases ---
297///   const add = math.add;
298///   ...
299///   // Generated code
300///   export fn add(...) ...
301fn generate_module_zig(module: &PerFileModule, async_host_fn_names: &[String]) -> String {
302    let mut out = String::new();
303    out.push_str(&format!("// Auto-generated from {}.js\n", module.mod_name));
304    out.push_str("const std = @import(\"std\");\n");
305    out.push_str("const builtin = @import(\"builtin\");\n");
306    out.push_str("const Io = std.Io;\n");
307    out.push_str("const Allocator = std.mem.Allocator;\n");
308    out.push('\n');
309    out.push_str("// Global allocator for generated code\n");
310    out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
311    out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n");
312    out.push('\n');
313    out.push_str("// Tier-3 runtime library imports\n");
314    out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
315    out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
316    out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
317    out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
318    out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
319    out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
320    out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
321    out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
322    out.push_str("const js_collections = @import(\"js_runtime/js_collections.zig\");\n");
323    out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
324    out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
325    out.push_str("const js_symbol = @import(\"js_runtime/js_symbol.zig\");\n");
326    out.push_str("const JsSymbol = @import(\"js_runtime/js_symbol.zig\").JsSymbol;\n");
327    out.push_str("const js_bigint = @import(\"js_runtime/js_bigint.zig\");\n");
328    out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
329    out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
330    out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
331    out.push('\n');
332
333    // Host function imports (if this module calls host functions or async fns exist)
334    if module.zig_code.contains("host.") || !async_host_fn_names.is_empty() {
335        out.push_str("// Host functions (Rust via C ABI)\n");
336        out.push_str("const host = @import(\"host.zig\");\n");
337        // Async function aliases: lets generated code call host.{name}_async as {name}
338        for name in async_host_fn_names {
339            out.push_str(&format!("const {} = host.{}_async;\n", name, name));
340        }
341        out.push('\n');
342    }
343
344    // Deduplicate dependency modules
345    let mut dep_modules: Vec<String> = Vec::new();
346    let mut seen_modules: HashSet<&str> = HashSet::new();
347    for (_, src_mod) in &module.dep_imports {
348        if seen_modules.insert(src_mod) {
349            dep_modules.push(src_mod.clone());
350        }
351    }
352
353    if !dep_modules.is_empty() {
354        out.push_str("// --- Dependency module imports ---\n");
355        for mod_name in &dep_modules {
356            out.push_str(&format!(
357                "const {} = @import(\"{}.zig\");\n",
358                mod_name, mod_name
359            ));
360        }
361        out.push('\n');
362
363        out.push_str("// --- Imported name aliases ---\n");
364        for (name, src_mod) in &module.dep_imports {
365            out.push_str(&format!("const {name} = {mod}.{name};\n", name = name, mod = src_mod));
366        }
367        out.push('\n');
368    }
369
370    // NOTE: No Windows LdrRegisterDllNotification stub here — it's in the orchestrator lib.zig.
371    // Per-file modules are only compiled as part of the orchestrator, so the stub is inherited.
372
373    out.push_str(&module.zig_code);
374    out
375}
376
377/// Generate the orchestrator lib.zig for multi-file mode.
378/// Imports all per-file modules, re-exports ALL public exports from all modules,
379/// includes test blocks.
380fn generate_orchestrator_lib(opts: &ProjectOptions) -> String {
381    let mut out = String::new();
382    out.push_str("// Auto-generated by js2rust (orchestrator)\n");
383    out.push_str("const std = @import(\"std\");\n");
384    out.push_str("const builtin = @import(\"builtin\");\n");
385    out.push_str("const Io = std.Io;\n");
386    out.push_str("const Allocator = std.mem.Allocator;\n");
387    out.push('\n');
388    out.push_str("// Global allocator for generated code\n");
389    out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
390    out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n");
391    out.push('\n');
392    out.push_str("// Tier-3 runtime library imports\n");
393    out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
394    out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
395    out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
396    out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
397    out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
398    out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
399    out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
400    out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
401    out.push_str("const js_collections = @import(\"js_runtime/js_collections.zig\");\n");
402    out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
403    out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
404    out.push_str("const js_symbol = @import(\"js_runtime/js_symbol.zig\");\n");
405    out.push_str("const JsSymbol = @import(\"js_runtime/js_symbol.zig\").JsSymbol;\n");
406    out.push_str("const js_bigint = @import(\"js_runtime/js_bigint.zig\");\n");
407    out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
408    out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
409    out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
410    out.push('\n');
411
412    // Host function declarations (if any)
413    if !opts.host_header.is_empty() {
414        out.push_str("// Tier-4 host functions (Rust via C ABI)\n");
415        out.push_str("const host = @import(\"host.zig\");\n");
416        out.push('\n');
417    }
418
419    // Windows stub (needed for Zig std.debug on Windows; only in one group)
420    // Uses platform-independent types so it compiles on all targets (native, WASM).
421    if opts.include_windows_stub {
422        out.push_str("// Windows stub for Zig std.debug.SelfInfo.Windows\n");
423        out.push_str(
424            "// Uses raw types (u32/i32) to avoid importing std.os.windows on non-Windows.\n",
425        );
426        out.push_str("pub export fn LdrRegisterDllNotification(\n");
427        out.push_str("    Flags: u32,\n");
428        out.push_str("    NotificationFunction: ?*const anyopaque,\n");
429        out.push_str("    Context: ?*anyopaque,\n");
430        out.push_str("    Cookie: *?*anyopaque,\n");
431        out.push_str(") callconv(.c) i32 {\n");
432        out.push_str("    _ = Flags;\n");
433        out.push_str("    _ = NotificationFunction;\n");
434        out.push_str("    _ = Context;\n");
435        out.push_str("    Cookie.* = @ptrFromInt(1);\n");
436        out.push_str("    return 0; // STATUS_SUCCESS\n");
437        out.push_str("}\n\n");
438    }
439
440    // Async host function aliases (if any) — lets orchestrator call async wrappers
441    if !opts.async_host_fn_names.is_empty() {
442        out.push_str("// Async host function aliases\n");
443        for name in &opts.async_host_fn_names {
444            out.push_str(&format!("const {} = host.{}_async;\n", name, name));
445        }
446        out.push('\n');
447    }
448
449    // Per-file module imports (prefixed with _ to avoid duplicate name errors
450    // when re-exporting pub const {name} = _{name}.{name}).
451    out.push_str("// Per-file module imports\n");
452    for module in &opts.per_file_code {
453        out.push_str(&format!(
454            "const _{} = @import(\"{}.zig\");\n",
455            module.mod_name, module.mod_name
456        ));
457    }
458    out.push('\n');
459
460    // --- Global initialization / deinitialization ---
461    out.push_str("/// Initialize the global allocator used by all generated functions.\n");
462    out.push_str("/// The allocator is created internally using ArenaAllocator (Zig 0.16.0: lock-free, thread-safe).\n");
463    out.push_str("pub fn init_js2rust() !void {\n");
464    out.push_str("    try js_allocator.init(null, null);\n");
465    out.push_str("    js_runtime.initIo(js_allocator.allocator());\n");
466    // Also call init_js2rust on each per-file module that defines its own
467    for module in &opts.per_file_code {
468        if module.zig_code.contains("pub fn init_js2rust") {
469            out.push_str(&format!("    _{}.init_js2rust();\n", module.mod_name));
470        }
471    }
472    out.push_str("}\n\n");
473    // C ABI compatible init/deinit (callable from Rust via FFI)
474    // Only generate in one group to avoid duplicate symbols when linking multiple groups.
475    if opts.include_windows_stub {
476        out.push_str("/// Initialize with ArenaAllocator (lock-free, thread-safe).\n");
477        out.push_str(
478            "/// Call this from Rust via C ABI before using any function that allocates.\n",
479        );
480        out.push_str("pub export fn js2rust_init() void {\n");
481        out.push_str("    init_js2rust() catch @panic(\"init_js2rust failed\");\n");
482        out.push_str("}\n\n");
483        out.push_str("/// Release global resources. Call this when done.\n");
484        out.push_str("pub export fn js2rust_deinit() void {\n");
485        out.push_str("    deinit_js2rust();\n");
486        out.push_str("}\n\n");
487        out.push_str(
488            "/// Allocate memory in Zig's Arena for zero-copy string returns from Rust host functions.\n",
489        );
490        out.push_str(
491            "/// Called from Rust via extern \"C\" { fn js_allocator_alloc(size: usize) -> ?*mut u8; }\n",
492        );
493        out.push_str("/// Memory is managed by the multi-arena allocator — no free needed.\n");
494        out.push_str("/// Returns null on OOM instead of panicking.\n");
495        out.push_str("pub export fn js_allocator_alloc(size: usize) ?[*]u8 {\n");
496        out.push_str("    const buf = js_allocator.allocBytes(size) catch return null;\n");
497        out.push_str("    return buf.ptr;\n");
498        out.push_str("}\n\n");
499        out.push_str(
500            "/// Allocate + copy in Zig Arena — single call for zero-copy string returns.\n",
501        );
502        out.push_str(
503            "/// Called from Rust via extern \"C\" { fn js_allocator_dupe(src: *const u8, len: usize) -> ?*mut u8; }\n",
504        );
505        out.push_str("/// Prefer this over js_allocator_alloc + manual copy — avoids a separate memcpy in Rust.\n");
506        out.push_str("/// Returns null on OOM instead of panicking.\n");
507        out.push_str("pub export fn js_allocator_dupe(src: [*]const u8, len: usize) ?[*]u8 {\n");
508        out.push_str("    const buf = js_allocator.dupeBytes(src[0..len]) catch return null;\n");
509        out.push_str("    return buf.ptr;\n");
510        out.push_str("}\n\n");
511    }
512    out.push_str("/// Release global resources allocated via init_js2rust.\n");
513    out.push_str("pub fn deinit_js2rust() void {\n");
514    out.push_str("    js_runtime.deinitIo();\n");
515    for module in &opts.per_file_code {
516        if module.zig_code.contains("pub fn deinit_js2rust") {
517            out.push_str(&format!("    _{}.deinit_js2rust();\n", module.mod_name));
518        }
519    }
520    out.push_str("    js_allocator.deinit();\n");
521    out.push_str("}\n\n");
522
523    // Build a set of functions that return C ABI strings ([*:0]const u8),
524    // so we can emit adapter wrappers instead of bare `pub const X = mod.X;`.
525    let cabi_string_fns = collect_cabi_string_fns(&opts.per_file_code);
526
527    // Re-export ALL public exports from ALL modules so tests can reference them
528    if !opts.external_exports.is_empty() {
529        out.push_str("// Re-export all public exports from per-file modules\n");
530        let mut exported: HashSet<&str> = HashSet::new();
531
532        for (exp_name, mod_name) in &opts.external_exports {
533            if !exported.insert(exp_name) {
534                continue;
535            }
536            // Skip names that already have C ABI pub export fn wrappers
537            // (they'd cause duplicate struct member errors in Zig).
538            if opts.cabi_names.contains(exp_name.as_str()) {
539                continue;
540            }
541            if cabi_string_fns.contains(exp_name.as_str()) {
542                // C ABI string-returning function: generate adapter
543                // pub fn greet(s: []const u8) []const u8 {
544                //     return std.mem.sliceTo(_mod.greet(@ptrCast(s.ptr)), 0);
545                // }
546                out.push_str(&format!(
547                    "pub fn {name}(s: []const u8) []const u8 {{\n    return std.mem.sliceTo(_{mod}.{name}(@ptrCast(s.ptr)), 0);\n}}\n",
548                    name = exp_name,
549                    mod = mod_name
550                ));
551            } else {
552                out.push_str(&format!(
553                    "pub const {exp} = _{mod}.{exp};\n",
554                    exp = exp_name,
555                    mod = mod_name
556                ));
557            }
558        }
559        out.push('\n');
560    }
561
562    // C ABI exports: pub export fn wrappers in root lib.zig calling per-file modules.
563    // Zig only propagates root-module pub export into the final .lib binary.
564    if !opts.cabi_wrapper_code.is_empty() {
565        out.push_str("// C ABI exports (pub export fn wrappers)\n");
566        out.push_str(&opts.cabi_wrapper_code);
567        out.push('\n');
568    }
569
570    // Append test blocks
571    if !opts.test_code.trim().is_empty() {
572        out.push_str(&opts.test_code);
573        out.push('\n');
574    }
575
576    out
577}
578
579/// Scan per-file modules' zig_code for functions that return C ABI strings
580/// (signatures containing `[*:0]const u8`)
581fn collect_cabi_string_fns(per_file_code: &[PerFileModule]) -> HashSet<String> {
582    let mut fns = HashSet::new();
583    for module in per_file_code {
584        for line in module.zig_code.lines() {
585            let trimmed = line.trim();
586            // Match: pub export fn greet(name: ...) StrRet {
587            if (trimmed.starts_with("pub export fn ") || trimmed.starts_with("pub fn "))
588                && trimmed.contains("StrRet")
589                && let Some(open_paren) = trimmed.find('(')
590            {
591                // Extract function name between `fn ` and `(`
592                let prefix_end = if trimmed.starts_with("pub export fn ") {
593                    "pub export fn ".len()
594                } else {
595                    "pub fn ".len()
596                };
597                let name = trimmed[prefix_end..open_paren].trim();
598                fns.insert(name.to_string());
599            }
600        }
601    }
602    fns
603}
604
605/// Recursively copy a directory
606fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
607    fs::create_dir_all(dst).map_err(|e| format!("create dir {}: {}", dst.display(), e))?;
608
609    for entry in fs::read_dir(src).map_err(|e| format!("read dir {}: {}", src.display(), e))? {
610        let entry = entry.map_err(|e| format!("read entry: {}", e))?;
611        let src_path = entry.path();
612        let dst_path = dst.join(entry.file_name());
613
614        if src_path.is_dir() {
615            copy_dir_recursive(&src_path, &dst_path)?;
616        } else if src_path.is_file() {
617            fs::copy(&src_path, &dst_path)
618                .map_err(|e| format!("copy {}: {}", src_path.display(), e))?;
619        }
620    }
621
622    Ok(())
623}