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_fn_names: Vec<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, &opts.async_host_fn_names);
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, async_host_fn_names: &[String]) -> 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_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
253 out.push('\n');
254
255 if module.zig_code.contains("host.") || !async_host_fn_names.is_empty() {
257 out.push_str("// Host functions (Rust via C ABI)\n");
258 out.push_str("const host = @import(\"host.zig\");\n");
259 for name in async_host_fn_names {
261 out.push_str(&format!("const {} = host.{}_async;\n", name, name));
262 }
263 out.push('\n');
264 }
265
266 let mut dep_modules: Vec<String> = Vec::new();
268 let mut seen_modules: HashSet<&str> = HashSet::new();
269 for (_, src_mod) in &module.dep_imports {
270 if seen_modules.insert(src_mod) {
271 dep_modules.push(src_mod.clone());
272 }
273 }
274
275 if !dep_modules.is_empty() {
276 out.push_str("// --- Dependency module imports ---\n");
277 for mod_name in &dep_modules {
278 out.push_str(&format!("const {} = @import(\"{}.zig\");\n", mod_name, mod_name));
279 }
280 out.push('\n');
281
282 out.push_str("// --- Imported name aliases ---\n");
283 for (name, src_mod) in &module.dep_imports {
284 out.push_str(&format!("const {name} = {mod}.{name};\n", name = name, mod = src_mod));
285 }
286 out.push('\n');
287 }
288
289 out.push_str(&module.zig_code);
293 out
294}
295
296fn generate_orchestrator_lib(opts: &ProjectOptions) -> String {
300 let mut out = String::new();
301 out.push_str("// Auto-generated by js2rust (orchestrator)\n");
302 out.push_str("const std = @import(\"std\");\n");
303 out.push_str("const builtin = @import(\"builtin\");\n");
304 out.push_str("const Io = std.Io;\n");
305 out.push_str("const Allocator = std.mem.Allocator;\n");
306 out.push('\n');
307 out.push_str("// Global allocator for generated code\n");
308 out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
309 out.push('\n');
310 out.push_str("// Tier-3 runtime library imports\n");
311 out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
312 out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
313 out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
314 out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
315 out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
316 out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
317 out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
318 out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
319 out.push_str("const js_map = @import(\"js_runtime/js_map.zig\");\n");
320 out.push_str("const js_set = @import(\"js_runtime/js_set.zig\");\n");
321 out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
322 out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
323 out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
324 out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
325 out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
326 out.push('\n');
327
328 if !opts.host_header.is_empty() {
330 out.push_str("// Tier-4 host functions (Rust via C ABI)\n");
331 out.push_str("const host = @import(\"host.zig\");\n");
332 out.push('\n');
333 }
334
335 if opts.include_windows_stub {
338 out.push_str("// Windows stub for Zig std.debug.SelfInfo.Windows\n");
339 out.push_str("// Uses raw types (u32/i32) to avoid importing std.os.windows on non-Windows.\n");
340 out.push_str("pub export fn LdrRegisterDllNotification(\n");
341 out.push_str(" Flags: u32,\n");
342 out.push_str(" NotificationFunction: ?*const anyopaque,\n");
343 out.push_str(" Context: ?*anyopaque,\n");
344 out.push_str(" Cookie: *?*anyopaque,\n");
345 out.push_str(") callconv(.c) i32 {\n");
346 out.push_str(" _ = Flags;\n");
347 out.push_str(" _ = NotificationFunction;\n");
348 out.push_str(" _ = Context;\n");
349 out.push_str(" Cookie.* = @ptrFromInt(1);\n");
350 out.push_str(" return 0; // STATUS_SUCCESS\n");
351 out.push_str("}\n\n");
352 }
353
354 if !opts.async_host_fn_names.is_empty() {
356 out.push_str("// Async host function aliases\n");
357 for name in &opts.async_host_fn_names {
358 out.push_str(&format!("const {} = host.{}_async;\n", name, name));
359 }
360 out.push('\n');
361 }
362
363 out.push_str("// Per-file module imports\n");
365 for module in &opts.per_file_code {
366 out.push_str(&format!(
367 "const {} = @import(\"{}.zig\");\n",
368 module.mod_name, module.mod_name
369 ));
370 }
371 out.push('\n');
372
373 out.push_str("/// Initialize the global allocator used by all generated functions.\n");
375 out.push_str("pub fn init_js2rust(allocator: std.mem.Allocator) void {\n");
376 out.push_str(" js_allocator.setGlobalAllocator(allocator);\n");
377 out.push_str(" js_runtime.initIo(allocator);\n");
378 for module in &opts.per_file_code {
380 if module.zig_code.contains("pub fn init_js2rust") {
381 out.push_str(&format!(" {}.init_js2rust(allocator);\n", module.mod_name));
382 }
383 }
384 out.push_str("}\n\n");
385 if opts.include_windows_stub {
388 out.push_str("/// Initialize with a default allocator (page_allocator).\n");
389 out.push_str("/// Call this from Rust via C ABI before using any function that allocates.\n");
390 out.push_str("pub export fn js2rust_init() void {\n");
391 out.push_str(" init_js2rust(std.heap.page_allocator);\n");
392 out.push_str("}\n\n");
393 out.push_str("/// Release global resources. Call this when done.\n");
394 out.push_str("pub export fn js2rust_deinit() void {\n");
395 out.push_str(" deinit_js2rust();\n");
396 out.push_str("}\n\n");
397 }
398 out.push_str("/// Release global resources allocated via init_js2rust.\n");
399 out.push_str("pub fn deinit_js2rust() void {\n");
400 out.push_str(" js_runtime.deinitIo();\n");
401 for module in &opts.per_file_code {
402 if module.zig_code.contains("pub fn deinit_js2rust") {
403 out.push_str(&format!(" {}.deinit_js2rust();\n", module.mod_name));
404 }
405 }
406 out.push_str("}\n\n");
407
408 let cabi_string_fns = collect_cabi_string_fns(&opts.per_file_code);
411
412 if !opts.external_exports.is_empty() {
414 out.push_str("// Re-export all public exports from per-file modules\n");
415 let mut exported: HashSet<&str> = HashSet::new();
416
417 for (exp_name, mod_name) in &opts.external_exports {
418 if !exported.insert(exp_name) {
419 continue;
420 }
421 if opts.cabi_names.contains(exp_name.as_str())
425 || (exp_name.starts_with("free_")
426 && opts.cabi_names.contains(&exp_name[5..]))
427 {
428 continue;
429 }
430 if cabi_string_fns.contains(exp_name.as_str()) {
431 out.push_str(&format!(
436 "pub fn {name}(s: []const u8) []const u8 {{\n return std.mem.sliceTo({mod}.{name}(@ptrCast(s.ptr)), 0);\n}}\n",
437 name = exp_name,
438 mod = mod_name
439 ));
440 } else {
441 out.push_str(&format!(
442 "pub const {exp} = {mod}.{exp};\n",
443 exp = exp_name,
444 mod = mod_name
445 ));
446 }
447 }
448 out.push('\n');
449 }
450
451 if !opts.cabi_wrapper_code.is_empty() {
454 out.push_str("// C ABI exports (pub export fn wrappers)\n");
455 out.push_str(&opts.cabi_wrapper_code);
456 out.push('\n');
457 }
458
459 if !opts.test_code.trim().is_empty() {
461 out.push_str(&opts.test_code);
462 out.push('\n');
463 }
464
465 out
466}
467
468fn collect_cabi_string_fns(per_file_code: &[PerFileModule]) -> HashSet<String> {
471 let mut fns = HashSet::new();
472 for module in per_file_code {
473 for line in module.zig_code.lines() {
474 let trimmed = line.trim();
475 if (trimmed.starts_with("pub export fn ") || trimmed.starts_with("pub fn "))
477 && trimmed.contains("[*:0]const u8")
478 && let Some(open_paren) = trimmed.find('(')
479 {
480 let prefix_end = if trimmed.starts_with("pub export fn ") {
482 "pub export fn ".len()
483 } else {
484 "pub fn ".len()
485 };
486 let name = trimmed[prefix_end..open_paren].trim();
487 fns.insert(name.to_string());
488 }
489 }
490 }
491 fns
492}
493
494fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
496 fs::create_dir_all(dst).map_err(|e| format!("create dir {}: {}", dst.display(), e))?;
497
498 for entry in fs::read_dir(src).map_err(|e| format!("read dir {}: {}", src.display(), e))? {
499 let entry = entry.map_err(|e| format!("read entry: {}", e))?;
500 let src_path = entry.path();
501 let dst_path = dst.join(entry.file_name());
502
503 if src_path.is_dir() {
504 copy_dir_recursive(&src_path, &dst_path)?;
505 } else if src_path.is_file() {
506 fs::copy(&src_path, &dst_path)
507 .map_err(|e| format!("copy {}: {}", src_path.display(), e))?;
508 }
509 }
510
511 Ok(())
512}