1use std::collections::HashSet;
3use std::fs;
4use std::path::{Path, PathBuf};
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: PathBuf,
25 pub per_file_code: Vec<PerFileModule>,
28 pub external_exports: Vec<(String, String, String)>,
34 pub cabi_wrapper_code: String,
38 pub cabi_names: HashSet<String>,
41 pub test_code: String,
43 pub runtime_dir: Option<PathBuf>,
45 pub host_header: String,
47 pub async_host_fn_names: Vec<String>,
49 pub needs_regex: bool,
51 pub needs_icu: bool,
56}
57
58pub fn generate(opts: &ProjectOptions) -> Result<(), String> {
60 let project_dir = opts.out_dir.join(&opts.name);
61 let src_dir = project_dir.join("src");
62
63 fs::create_dir_all(&src_dir).map_err(|e| format!("create {}: {}", project_dir.display(), e))?;
65
66 let zon_path = project_dir.join("build.zig.zon");
68 let zon_no_fp = generate_zon(&opts.name, None);
69 fs::write(&zon_path, &zon_no_fp).map_err(|e| format!("write build.zig.zon: {}", e))?;
70
71 let build_zig = generate_build_zig(&opts.name, opts.needs_regex, opts.needs_icu);
73 fs::write(project_dir.join("build.zig"), build_zig)
74 .map_err(|e| format!("write build.zig: {}", e))?;
75
76 for module in &opts.per_file_code {
78 let mod_zig = generate_module_zig(module, &opts.async_host_fn_names, opts.needs_regex);
79 let mod_path = src_dir.join(format!("{}.zig", module.mod_name));
80 fs::write(&mod_path, mod_zig)
81 .map_err(|e| format!("write {}.zig: {}", mod_path.display(), e))?;
82 }
83
84 let lib_zig = generate_orchestrator_lib(opts);
86 fs::write(src_dir.join("lib.zig"), lib_zig).map_err(|e| format!("write lib.zig: {}", e))?;
87
88 if !opts.host_header.is_empty() {
91 fs::write(src_dir.join("host.zig"), &opts.host_header)
92 .map_err(|e| format!("write host.zig: {}", e))?;
93 }
94
95 if opts.needs_regex {
98 let host_regex_content = r#"// Auto-generated host_regex.zig — regex host function declarations
99// These symbols are defined in Rust with #[no_mangle] pub extern "C".
100pub extern fn host_regex_test(
101 pattern_ptr: [*]const u8, pattern_len: usize,
102 subject_ptr: [*]const u8, subject_len: usize,
103) callconv(.c) bool;
104pub extern fn host_regex_search(
105 pattern_ptr: [*]const u8, pattern_len: usize,
106 subject_ptr: [*]const u8, subject_len: usize,
107) callconv(.c) i64;
108
109// Wrapper functions: the Emitter generates host_regex.regex_test(pattern, subject) (dot
110// notation, 2 args as []const u8 slices), but extern declarations use
111// host_regex_test with ptr+len pairs. These wrappers bridge the gap.
112pub fn regex_test(pattern: []const u8, subject: []const u8) bool {
113 return host_regex_test(pattern.ptr, pattern.len, subject.ptr, subject.len);
114}
115pub fn regex_search(pattern: []const u8, subject: []const u8) i64 {
116 return host_regex_search(pattern.ptr, pattern.len, subject.ptr, subject.len);
117}
118"#;
119 fs::write(src_dir.join("host_regex.zig"), host_regex_content)
120 .map_err(|e| format!("write host_regex.zig: {}", e))?;
121 }
122
123 if opts.needs_regex {
127 let stub_content = generate_host_regex_stubs();
128 fs::write(src_dir.join("host_regex_stubs.zig"), stub_content)
129 .map_err(|e| format!("write host_regex_stubs.zig: {}", e))?;
130 }
131
132 if opts.needs_icu {
136 let stub_content = generate_host_icu_stubs();
137 fs::write(src_dir.join("host_icu_stubs.zig"), stub_content)
138 .map_err(|e| format!("write host_icu_stubs.zig: {}", e))?;
139 }
140
141 if let Some(ref rt_dir) = opts.runtime_dir
143 && rt_dir.exists()
144 && rt_dir.is_dir()
145 {
146 let rt_dst = src_dir.join("js_runtime");
147 let _ = fs::remove_dir_all(&rt_dst);
149 if let Err(e) = copy_dir_recursive(rt_dir, &rt_dst) {
150 if !rt_dst.join("js_runtime.zig").exists() {
153 return Err(format!("copy {}: {}", rt_dst.display(), e));
154 }
155 }
156
157 if opts.needs_icu {
163 let icu_runtime = generate_js_string_icu_icu();
164 fs::write(rt_dst.join("js_string_icu.zig"), icu_runtime)
165 .map_err(|e| format!("write js_string_icu.zig: {}", e))?;
166 }
167 }
168
169 if let Some(fp) = compute_fingerprint(&project_dir) {
171 let zon_with_fp = generate_zon(&opts.name, Some(&fp));
172 fs::write(&zon_path, zon_with_fp)
173 .map_err(|e| format!("write build.zig.zon (with fingerprint): {}", e))?;
174 }
175
176 Ok(())
177}
178
179fn compute_fingerprint(project_dir: &Path) -> Option<String> {
181 let output = Command::new("zig")
182 .arg("build")
183 .current_dir(project_dir)
184 .output()
185 .ok()?;
186
187 let stderr = String::from_utf8_lossy(&output.stderr);
188 let prefix = "suggested value: ";
190 if let Some(pos) = stderr.find(prefix) {
191 let after = &stderr[pos + prefix.len()..];
192 let fp = after.split_whitespace().next()?;
193 if fp.starts_with("0x") && fp.len() >= 16 && fp[2..].chars().all(|c| c.is_ascii_hexdigit())
195 {
196 return Some(fp.to_string());
197 }
198 }
199 None
200}
201
202fn generate_zon(name: &str, fingerprint: Option<&str>) -> String {
203 let fp_line = match fingerprint {
204 Some(fp) => format!(" .fingerprint = {},\n", fp),
205 None => String::new(),
206 };
207 format!(
208 r#".{{
209 .name = .{name},
210{fp_line} .version = "0.1.0",
211 .minimum_zig_version = "0.16.0",
212 .paths = .{{"src", "build.zig", "build.zig.zon"}},
213 .dependencies = .{{}},
214}}
215"#,
216 name = name,
217 fp_line = fp_line
218 )
219}
220
221pub fn generate_host_regex_stubs() -> String {
226 r#"//! Stub implementations of host C ABI regex functions for zig test.
227//! These provide linkable symbols so that zig test can produce a standalone
228//! test binary without the Rust-side implementations. The real implementations
229//! live in js2rust-bridge (native_regex.rs) and are linked when Rust drives
230//! the final executable build. These stubs are only used by `zig build test`.
231
232const JsStr = extern struct { ptr: [*]const u8, len: isize };
233
234export fn host_regex_test(
235 pattern_ptr: [*]const u8,
236 pattern_len: usize,
237 text_ptr: [*]const u8,
238 text_len: usize,
239) callconv(.c) bool {
240 _ = pattern_ptr;
241 _ = pattern_len;
242 _ = text_ptr;
243 _ = text_len;
244 return false;
245}
246
247export fn host_regex_search(
248 pattern_ptr: [*]const u8,
249 pattern_len: usize,
250 text_ptr: [*]const u8,
251 text_len: usize,
252) callconv(.c) i64 {
253 _ = pattern_ptr;
254 _ = pattern_len;
255 _ = text_ptr;
256 _ = text_len;
257 return -1;
258}
259
260export fn host_regex_match(
261 pattern_ptr: [*]const u8,
262 pattern_len: usize,
263 text_ptr: [*]const u8,
264 text_len: usize,
265 out_count: *usize,
266) callconv(.c) JsStr {
267 _ = pattern_ptr;
268 _ = pattern_len;
269 _ = text_ptr;
270 _ = text_len;
271 out_count.* = 0;
272 return .{ .ptr = undefined, .len = 0 };
273}
274
275export fn host_regex_match_global(
276 pattern_ptr: [*]const u8,
277 pattern_len: usize,
278 text_ptr: [*]const u8,
279 text_len: usize,
280 out_count: *usize,
281) callconv(.c) JsStr {
282 _ = pattern_ptr;
283 _ = pattern_len;
284 _ = text_ptr;
285 _ = text_len;
286 out_count.* = 0;
287 return .{ .ptr = undefined, .len = 0 };
288}
289
290export fn host_regex_match_all(
291 pattern_ptr: [*]const u8,
292 pattern_len: usize,
293 text_ptr: [*]const u8,
294 text_len: usize,
295 out_match_count: *usize,
296 out_group_count: *usize,
297) callconv(.c) JsStr {
298 _ = pattern_ptr;
299 _ = pattern_len;
300 _ = text_ptr;
301 _ = text_len;
302 out_match_count.* = 0;
303 out_group_count.* = 0;
304 return .{ .ptr = undefined, .len = 0 };
305}
306"#
307 .to_string()
308}
309
310pub fn generate_build_zig(lib_name: &str, needs_regex: bool, needs_icu: bool) -> String {
311 let regex_stub_section = if needs_regex {
312 r#"
313 // Stub library: provides host_regex_* C ABI symbols for zig test.
314 // When Rust drives the final executable build it links its own real
315 // implementations (js2rust-bridge native_regex.rs). The stubs only
316 // exist so `zig build test` can produce a standalone test binary.
317 const stub_mod = b.createModule(.{
318 .root_source_file = b.path("src/host_regex_stubs.zig"),
319 .target = target,
320 .optimize = optimize,
321 .link_libc = true,
322 });
323 const stub_lib = b.addLibrary(.{
324 .name = "host_regex_stubs",
325 .linkage = .static,
326 .root_module = stub_mod,
327 });
328"#
329 .to_string()
330 } else {
331 String::new()
332 };
333
334 let icu_stub_section = if needs_icu {
335 r#"
336 // Stub library: provides host_icu_* C ABI symbols for zig test.
337 // When Rust drives the final executable build it links its own real
338 // implementations (js2rust-bridge native_icu.rs). The stubs only
339 // exist so `zig build test` can produce a standalone test binary.
340 const icu_stub_mod = b.createModule(.{
341 .root_source_file = b.path("src/host_icu_stubs.zig"),
342 .target = target,
343 .optimize = optimize,
344 .link_libc = true,
345 });
346 const icu_stub_lib = b.addLibrary(.{
347 .name = "host_icu_stubs",
348 .linkage = .static,
349 .root_module = icu_stub_mod,
350 });
351"#
352 .to_string()
353 } else {
354 String::new()
355 };
356
357 let test_link_stub = if needs_regex {
358 " test_mod.linkLibrary(stub_lib);\n"
359 } else {
360 ""
361 };
362
363 let test_link_icu_stub = if needs_icu {
364 " test_mod.linkLibrary(icu_stub_lib);\n"
365 } else {
366 ""
367 };
368
369 format!(
370 r#"const std = @import("std");
371
372pub fn build(b: *std.Build) void {{
373 const target = b.standardTargetOptions(.{{}});
374 const optimize = b.standardOptimizeOption(.{{}});
375
376 const lib_mod = b.createModule(.{{
377 .root_source_file = b.path("src/lib.zig"),
378 .target = target,
379 .optimize = optimize,
380 .link_libc = true,
381 }});
382
383 // Build as static library.
384 // bundle_compiler_rt = true: includes compiler-rt symbols in the .lib.
385 // MSVC link.exe cannot parse COMDAT sections in compiler_rt.obj (LNK1143),
386 // so users MUST use rust-lld as the linker:
387 // .cargo/config.toml: [target.x86_64-pc-windows-msvc] linker = "rust-lld.exe"
388 const lib = b.addLibrary(.{{
389 .name = "{name}",
390 .linkage = .static,
391 .root_module = lib_mod,
392 }});
393 lib.bundle_compiler_rt = true;
394 b.installArtifact(lib);
395{regex_stub_section}{icu_stub_section}
396 // Test step
397 // Create a test-only module that links the stub libraries, so the stub
398 // symbols (host_regex_*, host_icu_*) are available during `zig build test` but
399 // do NOT pollute the main library artifact linked by Rust.
400 const test_mod = b.createModule(.{{
401 .root_source_file = b.path("src/lib.zig"),
402 .target = target,
403 .optimize = optimize,
404 .link_libc = true,
405 }});
406{test_link_stub}{test_link_icu_stub} const tests = b.addTest(.{{
407 .root_module = test_mod,
408 }});
409 const run_tests = b.addRunArtifact(tests);
410 const test_step = b.step("test", "Run all library tests");
411 test_step.dependOn(&run_tests.step);
412
413 // WASM target step: `zig build wasm` produces a .wasm module
414 const wasm_mod = b.createModule(.{{
415 .root_source_file = b.path("src/lib.zig"),
416 .target = b.resolveTargetQuery(.{{
417 .cpu_arch = .wasm32,
418 .os_tag = .wasi,
419 }}),
420 .optimize = optimize,
421 }});
422 const wasm_lib = b.addExecutable(.{{
423 .name = "{name}",
424 .root_module = wasm_mod,
425 }});
426 wasm_lib.entry = .disabled;
427 const wasm_install = b.addInstallArtifact(wasm_lib, .{{}});
428 const wasm_step = b.step("wasm", "Build WASM target (wasm32-wasi)");
429 wasm_step.dependOn(&wasm_install.step);
430}}
431"#,
432 name = lib_name
433 )
434}
435
436fn push_runtime_imports(out: &mut String, needs_regex: bool) {
438 out.push_str("const std = @import(\"std\");\n");
439 out.push_str("const builtin = @import(\"builtin\");\n");
440 out.push_str("const Io = std.Io;\n");
441 out.push_str("const Allocator = std.mem.Allocator;\n");
442 out.push('\n');
443 out.push_str("// Global allocator for generated code\n");
444 out.push_str("const js_allocator = @import(\"js_runtime/js_allocator.zig\");\n");
445 out.push_str("const StrRet = @import(\"js_runtime/string.zig\").StrRet;\n");
446 out.push('\n');
447 out.push_str("// Tier-3 runtime library imports\n");
448 out.push_str("const js_string = @import(\"js_runtime/js_string.zig\");\n");
449 out.push_str("const js_string_icu = @import(\"js_runtime/js_string_icu.zig\");\n");
450 out.push_str("const js_console = @import(\"js_runtime/js_console.zig\");\n");
451 out.push_str("const js_json = @import(\"js_runtime/js_json.zig\");\n");
452 out.push_str("const js_array = @import(\"js_runtime/js_array.zig\");\n");
453 out.push_str("const js_object = @import(\"js_runtime/js_object.zig\");\n");
454 out.push_str("const js_number = @import(\"js_runtime/js_number.zig\");\n");
455 out.push_str("const js_date = @import(\"js_runtime/js_date.zig\");\n");
456 out.push_str("const js_error = @import(\"js_runtime/js_error.zig\");\n");
457 out.push_str("const js_collections = @import(\"js_runtime/js_collections.zig\");\n");
458 if needs_regex {
459 out.push_str("const js_regexp = @import(\"js_runtime/js_regexp.zig\");\n");
460 out.push_str("const js_string_regex = @import(\"js_runtime/js_string_regex.zig\");\n");
461 }
462 out.push_str("const js_uri = @import(\"js_runtime/js_uri.zig\");\n");
463 out.push_str("const js_symbol = @import(\"js_runtime/js_symbol.zig\");\n");
464 out.push_str("const JsSymbol = @import(\"js_runtime/js_symbol.zig\").JsSymbol;\n");
465 out.push_str("const js_bigint = @import(\"js_runtime/js_bigint.zig\");\n");
466 out.push_str("const JsValue = @import(\"js_runtime/jsvalue.zig\").JsValue;\n");
467 out.push_str("const JsAny = @import(\"js_runtime/jsany.zig\").JsAny;\n");
468 out.push_str("const js_runtime = @import(\"js_runtime/js_runtime.zig\");\n");
469 out.push('\n');
470}
471
472fn generate_module_zig(
487 module: &PerFileModule,
488 async_host_fn_names: &[String],
489 needs_regex: bool,
490) -> String {
491 let mut out = String::new();
492 out.push_str(&format!("// Auto-generated from {}.js\n", module.mod_name));
493 push_runtime_imports(&mut out, needs_regex);
494
495 let needs_host = module.zig_code.contains("host.") || !async_host_fn_names.is_empty();
497 let needs_host_regex = needs_regex && module.zig_code.contains("host_regex.");
498 if needs_host || needs_host_regex {
499 out.push_str("// Host functions (Rust via C ABI)\n");
500 if needs_host {
501 out.push_str("const host = @import(\"host.zig\");\n");
502 }
503 if needs_host_regex {
504 out.push_str("const host_regex = @import(\"host_regex.zig\");\n");
505 }
506 for name in async_host_fn_names {
508 out.push_str(&format!("const {} = host.{}_async;\n", name, name));
509 }
510 out.push('\n');
511 }
512
513 let mut dep_modules: Vec<String> = Vec::new();
515 let mut seen_modules: HashSet<&str> = HashSet::new();
516 for (_, src_mod) in &module.dep_imports {
517 if seen_modules.insert(src_mod) {
518 dep_modules.push(src_mod.clone());
519 }
520 }
521
522 if !dep_modules.is_empty() {
523 out.push_str("// --- Dependency module imports ---\n");
524 for mod_name in &dep_modules {
525 out.push_str(&format!(
526 "const {} = @import(\"{}.zig\");\n",
527 mod_name, mod_name
528 ));
529 }
530 out.push('\n');
531
532 out.push_str("// --- Imported name aliases ---\n");
533 for (name, src_mod) in &module.dep_imports {
534 out.push_str(&format!("const {name} = {mod}.{name};\n", name = name, mod = src_mod));
535 }
536 out.push('\n');
537 }
538
539 out.push_str(&module.zig_code);
543 out
544}
545
546fn generate_orchestrator_lib(opts: &ProjectOptions) -> String {
550 let mut out = String::new();
551 out.push_str("// Auto-generated by js2rust (orchestrator)\n");
552 push_runtime_imports(&mut out, opts.needs_regex);
553
554 if !opts.host_header.is_empty() || !opts.async_host_fn_names.is_empty() {
556 out.push_str("// User-defined host functions (Rust via C ABI)\n");
557 out.push_str("const host = @import(\"host.zig\");\n");
558 out.push('\n');
559 }
560 if opts.needs_regex {
561 out.push_str("// Host regex functions (Rust via C ABI)\n");
562 out.push_str("const host_regex = @import(\"host_regex.zig\");\n");
563 out.push('\n');
564 }
565
566 out.push_str("// Windows stub for Zig std.debug.SelfInfo.Windows\n");
571 out.push_str("// Uses raw types (u32/i32) to avoid importing std.os.windows on non-Windows.\n");
572 out.push_str("pub export fn LdrRegisterDllNotification(\n");
573 out.push_str(" Flags: u32,\n");
574 out.push_str(" NotificationFunction: ?*const anyopaque,\n");
575 out.push_str(" Context: ?*anyopaque,\n");
576 out.push_str(" Cookie: *?*anyopaque,\n");
577 out.push_str(") callconv(.c) i32 {\n");
578 out.push_str(" _ = Flags;\n");
579 out.push_str(" _ = NotificationFunction;\n");
580 out.push_str(" _ = Context;\n");
581 out.push_str(" Cookie.* = @ptrFromInt(1);\n");
582 out.push_str(" return 0; // STATUS_SUCCESS\n");
583 out.push_str("}\n\n");
584
585 if !opts.async_host_fn_names.is_empty() {
587 out.push_str("// Async host function aliases\n");
588 for name in &opts.async_host_fn_names {
589 out.push_str(&format!("const {} = host.{}_async;\n", name, name));
590 }
591 out.push('\n');
592 }
593
594 out.push_str("// Per-file module imports\n");
597 for module in &opts.per_file_code {
598 out.push_str(&format!(
599 "const _{} = @import(\"{}.zig\");\n",
600 module.mod_name, module.mod_name
601 ));
602 }
603 out.push('\n');
604
605 out.push_str("/// Initialize the global allocator used by all generated functions.\n");
607 out.push_str("/// The allocator is created internally using ArenaAllocator (Zig 0.16.0: lock-free, thread-safe).\n");
608 out.push_str("pub fn init_js2rust() !void {\n");
609 out.push_str(" try js_allocator.init(null, null);\n");
610 out.push_str(" js_runtime.initIo(js_allocator.allocator());\n");
611 for module in &opts.per_file_code {
613 if module.zig_code.contains("pub fn init_js2rust") {
614 out.push_str(&format!(" try _{}.init_js2rust();\n", module.mod_name));
615 }
616 }
617 out.push_str("}\n\n");
618 out.push_str("/// Initialize with ArenaAllocator (lock-free, thread-safe).\n");
620 out.push_str("/// Call this from Rust via C ABI before using any function that allocates.\n");
621 out.push_str("pub export fn js2rust_init() void {\n");
622 out.push_str(" init_js2rust() catch @panic(\"init_js2rust failed\");\n");
623 out.push_str("}\n\n");
624 out.push_str("/// Release global resources. Call this when done.\n");
625 out.push_str("pub export fn js2rust_deinit() void {\n");
626 out.push_str(" deinit_js2rust();\n");
627 out.push_str("}\n\n");
628 out.push_str(
629 "/// Allocate memory in Zig's Arena for zero-copy string returns from Rust host functions.\n",
630 );
631 out.push_str(
632 "/// Called from Rust via extern \"C\" { fn js_allocator_alloc(size: usize) -> ?*mut u8; }\n",
633 );
634 out.push_str("/// Memory is managed by the multi-arena allocator — no free needed.\n");
635 out.push_str("/// Returns null on OOM instead of panicking.\n");
636 out.push_str("pub export fn js_allocator_alloc(size: usize) ?[*]u8 {\n");
637 out.push_str(" const buf = js_allocator.allocBytes(size) catch return null;\n");
638 out.push_str(" return buf.ptr;\n");
639 out.push_str("}\n\n");
640 out.push_str("/// Allocate + copy in Zig Arena — single call for zero-copy string returns.\n");
641 out.push_str(
642 "/// Called from Rust via extern \"C\" { fn js_allocator_dupe(src: *const u8, len: usize) -> ?*mut u8; }\n",
643 );
644 out.push_str("/// Prefer this over js_allocator_alloc + manual copy — avoids a separate memcpy in Rust.\n");
645 out.push_str("/// Returns null on OOM instead of panicking.\n");
646 out.push_str("pub export fn js_allocator_dupe(src: [*]const u8, len: usize) ?[*]u8 {\n");
647 out.push_str(" const buf = js_allocator.dupeBytes(src[0..len]) catch return null;\n");
648 out.push_str(" return buf.ptr;\n");
649 out.push_str("}\n\n");
650 out.push_str("/// Release global resources allocated via init_js2rust.\n");
651 out.push_str("pub fn deinit_js2rust() void {\n");
652 out.push_str(" js_runtime.deinitIo();\n");
653 for module in &opts.per_file_code {
654 if module.zig_code.contains("pub fn deinit_js2rust") {
655 out.push_str(&format!(" _{}.deinit_js2rust();\n", module.mod_name));
656 }
657 }
658 out.push_str(" js_allocator.deinit();\n");
659 out.push_str("}\n\n");
660
661 let cabi_string_fns = collect_cabi_string_fns(&opts.per_file_code);
664
665 if !opts.external_exports.is_empty() {
667 out.push_str("// Re-export all public exports from per-file modules\n");
668 let mut exported: HashSet<&str> = HashSet::new();
669
670 for (cabi_name, mod_name, bare_name) in &opts.external_exports {
671 if !exported.insert(cabi_name.as_str()) {
672 continue;
673 }
674 if opts.cabi_names.contains(cabi_name.as_str()) {
677 continue;
678 }
679 if cabi_string_fns.contains(bare_name.as_str()) {
680 out.push_str(&format!(
684 "pub fn {cabi}(s: []const u8) []const u8 {{\n return std.mem.sliceTo(_{mod}.{bare}(@ptrCast(s.ptr)), 0);\n}}\n",
685 cabi = cabi_name,
686 mod = mod_name,
687 bare = bare_name,
688 ));
689 } else {
690 out.push_str(&format!(
691 "pub const {cabi} = _{mod}.{bare};\n",
692 cabi = cabi_name,
693 mod = mod_name,
694 bare = bare_name,
695 ));
696 }
697 }
698 out.push('\n');
699 }
700
701 if !opts.cabi_wrapper_code.is_empty() {
704 out.push_str("// C ABI exports (pub export fn wrappers)\n");
705 out.push_str(&opts.cabi_wrapper_code);
706 out.push('\n');
707 }
708
709 if !opts.test_code.trim().is_empty() {
711 out.push_str(&opts.test_code);
712 out.push('\n');
713 }
714
715 out
716}
717
718fn collect_cabi_string_fns(per_file_code: &[PerFileModule]) -> HashSet<String> {
721 let mut fns = HashSet::new();
722 for module in per_file_code {
723 for line in module.zig_code.lines() {
724 let trimmed = line.trim();
725 if (trimmed.starts_with("pub export fn ") || trimmed.starts_with("pub fn "))
727 && trimmed.contains("StrRet")
728 && let Some(open_paren) = trimmed.find('(')
729 {
730 let prefix_end = if trimmed.starts_with("pub export fn ") {
732 "pub export fn ".len()
733 } else {
734 "pub fn ".len()
735 };
736 let name = trimmed[prefix_end..open_paren].trim();
737 fns.insert(name.to_string());
738 }
739 }
740 }
741 fns
742}
743
744fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
746 fs::create_dir_all(dst).map_err(|e| format!("create dir {}: {}", dst.display(), e))?;
747
748 for entry in fs::read_dir(src).map_err(|e| format!("read dir {}: {}", src.display(), e))? {
749 let entry = entry.map_err(|e| format!("read entry: {}", e))?;
750 let src_path = entry.path();
751 let dst_path = dst.join(entry.file_name());
752
753 if src_path.is_dir() {
754 copy_dir_recursive(&src_path, &dst_path)?;
755 } else if src_path.is_file() {
756 fs::copy(&src_path, &dst_path)
757 .map_err(|e| format!("copy {}: {}", src_path.display(), e))?;
758 }
759 }
760
761 Ok(())
762}
763
764pub fn generate_host_icu_stubs() -> String {
769 r#"//! Stub implementations of host C ABI ICU functions for zig test.
770//! These provide linkable symbols so that zig test can produce a standalone
771//! test binary without the Rust-side implementations. The real implementations
772//! live in js2rust-bridge (native_icu.rs) and are linked when Rust drives
773//! the final executable build. These stubs are only used by `zig build test`.
774
775const JsStr = extern struct { ptr: [*]const u8, len: isize };
776
777export fn host_icu_locale_compare(
778 a_ptr: [*]const u8,
779 a_len: usize,
780 b_ptr: [*]const u8,
781 b_len: usize,
782) callconv(.c) i64 {
783 _ = a_ptr;
784 _ = a_len;
785 _ = b_ptr;
786 _ = b_len;
787 return 0;
788}
789
790export fn host_icu_normalize(
791 input_ptr: [*]const u8,
792 input_len: usize,
793 form_ptr: [*]const u8,
794 form_len: usize,
795) callconv(.c) JsStr {
796 _ = input_ptr;
797 _ = input_len;
798 _ = form_ptr;
799 _ = form_len;
800 return .{ .ptr = undefined, .len = 0 };
801}
802
803export fn host_icu_to_locale_upper_case(
804 input_ptr: [*]const u8,
805 input_len: usize,
806) callconv(.c) JsStr {
807 _ = input_ptr;
808 _ = input_len;
809 return .{ .ptr = undefined, .len = 0 };
810}
811
812export fn host_icu_to_locale_lower_case(
813 input_ptr: [*]const u8,
814 input_len: usize,
815) callconv(.c) JsStr {
816 _ = input_ptr;
817 _ = input_len;
818 return .{ .ptr = undefined, .len = 0 };
819}
820"#
821 .to_string()
822}
823
824fn generate_js_string_icu_icu() -> String {
828 r#"//! JS String ICU-dependent method implementations for Zig (ICU4X version).
829//! These functions rely on host_icu_* C ABI symbols provided by
830//! js2rust-bridge (native_icu.rs) at link time.
831//!
832//! This file overwrites the simplified runtime version when needs_icu = true.
833
834const std = @import("std");
835const Allocator = std.mem.Allocator;
836const JsAny = @import("jsany.zig").JsAny;
837
838// ── Host C ABI function declarations ──
839
840extern fn host_icu_locale_compare(
841 a_ptr: [*]const u8,
842 a_len: usize,
843 b_ptr: [*]const u8,
844 b_len: usize,
845) callconv(.c) i64;
846
847extern fn host_icu_normalize(
848 input_ptr: [*]const u8,
849 input_len: usize,
850 form_ptr: [*]const u8,
851 form_len: usize,
852) callconv(.c) extern struct { ptr: [*]const u8, len: isize };
853
854extern fn host_icu_to_locale_upper_case(
855 input_ptr: [*]const u8,
856 input_len: usize,
857) callconv(.c) extern struct { ptr: [*]const u8, len: isize };
858
859extern fn host_icu_to_locale_lower_case(
860 input_ptr: [*]const u8,
861 input_len: usize,
862) callconv(.c) extern struct { ptr: [*]const u8, len: isize };
863
864/// Locale-sensitive string comparison via ICU4X Collator.
865/// Returns -1 if self < other, 0 if equal, 1 if self > other.
866pub fn localeCompare(a: []const u8, b: []const u8) i64 {
867 return host_icu_locale_compare(a.ptr, a.len, b.ptr, b.len);
868}
869
870/// Normalize Unicode string using ICU4X Normalizer.
871/// Supports NFC (default), NFD, NFKC, NFKD normalization forms.
872pub fn normalize(alloc: Allocator, s: []const u8, form: []const u8) ![]const u8 {
873 const result = host_icu_normalize(s.ptr, s.len, form.ptr, form.len);
874 if (result.len == 0) return &[0]u8{};
875 const bytes = result.ptr[0..@intCast(result.len)];
876 return try alloc.dupe(u8, bytes);
877}
878
879/// Convert string to locale-specific uppercase via ICU4X CaseMapper.
880pub fn toLocaleUpper(alloc: Allocator, s: []const u8) ![]const u8 {
881 const result = host_icu_to_locale_upper_case(s.ptr, s.len);
882 if (result.len == 0) return &[0]u8{};
883 const bytes = result.ptr[0..@intCast(result.len)];
884 return try alloc.dupe(u8, bytes);
885}
886
887/// Convert string to locale-specific lowercase via ICU4X CaseMapper.
888pub fn toLocaleLower(alloc: Allocator, s: []const u8) ![]const u8 {
889 const result = host_icu_to_locale_lower_case(s.ptr, s.len);
890 if (result.len == 0) return &[0]u8{};
891 const bytes = result.ptr[0..@intCast(result.len)];
892 return try alloc.dupe(u8, bytes);
893}
894"#
895 .to_string()
896}