1use crate::analyzer::{analyze_single_group, sanitize_module_name};
2use crate::{ProjectConfig, ProjectResult};
3use std::collections::{HashMap, HashSet};
4use std::fs;
5use std::hash::{Hash, Hasher};
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9fn workspace_dir() -> PathBuf {
11 Path::new(env!("CARGO_MANIFEST_DIR"))
12 .parent()
13 .expect("CARGO_MANIFEST_DIR must have a parent directory (workspace root)")
14 .to_path_buf()
15}
16
17fn build_dep_imports(filename: &str, group: &crate::analyzer::FileGroup) -> Vec<(String, String)> {
21 let empty = Vec::new();
22 let raw_imports = group.imported_names.get(filename).unwrap_or(&empty);
23 raw_imports
24 .iter()
25 .map(|(imported_name, src_file)| {
26 let mod_name = group
27 .name_map
28 .get(src_file.as_str())
29 .cloned()
30 .unwrap_or_else(|| {
31 let stem = src_file.strip_suffix(".js").unwrap_or(src_file);
32 sanitize_module_name(stem)
33 });
34 (imported_name.clone(), mod_name)
35 })
36 .collect()
37}
38
39fn scan_pub_functions(zig_code: &str) -> Vec<String> {
43 let mut fns = Vec::new();
44 for line in zig_code.lines() {
45 let trimmed = line.trim();
46 let rest = if let Some(r) = trimmed.strip_prefix("pub export fn ") {
47 r
48 } else if let Some(r) = trimmed.strip_prefix("pub fn ") {
49 r
50 } else {
51 continue;
52 };
53 if let Some(paren) = rest.find('(') {
54 let name = rest[..paren].trim().to_string();
55 if name != "init_js2rust" && name != "deinit_js2rust" {
57 fns.push(name);
58 }
59 }
60 }
61 fns
62}
63
64fn compute_group_hash(
67 in_dir: &Path,
68 group: &crate::analyzer::FileGroup,
69 runtime_dir: &Path,
70) -> String {
71 let mut hasher = std::hash::DefaultHasher::new();
72
73 let mut members: Vec<&String> = group.members.iter().collect();
75 members.sort();
76 for member in &members {
77 member.hash(&mut hasher);
78 if let Ok(content) = fs::read(in_dir.join(member)) {
79 content.hash(&mut hasher);
80 }
81 }
82
83 if let Ok(entries) = fs::read_dir(runtime_dir) {
85 let mut rt_files: Vec<PathBuf> = entries
86 .filter_map(|e| e.ok())
87 .map(|e| e.path())
88 .filter(|p| p.extension().is_some_and(|ext| ext == "zig"))
89 .collect();
90 rt_files.sort();
91 for rt_file in &rt_files {
92 if let Ok(content) = fs::read(rt_file) {
93 rt_file.file_name().hash(&mut hasher);
94 content.hash(&mut hasher);
95 }
96 }
97 }
98
99 format!("{:016x}", hasher.finish())
100}
101
102fn read_build_cache(out_dir: &Path) -> HashMap<String, String> {
105 let cache_path = out_dir.join(".build_cache.json");
106 if let Ok(data) = fs::read_to_string(&cache_path)
107 && let Ok(map) = serde_json::from_str(&data)
108 {
109 return map;
110 }
111 HashMap::new()
112}
113
114fn write_build_cache(out_dir: &Path, cache: &HashMap<String, String>) {
116 let cache_path = out_dir.join(".build_cache.json");
117 if let Ok(json) = serde_json::to_string_pretty(cache) {
118 let _ = fs::write(cache_path, json);
119 }
120}
121
122pub fn transpile_project(config: &ProjectConfig) -> Result<ProjectResult, String> {
123 let ws = workspace_dir();
124
125 let js_file = &config.js_file;
127 let in_path = js_file
128 .parent()
129 .ok_or_else(|| format!("cannot get parent directory of '{}'", js_file.display()))?
130 .to_path_buf();
131 let core_file = js_file
132 .file_name()
133 .and_then(|n| n.to_str())
134 .ok_or_else(|| format!("invalid file name in '{}'", js_file.display()))?
135 .to_string();
136
137 let in_dir = in_path.to_string_lossy().to_string();
138 let out_dir: String = config.out_dir.to_string_lossy().to_string();
139 let force_rebuild = config.force_rebuild;
140
141 fs::create_dir_all(&out_dir)
143 .map_err(|e| format!("cannot create output directory '{}': {}", out_dir, e))?;
144
145 let additional_js_files: Vec<String> = config
147 .additional_js_files
148 .iter()
149 .filter_map(|p| {
150 p.file_name()
151 .and_then(|n| n.to_str())
152 .map(|s| s.to_string())
153 })
154 .collect();
155 let (groups, groups_json) = analyze_single_group(&in_dir, &core_file, &additional_js_files);
156
157 let groups_json_path = Path::new(&out_dir).join("groups.json");
158 if let Err(e) = fs::write(&groups_json_path, &groups_json) {
159 eprintln!(
160 "warning: could not write '{}': {}",
161 groups_json_path.display(),
162 e
163 );
164 } else {
165 println!("Wrote: {}/groups.json", out_dir);
166 }
167
168 if groups.is_empty() {
169 return Err(format!("no groups derived from core file '{}'", core_file));
170 }
171
172 let mut host_fns = crate::host::HostFnRegistry::new();
174
175 if let Some(ref host_config) = config.host_config {
177 for f in &host_config.functions {
179 let params: Vec<(String, crate::native_proto::ZigType)> = f
180 .params
181 .iter()
182 .enumerate()
183 .map(|(i, t)| (format!("arg{}", i), crate::native_proto::ZigType::from(*t)))
184 .collect();
185
186 if f.is_async {
187 if f.async_return_fields.is_empty() {
188 let return_type = f
190 .return_type
191 .map(crate::native_proto::ZigType::from)
192 .unwrap_or(crate::native_proto::ZigType::Void);
193 host_fns.register_async_simple(&f.name, &f.name, params, return_type);
194 } else {
195 let zig_name = f.struct_zig_name();
197 let c_name = f.struct_c_name();
198 let fields: Vec<crate::host::HostStructField> = f
199 .async_return_fields
200 .iter()
201 .map(|(name, ty)| crate::host::HostStructField {
202 name: name.clone(),
203 zig_type: ty.to_zig_field_type().to_string(),
204 c_type: ty.to_c_field_type().to_string(),
205 })
206 .collect();
207 let struct_def = crate::host::HostStructDef {
208 zig_name,
209 c_name,
210 fields,
211 };
212 host_fns.register_async(&f.name, &f.name, params, struct_def);
213 }
214 } else {
215 let return_type = f.return_type.map(crate::native_proto::ZigType::from);
216 host_fns.register(
217 &f.name,
218 params,
219 return_type.unwrap_or(crate::native_proto::ZigType::Void),
220 );
221 }
222 }
223 } else {
224 let config_path = ws.join("host_config.json");
226 if config_path.exists() {
227 match crate::host::HostFnRegistry::load_from_file(&config_path) {
228 Ok(registry) => {
229 host_fns = registry;
230 }
231 Err(e) => {
232 return Err(e);
233 }
234 }
235 } else {
236 }
238 };
239
240 let mut builtins = crate::builtins::BuiltinRegistry::new();
241 builtins.register_host_fns(&host_fns);
242 let host_header = host_fns.generate_zig_header();
243 let async_host_fn_names: Vec<String> = host_fns.async_fn_names();
244 let runtime_dir = ws.join("runtime").to_string_lossy().to_string();
245
246 let mut build_cache = read_build_cache(Path::new(&out_dir));
248 let runtime_path = ws.join("runtime");
249 let mut group_results: Vec<crate::GroupResult> = Vec::new();
250
251 for (group_idx, group) in groups.iter().enumerate() {
254 let is_test_group = group.core_name.starts_with("test_");
255 println!(
256 "\n=== {} ({} member{}) {}===",
257 group.core_name,
258 group.members.len(),
259 if group.members.len() == 1 { "" } else { "s" },
260 if is_test_group { "[test] " } else { "" }
261 );
262
263 let current_hash = compute_group_hash(&in_path, group, &runtime_path);
265 if !force_rebuild
266 && let Some(cached_hash) = build_cache.get(&group.core_name)
267 && *cached_hash == current_hash
268 {
269 println!(" unchanged, skipping (use --force to rebuild)");
270 let cabi_path = Path::new(&out_dir)
272 .join(&group.core_name)
273 .join("cabi_exports.json");
274 let cabi_json = fs::read_to_string(&cabi_path).unwrap_or_default();
275 group_results.push(crate::GroupResult {
276 name: group.core_name.clone(),
277 is_test: is_test_group,
278 cabi_exports_json: cabi_json,
279 diagnostics: Vec::new(), output_files: Vec::new(),
281 });
282 continue;
283 }
284
285 {
286 let mut per_file_modules: Vec<crate::project::PerFileModule> = Vec::new();
287 let mut all_module_exports: Vec<(String, String)> = Vec::new();
288 let mut all_test_code = String::new();
289 let mut combined_zig = String::new();
290 let mut all_cabi_exports: Vec<crate::native_proto::NativeCabiExport> = Vec::new();
291 let mut all_source_maps: Vec<crate::sourcemap::SourceMap> = Vec::new();
292 let mut has_error = false;
293 let mut file_diagnostics: Vec<String> = Vec::new();
294
295 let core_exports = group
297 .exported_names
298 .get(&group.core_file)
299 .cloned()
300 .unwrap_or_default();
301
302 let core_imports = group
304 .imported_names
305 .get(&group.core_file)
306 .cloned()
307 .unwrap_or_default();
308 let mut dep_re_exports: HashMap<String, HashSet<String>> = HashMap::new();
309 for (imported_name, source_file) in &core_imports {
310 if core_exports.contains(imported_name) {
311 dep_re_exports
312 .entry(source_file.clone())
313 .or_default()
314 .insert(imported_name.clone());
315 }
316 }
317
318 let additional_core_set: HashSet<String> =
320 additional_js_files.iter().cloned().collect();
321
322 for member in &group.members {
323 let src = match group.file_sources.get(member) {
324 Some(s) => s.clone(),
325 None => {
326 eprintln!(" skip '{}': no cached source", member);
327 continue;
328 }
329 };
330
331 if src.trim().is_empty() {
332 eprintln!(" skip '{}': empty source", member);
333 continue;
334 }
335
336 let module_name = group.name_map.get(member).cloned().unwrap_or_else(|| {
337 let stem = member.strip_suffix(".js").unwrap_or(member);
338 sanitize_module_name(stem)
339 });
340
341 let codegen_exports: HashSet<String> = if is_test_group {
346 group.all_fn_names.get(member).cloned().unwrap_or_default()
347 } else if *member == group.core_file || additional_core_set.contains(member) {
348 group
349 .exported_names
350 .get(member)
351 .cloned()
352 .unwrap_or_default()
353 } else {
354 dep_re_exports.get(member).cloned().unwrap_or_default()
355 };
356
357 let mut host_return_types: std::collections::HashMap<
359 String,
360 crate::native_proto::ZigType,
361 > = std::collections::HashMap::new();
362 let mut host_param_types: std::collections::HashMap<
363 String,
364 Vec<crate::native_proto::ZigType>,
365 > = std::collections::HashMap::new();
366 for def in host_fns.iter() {
367 host_return_types.insert(def.name.clone(), def.ret_type.clone());
368 host_param_types.insert(
369 def.name.clone(),
370 def.params.iter().map(|(_, t)| t.clone()).collect(),
371 );
372 }
373 let _host_struct_fields = host_fns.struct_fields_map();
374
375 let _async_fns: std::collections::HashSet<String> =
376 host_fns.async_fn_names().into_iter().collect();
377
378 let exports_for_all_modules = codegen_exports.clone();
381
382 let program = match group.parsed_programs.get(member) {
383 Some(p) => p,
384 None => {
385 eprintln!(" skip '{}': no parsed program in group", member);
386 continue;
387 }
388 };
389
390 let transpile_result =
391 crate::native_proto::transpile_js(program, &src, Some(codegen_exports), Some(&host_fns));
392
393 let (zig_code, diagnostics, closure_fns, fn_return_types, cabi_exports, source_map) =
394 match transpile_result {
395 Ok(result) => {
396 let mut diagnostics: Vec<crate::native_proto::Diagnostic> = result
398 .errors
399 .iter()
400 .map(|err| crate::native_proto::Diagnostic {
401 kind: crate::native_proto::DiagnosticKind::Error,
402 span: None,
403 message: err.clone(),
404 })
405 .collect();
406 diagnostics.extend(result.warnings.iter().map(|w| {
408 crate::native_proto::Diagnostic {
409 kind: crate::native_proto::DiagnosticKind::Warning,
410 span: None,
411 message: w.clone(),
412 }
413 }));
414
415 let cabi_exports = result.cabi_exports;
417
418 let closure_fns: std::collections::HashSet<String> =
420 std::collections::HashSet::new();
421
422 let fn_return_types: std::collections::HashMap<
424 String,
425 crate::native_proto::ZigType,
426 > = result
427 .var_types
428 .iter()
429 .map(|(k, v)| (k.clone(), v.clone()))
430 .collect();
431
432 let source_map = crate::sourcemap::SourceMap::new("");
434
435 (
436 result.zig_code,
437 diagnostics,
438 closure_fns,
439 fn_return_types,
440 cabi_exports,
441 source_map,
442 )
443 }
444 Err(e) => {
445 let diagnostics = vec![crate::native_proto::Diagnostic {
447 kind: crate::native_proto::DiagnosticKind::Error,
448 span: None,
449 message: e,
450 }];
451 (
452 String::new(),
453 diagnostics,
454 HashSet::new(),
455 HashMap::new(),
456 Vec::<crate::native_proto::NativeCabiExport>::new(),
457 crate::sourcemap::SourceMap::new(""),
458 )
459 }
460 };
461
462 let has_file_error = diagnostics
463 .iter()
464 .any(|d| d.kind == crate::native_proto::DiagnosticKind::Error);
465 if has_file_error {
466 let err_count = diagnostics
467 .iter()
468 .filter(|d| d.kind == crate::native_proto::DiagnosticKind::Error)
469 .count();
470 eprintln!(" skip '{}': {} codegen error(s)", member, err_count);
471 for diag in &diagnostics {
472 if diag.kind == crate::native_proto::DiagnosticKind::Error {
473 eprintln!(" {}", diag.message.as_str());
474 file_diagnostics.push(format!("{}: ERROR - {}", member, diag.message));
475 }
476 }
477 has_error = true;
478 break;
479 }
480
481 if !diagnostics.is_empty() {
482 eprintln!(" '{}': {} diagnostic(s)", member, diagnostics.len());
483 for diag in &diagnostics {
484 eprintln!(" {}", diag.message.as_str());
485 file_diagnostics.push(format!("{}: {}", member, diag.message));
486 }
487 }
488
489 for exp in &exports_for_all_modules {
490 all_module_exports.push((exp.clone(), module_name.clone()));
491 }
492 for fn_name in scan_pub_functions(&zig_code) {
494 if !exports_for_all_modules.contains(&fn_name) {
495 all_module_exports.push((fn_name, module_name.clone()));
496 }
497 }
498
499 let dep_imports = build_dep_imports(member, group);
500
501 per_file_modules.push(crate::project::PerFileModule {
502 mod_name: module_name.clone(),
503 zig_code: zig_code.to_string(),
504 dep_imports,
505 });
506
507 combined_zig.push_str(&zig_code);
508 if !source_map.mappings.is_empty() {
509 all_source_maps.push(source_map);
510 }
511
512 all_cabi_exports.extend(cabi_exports);
514
515 if is_test_group {
516 let test_cases = crate::testgen::extract_test_cases(program, &src);
519 let closure_fn_refs: HashSet<&str> =
520 closure_fns.iter().map(|s| s.as_str()).collect();
521 let ret_type_map: HashMap<String, String> = fn_return_types
522 .iter()
523 .map(|(k, v)| (k.clone(), v.to_zig_type()))
524 .collect();
525 let file_test_code = crate::testgen::generate_test_code(
526 &test_cases,
527 &closure_fn_refs,
528 &ret_type_map,
529 );
530 all_test_code.push_str(&file_test_code);
531 }
532 }
533
534 if has_error {
535 continue;
536 }
537
538 if per_file_modules.is_empty() {
539 eprintln!(" skip: no valid modules after codegen");
540 continue;
541 }
542
543 let mut name_to_module: HashMap<&str, &str> = HashMap::new();
545 for (exp_name, mod_name) in &all_module_exports {
546 name_to_module.entry(exp_name).or_insert(mod_name);
547 }
548 let mut name_to_cabi: HashMap<&str, &crate::native_proto::NativeCabiExport> =
549 HashMap::new();
550 for exp in &all_cabi_exports {
551 name_to_cabi.entry(&exp.name).or_insert(exp);
552 }
553 let cabi_wrapper_code = gen_cabi_wrappers(&name_to_module, &name_to_cabi);
554 let cabi_names: HashSet<String> = name_to_cabi.keys().map(|&k| k.to_string()).collect();
555
556 let project_opts = crate::project::ProjectOptions {
557 name: group.core_name.clone(),
558 out_dir: out_dir.clone(),
559 per_file_code: per_file_modules,
560 external_exports: all_module_exports,
561 cabi_wrapper_code,
562 cabi_names,
563 test_code: all_test_code,
564 runtime_dir: Some(runtime_dir.clone()),
565 host_header: if combined_zig.contains("host.") || !async_host_fn_names.is_empty() {
566 host_header.clone()
567 } else {
568 String::new()
569 },
570 async_host_fn_names: async_host_fn_names.clone(),
571 include_windows_stub: group_idx == 0,
572 };
573
574 match crate::project::generate(&project_opts) {
575 Ok(()) => println!(" Generated: {}/{}", out_dir, group.core_name),
576 Err(e) => {
577 eprintln!(" FAIL ({})", e);
578 continue;
579 }
580 }
581
582 if !host_fns.is_empty() {
584 let host_zig_path = Path::new(&out_dir).join(&group.core_name).join("host.zig");
585 let host_zig_content = host_fns.generate_zig_header();
586 if let Err(e) = fs::write(&host_zig_path, &host_zig_content) {
587 eprintln!(" warning: failed to write host.zig: {}", e);
588 } else {
589 println!(
590 " Generated: {}/{}",
591 out_dir,
592 host_zig_path.file_name().unwrap().to_string_lossy()
593 );
594 }
595 }
596
597 if !all_source_maps.is_empty() {
599 let sm_path = Path::new(&out_dir)
600 .join(&group.core_name)
601 .join("source_map.json");
602 let sm_json = serde_json::json!({
603 "version": 1,
604 "generator": "js2rustc",
605 "files": all_source_maps
606 .iter()
607 .map(|sm| serde_json::json!({
608 "source": sm.source_file,
609 "mappings": sm.mappings.iter().map(|m| serde_json::json!({
610 "zig_line": m.zig_line,
611 "js_file": m.js_file,
612 "js_line": m.js_line,
613 "js_col": m.js_col,
614 "kind": m.kind,
615 })).collect::<Vec<_>>()
616 }))
617 .collect::<Vec<_>>()
618 });
619 if let Ok(json_str) = serde_json::to_string_pretty(&sm_json) {
620 let _ = std::fs::write(&sm_path, json_str);
621 }
622 }
623
624 let include_init = !is_test_group && group_idx == 0;
627 write_cabi_metadata(
628 Path::new(&out_dir),
629 &group.core_name,
630 &all_cabi_exports,
631 &host_fns,
632 include_init,
633 );
634
635 let cabi_path = Path::new(&out_dir)
637 .join(&group.core_name)
638 .join("cabi_exports.json");
639 let cabi_json = fs::read_to_string(&cabi_path).unwrap_or_default();
640
641 group_results.push(crate::GroupResult {
642 name: group.core_name.clone(),
643 is_test: is_test_group,
644 cabi_exports_json: cabi_json,
645 diagnostics: file_diagnostics.clone(),
646 output_files: Vec::new(),
647 });
648
649 }
651
652 if !config.run_zig_build {
654 continue;
656 }
657
658 let project_path = Path::new(&out_dir).join(&group.core_name);
659 let mut build_ok = false;
660 let build_result = Command::new("zig")
661 .arg("build")
662 .current_dir(&project_path)
663 .output();
664 match build_result {
665 Ok(result) if result.status.success() => {
666 println!(" zig build: OK");
667 build_ok = true;
668 }
669 Ok(result) => {
670 let stderr = String::from_utf8_lossy(&result.stderr);
671 eprintln!(" zig build FAILED:\n{}", stderr);
672 }
673 Err(_) => eprintln!(" warning: zig not found — skipping build"),
674 }
675
676 let mut test_ok = false;
678 let test_result = Command::new("zig")
679 .arg("build")
680 .arg("test")
681 .current_dir(&project_path)
682 .output();
683 match test_result {
684 Ok(result) if result.status.success() => {
685 println!(" zig test: PASSED");
686 test_ok = true;
687 }
688 Ok(result) => {
689 let stderr = String::from_utf8_lossy(&result.stderr);
690 eprintln!(" zig test FAILED:\n{}", stderr);
691 }
692 Err(_) => {}
693 }
694
695 if build_ok && test_ok {
697 build_cache.insert(group.core_name.clone(), current_hash.clone());
698 }
699 }
700
701 write_build_cache(Path::new(&out_dir), &build_cache);
703
704 let all_diagnostics: Vec<String> = group_results
705 .iter()
706 .flat_map(|g| g.diagnostics.clone())
707 .collect();
708
709 Ok(ProjectResult {
710 groups: group_results,
711 diagnostics: all_diagnostics,
712 })
713}
714
715pub fn gen_cabi_wrappers(
723 name_to_module: &HashMap<&str, &str>,
724 name_to_cabi: &HashMap<&str, &crate::native_proto::NativeCabiExport>,
725) -> String {
726 use std::collections::HashSet;
727
728 let mut out = String::new();
729 let mut emitted: HashSet<&str> = HashSet::new();
730
731 for (&name, exp) in name_to_cabi {
732 if !emitted.insert(name) {
733 continue;
734 }
735 let Some(&module) = name_to_module.get(name) else {
736 continue;
737 };
738
739 let returns_string = exp.ret_type == crate::native_proto::ZigType::Str;
740 let ret_is_js_any = exp.ret_type == crate::native_proto::ZigType::Anytype;
741
742 if ret_is_js_any {
745 out.push_str(&format!(
746 "pub const {name} = {mod}.{name};\n\n",
747 name = name,
748 mod = module,
749 ));
750 continue;
751 }
752
753 let has_js_obj_param = exp.params.iter().any(|(_, ty)| {
755 *ty == crate::native_proto::ZigType::Void
756 || *ty == crate::native_proto::ZigType::Anytype
757 });
758 if has_js_obj_param {
759 out.push_str(&format!(
761 "pub const {name} = {mod}.{name};\n\n",
762 name = name,
763 mod = module,
764 ));
765 continue;
766 }
767
768 let mut cabi_params: Vec<String> = Vec::new();
770 let mut zig_params: Vec<String> = Vec::new();
771 let mut arg_names: Vec<String> = Vec::new();
772 let mut cabi_to_zig_conversions: Vec<String> = Vec::new();
773
774 for (pname, ptype) in &exp.params {
775 arg_names.push(pname.clone());
776 if *ptype == crate::native_proto::ZigType::Str {
777 cabi_params.push(format!("{}: [*:0]const u8", pname));
778 zig_params.push(format!("{}: []const u8", pname));
779 cabi_to_zig_conversions.push(format!(
780 " const {p}_slice: []const u8 = std.mem.span({p});",
781 p = pname
782 ));
783 } else {
784 let zig_ty = ptype.to_zig_type();
785 cabi_params.push(format!("{}: {}", pname, zig_ty));
786 zig_params.push(format!("{}: {}", pname, zig_ty));
787 }
788 }
789
790 let zig_call_args: String = arg_names.join(", ");
792 let cabi_call_args: String = exp
793 .params
794 .iter()
795 .map(|(pname, ptype)| {
796 if *ptype == crate::native_proto::ZigType::Str {
797 format!("{}_slice", pname)
798 } else {
799 pname.clone()
800 }
801 })
802 .collect::<Vec<_>>()
803 .join(", ");
804
805 if exp.is_async {
807 let async_zig_args = if zig_call_args.is_empty() {
808 "js_runtime.getIo()".to_string()
809 } else {
810 format!("js_runtime.getIo(), {}", zig_call_args)
811 };
812 let async_cabi_args = if cabi_call_args.is_empty() {
813 "js_runtime.getIo()".to_string()
814 } else {
815 format!("js_runtime.getIo(), {}", cabi_call_args)
816 };
817
818 if returns_string {
819 out.push_str(&format!(
821 "pub fn {name}({params}) []const u8 {{\n return {mod}.{name}({args}) catch @panic(\"async error in {name}\");\n}}\n",
822 name = name,
823 params = zig_params.join(", "),
824 mod = module,
825 args = async_zig_args,
826 ));
827 let conversions = if cabi_to_zig_conversions.is_empty() {
829 String::new()
830 } else {
831 format!("{}\n", cabi_to_zig_conversions.join("\n"))
832 };
833 out.push_str(&format!(
834 "pub export fn {name}_cabi({cabi_params}) StrRet {{\n{conv} return StrRet.from({mod}.{name}({args}) catch |err| return StrRet.from_panic(err));\n}}\n",
835 name = name,
836 cabi_params = cabi_params.join(", "),
837 conv = conversions,
838 mod = module,
839 args = async_cabi_args,
840 ));
841 out.push_str(&format!(
842 "comptime {{ @export(&{name}_cabi, .{{ .name = \"{name}\", .linkage = .strong }}); }}\n",
843 name = name,
844 ));
845 } else {
846 let ret_zig = if exp.ret_type == crate::native_proto::ZigType::Void {
847 "void".to_string()
848 } else {
849 exp.ret_type.to_zig_type()
850 };
851 let exp_ret_is_js_value = exp.ret_type == crate::native_proto::ZigType::Void;
852 let conversions = if cabi_to_zig_conversions.is_empty() {
853 String::new()
854 } else {
855 format!("{}\n", cabi_to_zig_conversions.join("\n"))
856 };
857
858 let mut cabi_params_with_err = cabi_params.clone();
860 if exp.can_throw {
861 cabi_params_with_err.push("err_out: *?[*:0]const u8".to_string());
862 }
863 let cabi_params_str = cabi_params_with_err.join(", ");
864
865 let catch_clause = if exp.can_throw {
866 format!(
867 " catch |err| {{\n err_out.* = @errorName(err);\n return {default};\n }}",
868 default = if ret_zig == "void" { "".to_string() } else { "0".to_string() },
869 )
870 } else {
871 format!(" catch @panic(\"async error in {name}\")", name = name)
872 };
873
874 let err_setup = if exp.can_throw && ret_zig == "void" {
875 " err_out.* = null;\n"
876 } else {
877 ""
878 };
879
880 if ret_zig == "void" {
881 out.push_str(&format!(
882 "pub export fn {name}({params}) void {{\n{conv}{err_setup} {mod}.{name}({args}){catch_clause};\n}}\n",
883 name = name,
884 params = cabi_params_str,
885 conv = conversions,
886 err_setup = err_setup,
887 mod = module,
888 args = async_cabi_args,
889 catch_clause = catch_clause,
890 ));
891 } else if exp_ret_is_js_value {
892 out.push_str(&format!(
893 "pub export fn {name}({params}) i64 {{\n{conv} const _result = {mod}.{name}({args}){catch_clause};\n return _result.int;\n}}\n",
894 name = name,
895 params = cabi_params_str,
896 conv = conversions,
897 mod = module,
898 args = async_cabi_args,
899 catch_clause = catch_clause,
900 ));
901 } else {
902 out.push_str(&format!(
903 "pub export fn {name}({params}) {ret} {{\n{conv} return {mod}.{name}({args}){catch_clause};\n}}\n",
904 name = name,
905 params = cabi_params_str,
906 conv = conversions,
907 ret = ret_zig,
908 mod = module,
909 args = async_cabi_args,
910 catch_clause = catch_clause,
911 ));
912 }
913 }
914
915 out.push('\n');
916 continue;
917 }
918
919 if returns_string {
920 let test_call = if exp.can_throw {
922 format!(
923 "{mod}.{name}({args}) catch @panic(\"error in {name}\")",
924 mod = module,
925 name = name,
926 args = zig_call_args,
927 )
928 } else {
929 format!("{mod}.{name}({args})", mod = module, name = name, args = zig_call_args)
930 };
931 out.push_str(&format!(
932 "pub fn {name}({params}) []const u8 {{\n return {test_call};\n}}\n",
933 name = name,
934 params = zig_params.join(", "),
935 test_call = test_call,
936 ));
937
938 let conversions = if cabi_to_zig_conversions.is_empty() {
940 String::new()
941 } else {
942 format!("{}\n", cabi_to_zig_conversions.join("\n"))
943 };
944 let cabi_call = if exp.can_throw {
945 format!(
946 "{mod}.{name}({args}) catch |err| return StrRet.from_panic(err)",
947 mod = module,
948 name = name,
949 args = cabi_call_args,
950 )
951 } else {
952 format!(
953 "{mod}.{name}({args})",
954 mod = module,
955 name = name,
956 args = cabi_call_args,
957 )
958 };
959 out.push_str(&format!(
960 "pub export fn {name}_cabi({cabi_params}) StrRet {{\n{conv} return StrRet.from({cabi_call});\n}}\n",
961 name = name,
962 cabi_params = cabi_params.join(", "),
963 conv = conversions,
964 cabi_call = cabi_call,
965 ));
966 out.push_str(&format!(
967 "comptime {{ @export(&{name}_cabi, .{{ .name = \"{name}\", .linkage = .strong }}); }}\n",
968 name = name,
969 ));
970 } else {
971 let ret_zig = if exp.ret_type == crate::native_proto::ZigType::Void {
972 "void".to_string()
973 } else {
974 exp.ret_type.to_zig_type()
975 };
976 let exp_ret_is_js_value = exp.ret_type == crate::native_proto::ZigType::Void;
977
978 let mut cabi_params_with_err = cabi_params.clone();
980 if exp.can_throw {
981 cabi_params_with_err.push("err_out: *?[*:0]const u8".to_string());
982 }
983 let cabi_params_str = cabi_params_with_err.join(", ");
984
985 let (call_expr, err_setup) = if exp.can_throw {
987 let err_handle = if ret_zig == "void" {
988 format!(
990 " {mod}.{name}({args}) catch |err| {{\n err_out.* = @errorName(err);\n return;\n }};",
991 mod = module,
992 name = name,
993 args = cabi_call_args,
994 )
995 } else {
996 format!(
997 " const _result = {mod}.{name}({args}) catch |err| {{\n err_out.* = @errorName(err);\n return 0;\n }};",
998 mod = module,
999 name = name,
1000 args = cabi_call_args,
1001 )
1002 };
1003 let setup = if ret_zig == "void" {
1004 " err_out.* = null;\n".to_string()
1005 } else {
1006 String::new()
1007 };
1008 (err_handle, setup)
1009 } else {
1010 (format!(
1011 "{mod}.{name}({args})",
1012 mod = module,
1013 name = name,
1014 args = cabi_call_args,
1015 ), String::new())
1016 };
1017
1018 let conversions = if cabi_to_zig_conversions.is_empty() {
1019 String::new()
1020 } else {
1021 format!("{}\n", cabi_to_zig_conversions.join("\n"))
1022 };
1023
1024 if ret_zig == "void" {
1025 if exp.can_throw {
1026 out.push_str(&format!(
1027 "pub export fn {name}({params}) void {{\n{conv}{err_setup}{call_expr}\n}}\n",
1028 name = name,
1029 params = cabi_params_str,
1030 conv = conversions,
1031 err_setup = err_setup,
1032 call_expr = call_expr,
1033 ));
1034 } else {
1035 out.push_str(&format!(
1036 "pub export fn {name}({params}) void {{\n{conv} {mod}.{name}({args});\n}}\n",
1037 name = name,
1038 params = cabi_params_str,
1039 conv = conversions,
1040 mod = module,
1041 args = cabi_call_args,
1042 ));
1043 }
1044 } else if exp_ret_is_js_value {
1045 if exp.can_throw {
1047 out.push_str(&format!(
1048 "pub export fn {name}({params}) i64 {{\n{conv}{call_expr}\n return _result.int;\n}}\n",
1049 name = name,
1050 params = cabi_params_str,
1051 conv = conversions,
1052 call_expr = call_expr,
1053 ));
1054 } else {
1055 out.push_str(&format!(
1056 "pub export fn {name}({params}) i64 {{\n{conv} const _result = {mod}.{name}({args});\n return _result.int;\n}}\n",
1057 name = name,
1058 params = cabi_params_str,
1059 conv = conversions,
1060 mod = module,
1061 args = cabi_call_args,
1062 ));
1063 }
1064 } else {
1065 if exp.can_throw {
1066 out.push_str(&format!(
1067 "pub export fn {name}({params}) {ret} {{\n{conv}{call_expr}\n return _result;\n}}\n",
1068 name = name,
1069 params = cabi_params_str,
1070 conv = conversions,
1071 ret = ret_zig,
1072 call_expr = call_expr,
1073 ));
1074 } else {
1075 out.push_str(&format!(
1076 "pub export fn {name}({params}) {ret} {{\n{conv} return {mod}.{name}({args});\n}}\n",
1077 name = name,
1078 params = cabi_params_str,
1079 ret = ret_zig,
1080 conv = conversions,
1081 mod = module,
1082 args = cabi_call_args,
1083 ));
1084 }
1085 }
1086 }
1087
1088 out.push('\n');
1089 }
1090
1091 out
1092}
1093
1094pub fn write_cabi_metadata(
1096 out_dir: &Path,
1097 group_name: &str,
1098 cabi_exports: &[crate::native_proto::NativeCabiExport],
1099 host_fns: &crate::host::HostFnRegistry,
1100 include_init: bool,
1101) {
1102 let project_dir = out_dir.join(group_name);
1103
1104 let exports_path = project_dir.join("cabi_exports.json");
1106 let mut exports_value: Vec<serde_json::Value> = cabi_exports
1107 .iter()
1108 .filter(|exp| exp.ret_type != crate::native_proto::ZigType::Anytype)
1109 .map(|exp| {
1110 let params: Vec<serde_json::Value> = exp
1112 .params
1113 .iter()
1114 .map(|(name, ty)| {
1115 serde_json::json!({
1116 "name": name,
1117 "zig_type": ty.to_zig_type()
1118 })
1119 })
1120 .collect();
1121
1122 let ret_type_str = exp.ret_type.to_cabi_str();
1126
1127 serde_json::json!({
1128 "name": exp.name,
1129 "params": params,
1130 "ret_type": ret_type_str,
1131 "can_throw": exp.can_throw,
1132 })
1133 })
1134 .collect();
1135
1136 if include_init {
1138 exports_value.push(serde_json::json!({
1139 "name": "js2rust_init",
1140 "params": [],
1141 "ret_type": "void",
1142 }));
1143 exports_value.push(serde_json::json!({
1144 "name": "js2rust_deinit",
1145 "params": [],
1146 "ret_type": "void",
1147 }));
1148 }
1149
1150 if let Ok(json_str) = serde_json::to_string_pretty(&exports_value) {
1151 let _ = fs::write(&exports_path, &json_str);
1152 }
1153
1154 let imports_path = project_dir.join("cabi_imports.json");
1156 let imports_value = host_fns.to_json_value();
1157 if let Ok(json_str) = serde_json::to_string_pretty(&imports_value) {
1158 let _ = fs::write(&imports_path, &json_str);
1159 }
1160}