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 let host_content = if opts.host_header.is_empty() {
88 r#"// Auto-generated host.zig — minimum declarations for builtin codegen
91// These symbols are defined in Rust with #[no_mangle] pub extern "C".
92pub extern fn host_regex_test(
93 pattern_ptr: [*]const u8, pattern_len: usize,
94 subject_ptr: [*]const u8, subject_len: usize,
95) callconv(.c) bool;
96pub extern fn host_regex_search(
97 pattern_ptr: [*]const u8, pattern_len: usize,
98 subject_ptr: [*]const u8, subject_len: usize,
99) callconv(.c) i64;
100
101// Wrapper functions: codegen generates host.regex_test(pattern, subject) (dot
102// notation, 2 args as []const u8 slices), but extern declarations use
103// host_regex_test with ptr+len pairs. These wrappers bridge the gap.
104pub fn regex_test(pattern: []const u8, subject: []const u8) bool {
105 return host_regex_test(pattern.ptr, pattern.len, subject.ptr, subject.len);
106}
107pub fn regex_search(pattern: []const u8, subject: []const u8) i64 {
108 return host_regex_search(pattern.ptr, pattern.len, subject.ptr, subject.len);
109}
110"#
111 .to_string()
112 } else {
113 let mut content = opts.host_header.clone();
114 if !content.contains("host_regex_test") {
116 content.push_str(
117 r#"
118pub extern fn host_regex_test(
119 pattern_ptr: [*]const u8, pattern_len: usize,
120 subject_ptr: [*]const u8, subject_len: usize,
121) callconv(.c) bool;
122"#,
123 );
124 }
125 if !content.contains("host_regex_search") {
126 content.push_str(
127 r#"pub extern fn host_regex_search(
128 pattern_ptr: [*]const u8, pattern_len: usize,
129 subject_ptr: [*]const u8, subject_len: usize,
130) callconv(.c) i64;
131"#,
132 );
133 }
134 if !content.contains("pub fn regex_test(") {
137 content.push_str(
138 r#"
139pub fn regex_test(pattern: []const u8, subject: []const u8) bool {
140 return host_regex_test(pattern.ptr, pattern.len, subject.ptr, subject.len);
141}
142"#,
143 );
144 }
145 if !content.contains("pub fn regex_search(") {
146 content.push_str(
147 r#"
148pub fn regex_search(pattern: []const u8, subject: []const u8) i64 {
149 return host_regex_search(pattern.ptr, pattern.len, subject.ptr, subject.len);
150}
151"#,
152 );
153 }
154 content
155 };
156 fs::write(src_dir.join("host.zig"), &host_content)
157 .map_err(|e| format!("write host.zig: {}", e))?;
158
159 if let Some(ref rt_dir) = opts.runtime_dir {
161 let rt_src = Path::new(rt_dir);
162 if rt_src.exists() && rt_src.is_dir() {
163 let rt_dst = src_dir.join("js_runtime");
164 let _ = fs::remove_dir_all(&rt_dst);
166 if let Err(e) = copy_dir_recursive(rt_src, &rt_dst) {
167 if !rt_dst.join("js_runtime.zig").exists() {
170 return Err(format!("copy {}: {}", rt_dst.display(), e));
171 }
172 }
173 }
174 }
175
176 if let Some(fp) = compute_fingerprint(&project_dir) {
178 let zon_with_fp = generate_zon(&opts.name, Some(&fp));
179 fs::write(&zon_path, zon_with_fp)
180 .map_err(|e| format!("write build.zig.zon (with fingerprint): {}", e))?;
181 }
182
183 Ok(())
184}
185
186fn compute_fingerprint(project_dir: &Path) -> Option<String> {
188 let output = Command::new("zig")
189 .arg("build")
190 .current_dir(project_dir)
191 .output()
192 .ok()?;
193
194 let stderr = String::from_utf8_lossy(&output.stderr);
195 let prefix = "suggested value: ";
197 if let Some(pos) = stderr.find(prefix) {
198 let after = &stderr[pos + prefix.len()..];
199 let fp = after.split_whitespace().next()?;
200 if fp.starts_with("0x") && fp.len() >= 16 && fp[2..].chars().all(|c| c.is_ascii_hexdigit())
202 {
203 return Some(fp.to_string());
204 }
205 }
206 None
207}
208
209fn generate_zon(name: &str, fingerprint: Option<&str>) -> String {
210 let fp_line = match fingerprint {
211 Some(fp) => format!(" .fingerprint = {},\n", fp),
212 None => String::new(),
213 };
214 format!(
215 r#".{{
216 .name = .{name},
217{fp_line} .version = "0.1.0",
218 .minimum_zig_version = "0.16.0",
219 .paths = .{{"src", "build.zig", "build.zig.zon"}},
220 .dependencies = .{{}},
221}}
222"#,
223 name = name,
224 fp_line = fp_line
225 )
226}
227
228pub fn generate_build_zig(lib_name: &str) -> String {
229 format!(
230 r#"const std = @import("std");
231
232pub fn build(b: *std.Build) void {{
233 const target = b.standardTargetOptions(.{{}});
234 const optimize = b.standardOptimizeOption(.{{}});
235
236 const lib_mod = b.createModule(.{{
237 .root_source_file = b.path("src/lib.zig"),
238 .target = target,
239 .optimize = optimize,
240 .link_libc = true,
241 }});
242
243 // Build as static library.
244 // bundle_compiler_rt = true: includes compiler-rt symbols in the .lib.
245 // MSVC link.exe cannot parse COMDAT sections in compiler_rt.obj (LNK1143),
246 // so users MUST use rust-lld as the linker:
247 // .cargo/config.toml: [target.x86_64-pc-windows-msvc] linker = "rust-lld.exe"
248 const lib = b.addLibrary(.{{
249 .name = "{name}",
250 .linkage = .static,
251 .root_module = lib_mod,
252 }});
253 lib.bundle_compiler_rt = true;
254 b.installArtifact(lib);
255
256 // Test step
257 const tests = b.addTest(.{{
258 .root_module = lib_mod,
259 }});
260 const run_tests = b.addRunArtifact(tests);
261 const test_step = b.step("test", "Run all library tests");
262 test_step.dependOn(&run_tests.step);
263
264 // WASM target step: `zig build wasm` produces a .wasm module
265 const wasm_mod = b.createModule(.{{
266 .root_source_file = b.path("src/lib.zig"),
267 .target = b.resolveTargetQuery(.{{
268 .cpu_arch = .wasm32,
269 .os_tag = .wasi,
270 }}),
271 .optimize = optimize,
272 }});
273 const wasm_lib = b.addExecutable(.{{
274 .name = "{name}",
275 .root_module = wasm_mod,
276 }});
277 wasm_lib.entry = .disabled;
278 const wasm_install = b.addInstallArtifact(wasm_lib, .{{}});
279 const wasm_step = b.step("wasm", "Build WASM target (wasm32-wasi)");
280 wasm_step.dependOn(&wasm_install.step);
281}}
282"#,
283 name = lib_name
284 )
285}
286
287fn generate_module_zig(module: &PerFileModule, async_host_fn_names: &[String]) -> String {
302 let mut out = String::new();
303 out.push_str(&format!("// Auto-generated from {}.js\n", module.mod_name));
304 out.push_str("const std = @import(\"std\");\n");
305 out.push_str("const builtin = @import(\"builtin\");\n");
306 out.push_str("const Io = std.Io;\n");
307 out.push_str("const Allocator = std.mem.Allocator;\n");
308 out.push('\n');
309 out.push_str("// Global allocator for generated code\n");
310 out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
311 out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n");
312 out.push('\n');
313 out.push_str("// Tier-3 runtime library imports\n");
314 out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
315 out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
316 out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
317 out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
318 out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
319 out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
320 out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
321 out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
322 out.push_str("const js_collections = @import(\"js_runtime/js_collections.zig\");\n");
323 out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
324 out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
325 out.push_str("const js_symbol = @import(\"js_runtime/js_symbol.zig\");\n");
326 out.push_str("const JsSymbol = @import(\"js_runtime/js_symbol.zig\").JsSymbol;\n");
327 out.push_str("const js_bigint = @import(\"js_runtime/js_bigint.zig\");\n");
328 out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
329 out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
330 out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
331 out.push('\n');
332
333 if module.zig_code.contains("host.") || !async_host_fn_names.is_empty() {
335 out.push_str("// Host functions (Rust via C ABI)\n");
336 out.push_str("const host = @import(\"host.zig\");\n");
337 for name in async_host_fn_names {
339 out.push_str(&format!("const {} = host.{}_async;\n", name, name));
340 }
341 out.push('\n');
342 }
343
344 let mut dep_modules: Vec<String> = Vec::new();
346 let mut seen_modules: HashSet<&str> = HashSet::new();
347 for (_, src_mod) in &module.dep_imports {
348 if seen_modules.insert(src_mod) {
349 dep_modules.push(src_mod.clone());
350 }
351 }
352
353 if !dep_modules.is_empty() {
354 out.push_str("// --- Dependency module imports ---\n");
355 for mod_name in &dep_modules {
356 out.push_str(&format!(
357 "const {} = @import(\"{}.zig\");\n",
358 mod_name, mod_name
359 ));
360 }
361 out.push('\n');
362
363 out.push_str("// --- Imported name aliases ---\n");
364 for (name, src_mod) in &module.dep_imports {
365 out.push_str(&format!("const {name} = {mod}.{name};\n", name = name, mod = src_mod));
366 }
367 out.push('\n');
368 }
369
370 out.push_str(&module.zig_code);
374 out
375}
376
377fn generate_orchestrator_lib(opts: &ProjectOptions) -> String {
381 let mut out = String::new();
382 out.push_str("// Auto-generated by js2rust (orchestrator)\n");
383 out.push_str("const std = @import(\"std\");\n");
384 out.push_str("const builtin = @import(\"builtin\");\n");
385 out.push_str("const Io = std.Io;\n");
386 out.push_str("const Allocator = std.mem.Allocator;\n");
387 out.push('\n');
388 out.push_str("// Global allocator for generated code\n");
389 out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
390 out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n");
391 out.push('\n');
392 out.push_str("// Tier-3 runtime library imports\n");
393 out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
394 out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
395 out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
396 out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
397 out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
398 out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
399 out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
400 out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
401 out.push_str("const js_collections = @import(\"js_runtime/js_collections.zig\");\n");
402 out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
403 out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
404 out.push_str("const js_symbol = @import(\"js_runtime/js_symbol.zig\");\n");
405 out.push_str("const JsSymbol = @import(\"js_runtime/js_symbol.zig\").JsSymbol;\n");
406 out.push_str("const js_bigint = @import(\"js_runtime/js_bigint.zig\");\n");
407 out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
408 out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
409 out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
410 out.push('\n');
411
412 if !opts.host_header.is_empty() {
414 out.push_str("// Tier-4 host functions (Rust via C ABI)\n");
415 out.push_str("const host = @import(\"host.zig\");\n");
416 out.push('\n');
417 }
418
419 if opts.include_windows_stub {
422 out.push_str("// Windows stub for Zig std.debug.SelfInfo.Windows\n");
423 out.push_str(
424 "// Uses raw types (u32/i32) to avoid importing std.os.windows on non-Windows.\n",
425 );
426 out.push_str("pub export fn LdrRegisterDllNotification(\n");
427 out.push_str(" Flags: u32,\n");
428 out.push_str(" NotificationFunction: ?*const anyopaque,\n");
429 out.push_str(" Context: ?*anyopaque,\n");
430 out.push_str(" Cookie: *?*anyopaque,\n");
431 out.push_str(") callconv(.c) i32 {\n");
432 out.push_str(" _ = Flags;\n");
433 out.push_str(" _ = NotificationFunction;\n");
434 out.push_str(" _ = Context;\n");
435 out.push_str(" Cookie.* = @ptrFromInt(1);\n");
436 out.push_str(" return 0; // STATUS_SUCCESS\n");
437 out.push_str("}\n\n");
438 }
439
440 if !opts.async_host_fn_names.is_empty() {
442 out.push_str("// Async host function aliases\n");
443 for name in &opts.async_host_fn_names {
444 out.push_str(&format!("const {} = host.{}_async;\n", name, name));
445 }
446 out.push('\n');
447 }
448
449 out.push_str("// Per-file module imports\n");
452 for module in &opts.per_file_code {
453 out.push_str(&format!(
454 "const _{} = @import(\"{}.zig\");\n",
455 module.mod_name, module.mod_name
456 ));
457 }
458 out.push('\n');
459
460 out.push_str("/// Initialize the global allocator used by all generated functions.\n");
462 out.push_str("/// The allocator is created internally using ArenaAllocator (Zig 0.16.0: lock-free, thread-safe).\n");
463 out.push_str("pub fn init_js2rust() !void {\n");
464 out.push_str(" try js_allocator.init(null, null);\n");
465 out.push_str(" js_runtime.initIo(js_allocator.allocator());\n");
466 for module in &opts.per_file_code {
468 if module.zig_code.contains("pub fn init_js2rust") {
469 out.push_str(&format!(" _{}.init_js2rust();\n", module.mod_name));
470 }
471 }
472 out.push_str("}\n\n");
473 if opts.include_windows_stub {
476 out.push_str("/// Initialize with ArenaAllocator (lock-free, thread-safe).\n");
477 out.push_str(
478 "/// Call this from Rust via C ABI before using any function that allocates.\n",
479 );
480 out.push_str("pub export fn js2rust_init() void {\n");
481 out.push_str(" init_js2rust() catch @panic(\"init_js2rust failed\");\n");
482 out.push_str("}\n\n");
483 out.push_str("/// Release global resources. Call this when done.\n");
484 out.push_str("pub export fn js2rust_deinit() void {\n");
485 out.push_str(" deinit_js2rust();\n");
486 out.push_str("}\n\n");
487 out.push_str(
488 "/// Allocate memory in Zig's Arena for zero-copy string returns from Rust host functions.\n",
489 );
490 out.push_str(
491 "/// Called from Rust via extern \"C\" { fn js_allocator_alloc(size: usize) -> ?*mut u8; }\n",
492 );
493 out.push_str("/// Memory is managed by the multi-arena allocator — no free needed.\n");
494 out.push_str("/// Returns null on OOM instead of panicking.\n");
495 out.push_str("pub export fn js_allocator_alloc(size: usize) ?[*]u8 {\n");
496 out.push_str(" const buf = js_allocator.allocBytes(size) catch return null;\n");
497 out.push_str(" return buf.ptr;\n");
498 out.push_str("}\n\n");
499 out.push_str(
500 "/// Allocate + copy in Zig Arena — single call for zero-copy string returns.\n",
501 );
502 out.push_str(
503 "/// Called from Rust via extern \"C\" { fn js_allocator_dupe(src: *const u8, len: usize) -> ?*mut u8; }\n",
504 );
505 out.push_str("/// Prefer this over js_allocator_alloc + manual copy — avoids a separate memcpy in Rust.\n");
506 out.push_str("/// Returns null on OOM instead of panicking.\n");
507 out.push_str("pub export fn js_allocator_dupe(src: [*]const u8, len: usize) ?[*]u8 {\n");
508 out.push_str(" const buf = js_allocator.dupeBytes(src[0..len]) catch return null;\n");
509 out.push_str(" return buf.ptr;\n");
510 out.push_str("}\n\n");
511 }
512 out.push_str("/// Release global resources allocated via init_js2rust.\n");
513 out.push_str("pub fn deinit_js2rust() void {\n");
514 out.push_str(" js_runtime.deinitIo();\n");
515 for module in &opts.per_file_code {
516 if module.zig_code.contains("pub fn deinit_js2rust") {
517 out.push_str(&format!(" _{}.deinit_js2rust();\n", module.mod_name));
518 }
519 }
520 out.push_str(" js_allocator.deinit();\n");
521 out.push_str("}\n\n");
522
523 let cabi_string_fns = collect_cabi_string_fns(&opts.per_file_code);
526
527 if !opts.external_exports.is_empty() {
529 out.push_str("// Re-export all public exports from per-file modules\n");
530 let mut exported: HashSet<&str> = HashSet::new();
531
532 for (exp_name, mod_name) in &opts.external_exports {
533 if !exported.insert(exp_name) {
534 continue;
535 }
536 if opts.cabi_names.contains(exp_name.as_str()) {
539 continue;
540 }
541 if cabi_string_fns.contains(exp_name.as_str()) {
542 out.push_str(&format!(
547 "pub fn {name}(s: []const u8) []const u8 {{\n return std.mem.sliceTo(_{mod}.{name}(@ptrCast(s.ptr)), 0);\n}}\n",
548 name = exp_name,
549 mod = mod_name
550 ));
551 } else {
552 out.push_str(&format!(
553 "pub const {exp} = _{mod}.{exp};\n",
554 exp = exp_name,
555 mod = mod_name
556 ));
557 }
558 }
559 out.push('\n');
560 }
561
562 if !opts.cabi_wrapper_code.is_empty() {
565 out.push_str("// C ABI exports (pub export fn wrappers)\n");
566 out.push_str(&opts.cabi_wrapper_code);
567 out.push('\n');
568 }
569
570 if !opts.test_code.trim().is_empty() {
572 out.push_str(&opts.test_code);
573 out.push('\n');
574 }
575
576 out
577}
578
579fn collect_cabi_string_fns(per_file_code: &[PerFileModule]) -> HashSet<String> {
582 let mut fns = HashSet::new();
583 for module in per_file_code {
584 for line in module.zig_code.lines() {
585 let trimmed = line.trim();
586 if (trimmed.starts_with("pub export fn ") || trimmed.starts_with("pub fn "))
588 && trimmed.contains("StrRet")
589 && let Some(open_paren) = trimmed.find('(')
590 {
591 let prefix_end = if trimmed.starts_with("pub export fn ") {
593 "pub export fn ".len()
594 } else {
595 "pub fn ".len()
596 };
597 let name = trimmed[prefix_end..open_paren].trim();
598 fns.insert(name.to_string());
599 }
600 }
601 }
602 fns
603}
604
605fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
607 fs::create_dir_all(dst).map_err(|e| format!("create dir {}: {}", dst.display(), e))?;
608
609 for entry in fs::read_dir(src).map_err(|e| format!("read dir {}: {}", src.display(), e))? {
610 let entry = entry.map_err(|e| format!("read entry: {}", e))?;
611 let src_path = entry.path();
612 let dst_path = dst.join(entry.file_name());
613
614 if src_path.is_dir() {
615 copy_dir_recursive(&src_path, &dst_path)?;
616 } else if src_path.is_file() {
617 fs::copy(&src_path, &dst_path)
618 .map_err(|e| format!("copy {}: {}", src_path.display(), e))?;
619 }
620 }
621
622 Ok(())
623}