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).map_err(|e| format!("write build.zig.zon: {}", e))?;
66
67 let build_zig = generate_build_zig(&opts.name);
69 fs::write(project_dir.join("build.zig"), build_zig)
70 .map_err(|e| format!("write build.zig: {}", e))?;
71
72 for module in &opts.per_file_code {
74 let mod_zig = generate_module_zig(module, &opts.async_host_fn_names);
75 let mod_path = src_dir.join(format!("{}.zig", module.mod_name));
76 fs::write(&mod_path, mod_zig)
77 .map_err(|e| format!("write {}.zig: {}", mod_path.display(), e))?;
78 }
79
80 let lib_zig = generate_orchestrator_lib(opts);
82 fs::write(src_dir.join("lib.zig"), lib_zig).map_err(|e| format!("write lib.zig: {}", e))?;
83
84 if !opts.host_header.is_empty() {
86 fs::write(src_dir.join("host.zig"), &opts.host_header)
87 .map_err(|e| format!("write host.zig: {}", e))?;
88 }
89
90 if let Some(ref rt_dir) = opts.runtime_dir {
92 let rt_src = Path::new(rt_dir);
93 if rt_src.exists() && rt_src.is_dir() {
94 let rt_dst = src_dir.join("js_runtime");
95 if !rt_dst.join("js_runtime.zig").exists() {
97 let _ = fs::remove_dir_all(&rt_dst);
98 if let Err(e) = copy_dir_recursive(rt_src, &rt_dst) {
99 if !rt_dst.join("js_runtime.zig").exists() {
102 return Err(format!("copy {}: {}", rt_dst.display(), e));
103 }
104 }
105 }
106 }
107 }
108
109 if let Some(fp) = compute_fingerprint(&project_dir) {
111 let zon_with_fp = generate_zon(&opts.name, Some(&fp));
112 fs::write(&zon_path, zon_with_fp)
113 .map_err(|e| format!("write build.zig.zon (with fingerprint): {}", e))?;
114 }
115
116 Ok(())
117}
118
119fn compute_fingerprint(project_dir: &Path) -> Option<String> {
121 let output = Command::new("zig")
122 .arg("build")
123 .current_dir(project_dir)
124 .output()
125 .ok()?;
126
127 let stderr = String::from_utf8_lossy(&output.stderr);
128 let prefix = "suggested value: ";
130 if let Some(pos) = stderr.find(prefix) {
131 let after = &stderr[pos + prefix.len()..];
132 let fp = after.split_whitespace().next()?;
133 if fp.starts_with("0x") && fp.len() >= 16 && fp[2..].chars().all(|c| c.is_ascii_hexdigit())
135 {
136 return Some(fp.to_string());
137 }
138 }
139 None
140}
141
142fn generate_zon(name: &str, fingerprint: Option<&str>) -> String {
143 let fp_line = match fingerprint {
144 Some(fp) => format!(" .fingerprint = {},\n", fp),
145 None => String::new(),
146 };
147 format!(
148 r#".{{
149 .name = .{name},
150{fp_line} .version = "0.1.0",
151 .minimum_zig_version = "0.16.0",
152 .paths = .{{"src", "build.zig", "build.zig.zon"}},
153 .dependencies = .{{}},
154}}
155"#,
156 name = name,
157 fp_line = fp_line
158 )
159}
160
161pub fn generate_build_zig(lib_name: &str) -> String {
162 format!(
163 r#"const std = @import("std");
164
165pub fn build(b: *std.Build) void {{
166 const target = b.standardTargetOptions(.{{}});
167 const optimize = b.standardOptimizeOption(.{{}});
168
169 const lib_mod = b.createModule(.{{
170 .root_source_file = b.path("src/lib.zig"),
171 .target = target,
172 .optimize = optimize,
173 .link_libc = true,
174 }});
175
176 // Build as static library.
177 // bundle_compiler_rt = true: includes compiler-rt symbols in the .lib.
178 // MSVC link.exe cannot parse COMDAT sections in compiler_rt.obj (LNK1143),
179 // so users MUST use rust-lld as the linker:
180 // .cargo/config.toml: [target.x86_64-pc-windows-msvc] linker = "rust-lld.exe"
181 const lib = b.addLibrary(.{{
182 .name = "{name}",
183 .linkage = .static,
184 .root_module = lib_mod,
185 }});
186 lib.bundle_compiler_rt = true;
187 b.installArtifact(lib);
188
189 // Test step
190 const tests = b.addTest(.{{
191 .root_module = lib_mod,
192 }});
193 const run_tests = b.addRunArtifact(tests);
194 const test_step = b.step("test", "Run all library tests");
195 test_step.dependOn(&run_tests.step);
196
197 // WASM target step: `zig build wasm` produces a .wasm module
198 const wasm_mod = b.createModule(.{{
199 .root_source_file = b.path("src/lib.zig"),
200 .target = b.resolveTargetQuery(.{{
201 .cpu_arch = .wasm32,
202 .os_tag = .wasi,
203 }}),
204 .optimize = optimize,
205 }});
206 const wasm_lib = b.addExecutable(.{{
207 .name = "{name}",
208 .root_module = wasm_mod,
209 }});
210 wasm_lib.entry = .disabled;
211 const wasm_install = b.addInstallArtifact(wasm_lib, .{{}});
212 const wasm_step = b.step("wasm", "Build WASM target (wasm32-wasi)");
213 wasm_step.dependOn(&wasm_install.step);
214}}
215"#,
216 name = lib_name
217 )
218}
219
220fn generate_module_zig(module: &PerFileModule, async_host_fn_names: &[String]) -> String {
235 let mut out = String::new();
236 out.push_str(&format!("// Auto-generated from {}.js\n", module.mod_name));
237 out.push_str("const std = @import(\"std\");\n");
238 out.push_str("const builtin = @import(\"builtin\");\n");
239 out.push_str("const Io = std.Io;\n");
240 out.push_str("const Allocator = std.mem.Allocator;\n");
241 out.push('\n');
242 out.push_str("// Global allocator for generated code\n");
243 out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
244 out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n");
245 out.push('\n');
246 out.push_str("// Tier-3 runtime library imports\n");
247 out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
248 out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
249 out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
250 out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
251 out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
252 out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
253 out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
254 out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
255 out.push_str("const js_map = @import(\"js_runtime/js_map.zig\");\n");
256 out.push_str("const js_set = @import(\"js_runtime/js_set.zig\");\n");
257 out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
258 out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
259 out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
260 out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
261 out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
262 out.push('\n');
263
264 if module.zig_code.contains("host.") || !async_host_fn_names.is_empty() {
266 out.push_str("// Host functions (Rust via C ABI)\n");
267 out.push_str("const host = @import(\"host.zig\");\n");
268 for name in async_host_fn_names {
270 out.push_str(&format!("const {} = host.{}_async;\n", name, name));
271 }
272 out.push('\n');
273 }
274
275 let mut dep_modules: Vec<String> = Vec::new();
277 let mut seen_modules: HashSet<&str> = HashSet::new();
278 for (_, src_mod) in &module.dep_imports {
279 if seen_modules.insert(src_mod) {
280 dep_modules.push(src_mod.clone());
281 }
282 }
283
284 if !dep_modules.is_empty() {
285 out.push_str("// --- Dependency module imports ---\n");
286 for mod_name in &dep_modules {
287 out.push_str(&format!(
288 "const {} = @import(\"{}.zig\");\n",
289 mod_name, mod_name
290 ));
291 }
292 out.push('\n');
293
294 out.push_str("// --- Imported name aliases ---\n");
295 for (name, src_mod) in &module.dep_imports {
296 out.push_str(&format!("const {name} = {mod}.{name};\n", name = name, mod = src_mod));
297 }
298 out.push('\n');
299 }
300
301 out.push_str(&module.zig_code);
305 out
306}
307
308fn generate_orchestrator_lib(opts: &ProjectOptions) -> String {
312 let mut out = String::new();
313 out.push_str("// Auto-generated by js2rust (orchestrator)\n");
314 out.push_str("const std = @import(\"std\");\n");
315 out.push_str("const builtin = @import(\"builtin\");\n");
316 out.push_str("const Io = std.Io;\n");
317 out.push_str("const Allocator = std.mem.Allocator;\n");
318 out.push('\n');
319 out.push_str("// Global allocator for generated code\n");
320 out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
321 out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n");
322 out.push('\n');
323 out.push_str("// Tier-3 runtime library imports\n");
324 out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
325 out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
326 out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
327 out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
328 out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
329 out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
330 out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
331 out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
332 out.push_str("const js_map = @import(\"js_runtime/js_map.zig\");\n");
333 out.push_str("const js_set = @import(\"js_runtime/js_set.zig\");\n");
334 out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
335 out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
336 out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
337 out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
338 out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
339 out.push('\n');
340
341 if !opts.host_header.is_empty() {
343 out.push_str("// Tier-4 host functions (Rust via C ABI)\n");
344 out.push_str("const host = @import(\"host.zig\");\n");
345 out.push('\n');
346 }
347
348 if opts.include_windows_stub {
351 out.push_str("// Windows stub for Zig std.debug.SelfInfo.Windows\n");
352 out.push_str(
353 "// Uses raw types (u32/i32) to avoid importing std.os.windows on non-Windows.\n",
354 );
355 out.push_str("pub export fn LdrRegisterDllNotification(\n");
356 out.push_str(" Flags: u32,\n");
357 out.push_str(" NotificationFunction: ?*const anyopaque,\n");
358 out.push_str(" Context: ?*anyopaque,\n");
359 out.push_str(" Cookie: *?*anyopaque,\n");
360 out.push_str(") callconv(.c) i32 {\n");
361 out.push_str(" _ = Flags;\n");
362 out.push_str(" _ = NotificationFunction;\n");
363 out.push_str(" _ = Context;\n");
364 out.push_str(" Cookie.* = @ptrFromInt(1);\n");
365 out.push_str(" return 0; // STATUS_SUCCESS\n");
366 out.push_str("}\n\n");
367 }
368
369 if !opts.async_host_fn_names.is_empty() {
371 out.push_str("// Async host function aliases\n");
372 for name in &opts.async_host_fn_names {
373 out.push_str(&format!("const {} = host.{}_async;\n", name, name));
374 }
375 out.push('\n');
376 }
377
378 out.push_str("// Per-file module imports\n");
380 for module in &opts.per_file_code {
381 out.push_str(&format!(
382 "const {} = @import(\"{}.zig\");\n",
383 module.mod_name, module.mod_name
384 ));
385 }
386 out.push('\n');
387
388 out.push_str("/// Initialize the global allocator used by all generated functions.\n");
390 out.push_str("/// The allocator is created internally using ArenaAllocator (Zig 0.16.0: lock-free, thread-safe).\n");
391 out.push_str("pub fn init_js2rust() void {\n");
392 out.push_str(" js_allocator.initGlobalAllocator();\n");
393 out.push_str(" js_runtime.initIo(js_allocator.getAllocator());\n");
394 for module in &opts.per_file_code {
396 if module.zig_code.contains("pub fn init_js2rust") {
397 out.push_str(&format!(" {}.init_js2rust();\n", module.mod_name));
398 }
399 }
400 out.push_str("}\n\n");
401 if opts.include_windows_stub {
404 out.push_str("/// Initialize with ArenaAllocator (lock-free, thread-safe).\n");
405 out.push_str(
406 "/// Call this from Rust via C ABI before using any function that allocates.\n",
407 );
408 out.push_str("pub export fn js2rust_init() void {\n");
409 out.push_str(" init_js2rust();\n");
410 out.push_str("}\n\n");
411 out.push_str("/// Release global resources. Call this when done.\n");
412 out.push_str("pub export fn js2rust_deinit() void {\n");
413 out.push_str(" deinit_js2rust();\n");
414 out.push_str("}\n\n");
415 out.push_str(
416 "/// Reset the arena allocator (free all allocated memory, keep allocator active).\n",
417 );
418 out.push_str("/// Call this periodically to prevent excessive memory usage.\n");
419 out.push_str("/// Thread-safe: uses atomic spinlock internally.\n");
420 out.push_str("pub export fn js2rust_reset() void {\n");
421 out.push_str(" js_allocator.resetGlobalAllocator();\n");
422 out.push_str("}\n\n");
423 out.push_str(
424 "/// Allocate memory in Zig's Arena for zero-copy string returns from Rust host functions.\n",
425 );
426 out.push_str(
427 "/// Called from Rust via extern \"C\" { fn js_allocator_alloc(size: usize) -> *mut u8; }\n",
428 );
429 out.push_str("/// Memory is managed by the dual-arena allocator — no free needed.\n");
430 out.push_str("pub export fn js_allocator_alloc(size: usize) [*]u8 {\n");
431 out.push_str(" return js_allocator.js_allocator_alloc(size).ptr;\n");
432 out.push_str("}\n\n");
433 }
434 out.push_str("/// Release global resources allocated via init_js2rust.\n");
435 out.push_str("pub fn deinit_js2rust() void {\n");
436 out.push_str(" js_runtime.deinitIo();\n");
437 for module in &opts.per_file_code {
438 if module.zig_code.contains("pub fn deinit_js2rust") {
439 out.push_str(&format!(" {}.deinit_js2rust();\n", module.mod_name));
440 }
441 }
442 out.push_str(" js_allocator.deinitGlobalAllocator();\n");
443 out.push_str("}\n\n");
444
445 let cabi_string_fns = collect_cabi_string_fns(&opts.per_file_code);
448
449 if !opts.external_exports.is_empty() {
451 out.push_str("// Re-export all public exports from per-file modules\n");
452 let mut exported: HashSet<&str> = HashSet::new();
453
454 for (exp_name, mod_name) in &opts.external_exports {
455 if !exported.insert(exp_name) {
456 continue;
457 }
458 if opts.cabi_names.contains(exp_name.as_str()) {
461 continue;
462 }
463 if cabi_string_fns.contains(exp_name.as_str()) {
464 out.push_str(&format!(
469 "pub fn {name}(s: []const u8) []const u8 {{\n return std.mem.sliceTo({mod}.{name}(@ptrCast(s.ptr)), 0);\n}}\n",
470 name = exp_name,
471 mod = mod_name
472 ));
473 } else {
474 out.push_str(&format!(
475 "pub const {exp} = {mod}.{exp};\n",
476 exp = exp_name,
477 mod = mod_name
478 ));
479 }
480 }
481 out.push('\n');
482 }
483
484 if !opts.cabi_wrapper_code.is_empty() {
487 out.push_str("// C ABI exports (pub export fn wrappers)\n");
488 out.push_str(&opts.cabi_wrapper_code);
489 out.push('\n');
490 }
491
492 if !opts.test_code.trim().is_empty() {
494 out.push_str(&opts.test_code);
495 out.push('\n');
496 }
497
498 out
499}
500
501fn collect_cabi_string_fns(per_file_code: &[PerFileModule]) -> HashSet<String> {
504 let mut fns = HashSet::new();
505 for module in per_file_code {
506 for line in module.zig_code.lines() {
507 let trimmed = line.trim();
508 if (trimmed.starts_with("pub export fn ") || trimmed.starts_with("pub fn "))
510 && trimmed.contains("StrRet")
511 && let Some(open_paren) = trimmed.find('(')
512 {
513 let prefix_end = if trimmed.starts_with("pub export fn ") {
515 "pub export fn ".len()
516 } else {
517 "pub fn ".len()
518 };
519 let name = trimmed[prefix_end..open_paren].trim();
520 fns.insert(name.to_string());
521 }
522 }
523 }
524 fns
525}
526
527fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
529 fs::create_dir_all(dst).map_err(|e| format!("create dir {}: {}", dst.display(), e))?;
530
531 for entry in fs::read_dir(src).map_err(|e| format!("read dir {}: {}", src.display(), e))? {
532 let entry = entry.map_err(|e| format!("read entry: {}", e))?;
533 let src_path = entry.path();
534 let dst_path = dst.join(entry.file_name());
535
536 if src_path.is_dir() {
537 copy_dir_recursive(&src_path, &dst_path)?;
538 } else if src_path.is_file() {
539 fs::copy(&src_path, &dst_path)
540 .map_err(|e| format!("copy {}: {}", src_path.display(), e))?;
541 }
542 }
543
544 Ok(())
545}