1use std::collections::HashSet;
3use std::fs;
4use std::path::Path;
5use std::process::Command;
6
7#[derive(Debug, Clone)]
9pub struct PerFileModule {
10 pub mod_name: String,
12 pub zig_code: String,
14 pub dep_imports: Vec<(String, String)>,
17}
18
19pub struct ProjectOptions {
21 pub name: String,
23 pub out_dir: String,
25 pub per_file_code: Vec<PerFileModule>,
28 pub external_exports: Vec<(String, String)>,
32 pub cabi_wrapper_code: String,
36 pub cabi_names: std::collections::HashSet<String>,
39 pub test_code: String,
41 pub runtime_dir: Option<String>,
43 pub host_header: String,
45 pub async_host_wrappers: String,
47 pub include_windows_stub: bool,
52}
53
54pub 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 fs::create_dir_all(&src_dir).map_err(|e| format!("create {}: {}", project_dir.display(), e))?;
61
62 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 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 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 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 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 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 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
114fn 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 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 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
212fn 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 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 out.push_str(&module.zig_code);
281 out
282}
283
284fn 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 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 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 if !opts.async_host_wrappers.is_empty() {
343 out.push_str(&opts.async_host_wrappers);
344 out.push('\n');
345 }
346
347 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 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 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 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 let cabi_string_fns = collect_cabi_string_fns(&opts.per_file_code);
393
394 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 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 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 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 if !opts.test_code.trim().is_empty() {
443 out.push_str(&opts.test_code);
444 out.push('\n');
445 }
446
447 out
448}
449
450fn 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 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 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
476fn 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}