Skip to main content

js2zig_core/
project.rs

1/// Generate a complete Zig library project from translated JS code.
2use std::collections::HashSet;
3use std::fs;
4use std::path::Path;
5use std::process::Command;
6
7/// A single per-file Zig module with its dependency info.
8#[derive(Debug, Clone)]
9pub struct PerFileModule {
10    /// Sanitized module name (e.g. "math", "string_utils", "main")
11    pub mod_name: String,
12    /// Translated Zig source code for this file
13    pub zig_code: String,
14    /// Dependency imports: Vec<(imported_name, source_module_name)>
15    /// e.g. [("add", "math"), ("multiply", "math"), ("greet", "string_utils")]
16    pub dep_imports: Vec<(String, String)>,
17}
18
19/// Project generation options
20pub struct ProjectOptions {
21    /// Name of the Zig library (also the output directory name)
22    pub name: String,
23    /// Output directory (e.g. "out")
24    pub out_dir: String,
25    /// Per-file Zig modules. Each entry is written as `{mod_name}.zig`, and lib.zig
26    /// becomes a thin orchestrator that imports all per-file modules.
27    pub per_file_code: Vec<PerFileModule>,
28    /// Export names that should be re-exported from lib.zig.
29    /// Each entry: (export_name, source_module_name).
30    /// In multi-file mode, this should include ALL public exports from ALL modules.
31    pub external_exports: Vec<(String, String)>,
32    /// Pre-generated `pub export fn` wrapper code for C ABI exports.
33    /// Each wrapper calls a per-file module function and lives in the root lib.zig
34    /// so that Zig propagates the symbols into the final .lib.
35    pub cabi_wrapper_code: String,
36    /// Names that have C ABI wrappers — these are skipped in the re-export section
37    /// to avoid duplicate struct member errors.
38    pub cabi_names: std::collections::HashSet<String>,
39    /// Auto-generated test code (from testgen)
40    pub test_code: String,
41    /// Runtime source directory (relative to project root, e.g. "runtime")
42    pub runtime_dir: Option<String>,
43    /// Host function extern "c" declarations (from host::HostFnRegistry)
44    pub host_header: String,
45    /// Async host function wrapper code (generated by host::HostFnRegistry)
46    pub async_host_wrappers: String,
47    /// Whether to include the Windows LdrRegisterDllNotification stub.
48    /// Must be `true` for exactly one group (the first one), because Zig's
49    /// standard library references this symbol and Windows COFF doesn't
50    /// support weak linkage across object files.
51    pub include_windows_stub: bool,
52}
53
54/// Generate the full Zig library project.
55pub fn generate(opts: &ProjectOptions) -> Result<(), String> {
56    let project_dir = Path::new(&opts.out_dir).join(&opts.name);
57    let src_dir = project_dir.join("src");
58
59    // Create directories
60    fs::create_dir_all(&src_dir).map_err(|e| format!("create {}: {}", project_dir.display(), e))?;
61
62    // 1. build.zig.zon - first pass without fingerprint
63    let zon_path = project_dir.join("build.zig.zon");
64    let zon_no_fp = generate_zon(&opts.name, None);
65    fs::write(&zon_path, &zon_no_fp)
66        .map_err(|e| format!("write build.zig.zon: {}", e))?;
67
68    // 2. build.zig
69    let build_zig = generate_build_zig(&opts.name);
70    fs::write(project_dir.join("build.zig"), build_zig)
71        .map_err(|e| format!("write build.zig: {}", e))?;
72
73    // 3. Write per-file .zig files + orchestrator lib.zig
74    for module in &opts.per_file_code {
75        let mod_zig = generate_module_zig(module);
76        let mod_path = src_dir.join(format!("{}.zig", module.mod_name));
77        fs::write(&mod_path, mod_zig)
78            .map_err(|e| format!("write {}.zig: {}", mod_path.display(), e))?;
79    }
80
81    // Generate orchestrator lib.zig
82    let lib_zig = generate_orchestrator_lib(opts);
83    fs::write(src_dir.join("lib.zig"), lib_zig)
84        .map_err(|e| format!("write lib.zig: {}", e))?;
85
86    // 3.5 src/host.zig — host function extern "c" declarations
87    if !opts.host_header.is_empty() {
88        fs::write(src_dir.join("host.zig"), &opts.host_header)
89            .map_err(|e| format!("write host.zig: {}", e))?;
90    }
91
92    // 4. Copy runtime/ if it exists
93    if let Some(ref rt_dir) = opts.runtime_dir {
94        let rt_src = Path::new(rt_dir);
95        if rt_src.exists() && rt_src.is_dir() {
96            let rt_dst = src_dir.join("js_runtime");
97            if rt_dst.exists() {
98                fs::remove_dir_all(&rt_dst).ok();
99            }
100            copy_dir_recursive(rt_src, &rt_dst)?;
101        }
102    }
103
104    // 5. Auto-compute fingerprint via zig build
105    if let Some(fp) = compute_fingerprint(&project_dir) {
106        let zon_with_fp = generate_zon(&opts.name, Some(&fp));
107        fs::write(&zon_path, zon_with_fp)
108            .map_err(|e| format!("write build.zig.zon (with fingerprint): {}", e))?;
109    }
110
111    Ok(())
112}
113
114/// Run `zig build` in the project directory to get the suggested fingerprint.
115fn compute_fingerprint(project_dir: &Path) -> Option<String> {
116    let output = Command::new("zig")
117        .arg("build")
118        .current_dir(project_dir)
119        .output()
120        .ok()?;
121
122    let stderr = String::from_utf8_lossy(&output.stderr);
123    // Parse: "suggested value: 0x8f0f7e479be9961b"
124    let prefix = "suggested value: ";
125    if let Some(pos) = stderr.find(prefix) {
126        let after = &stderr[pos + prefix.len()..];
127        let fp = after.split_whitespace().next()?;
128        // Validate it looks like 0xHEX (length varies: 16–18 chars)
129        if fp.starts_with("0x") && fp.len() >= 16 && fp[2..].chars().all(|c| c.is_ascii_hexdigit()) {
130            return Some(fp.to_string());
131        }
132    }
133    None
134}
135
136fn generate_zon(name: &str, fingerprint: Option<&str>) -> String {
137    let fp_line = match fingerprint {
138        Some(fp) => format!("    .fingerprint = {},\n", fp),
139        None => String::new(),
140    };
141    format!(
142        r#".{{
143    .name = .{name},
144{fp_line}    .version = "0.1.0",
145    .minimum_zig_version = "0.16.0",
146    .paths = .{{"src", "build.zig", "build.zig.zon"}},
147    .dependencies = .{{}},
148}}
149"#,
150        name = name,
151        fp_line = fp_line
152    )
153}
154
155pub fn generate_build_zig(lib_name: &str) -> String {
156    format!(
157        r#"const std = @import("std");
158
159pub fn build(b: *std.Build) void {{
160    const target = b.standardTargetOptions(.{{}});
161    const optimize = b.standardOptimizeOption(.{{}});
162
163    const lib_mod = b.createModule(.{{
164        .root_source_file = b.path("src/lib.zig"),
165        .target = target,
166        .optimize = optimize,
167        .link_libc = true,
168    }});
169
170    // Build as static library with bundled compiler-rt.
171    // Uses rust-lld (LLVM linker) at final link time to handle COMDAT sections
172    // that MSVC link.exe cannot parse from Zig-generated COFF objects.
173    const lib = b.addLibrary(.{{
174        .name = "{name}",
175        .linkage = .static,
176        .root_module = lib_mod,
177    }});
178    lib.bundle_compiler_rt = true;
179    b.installArtifact(lib);
180
181    // Test step
182    const tests = b.addTest(.{{
183        .root_module = lib_mod,
184    }});
185    const run_tests = b.addRunArtifact(tests);
186    const test_step = b.step("test", "Run all library tests");
187    test_step.dependOn(&run_tests.step);
188
189    // WASM target step: `zig build wasm` produces a .wasm module
190    const wasm_mod = b.createModule(.{{
191        .root_source_file = b.path("src/lib.zig"),
192        .target = b.resolveTargetQuery(.{{
193            .cpu_arch = .wasm32,
194            .os_tag = .wasi,
195        }}),
196        .optimize = optimize,
197    }});
198    const wasm_lib = b.addExecutable(.{{
199        .name = "{name}",
200        .root_module = wasm_mod,
201    }});
202    wasm_lib.entry = .disabled;
203    const wasm_install = b.addInstallArtifact(wasm_lib, .{{}});
204    const wasm_step = b.step("wasm", "Build WASM target (wasm32-wasi)");
205    wasm_step.dependOn(&wasm_install.step);
206}}
207"#,
208        name = lib_name
209    )
210}
211
212/// Generate a per-file Zig module with dependency imports and full runtime imports.
213///
214/// Produces:
215///   // Auto-generated from {mod_name}.js
216///   const std = ...
217///   const js_allocator = ...
218///   // --- Dependency module imports ---
219///   const math = @import("math.zig");
220///   const string_utils = @import("string_utils.zig");
221///   // --- Imported name aliases ---
222///   const add = math.add;
223///   ...
224///   // Generated code
225///   export fn add(...) ...
226fn generate_module_zig(module: &PerFileModule) -> String {
227    let mut out = String::new();
228    out.push_str(&format!("// Auto-generated from {}.js\n", module.mod_name));
229    out.push_str("const std = @import(\"std\");\n");
230    out.push_str("const builtin = @import(\"builtin\");\n");
231    out.push_str("const Io = std.Io;\n");
232    out.push_str("const Allocator = std.mem.Allocator;\n");
233    out.push('\n');
234    out.push_str("// Global allocator for generated code\n");
235    out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
236    out.push('\n');
237    out.push_str("// Tier-3 runtime library imports\n");
238    out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
239    out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
240    out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
241    out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
242    out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
243    out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
244    out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
245    out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
246    out.push_str("const js_map = @import(\"js_runtime/js_map.zig\");\n");
247    out.push_str("const js_set = @import(\"js_runtime/js_set.zig\");\n");
248    out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
249    out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
250    out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
251    out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
252    out.push('\n');
253
254    // Deduplicate dependency modules
255    let mut dep_modules: Vec<String> = Vec::new();
256    let mut seen_modules: HashSet<&str> = HashSet::new();
257    for (_, src_mod) in &module.dep_imports {
258        if seen_modules.insert(src_mod) {
259            dep_modules.push(src_mod.clone());
260        }
261    }
262
263    if !dep_modules.is_empty() {
264        out.push_str("// --- Dependency module imports ---\n");
265        for mod_name in &dep_modules {
266            out.push_str(&format!("const {} = @import(\"{}.zig\");\n", mod_name, mod_name));
267        }
268        out.push('\n');
269
270        out.push_str("// --- Imported name aliases ---\n");
271        for (name, src_mod) in &module.dep_imports {
272            out.push_str(&format!("const {name} = {mod}.{name};\n", name = name, mod = src_mod));
273        }
274        out.push('\n');
275    }
276
277    // NOTE: No Windows LdrRegisterDllNotification stub here — it's in the orchestrator lib.zig.
278    // Per-file modules are only compiled as part of the orchestrator, so the stub is inherited.
279
280    out.push_str(&module.zig_code);
281    out
282}
283
284/// Generate the orchestrator lib.zig for multi-file mode.
285/// Imports all per-file modules, re-exports ALL public exports from all modules,
286/// includes test blocks.
287fn generate_orchestrator_lib(opts: &ProjectOptions) -> String {
288    let mut out = String::new();
289    out.push_str("// Auto-generated by js2rust (orchestrator)\n");
290    out.push_str("const std = @import(\"std\");\n");
291    out.push_str("const builtin = @import(\"builtin\");\n");
292    out.push_str("const Io = std.Io;\n");
293    out.push_str("const Allocator = std.mem.Allocator;\n");
294    out.push('\n');
295    out.push_str("// Global allocator for generated code\n");
296    out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
297    out.push('\n');
298    out.push_str("// Tier-3 runtime library imports\n");
299    out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
300    out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
301    out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
302    out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
303    out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
304    out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
305    out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
306    out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
307    out.push_str("const js_map = @import(\"js_runtime/js_map.zig\");\n");
308    out.push_str("const js_set = @import(\"js_runtime/js_set.zig\");\n");
309    out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
310    out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
311    out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
312    out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
313    out.push('\n');
314
315    // Host function declarations (if any)
316    if !opts.host_header.is_empty() {
317        out.push_str("// Tier-4 host functions (Rust via C ABI)\n");
318        out.push_str("const host = @import(\"host.zig\");\n");
319        out.push('\n');
320    }
321
322    // Windows stub (needed for Zig std.debug on Windows; only in one group)
323    // Uses platform-independent types so it compiles on all targets (native, WASM).
324    if opts.include_windows_stub {
325        out.push_str("// Windows stub for Zig std.debug.SelfInfo.Windows\n");
326        out.push_str("// Uses raw types (u32/i32) to avoid importing std.os.windows on non-Windows.\n");
327        out.push_str("pub export fn LdrRegisterDllNotification(\n");
328        out.push_str("    Flags: u32,\n");
329        out.push_str("    NotificationFunction: ?*const anyopaque,\n");
330        out.push_str("    Context: ?*anyopaque,\n");
331        out.push_str("    Cookie: *?*anyopaque,\n");
332        out.push_str(") callconv(.c) i32 {\n");
333        out.push_str("    _ = Flags;\n");
334        out.push_str("    _ = NotificationFunction;\n");
335        out.push_str("    _ = Context;\n");
336        out.push_str("    Cookie.* = @ptrFromInt(1);\n");
337        out.push_str("    return 0; // STATUS_SUCCESS\n");
338        out.push_str("}\n\n");
339    }
340
341    // Async host function wrappers (if any)
342    if !opts.async_host_wrappers.is_empty() {
343        out.push_str(&opts.async_host_wrappers);
344        out.push('\n');
345    }
346
347    // Per-file module imports
348    out.push_str("// Per-file module imports\n");
349    for module in &opts.per_file_code {
350        out.push_str(&format!(
351            "const {} = @import(\"{}.zig\");\n",
352            module.mod_name, module.mod_name
353        ));
354    }
355    out.push('\n');
356
357    // --- Global initialization / deinitialization ---
358    out.push_str("/// Initialize the global allocator used by all generated functions.\n");
359    out.push_str("pub fn init_js2rust(allocator: std.mem.Allocator) void {\n");
360    out.push_str("    js_allocator.setGlobalAllocator(allocator);\n");
361    // Also call init_js2rust on each per-file module that defines its own
362    for module in &opts.per_file_code {
363        if module.zig_code.contains("pub fn init_js2rust") {
364            out.push_str(&format!("    {}.init_js2rust(allocator);\n", module.mod_name));
365        }
366    }
367    out.push_str("}\n\n");
368    // C ABI compatible init/deinit (callable from Rust via FFI)
369    // Only generate in one group to avoid duplicate symbols when linking multiple groups.
370    if opts.include_windows_stub {
371        out.push_str("/// Initialize with a default allocator (page_allocator).\n");
372        out.push_str("/// Call this from Rust via C ABI before using any function that allocates.\n");
373        out.push_str("pub export fn js2rust_init() void {\n");
374        out.push_str("    init_js2rust(std.heap.page_allocator);\n");
375        out.push_str("}\n\n");
376        out.push_str("/// Release global resources. Call this when done.\n");
377        out.push_str("pub export fn js2rust_deinit() void {\n");
378        out.push_str("    deinit_js2rust();\n");
379        out.push_str("}\n\n");
380    }
381    out.push_str("/// Release global resources allocated via init_js2rust.\n");
382    out.push_str("pub fn deinit_js2rust() void {\n");
383    for module in &opts.per_file_code {
384        if module.zig_code.contains("pub fn deinit_js2rust") {
385            out.push_str(&format!("    {}.deinit_js2rust();\n", module.mod_name));
386        }
387    }
388    out.push_str("}\n\n");
389
390    // Build a set of functions that return C ABI strings ([*:0]const u8),
391    // so we can emit adapter wrappers instead of bare `pub const X = mod.X;`.
392    let cabi_string_fns = collect_cabi_string_fns(&opts.per_file_code);
393
394    // Re-export ALL public exports from ALL modules so tests can reference them
395    if !opts.external_exports.is_empty() {
396        out.push_str("// Re-export all public exports from per-file modules\n");
397        let mut exported: HashSet<&str> = HashSet::new();
398
399        for (exp_name, mod_name) in &opts.external_exports {
400            if !exported.insert(exp_name) {
401                continue;
402            }
403            // Skip names that already have C ABI pub export fn wrappers
404            // (they'd cause duplicate struct member errors in Zig).
405            // Also skip free_xxx variants of C ABI names.
406            if opts.cabi_names.contains(exp_name.as_str())
407                || (exp_name.starts_with("free_")
408                    && opts.cabi_names.contains(&exp_name[5..]))
409            {
410                continue;
411            }
412            if cabi_string_fns.contains(exp_name.as_str()) {
413                // C ABI string-returning function: generate adapter
414                // pub fn greet(s: []const u8) []const u8 {
415                //     return std.mem.sliceTo(mod.greet(@ptrCast(s.ptr)), 0);
416                // }
417                out.push_str(&format!(
418                    "pub fn {name}(s: []const u8) []const u8 {{\n    return std.mem.sliceTo({mod}.{name}(@ptrCast(s.ptr)), 0);\n}}\n",
419                    name = exp_name,
420                    mod = mod_name
421                ));
422            } else {
423                out.push_str(&format!(
424                    "pub const {exp} = {mod}.{exp};\n",
425                    exp = exp_name,
426                    mod = mod_name
427                ));
428            }
429        }
430        out.push('\n');
431    }
432
433    // C ABI exports: pub export fn wrappers in root lib.zig calling per-file modules.
434    // Zig only propagates root-module pub export into the final .lib binary.
435    if !opts.cabi_wrapper_code.is_empty() {
436        out.push_str("// C ABI exports (pub export fn wrappers)\n");
437        out.push_str(&opts.cabi_wrapper_code);
438        out.push('\n');
439    }
440
441    // Append test blocks
442    if !opts.test_code.trim().is_empty() {
443        out.push_str(&opts.test_code);
444        out.push('\n');
445    }
446
447    out
448}
449
450/// Scan per-file modules' zig_code for functions that return C ABI strings
451/// (signatures containing `[*:0]const u8`)
452fn collect_cabi_string_fns(per_file_code: &[PerFileModule]) -> HashSet<String> {
453    let mut fns = HashSet::new();
454    for module in per_file_code {
455        for line in module.zig_code.lines() {
456            let trimmed = line.trim();
457            // Match: pub export fn greet(name: ...) callconv(.c) [*:0]const u8 {
458            if (trimmed.starts_with("pub export fn ") || trimmed.starts_with("pub fn "))
459                && trimmed.contains("[*:0]const u8")
460                && let Some(open_paren) = trimmed.find('(')
461            {
462                // Extract function name between `fn ` and `(`
463                let prefix_end = if trimmed.starts_with("pub export fn ") {
464                    "pub export fn ".len()
465                } else {
466                    "pub fn ".len()
467                };
468                let name = trimmed[prefix_end..open_paren].trim();
469                fns.insert(name.to_string());
470            }
471        }
472    }
473    fns
474}
475
476/// Recursively copy a directory
477fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
478    fs::create_dir_all(dst).map_err(|e| format!("create dir {}: {}", dst.display(), e))?;
479
480    for entry in fs::read_dir(src).map_err(|e| format!("read dir {}: {}", src.display(), e))? {
481        let entry = entry.map_err(|e| format!("read entry: {}", e))?;
482        let src_path = entry.path();
483        let dst_path = dst.join(entry.file_name());
484
485        if src_path.is_dir() {
486            copy_dir_recursive(&src_path, &dst_path)?;
487        } else if src_path.is_file() {
488            fs::copy(&src_path, &dst_path)
489                .map_err(|e| format!("copy {}: {}", src_path.display(), e))?;
490        }
491    }
492
493    Ok(())
494}