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, PathBuf};
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: PathBuf,
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: (cabi_name, source_module_name, bare_fn_name).
30    /// In multi-file mode, this should include ALL public exports from ALL modules.
31    /// `cabi_name` is the disambiguated public name (may be `{fn}_{module}` on collision).
32    /// `bare_fn_name` is the original function name inside the per-file module.
33    pub external_exports: Vec<(String, String, String)>,
34    /// Pre-generated `pub export fn` wrapper code for C ABI exports.
35    /// Each wrapper calls a per-file module function and lives in the root lib.zig
36    /// so that Zig propagates the symbols into the final .lib.
37    pub cabi_wrapper_code: String,
38    /// Names that have C ABI wrappers — these are skipped in the re-export section
39    /// to avoid duplicate struct member errors.
40    pub cabi_names: HashSet<String>,
41    /// Auto-generated test code (from testgen)
42    pub test_code: String,
43    /// Runtime source directory (relative to project root, e.g. "runtime")
44    pub runtime_dir: Option<PathBuf>,
45    /// Host function extern "c" declarations (from host::HostFnRegistry)
46    pub host_header: String,
47    /// Names of async host functions (used to generate aliases in per-file modules)
48    pub async_host_fn_names: Vec<String>,
49    /// Whether the transpiled JS code uses RegExp/regex features
50    pub needs_regex: bool,
51    /// Whether the transpiled JS code uses ICU-dependent features
52    /// (localeCompare, normalize, toLocaleUpperCase, toLocaleLowerCase).
53    /// When true, js_string_icu.zig is overwritten with the ICU4X version
54    /// and host_icu_stubs.zig is generated for zig test.
55    pub needs_icu: bool,
56}
57
58/// Generate the full Zig library project.
59pub fn generate(opts: &ProjectOptions) -> Result<(), String> {
60    let project_dir = opts.out_dir.join(&opts.name);
61    let src_dir = project_dir.join("src");
62
63    // Create directories
64    fs::create_dir_all(&src_dir).map_err(|e| format!("create {}: {}", project_dir.display(), e))?;
65
66    // 1. build.zig.zon - first pass without fingerprint
67    let zon_path = project_dir.join("build.zig.zon");
68    let zon_no_fp = generate_zon(&opts.name, None);
69    fs::write(&zon_path, &zon_no_fp).map_err(|e| format!("write build.zig.zon: {}", e))?;
70
71    // 2. build.zig
72    let build_zig = generate_build_zig(&opts.name, opts.needs_regex, opts.needs_icu);
73    fs::write(project_dir.join("build.zig"), build_zig)
74        .map_err(|e| format!("write build.zig: {}", e))?;
75
76    // 3. Write per-file .zig files + orchestrator lib.zig
77    for module in &opts.per_file_code {
78        let mod_zig = generate_module_zig(module, &opts.async_host_fn_names, opts.needs_regex);
79        let mod_path = src_dir.join(format!("{}.zig", module.mod_name));
80        fs::write(&mod_path, mod_zig)
81            .map_err(|e| format!("write {}.zig: {}", mod_path.display(), e))?;
82    }
83
84    // Generate orchestrator lib.zig
85    let lib_zig = generate_orchestrator_lib(opts);
86    fs::write(src_dir.join("lib.zig"), lib_zig).map_err(|e| format!("write lib.zig: {}", e))?;
87
88    // 3.5 src/host.zig — user-defined host function extern "c" declarations.
89    // Written when host_header is non-empty (i.e. the user registered custom host fns).
90    if !opts.host_header.is_empty() {
91        fs::write(src_dir.join("host.zig"), &opts.host_header)
92            .map_err(|e| format!("write host.zig: {}", e))?;
93    }
94
95    // 3.5b src/host_regex.zig — regex host function extern "c" declarations.
96    // Only generated when the transpiled JS code uses RegExp/regex features.
97    if opts.needs_regex {
98        let host_regex_content = r#"// Auto-generated host_regex.zig — regex host function declarations
99// These symbols are defined in Rust with #[no_mangle] pub extern "C".
100pub extern fn host_regex_test(
101    pattern_ptr: [*]const u8, pattern_len: usize,
102    subject_ptr: [*]const u8, subject_len: usize,
103) callconv(.c) bool;
104pub extern fn host_regex_search(
105    pattern_ptr: [*]const u8, pattern_len: usize,
106    subject_ptr: [*]const u8, subject_len: usize,
107) callconv(.c) i64;
108
109// Wrapper functions: the Emitter generates host_regex.regex_test(pattern, subject) (dot
110// notation, 2 args as []const u8 slices), but extern declarations use
111// host_regex_test with ptr+len pairs. These wrappers bridge the gap.
112pub fn regex_test(pattern: []const u8, subject: []const u8) bool {
113    return host_regex_test(pattern.ptr, pattern.len, subject.ptr, subject.len);
114}
115pub fn regex_search(pattern: []const u8, subject: []const u8) i64 {
116    return host_regex_search(pattern.ptr, pattern.len, subject.ptr, subject.len);
117}
118"#;
119        fs::write(src_dir.join("host_regex.zig"), host_regex_content)
120            .map_err(|e| format!("write host_regex.zig: {}", e))?;
121    }
122
123    // 3.6 src/host_regex_stubs.zig — stub host regex C ABI implementations
124    // for zig test (real implementations are in js2rust-bridge, linked by Rust).
125    // Only generated when regex features are used.
126    if opts.needs_regex {
127        let stub_content = generate_host_regex_stubs();
128        fs::write(src_dir.join("host_regex_stubs.zig"), stub_content)
129            .map_err(|e| format!("write host_regex_stubs.zig: {}", e))?;
130    }
131
132    // 3.7 src/host_icu_stubs.zig — stub host ICU C ABI implementations
133    // for zig test (real implementations are in js2rust-bridge, linked by Rust).
134    // Only generated when ICU features are auto-detected in the transpiled code.
135    if opts.needs_icu {
136        let stub_content = generate_host_icu_stubs();
137        fs::write(src_dir.join("host_icu_stubs.zig"), stub_content)
138            .map_err(|e| format!("write host_icu_stubs.zig: {}", e))?;
139    }
140
141    // 4. Copy runtime/ if it exists (always overwrite to pick up runtime changes)
142    if let Some(ref rt_dir) = opts.runtime_dir
143        && rt_dir.exists()
144        && rt_dir.is_dir()
145    {
146        let rt_dst = src_dir.join("js_runtime");
147        // Always re-copy runtime files to pick up changes (e.g. js_console.zig updates)
148        let _ = fs::remove_dir_all(&rt_dst);
149        if let Err(e) = copy_dir_recursive(rt_dir, &rt_dst) {
150            // If copy fails (e.g. concurrent process has the file), check if
151            // another process already completed the copy.
152            if !rt_dst.join("js_runtime.zig").exists() {
153                return Err(format!("copy {}: {}", rt_dst.display(), e));
154            }
155        }
156
157        // 4.1 When needs_icu=true (auto-detected), overwrite js_string_icu.zig with the
158        // ICU4X-based version (extern fn declarations + host function calls).
159        // The simplified version (copied from runtime/) is used when needs_icu=false.
160        // The Cargo.toml `icu` feature on js2rust-bridge ensures the Rust-side
161        // host_icu_* C ABI symbols are available for linking.
162        if opts.needs_icu {
163            let icu_runtime = generate_js_string_icu_icu();
164            fs::write(rt_dst.join("js_string_icu.zig"), icu_runtime)
165                .map_err(|e| format!("write js_string_icu.zig: {}", e))?;
166        }
167    }
168
169    // 5. Auto-compute fingerprint via zig build
170    if let Some(fp) = compute_fingerprint(&project_dir) {
171        let zon_with_fp = generate_zon(&opts.name, Some(&fp));
172        fs::write(&zon_path, zon_with_fp)
173            .map_err(|e| format!("write build.zig.zon (with fingerprint): {}", e))?;
174    }
175
176    Ok(())
177}
178
179/// Run `zig build` in the project directory to get the suggested fingerprint.
180fn compute_fingerprint(project_dir: &Path) -> Option<String> {
181    let output = Command::new("zig")
182        .arg("build")
183        .current_dir(project_dir)
184        .output()
185        .ok()?;
186
187    let stderr = String::from_utf8_lossy(&output.stderr);
188    // Parse: "suggested value: 0x8f0f7e479be9961b"
189    let prefix = "suggested value: ";
190    if let Some(pos) = stderr.find(prefix) {
191        let after = &stderr[pos + prefix.len()..];
192        let fp = after.split_whitespace().next()?;
193        // Validate it looks like 0xHEX (length varies: 16–18 chars)
194        if fp.starts_with("0x") && fp.len() >= 16 && fp[2..].chars().all(|c| c.is_ascii_hexdigit())
195        {
196            return Some(fp.to_string());
197        }
198    }
199    None
200}
201
202fn generate_zon(name: &str, fingerprint: Option<&str>) -> String {
203    let fp_line = match fingerprint {
204        Some(fp) => format!("    .fingerprint = {},\n", fp),
205        None => String::new(),
206    };
207    format!(
208        r#".{{
209    .name = .{name},
210{fp_line}    .version = "0.1.0",
211    .minimum_zig_version = "0.16.0",
212    .paths = .{{"src", "build.zig", "build.zig.zon"}},
213    .dependencies = .{{}},
214}}
215"#,
216        name = name,
217        fp_line = fp_line
218    )
219}
220
221/// Generate `host_regex_stubs.zig` — stub implementations of the host C ABI
222/// regex functions so that `zig build test` can link a standalone test binary.
223/// The real implementations live in `js2rust-bridge` (native_regex.rs) and are
224/// linked when Rust drives the final executable build.
225pub fn generate_host_regex_stubs() -> String {
226    r#"//! Stub implementations of host C ABI regex functions for zig test.
227//! These provide linkable symbols so that zig test can produce a standalone
228//! test binary without the Rust-side implementations.  The real implementations
229//! live in js2rust-bridge (native_regex.rs) and are linked when Rust drives
230//! the final executable build.  These stubs are only used by `zig build test`.
231
232const JsStr = extern struct { ptr: [*]const u8, len: isize };
233
234export fn host_regex_test(
235    pattern_ptr: [*]const u8,
236    pattern_len: usize,
237    text_ptr: [*]const u8,
238    text_len: usize,
239) callconv(.c) bool {
240    _ = pattern_ptr;
241    _ = pattern_len;
242    _ = text_ptr;
243    _ = text_len;
244    return false;
245}
246
247export fn host_regex_search(
248    pattern_ptr: [*]const u8,
249    pattern_len: usize,
250    text_ptr: [*]const u8,
251    text_len: usize,
252) callconv(.c) i64 {
253    _ = pattern_ptr;
254    _ = pattern_len;
255    _ = text_ptr;
256    _ = text_len;
257    return -1;
258}
259
260export fn host_regex_match(
261    pattern_ptr: [*]const u8,
262    pattern_len: usize,
263    text_ptr: [*]const u8,
264    text_len: usize,
265    out_count: *usize,
266) callconv(.c) JsStr {
267    _ = pattern_ptr;
268    _ = pattern_len;
269    _ = text_ptr;
270    _ = text_len;
271    out_count.* = 0;
272    return .{ .ptr = undefined, .len = 0 };
273}
274
275export fn host_regex_match_global(
276    pattern_ptr: [*]const u8,
277    pattern_len: usize,
278    text_ptr: [*]const u8,
279    text_len: usize,
280    out_count: *usize,
281) callconv(.c) JsStr {
282    _ = pattern_ptr;
283    _ = pattern_len;
284    _ = text_ptr;
285    _ = text_len;
286    out_count.* = 0;
287    return .{ .ptr = undefined, .len = 0 };
288}
289
290export fn host_regex_match_all(
291    pattern_ptr: [*]const u8,
292    pattern_len: usize,
293    text_ptr: [*]const u8,
294    text_len: usize,
295    out_match_count: *usize,
296    out_group_count: *usize,
297) callconv(.c) JsStr {
298    _ = pattern_ptr;
299    _ = pattern_len;
300    _ = text_ptr;
301    _ = text_len;
302    out_match_count.* = 0;
303    out_group_count.* = 0;
304    return .{ .ptr = undefined, .len = 0 };
305}
306"#
307    .to_string()
308}
309
310pub fn generate_build_zig(lib_name: &str, needs_regex: bool, needs_icu: bool) -> String {
311    let regex_stub_section = if needs_regex {
312        r#"
313    // Stub library: provides host_regex_* C ABI symbols for zig test.
314    // When Rust drives the final executable build it links its own real
315    // implementations (js2rust-bridge native_regex.rs).  The stubs only
316    // exist so `zig build test` can produce a standalone test binary.
317    const stub_mod = b.createModule(.{
318        .root_source_file = b.path("src/host_regex_stubs.zig"),
319        .target = target,
320        .optimize = optimize,
321        .link_libc = true,
322    });
323    const stub_lib = b.addLibrary(.{
324        .name = "host_regex_stubs",
325        .linkage = .static,
326        .root_module = stub_mod,
327    });
328"#
329        .to_string()
330    } else {
331        String::new()
332    };
333
334    let icu_stub_section = if needs_icu {
335        r#"
336    // Stub library: provides host_icu_* C ABI symbols for zig test.
337    // When Rust drives the final executable build it links its own real
338    // implementations (js2rust-bridge native_icu.rs).  The stubs only
339    // exist so `zig build test` can produce a standalone test binary.
340    const icu_stub_mod = b.createModule(.{
341        .root_source_file = b.path("src/host_icu_stubs.zig"),
342        .target = target,
343        .optimize = optimize,
344        .link_libc = true,
345    });
346    const icu_stub_lib = b.addLibrary(.{
347        .name = "host_icu_stubs",
348        .linkage = .static,
349        .root_module = icu_stub_mod,
350    });
351"#
352        .to_string()
353    } else {
354        String::new()
355    };
356
357    let test_link_stub = if needs_regex {
358        "    test_mod.linkLibrary(stub_lib);\n"
359    } else {
360        ""
361    };
362
363    let test_link_icu_stub = if needs_icu {
364        "    test_mod.linkLibrary(icu_stub_lib);\n"
365    } else {
366        ""
367    };
368
369    format!(
370        r#"const std = @import("std");
371
372pub fn build(b: *std.Build) void {{
373    const target = b.standardTargetOptions(.{{}});
374    const optimize = b.standardOptimizeOption(.{{}});
375
376    const lib_mod = b.createModule(.{{
377        .root_source_file = b.path("src/lib.zig"),
378        .target = target,
379        .optimize = optimize,
380        .link_libc = true,
381    }});
382
383    // Build as static library.
384    // bundle_compiler_rt = true: includes compiler-rt symbols in the .lib.
385    // MSVC link.exe cannot parse COMDAT sections in compiler_rt.obj (LNK1143),
386    // so users MUST use rust-lld as the linker:
387    //   .cargo/config.toml: [target.x86_64-pc-windows-msvc] linker = "rust-lld.exe"
388    const lib = b.addLibrary(.{{
389        .name = "{name}",
390        .linkage = .static,
391        .root_module = lib_mod,
392    }});
393    lib.bundle_compiler_rt = true;
394    b.installArtifact(lib);
395{regex_stub_section}{icu_stub_section}
396    // Test step
397    // Create a test-only module that links the stub libraries, so the stub
398    // symbols (host_regex_*, host_icu_*) are available during `zig build test` but
399    // do NOT pollute the main library artifact linked by Rust.
400    const test_mod = b.createModule(.{{
401        .root_source_file = b.path("src/lib.zig"),
402        .target = target,
403        .optimize = optimize,
404        .link_libc = true,
405    }});
406{test_link_stub}{test_link_icu_stub}    const tests = b.addTest(.{{
407        .root_module = test_mod,
408    }});
409    const run_tests = b.addRunArtifact(tests);
410    const test_step = b.step("test", "Run all library tests");
411    test_step.dependOn(&run_tests.step);
412
413    // WASM target step: `zig build wasm` produces a .wasm module
414    const wasm_mod = b.createModule(.{{
415        .root_source_file = b.path("src/lib.zig"),
416        .target = b.resolveTargetQuery(.{{
417            .cpu_arch = .wasm32,
418            .os_tag = .wasi,
419        }}),
420        .optimize = optimize,
421    }});
422    const wasm_lib = b.addExecutable(.{{
423        .name = "{name}",
424        .root_module = wasm_mod,
425    }});
426    wasm_lib.entry = .disabled;
427    const wasm_install = b.addInstallArtifact(wasm_lib, .{{}});
428    const wasm_step = b.step("wasm", "Build WASM target (wasm32-wasi)");
429    wasm_step.dependOn(&wasm_install.step);
430}}
431"#,
432        name = lib_name
433    )
434}
435
436/// Emit the standard runtime @import preamble (std, allocator, tier-3 runtime libs).
437fn push_runtime_imports(out: &mut String, needs_regex: bool) {
438    out.push_str("const std = @import(\"std\");\n");
439    out.push_str("const builtin = @import(\"builtin\");\n");
440    out.push_str("const Io = std.Io;\n");
441    out.push_str("const Allocator = std.mem.Allocator;\n");
442    out.push('\n');
443    out.push_str("// Global allocator for generated code\n");
444    out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
445    out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n");
446    out.push('\n');
447    out.push_str("// Tier-3 runtime library imports\n");
448    out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
449    out.push_str("const js_string_icu = @import(\"js_runtime/js_string_icu.zig\");\n");
450    out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
451    out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
452    out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
453    out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
454    out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
455    out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
456    out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
457    out.push_str("const js_collections = @import(\"js_runtime/js_collections.zig\");\n");
458    if needs_regex {
459        out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
460        out.push_str("const js_string_regex = @import(\"js_runtime/js_string_regex.zig\");\n");
461    }
462    out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
463    out.push_str("const js_symbol = @import(\"js_runtime/js_symbol.zig\");\n");
464    out.push_str("const JsSymbol = @import(\"js_runtime/js_symbol.zig\").JsSymbol;\n");
465    out.push_str("const js_bigint = @import(\"js_runtime/js_bigint.zig\");\n");
466    out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
467    out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
468    out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
469    out.push('\n');
470}
471
472/// Generate a per-file Zig module with dependency imports and full runtime imports.
473///
474/// Produces:
475///   // Auto-generated from {mod_name}.js
476///   const std = ...
477///   const js_allocator = ...
478///   // --- Dependency module imports ---
479///   const math = @import("math.zig");
480///   const string_utils = @import("string_utils.zig");
481///   // --- Imported name aliases ---
482///   const add = math.add;
483///   ...
484///   // Generated code
485///   export fn add(...) ...
486fn generate_module_zig(
487    module: &PerFileModule,
488    async_host_fn_names: &[String],
489    needs_regex: bool,
490) -> String {
491    let mut out = String::new();
492    out.push_str(&format!("// Auto-generated from {}.js\n", module.mod_name));
493    push_runtime_imports(&mut out, needs_regex);
494
495    // Host function imports (if this module calls host functions or async fns exist)
496    let needs_host = module.zig_code.contains("host.") || !async_host_fn_names.is_empty();
497    let needs_host_regex = needs_regex && module.zig_code.contains("host_regex.");
498    if needs_host || needs_host_regex {
499        out.push_str("// Host functions (Rust via C ABI)\n");
500        if needs_host {
501            out.push_str("const host = @import(\"host.zig\");\n");
502        }
503        if needs_host_regex {
504            out.push_str("const host_regex = @import(\"host_regex.zig\");\n");
505        }
506        // Async function aliases: lets generated code call host.{name}_async as {name}
507        for name in async_host_fn_names {
508            out.push_str(&format!("const {} = host.{}_async;\n", name, name));
509        }
510        out.push('\n');
511    }
512
513    // Deduplicate dependency modules
514    let mut dep_modules: Vec<String> = Vec::new();
515    let mut seen_modules: HashSet<&str> = HashSet::new();
516    for (_, src_mod) in &module.dep_imports {
517        if seen_modules.insert(src_mod) {
518            dep_modules.push(src_mod.clone());
519        }
520    }
521
522    if !dep_modules.is_empty() {
523        out.push_str("// --- Dependency module imports ---\n");
524        for mod_name in &dep_modules {
525            out.push_str(&format!(
526                "const {} = @import(\"{}.zig\");\n",
527                mod_name, mod_name
528            ));
529        }
530        out.push('\n');
531
532        out.push_str("// --- Imported name aliases ---\n");
533        for (name, src_mod) in &module.dep_imports {
534            out.push_str(&format!("const {name} = {mod}.{name};\n", name = name, mod = src_mod));
535        }
536        out.push('\n');
537    }
538
539    // NOTE: No Windows LdrRegisterDllNotification stub here — it's in the orchestrator lib.zig.
540    // Per-file modules are only compiled as part of the orchestrator, so the stub is inherited.
541
542    out.push_str(&module.zig_code);
543    out
544}
545
546/// Generate the orchestrator lib.zig for multi-file mode.
547/// Imports all per-file modules, re-exports ALL public exports from all modules,
548/// includes test blocks.
549fn generate_orchestrator_lib(opts: &ProjectOptions) -> String {
550    let mut out = String::new();
551    out.push_str("// Auto-generated by js2rust (orchestrator)\n");
552    push_runtime_imports(&mut out, opts.needs_regex);
553
554    // Host function declarations
555    if !opts.host_header.is_empty() || !opts.async_host_fn_names.is_empty() {
556        out.push_str("// User-defined host functions (Rust via C ABI)\n");
557        out.push_str("const host = @import(\"host.zig\");\n");
558        out.push('\n');
559    }
560    if opts.needs_regex {
561        out.push_str("// Host regex functions (Rust via C ABI)\n");
562        out.push_str("const host_regex = @import(\"host_regex.zig\");\n");
563        out.push('\n');
564    }
565
566    // Windows stub (needed for Zig std.debug on Windows)
567    // Uses platform-independent types so it compiles on all targets (native, WASM).
568    // Always included because Zig's standard library references this symbol and
569    // Windows COFF doesn't support weak linkage across object files.
570    out.push_str("// Windows stub for Zig std.debug.SelfInfo.Windows\n");
571    out.push_str("// Uses raw types (u32/i32) to avoid importing std.os.windows on non-Windows.\n");
572    out.push_str("pub export fn LdrRegisterDllNotification(\n");
573    out.push_str("    Flags: u32,\n");
574    out.push_str("    NotificationFunction: ?*const anyopaque,\n");
575    out.push_str("    Context: ?*anyopaque,\n");
576    out.push_str("    Cookie: *?*anyopaque,\n");
577    out.push_str(") callconv(.c) i32 {\n");
578    out.push_str("    _ = Flags;\n");
579    out.push_str("    _ = NotificationFunction;\n");
580    out.push_str("    _ = Context;\n");
581    out.push_str("    Cookie.* = @ptrFromInt(1);\n");
582    out.push_str("    return 0; // STATUS_SUCCESS\n");
583    out.push_str("}\n\n");
584
585    // Async host function aliases (if any) — lets orchestrator call async wrappers
586    if !opts.async_host_fn_names.is_empty() {
587        out.push_str("// Async host function aliases\n");
588        for name in &opts.async_host_fn_names {
589            out.push_str(&format!("const {} = host.{}_async;\n", name, name));
590        }
591        out.push('\n');
592    }
593
594    // Per-file module imports (prefixed with _ to avoid duplicate name errors
595    // when re-exporting pub const {name} = _{name}.{name}).
596    out.push_str("// Per-file module imports\n");
597    for module in &opts.per_file_code {
598        out.push_str(&format!(
599            "const _{} = @import(\"{}.zig\");\n",
600            module.mod_name, module.mod_name
601        ));
602    }
603    out.push('\n');
604
605    // --- Global initialization / deinitialization ---
606    out.push_str("/// Initialize the global allocator used by all generated functions.\n");
607    out.push_str("/// The allocator is created internally using ArenaAllocator (Zig 0.16.0: lock-free, thread-safe).\n");
608    out.push_str("pub fn init_js2rust() !void {\n");
609    out.push_str("    try js_allocator.init(null, null);\n");
610    out.push_str("    js_runtime.initIo(js_allocator.allocator());\n");
611    // Also call init_js2rust on each per-file module that defines its own
612    for module in &opts.per_file_code {
613        if module.zig_code.contains("pub fn init_js2rust") {
614            out.push_str(&format!("    try _{}.init_js2rust();\n", module.mod_name));
615        }
616    }
617    out.push_str("}\n\n");
618    // C ABI compatible init/deinit (callable from Rust via FFI)
619    out.push_str("/// Initialize with ArenaAllocator (lock-free, thread-safe).\n");
620    out.push_str("/// Call this from Rust via C ABI before using any function that allocates.\n");
621    out.push_str("pub export fn js2rust_init() void {\n");
622    out.push_str("    init_js2rust() catch @panic(\"init_js2rust failed\");\n");
623    out.push_str("}\n\n");
624    out.push_str("/// Release global resources. Call this when done.\n");
625    out.push_str("pub export fn js2rust_deinit() void {\n");
626    out.push_str("    deinit_js2rust();\n");
627    out.push_str("}\n\n");
628    out.push_str(
629        "/// Allocate memory in Zig's Arena for zero-copy string returns from Rust host functions.\n",
630    );
631    out.push_str(
632        "/// Called from Rust via extern \"C\" { fn js_allocator_alloc(size: usize) -> ?*mut u8; }\n",
633    );
634    out.push_str("/// Memory is managed by the multi-arena allocator — no free needed.\n");
635    out.push_str("/// Returns null on OOM instead of panicking.\n");
636    out.push_str("pub export fn js_allocator_alloc(size: usize) ?[*]u8 {\n");
637    out.push_str("    const buf = js_allocator.allocBytes(size) catch return null;\n");
638    out.push_str("    return buf.ptr;\n");
639    out.push_str("}\n\n");
640    out.push_str("/// Allocate + copy in Zig Arena — single call for zero-copy string returns.\n");
641    out.push_str(
642        "/// Called from Rust via extern \"C\" { fn js_allocator_dupe(src: *const u8, len: usize) -> ?*mut u8; }\n",
643    );
644    out.push_str("/// Prefer this over js_allocator_alloc + manual copy — avoids a separate memcpy in Rust.\n");
645    out.push_str("/// Returns null on OOM instead of panicking.\n");
646    out.push_str("pub export fn js_allocator_dupe(src: [*]const u8, len: usize) ?[*]u8 {\n");
647    out.push_str("    const buf = js_allocator.dupeBytes(src[0..len]) catch return null;\n");
648    out.push_str("    return buf.ptr;\n");
649    out.push_str("}\n\n");
650    out.push_str("/// Release global resources allocated via init_js2rust.\n");
651    out.push_str("pub fn deinit_js2rust() void {\n");
652    out.push_str("    js_runtime.deinitIo();\n");
653    for module in &opts.per_file_code {
654        if module.zig_code.contains("pub fn deinit_js2rust") {
655            out.push_str(&format!("    _{}.deinit_js2rust();\n", module.mod_name));
656        }
657    }
658    out.push_str("    js_allocator.deinit();\n");
659    out.push_str("}\n\n");
660
661    // Build a set of functions that return C ABI strings ([*:0]const u8),
662    // so we can emit adapter wrappers instead of bare `pub const X = mod.X;`.
663    let cabi_string_fns = collect_cabi_string_fns(&opts.per_file_code);
664
665    // Re-export ALL public exports from ALL modules so tests can reference them
666    if !opts.external_exports.is_empty() {
667        out.push_str("// Re-export all public exports from per-file modules\n");
668        let mut exported: HashSet<&str> = HashSet::new();
669
670        for (cabi_name, mod_name, bare_name) in &opts.external_exports {
671            if !exported.insert(cabi_name.as_str()) {
672                continue;
673            }
674            // Skip names that already have C ABI pub export fn wrappers
675            // (they'd cause duplicate struct member errors in Zig).
676            if opts.cabi_names.contains(cabi_name.as_str()) {
677                continue;
678            }
679            if cabi_string_fns.contains(bare_name.as_str()) {
680                // C ABI string-returning function: generate adapter
681                // The public name is cabi_name (possibly disambiguated),
682                // but the internal call uses bare_name (original fn name in module).
683                out.push_str(&format!(
684                    "pub fn {cabi}(s: []const u8) []const u8 {{\n    return std.mem.sliceTo(_{mod}.{bare}(@ptrCast(s.ptr)), 0);\n}}\n",
685                    cabi = cabi_name,
686                    mod = mod_name,
687                    bare = bare_name,
688                ));
689            } else {
690                out.push_str(&format!(
691                    "pub const {cabi} = _{mod}.{bare};\n",
692                    cabi = cabi_name,
693                    mod = mod_name,
694                    bare = bare_name,
695                ));
696            }
697        }
698        out.push('\n');
699    }
700
701    // C ABI exports: pub export fn wrappers in root lib.zig calling per-file modules.
702    // Zig only propagates root-module pub export into the final .lib binary.
703    if !opts.cabi_wrapper_code.is_empty() {
704        out.push_str("// C ABI exports (pub export fn wrappers)\n");
705        out.push_str(&opts.cabi_wrapper_code);
706        out.push('\n');
707    }
708
709    // Append test blocks
710    if !opts.test_code.trim().is_empty() {
711        out.push_str(&opts.test_code);
712        out.push('\n');
713    }
714
715    out
716}
717
718/// Scan per-file modules' zig_code for functions that return C ABI strings
719/// (signatures containing `[*:0]const u8`)
720fn collect_cabi_string_fns(per_file_code: &[PerFileModule]) -> HashSet<String> {
721    let mut fns = HashSet::new();
722    for module in per_file_code {
723        for line in module.zig_code.lines() {
724            let trimmed = line.trim();
725            // Match: pub export fn greet(name: ...) StrRet {
726            if (trimmed.starts_with("pub export fn ") || trimmed.starts_with("pub fn "))
727                && trimmed.contains("StrRet")
728                && let Some(open_paren) = trimmed.find('(')
729            {
730                // Extract function name between `fn ` and `(`
731                let prefix_end = if trimmed.starts_with("pub export fn ") {
732                    "pub export fn ".len()
733                } else {
734                    "pub fn ".len()
735                };
736                let name = trimmed[prefix_end..open_paren].trim();
737                fns.insert(name.to_string());
738            }
739        }
740    }
741    fns
742}
743
744/// Recursively copy a directory
745fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
746    fs::create_dir_all(dst).map_err(|e| format!("create dir {}: {}", dst.display(), e))?;
747
748    for entry in fs::read_dir(src).map_err(|e| format!("read dir {}: {}", src.display(), e))? {
749        let entry = entry.map_err(|e| format!("read entry: {}", e))?;
750        let src_path = entry.path();
751        let dst_path = dst.join(entry.file_name());
752
753        if src_path.is_dir() {
754            copy_dir_recursive(&src_path, &dst_path)?;
755        } else if src_path.is_file() {
756            fs::copy(&src_path, &dst_path)
757                .map_err(|e| format!("copy {}: {}", src_path.display(), e))?;
758        }
759    }
760
761    Ok(())
762}
763
764/// Generate `host_icu_stubs.zig` — stub implementations of the host C ABI
765/// ICU functions so that `zig build test` can link a standalone test binary.
766/// The real implementations live in `js2rust-bridge` (native_icu.rs) and are
767/// linked when Rust drives the final executable build.
768pub fn generate_host_icu_stubs() -> String {
769    r#"//! Stub implementations of host C ABI ICU functions for zig test.
770//! These provide linkable symbols so that zig test can produce a standalone
771//! test binary without the Rust-side implementations.  The real implementations
772//! live in js2rust-bridge (native_icu.rs) and are linked when Rust drives
773//! the final executable build.  These stubs are only used by `zig build test`.
774
775const JsStr = extern struct { ptr: [*]const u8, len: isize };
776
777export fn host_icu_locale_compare(
778    a_ptr: [*]const u8,
779    a_len: usize,
780    b_ptr: [*]const u8,
781    b_len: usize,
782) callconv(.c) i64 {
783    _ = a_ptr;
784    _ = a_len;
785    _ = b_ptr;
786    _ = b_len;
787    return 0;
788}
789
790export fn host_icu_normalize(
791    input_ptr: [*]const u8,
792    input_len: usize,
793    form_ptr: [*]const u8,
794    form_len: usize,
795) callconv(.c) JsStr {
796    _ = input_ptr;
797    _ = input_len;
798    _ = form_ptr;
799    _ = form_len;
800    return .{ .ptr = undefined, .len = 0 };
801}
802
803export fn host_icu_to_locale_upper_case(
804    input_ptr: [*]const u8,
805    input_len: usize,
806) callconv(.c) JsStr {
807    _ = input_ptr;
808    _ = input_len;
809    return .{ .ptr = undefined, .len = 0 };
810}
811
812export fn host_icu_to_locale_lower_case(
813    input_ptr: [*]const u8,
814    input_len: usize,
815) callconv(.c) JsStr {
816    _ = input_ptr;
817    _ = input_len;
818    return .{ .ptr = undefined, .len = 0 };
819}
820"#
821    .to_string()
822}
823
824/// Generate the ICU4X-based `js_string_icu.zig` that uses host_icu_* C ABI
825/// functions for proper locale-sensitive string operations.
826/// This version overwrites the simplified runtime version when needs_icu=true.
827fn generate_js_string_icu_icu() -> String {
828    r#"//! JS String ICU-dependent method implementations for Zig (ICU4X version).
829//! These functions rely on host_icu_* C ABI symbols provided by
830//! js2rust-bridge (native_icu.rs) at link time.
831//!
832//! This file overwrites the simplified runtime version when needs_icu = true.
833
834const std = @import("std");
835const Allocator = std.mem.Allocator;
836const JsAny = @import("jsany.zig").JsAny;
837
838// ── Host C ABI function declarations ──
839
840extern fn host_icu_locale_compare(
841    a_ptr: [*]const u8,
842    a_len: usize,
843    b_ptr: [*]const u8,
844    b_len: usize,
845) callconv(.c) i64;
846
847extern fn host_icu_normalize(
848    input_ptr: [*]const u8,
849    input_len: usize,
850    form_ptr: [*]const u8,
851    form_len: usize,
852) callconv(.c) extern struct { ptr: [*]const u8, len: isize };
853
854extern fn host_icu_to_locale_upper_case(
855    input_ptr: [*]const u8,
856    input_len: usize,
857) callconv(.c) extern struct { ptr: [*]const u8, len: isize };
858
859extern fn host_icu_to_locale_lower_case(
860    input_ptr: [*]const u8,
861    input_len: usize,
862) callconv(.c) extern struct { ptr: [*]const u8, len: isize };
863
864/// Locale-sensitive string comparison via ICU4X Collator.
865/// Returns -1 if self < other, 0 if equal, 1 if self > other.
866pub fn localeCompare(a: []const u8, b: []const u8) i64 {
867    return host_icu_locale_compare(a.ptr, a.len, b.ptr, b.len);
868}
869
870/// Normalize Unicode string using ICU4X Normalizer.
871/// Supports NFC (default), NFD, NFKC, NFKD normalization forms.
872pub fn normalize(alloc: Allocator, s: []const u8, form: []const u8) ![]const u8 {
873    const result = host_icu_normalize(s.ptr, s.len, form.ptr, form.len);
874    if (result.len == 0) return &[0]u8{};
875    const bytes = result.ptr[0..@intCast(result.len)];
876    return try alloc.dupe(u8, bytes);
877}
878
879/// Convert string to locale-specific uppercase via ICU4X CaseMapper.
880pub fn toLocaleUpper(alloc: Allocator, s: []const u8) ![]const u8 {
881    const result = host_icu_to_locale_upper_case(s.ptr, s.len);
882    if (result.len == 0) return &[0]u8{};
883    const bytes = result.ptr[0..@intCast(result.len)];
884    return try alloc.dupe(u8, bytes);
885}
886
887/// Convert string to locale-specific lowercase via ICU4X CaseMapper.
888pub fn toLocaleLower(alloc: Allocator, s: []const u8) ![]const u8 {
889    const result = host_icu_to_locale_lower_case(s.ptr, s.len);
890    if (result.len == 0) return &[0]u8{};
891    const bytes = result.ptr[0..@intCast(result.len)];
892    return try alloc.dupe(u8, bytes);
893}
894"#
895    .to_string()
896}