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
307export fn host_regex_replace(
308    pattern_ptr: [*]const u8,
309    pattern_len: usize,
310    text_ptr: [*]const u8,
311    text_len: usize,
312    replacement_ptr: [*]const u8,
313    replacement_len: usize,
314) callconv(.c) JsStr {
315    _ = pattern_ptr;
316    _ = pattern_len;
317    _ = text_ptr;
318    _ = text_len;
319    _ = replacement_ptr;
320    _ = replacement_len;
321    return .{ .ptr = undefined, .len = 0 };
322}
323
324export fn host_regex_replace_all(
325    pattern_ptr: [*]const u8,
326    pattern_len: usize,
327    text_ptr: [*]const u8,
328    text_len: usize,
329    replacement_ptr: [*]const u8,
330    replacement_len: usize,
331) callconv(.c) JsStr {
332    _ = pattern_ptr;
333    _ = pattern_len;
334    _ = text_ptr;
335    _ = text_len;
336    _ = replacement_ptr;
337    _ = replacement_len;
338    return .{ .ptr = undefined, .len = 0 };
339}
340"#
341    .to_string()
342}
343
344pub fn generate_build_zig(lib_name: &str, needs_regex: bool, needs_icu: bool) -> String {
345    let regex_stub_section = if needs_regex {
346        r#"
347    // Stub library: provides host_regex_* C ABI symbols for zig test.
348    // When Rust drives the final executable build it links its own real
349    // implementations (js2rust-bridge native_regex.rs).  The stubs only
350    // exist so `zig build test` can produce a standalone test binary.
351    const stub_mod = b.createModule(.{
352        .root_source_file = b.path("src/host_regex_stubs.zig"),
353        .target = target,
354        .optimize = optimize,
355        .link_libc = true,
356    });
357    const stub_lib = b.addLibrary(.{
358        .name = "host_regex_stubs",
359        .linkage = .static,
360        .root_module = stub_mod,
361    });
362"#
363        .to_string()
364    } else {
365        String::new()
366    };
367
368    let icu_stub_section = if needs_icu {
369        r#"
370    // Stub library: provides host_icu_* C ABI symbols for zig test.
371    // When Rust drives the final executable build it links its own real
372    // implementations (js2rust-bridge native_icu.rs).  The stubs only
373    // exist so `zig build test` can produce a standalone test binary.
374    const icu_stub_mod = b.createModule(.{
375        .root_source_file = b.path("src/host_icu_stubs.zig"),
376        .target = target,
377        .optimize = optimize,
378        .link_libc = true,
379    });
380    const icu_stub_lib = b.addLibrary(.{
381        .name = "host_icu_stubs",
382        .linkage = .static,
383        .root_module = icu_stub_mod,
384    });
385"#
386        .to_string()
387    } else {
388        String::new()
389    };
390
391    let test_link_stub = if needs_regex {
392        "    test_mod.linkLibrary(stub_lib);\n"
393    } else {
394        ""
395    };
396
397    let test_link_icu_stub = if needs_icu {
398        "    test_mod.linkLibrary(icu_stub_lib);\n"
399    } else {
400        ""
401    };
402
403    format!(
404        r#"const std = @import("std");
405
406pub fn build(b: *std.Build) void {{
407    const target = b.standardTargetOptions(.{{}});
408    const optimize = b.standardOptimizeOption(.{{}});
409
410    const lib_mod = b.createModule(.{{
411        .root_source_file = b.path("src/lib.zig"),
412        .target = target,
413        .optimize = optimize,
414        .link_libc = true,
415    }});
416
417    // Build as static library.
418    // bundle_compiler_rt = true: includes compiler-rt symbols in the .lib.
419    // MSVC link.exe cannot parse COMDAT sections in compiler_rt.obj (LNK1143),
420    // so users MUST use rust-lld as the linker:
421    //   .cargo/config.toml: [target.x86_64-pc-windows-msvc] linker = "rust-lld.exe"
422    const lib = b.addLibrary(.{{
423        .name = "{name}",
424        .linkage = .static,
425        .root_module = lib_mod,
426    }});
427    lib.bundle_compiler_rt = true;
428    b.installArtifact(lib);
429{regex_stub_section}{icu_stub_section}
430    // Test step
431    // Create a test-only module that links the stub libraries, so the stub
432    // symbols (host_regex_*, host_icu_*) are available during `zig build test` but
433    // do NOT pollute the main library artifact linked by Rust.
434    const test_mod = b.createModule(.{{
435        .root_source_file = b.path("src/lib.zig"),
436        .target = target,
437        .optimize = optimize,
438        .link_libc = true,
439    }});
440{test_link_stub}{test_link_icu_stub}    const tests = b.addTest(.{{
441        .root_module = test_mod,
442    }});
443    const run_tests = b.addRunArtifact(tests);
444    const test_step = b.step("test", "Run all library tests");
445    test_step.dependOn(&run_tests.step);
446}}
447"#,
448        name = lib_name
449    )
450}
451
452/// Emit the standard runtime @import preamble (std, allocator, tier-3 runtime libs).
453fn push_runtime_imports(out: &mut String, needs_regex: bool) {
454    out.push_str("const std = @import(\"std\");\n");
455    out.push_str("const builtin = @import(\"builtin\");\n");
456    out.push_str("const Io = std.Io;\n");
457    out.push_str("const Allocator = std.mem.Allocator;\n");
458    out.push('\n');
459    out.push_str("// Global allocator for generated code\n");
460    out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
461    out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n");
462    out.push('\n');
463    out.push_str("// Tier-3 runtime library imports\n");
464    out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
465    out.push_str("const js_string_icu = @import(\"js_runtime/js_string_icu.zig\");\n");
466    out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
467    out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
468    out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
469    out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
470    out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
471    out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
472    out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
473    out.push_str("const js_collections = @import(\"js_runtime/js_collections.zig\");\n");
474    // Type aliases so class field type annotations (e.g. `m: Map,`) resolve.
475    // NamedStruct("Map")/("Set") emit unqualified names via to_zig_type().
476    out.push_str("const Map = js_collections.JsMap;\n");
477    out.push_str("const Set = js_collections.JsSet;\n");
478    if needs_regex {
479        out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
480        out.push_str("const js_string_regex = @import(\"js_runtime/js_string_regex.zig\");\n");
481    }
482    out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
483    out.push_str("const js_symbol = @import(\"js_runtime/js_symbol.zig\");\n");
484    out.push_str("const JsSymbol = @import(\"js_runtime/js_symbol.zig\").JsSymbol;\n");
485    out.push_str("const js_bigint = @import(\"js_runtime/js_bigint.zig\");\n");
486    out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
487    out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
488    out.push_str("const JsObjectMap = @import(\"js_runtime/jsany.zig\").JsObjectMap;\n");
489    out.push_str("const StringArrayHashMap = @import(\"js_runtime/string_array_hash_map.zig\").StringArrayHashMap;\n");
490    out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
491    out.push('\n');
492}
493
494/// Generate a per-file Zig module with dependency imports and full runtime imports.
495///
496/// Produces:
497///   // Auto-generated from {mod_name}.js
498///   const std = ...
499///   const js_allocator = ...
500///   // --- Dependency module imports ---
501///   const math = @import("math.zig");
502///   const string_utils = @import("string_utils.zig");
503///   // --- Imported name aliases ---
504///   const add = math.add;
505///   ...
506///   // Generated code
507///   export fn add(...) ...
508fn generate_module_zig(
509    module: &PerFileModule,
510    async_host_fn_names: &[String],
511    needs_regex: bool,
512) -> String {
513    let mut out = String::new();
514    out.push_str(&format!("// Auto-generated from {}.js\n", module.mod_name));
515    push_runtime_imports(&mut out, needs_regex);
516
517    // Host function imports (if this module calls host functions or async fns exist)
518    let needs_host = module.zig_code.contains("host.") || !async_host_fn_names.is_empty();
519    let needs_host_regex = needs_regex && module.zig_code.contains("host_regex.");
520    if needs_host || needs_host_regex {
521        out.push_str("// Host functions (Rust via C ABI)\n");
522        if needs_host {
523            out.push_str("const host = @import(\"host.zig\");\n");
524        }
525        if needs_host_regex {
526            out.push_str("const host_regex = @import(\"host_regex.zig\");\n");
527        }
528        // Async function aliases: lets generated code call host.{name}_async as {name}
529        for name in async_host_fn_names {
530            out.push_str(&format!("const {} = host.{}_async;\n", name, name));
531        }
532        out.push('\n');
533    }
534
535    // Deduplicate dependency modules
536    let mut dep_modules: Vec<String> = Vec::new();
537    let mut seen_modules: HashSet<&str> = HashSet::new();
538    for (_, src_mod) in &module.dep_imports {
539        if seen_modules.insert(src_mod) {
540            dep_modules.push(src_mod.clone());
541        }
542    }
543
544    if !dep_modules.is_empty() {
545        out.push_str("// --- Dependency module imports ---\n");
546        for mod_name in &dep_modules {
547            out.push_str(&format!(
548                "const {} = @import(\"{}.zig\");\n",
549                mod_name, mod_name
550            ));
551        }
552        out.push('\n');
553
554        out.push_str("// --- Imported name aliases ---\n");
555        for (name, src_mod) in &module.dep_imports {
556            out.push_str(&format!("const {name} = {mod}.{name};\n", name = name, mod = src_mod));
557        }
558        out.push('\n');
559    }
560
561    // NOTE: No Windows LdrRegisterDllNotification stub here — it's in the orchestrator lib.zig.
562    // Per-file modules are only compiled as part of the orchestrator, so the stub is inherited.
563
564    out.push_str(&module.zig_code);
565    out
566}
567
568/// Generate the orchestrator lib.zig for multi-file mode.
569/// Imports all per-file modules, re-exports ALL public exports from all modules,
570/// includes test blocks.
571fn generate_orchestrator_lib(opts: &ProjectOptions) -> String {
572    let mut out = String::new();
573    out.push_str("// Auto-generated by js2rust (orchestrator)\n");
574    push_runtime_imports(&mut out, opts.needs_regex);
575
576    // Host function declarations
577    if !opts.host_header.is_empty() || !opts.async_host_fn_names.is_empty() {
578        out.push_str("// User-defined host functions (Rust via C ABI)\n");
579        out.push_str("const host = @import(\"host.zig\");\n");
580        out.push('\n');
581    }
582    if opts.needs_regex {
583        out.push_str("// Host regex functions (Rust via C ABI)\n");
584        out.push_str("const host_regex = @import(\"host_regex.zig\");\n");
585        out.push('\n');
586    }
587
588    // Windows stub (needed for Zig std.debug on Windows)
589    // Uses platform-independent types so it compiles on all targets (native, WASM).
590    // Always included because Zig's standard library references this symbol and
591    // Windows COFF doesn't support weak linkage across object files.
592    out.push_str("// Windows stub for Zig std.debug.SelfInfo.Windows\n");
593    out.push_str("// Uses raw types (u32/i32) to avoid importing std.os.windows on non-Windows.\n");
594    out.push_str("pub export fn LdrRegisterDllNotification(\n");
595    out.push_str("    Flags: u32,\n");
596    out.push_str("    NotificationFunction: ?*const anyopaque,\n");
597    out.push_str("    Context: ?*anyopaque,\n");
598    out.push_str("    Cookie: *?*anyopaque,\n");
599    out.push_str(") callconv(.c) i32 {\n");
600    out.push_str("    _ = Flags;\n");
601    out.push_str("    _ = NotificationFunction;\n");
602    out.push_str("    _ = Context;\n");
603    out.push_str("    Cookie.* = @ptrFromInt(1);\n");
604    out.push_str("    return 0; // STATUS_SUCCESS\n");
605    out.push_str("}\n\n");
606
607    // Async host function aliases (if any) — lets orchestrator call async wrappers
608    if !opts.async_host_fn_names.is_empty() {
609        out.push_str("// Async host function aliases\n");
610        for name in &opts.async_host_fn_names {
611            out.push_str(&format!("const {} = host.{}_async;\n", name, name));
612        }
613        out.push('\n');
614    }
615
616    // Per-file module imports (prefixed with _ to avoid duplicate name errors
617    // when re-exporting pub const {name} = _{name}.{name}).
618    out.push_str("// Per-file module imports\n");
619    for module in &opts.per_file_code {
620        out.push_str(&format!(
621            "const _{} = @import(\"{}.zig\");\n",
622            module.mod_name, module.mod_name
623        ));
624    }
625    out.push('\n');
626
627    // --- Global initialization / deinitialization ---
628    out.push_str("/// Initialize the global allocator used by all generated functions.\n");
629    out.push_str("/// The allocator is created internally using ArenaAllocator (Zig 0.16.0: lock-free, thread-safe).\n");
630    out.push_str("pub fn init_js2rust() !void {\n");
631    out.push_str("    try js_allocator.init(null, null);\n");
632    out.push_str("    js_runtime.initIo(js_allocator.allocator());\n");
633    // Also call init_js2rust on each per-file module that defines its own
634    for module in &opts.per_file_code {
635        if module.zig_code.contains("pub fn init_js2rust") {
636            out.push_str(&format!("    try _{}.init_js2rust();\n", module.mod_name));
637        }
638    }
639    out.push_str("}\n\n");
640    // C ABI compatible init/deinit (callable from Rust via FFI)
641    out.push_str("/// Initialize with ArenaAllocator (lock-free, thread-safe).\n");
642    out.push_str("/// Call this from Rust via C ABI before using any function that allocates.\n");
643    out.push_str("pub export fn js2rust_init() void {\n");
644    out.push_str("    init_js2rust() catch @panic(\"init_js2rust failed\");\n");
645    out.push_str("}\n\n");
646    out.push_str("/// Release global resources. Call this when done.\n");
647    out.push_str("pub export fn js2rust_deinit() void {\n");
648    out.push_str("    deinit_js2rust();\n");
649    out.push_str("}\n\n");
650    out.push_str(
651        "/// Allocate memory in Zig's Arena for zero-copy string returns from Rust host functions.\n",
652    );
653    out.push_str(
654        "/// Called from Rust via extern \"C\" { fn js_allocator_alloc(size: usize) -> ?*mut u8; }\n",
655    );
656    out.push_str("/// Memory is managed by the multi-arena allocator — no free needed.\n");
657    out.push_str("/// Returns null on OOM instead of panicking.\n");
658    out.push_str("pub export fn js_allocator_alloc(size: usize) ?[*]u8 {\n");
659    out.push_str("    const buf = js_allocator.allocBytes(size) catch return null;\n");
660    out.push_str("    return buf.ptr;\n");
661    out.push_str("}\n\n");
662    out.push_str("/// Allocate + copy in Zig Arena — single call for zero-copy string returns.\n");
663    out.push_str(
664        "/// Called from Rust via extern \"C\" { fn js_allocator_dupe(src: *const u8, len: usize) -> ?*mut u8; }\n",
665    );
666    out.push_str("/// Prefer this over js_allocator_alloc + manual copy — avoids a separate memcpy in Rust.\n");
667    out.push_str("/// Returns null on OOM instead of panicking.\n");
668    out.push_str("pub export fn js_allocator_dupe(src: [*]const u8, len: usize) ?[*]u8 {\n");
669    out.push_str("    const buf = js_allocator.dupeBytes(src[0..len]) catch return null;\n");
670    out.push_str("    return buf.ptr;\n");
671    out.push_str("}\n\n");
672    out.push_str("/// Release global resources allocated via init_js2rust.\n");
673    out.push_str("pub fn deinit_js2rust() void {\n");
674    out.push_str("    js_runtime.deinitIo();\n");
675    for module in &opts.per_file_code {
676        if module.zig_code.contains("pub fn deinit_js2rust") {
677            out.push_str(&format!("    _{}.deinit_js2rust();\n", module.mod_name));
678        }
679    }
680    out.push_str("    js_allocator.deinit();\n");
681    out.push_str("}\n\n");
682
683    // Build a set of functions that return C ABI strings ([*:0]const u8),
684    // so we can emit adapter wrappers instead of bare `pub const X = mod.X;`.
685    let cabi_string_fns = collect_cabi_string_fns(&opts.per_file_code);
686
687    // Re-export ALL public exports from ALL modules so tests can reference them
688    if !opts.external_exports.is_empty() {
689        out.push_str("// Re-export all public exports from per-file modules\n");
690        let mut exported: HashSet<&str> = HashSet::new();
691
692        for (cabi_name, mod_name, bare_name) in &opts.external_exports {
693            if !exported.insert(cabi_name.as_str()) {
694                continue;
695            }
696            // Skip names that already have C ABI pub export fn wrappers
697            // (they'd cause duplicate struct member errors in Zig).
698            if opts.cabi_names.contains(cabi_name.as_str()) {
699                continue;
700            }
701            if cabi_string_fns.contains(bare_name.as_str()) {
702                // C ABI string-returning function: generate adapter
703                // The public name is cabi_name (possibly disambiguated),
704                // but the internal call uses bare_name (original fn name in module).
705                out.push_str(&format!(
706                    "pub fn {cabi}(s: []const u8) []const u8 {{\n    return std.mem.sliceTo(_{mod}.{bare}(@ptrCast(s.ptr)), 0);\n}}\n",
707                    cabi = cabi_name,
708                    mod = mod_name,
709                    bare = bare_name,
710                ));
711            } else {
712                out.push_str(&format!(
713                    "pub const {cabi} = _{mod}.{bare};\n",
714                    cabi = cabi_name,
715                    mod = mod_name,
716                    bare = bare_name,
717                ));
718            }
719        }
720        out.push('\n');
721    }
722
723    // C ABI exports: pub export fn wrappers in root lib.zig calling per-file modules.
724    // Zig only propagates root-module pub export into the final .lib binary.
725    if !opts.cabi_wrapper_code.is_empty() {
726        out.push_str("// C ABI exports (pub export fn wrappers)\n");
727        out.push_str(&opts.cabi_wrapper_code);
728        out.push('\n');
729    }
730
731    // Append test blocks
732    if !opts.test_code.trim().is_empty() {
733        out.push_str(&opts.test_code);
734        out.push('\n');
735    }
736
737    out
738}
739
740/// Scan per-file modules' zig_code for functions that return C ABI strings
741/// (signatures containing `[*:0]const u8`)
742fn collect_cabi_string_fns(per_file_code: &[PerFileModule]) -> HashSet<String> {
743    let mut fns = HashSet::new();
744    for module in per_file_code {
745        for line in module.zig_code.lines() {
746            let trimmed = line.trim();
747            // Match: pub export fn greet(name: ...) StrRet {
748            if (trimmed.starts_with("pub export fn ") || trimmed.starts_with("pub fn "))
749                && trimmed.contains("StrRet")
750                && let Some(open_paren) = trimmed.find('(')
751            {
752                // Extract function name between `fn ` and `(`
753                let prefix_end = if trimmed.starts_with("pub export fn ") {
754                    "pub export fn ".len()
755                } else {
756                    "pub fn ".len()
757                };
758                let name = trimmed[prefix_end..open_paren].trim();
759                fns.insert(name.to_string());
760            }
761        }
762    }
763    fns
764}
765
766/// Recursively copy a directory
767fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
768    fs::create_dir_all(dst).map_err(|e| format!("create dir {}: {}", dst.display(), e))?;
769
770    for entry in fs::read_dir(src).map_err(|e| format!("read dir {}: {}", src.display(), e))? {
771        let entry = entry.map_err(|e| format!("read entry: {}", e))?;
772        let src_path = entry.path();
773        let dst_path = dst.join(entry.file_name());
774
775        if src_path.is_dir() {
776            copy_dir_recursive(&src_path, &dst_path)?;
777        } else if src_path.is_file() {
778            fs::copy(&src_path, &dst_path)
779                .map_err(|e| format!("copy {}: {}", src_path.display(), e))?;
780        }
781    }
782
783    Ok(())
784}
785
786/// Generate `host_icu_stubs.zig` — stub implementations of the host C ABI
787/// ICU functions so that `zig build test` can link a standalone test binary.
788/// The real implementations live in `js2rust-bridge` (native_icu.rs) and are
789/// linked when Rust drives the final executable build.
790pub fn generate_host_icu_stubs() -> String {
791    r#"//! Stub implementations of host C ABI ICU functions for zig test.
792//! These provide linkable symbols so that zig test can produce a standalone
793//! test binary without the Rust-side implementations.  The real implementations
794//! live in js2rust-bridge (native_icu.rs) and are linked when Rust drives
795//! the final executable build.  These stubs are only used by `zig build test`.
796
797const JsStr = extern struct { ptr: [*]const u8, len: isize };
798
799export fn host_icu_locale_compare(
800    a_ptr: [*]const u8,
801    a_len: usize,
802    b_ptr: [*]const u8,
803    b_len: usize,
804) callconv(.c) i64 {
805    _ = a_ptr;
806    _ = a_len;
807    _ = b_ptr;
808    _ = b_len;
809    return 0;
810}
811
812export fn host_icu_normalize(
813    input_ptr: [*]const u8,
814    input_len: usize,
815    form_ptr: [*]const u8,
816    form_len: usize,
817) callconv(.c) JsStr {
818    _ = input_ptr;
819    _ = input_len;
820    _ = form_ptr;
821    _ = form_len;
822    return .{ .ptr = undefined, .len = 0 };
823}
824
825export fn host_icu_to_locale_upper_case(
826    input_ptr: [*]const u8,
827    input_len: usize,
828) callconv(.c) JsStr {
829    _ = input_ptr;
830    _ = input_len;
831    return .{ .ptr = undefined, .len = 0 };
832}
833
834export fn host_icu_to_locale_lower_case(
835    input_ptr: [*]const u8,
836    input_len: usize,
837) callconv(.c) JsStr {
838    _ = input_ptr;
839    _ = input_len;
840    return .{ .ptr = undefined, .len = 0 };
841}
842"#
843    .to_string()
844}
845
846/// Generate the ICU4X-based `js_string_icu.zig` that uses host_icu_* C ABI
847/// functions for proper locale-sensitive string operations.
848/// This version overwrites the simplified runtime version when needs_icu=true.
849fn generate_js_string_icu_icu() -> String {
850    r#"//! JS String ICU-dependent method implementations for Zig (ICU4X version).
851//! These functions rely on host_icu_* C ABI symbols provided by
852//! js2rust-bridge (native_icu.rs) at link time.
853//!
854//! This file overwrites the simplified runtime version when needs_icu = true.
855
856const std = @import("std");
857const Allocator = std.mem.Allocator;
858const JsAny = @import("jsany.zig").JsAny;
859
860// ── Host C ABI function declarations ──
861
862extern fn host_icu_locale_compare(
863    a_ptr: [*]const u8,
864    a_len: usize,
865    b_ptr: [*]const u8,
866    b_len: usize,
867) callconv(.c) i64;
868
869extern fn host_icu_normalize(
870    input_ptr: [*]const u8,
871    input_len: usize,
872    form_ptr: [*]const u8,
873    form_len: usize,
874) callconv(.c) extern struct { ptr: [*]const u8, len: isize };
875
876extern fn host_icu_to_locale_upper_case(
877    input_ptr: [*]const u8,
878    input_len: usize,
879) callconv(.c) extern struct { ptr: [*]const u8, len: isize };
880
881extern fn host_icu_to_locale_lower_case(
882    input_ptr: [*]const u8,
883    input_len: usize,
884) callconv(.c) extern struct { ptr: [*]const u8, len: isize };
885
886/// Locale-sensitive string comparison via ICU4X Collator.
887/// Returns -1 if self < other, 0 if equal, 1 if self > other.
888pub fn localeCompare(a: []const u8, b: []const u8) i64 {
889    return host_icu_locale_compare(a.ptr, a.len, b.ptr, b.len);
890}
891
892/// Normalize Unicode string using ICU4X Normalizer.
893/// Supports NFC (default), NFD, NFKC, NFKD normalization forms.
894pub fn normalize(alloc: Allocator, s: []const u8, form: []const u8) ![]const u8 {
895    const result = host_icu_normalize(s.ptr, s.len, form.ptr, form.len);
896    if (result.len == 0) return &[0]u8{};
897    const bytes = result.ptr[0..@intCast(result.len)];
898    return try alloc.dupe(u8, bytes);
899}
900
901/// Convert string to locale-specific uppercase via ICU4X CaseMapper.
902pub fn toLocaleUpper(alloc: Allocator, s: []const u8) ![]const u8 {
903    const result = host_icu_to_locale_upper_case(s.ptr, s.len);
904    if (result.len == 0) return &[0]u8{};
905    const bytes = result.ptr[0..@intCast(result.len)];
906    return try alloc.dupe(u8, bytes);
907}
908
909/// Convert string to locale-specific lowercase via ICU4X CaseMapper.
910pub fn toLocaleLower(alloc: Allocator, s: []const u8) ![]const u8 {
911    const result = host_icu_to_locale_lower_case(s.ptr, s.len);
912    if (result.len == 0) return &[0]u8{};
913    const bytes = result.ptr[0..@intCast(result.len)];
914    return try alloc.dupe(u8, bytes);
915}
916"#
917    .to_string()
918}