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