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 eprintln!(
141 "DEBUG transpile_project: name='{}', force_rebuild={}, run_zig_build={}",
142 config.name, force_rebuild, config.run_zig_build
143 );
144
145 fs::create_dir_all(&out_dir)
147 .map_err(|e| format!("cannot create output directory '{}': {}", out_dir, e))?;
148
149 let additional_js_files: Vec<String> = config
151 .additional_js_files
152 .iter()
153 .filter_map(|p| {
154 p.file_name()
155 .and_then(|n| n.to_str())
156 .map(|s| s.to_string())
157 })
158 .collect();
159 let (groups, groups_json) = analyze_single_group(&in_dir, &core_file, &additional_js_files);
160
161 let groups_json_path = Path::new(&out_dir).join("groups.json");
162 if let Err(e) = fs::write(&groups_json_path, &groups_json) {
163 eprintln!(
164 "warning: could not write '{}': {}",
165 groups_json_path.display(),
166 e
167 );
168 } else {
169 println!("Wrote: {}/groups.json", out_dir);
170 }
171
172 if groups.is_empty() {
173 return Err(format!("no groups derived from core file '{}'", core_file));
174 }
175
176 let mut host_fns = crate::host::HostFnRegistry::new();
178
179 if let Some(ref host_config) = config.host_config {
181 for f in &host_config.functions {
183 let params: Vec<(String, crate::native_proto::ZigType)> = f
184 .params
185 .iter()
186 .enumerate()
187 .map(|(i, t)| (format!("arg{}", i), crate::native_proto::ZigType::from(*t)))
188 .collect();
189
190 if f.is_async {
191 if f.async_return_fields.is_empty() {
192 let return_type = f
194 .return_type
195 .map(crate::native_proto::ZigType::from)
196 .unwrap_or(crate::native_proto::ZigType::Void);
197 host_fns.register_async_simple(&f.name, &f.name, params, return_type);
198 } else {
199 let zig_name = f.struct_zig_name();
201 let c_name = f.struct_c_name();
202 let fields: Vec<crate::host::HostStructField> = f
203 .async_return_fields
204 .iter()
205 .map(|(name, ty)| crate::host::HostStructField {
206 name: name.clone(),
207 zig_type: ty.to_zig_field_type().to_string(),
208 c_type: ty.to_c_field_type().to_string(),
209 })
210 .collect();
211 let struct_def = crate::host::HostStructDef {
212 zig_name,
213 c_name,
214 fields,
215 };
216 host_fns.register_async(&f.name, &f.name, params, struct_def);
217 }
218 } else {
219 let return_type = f.return_type.map(crate::native_proto::ZigType::from);
220 host_fns.register(
221 &f.name,
222 params,
223 return_type.unwrap_or(crate::native_proto::ZigType::Void),
224 );
225 }
226 }
227 } else {
228 let config_path = ws.join("host_config.json");
230 if config_path.exists() {
231 match crate::host::HostFnRegistry::load_from_file(&config_path) {
232 Ok(registry) => {
233 host_fns = registry;
234 }
235 Err(e) => {
236 return Err(e);
237 }
238 }
239 } else {
240 }
242 };
243
244 let host_header = host_fns.generate_zig_header();
245 let async_host_fn_names: Vec<String> = host_fns.async_fn_names();
246 let runtime_dir = ws.join("runtime").to_string_lossy().to_string();
247
248 let mut build_cache = read_build_cache(Path::new(&out_dir));
250 let runtime_path = ws.join("runtime");
251 let mut group_results: Vec<crate::GroupResult> = Vec::new();
252
253 for (group_idx, group) in groups.iter().enumerate() {
256 let is_test_group = group.core_name.starts_with("test_");
257 println!(
258 "\n=== {} ({} member{}) {}===",
259 group.core_name,
260 group.members.len(),
261 if group.members.len() == 1 { "" } else { "s" },
262 if is_test_group { "[test] " } else { "" }
263 );
264
265 let current_hash = compute_group_hash(&in_path, group, &runtime_path);
267 eprintln!(
268 "DEBUG: group={}, force_rebuild={}, has_cache={}, hash_len={}",
269 group.core_name,
270 force_rebuild,
271 build_cache.contains_key(&group.core_name),
272 current_hash.len()
273 );
274 if !force_rebuild
275 && let Some(cached_hash) = build_cache.get(&group.core_name)
276 && *cached_hash == current_hash
277 {
278 eprintln!("DEBUG: SKIPPING (cache HIT)");
279 println!(" unchanged, skipping (use --force to rebuild)");
280 let cabi_path = Path::new(&out_dir)
282 .join(&group.core_name)
283 .join("cabi_exports.json");
284 let cabi_json = fs::read_to_string(&cabi_path).unwrap_or_default();
285 group_results.push(crate::GroupResult {
286 name: group.core_name.clone(),
287 is_test: is_test_group,
288 cabi_exports_json: cabi_json,
289 diagnostics: Vec::new(), output_files: Vec::new(),
291 });
292 continue;
293 }
294
295 {
296 let mut per_file_modules: Vec<crate::project::PerFileModule> = Vec::new();
297 let mut all_module_exports: Vec<(String, String)> = Vec::new();
298 let mut all_test_code = String::new();
299 let mut combined_zig = String::new();
300 let mut all_cabi_exports: Vec<crate::native_proto::NativeCabiExport> = Vec::new();
301 let mut all_source_maps: Vec<crate::sourcemap::SourceMap> = Vec::new();
302 let mut has_error = false;
303 let mut file_diagnostics: Vec<String> = Vec::new();
304
305 let core_exports = group
307 .exported_names
308 .get(&group.core_file)
309 .cloned()
310 .unwrap_or_default();
311
312 let core_imports = group
314 .imported_names
315 .get(&group.core_file)
316 .cloned()
317 .unwrap_or_default();
318 let mut dep_re_exports: HashMap<String, HashSet<String>> = HashMap::new();
319 for (imported_name, source_file) in &core_imports {
320 if core_exports.contains(imported_name) {
321 dep_re_exports
322 .entry(source_file.clone())
323 .or_default()
324 .insert(imported_name.clone());
325 }
326 }
327
328 let additional_core_set: HashSet<String> =
330 additional_js_files.iter().cloned().collect();
331
332 for member in &group.members {
333 let src = match group.file_sources.get(member) {
334 Some(s) => s.clone(),
335 None => {
336 eprintln!(" skip '{}': no cached source", member);
337 continue;
338 }
339 };
340
341 if src.trim().is_empty() {
342 eprintln!(" skip '{}': empty source", member);
343 continue;
344 }
345
346 let module_name = group.name_map.get(member).cloned().unwrap_or_else(|| {
347 let stem = member.strip_suffix(".js").unwrap_or(member);
348 sanitize_module_name(stem)
349 });
350
351 let codegen_exports: HashSet<String> = if is_test_group {
356 group.all_fn_names.get(member).cloned().unwrap_or_default()
357 } else if *member == group.core_file || additional_core_set.contains(member) {
358 group
359 .exported_names
360 .get(member)
361 .cloned()
362 .unwrap_or_default()
363 } else {
364 dep_re_exports.get(member).cloned().unwrap_or_default()
365 };
366
367 let mut host_return_types: std::collections::HashMap<
369 String,
370 crate::native_proto::ZigType,
371 > = std::collections::HashMap::new();
372 let mut host_param_types: std::collections::HashMap<
373 String,
374 Vec<crate::native_proto::ZigType>,
375 > = std::collections::HashMap::new();
376 for def in host_fns.iter() {
377 host_return_types.insert(def.name.clone(), def.ret_type.clone());
378 host_param_types.insert(
379 def.name.clone(),
380 def.params.iter().map(|(_, t)| t.clone()).collect(),
381 );
382 }
383 let _host_struct_fields = host_fns.struct_fields_map();
384
385 let _async_fns: std::collections::HashSet<String> =
386 host_fns.async_fn_names().into_iter().collect();
387
388 let exports_for_all_modules = codegen_exports.clone();
391
392 let program = match group.parsed_programs.get(member) {
393 Some(p) => p,
394 None => {
395 eprintln!(" skip '{}': no parsed program in group", member);
396 continue;
397 }
398 };
399
400 let transpile_result = crate::native_proto::transpile_js(
401 program,
402 &src,
403 Some(codegen_exports),
404 Some(&host_fns),
405 );
406
407 let (zig_code, diagnostics, closure_fns, fn_return_types, cabi_exports, source_map) =
408 match transpile_result {
409 Ok(result) => {
410 let mut diagnostics: Vec<crate::native_proto::Diagnostic> = result
412 .errors
413 .iter()
414 .map(|err| crate::native_proto::Diagnostic {
415 kind: crate::native_proto::DiagnosticKind::Error,
416 span: None,
417 message: err.clone(),
418 })
419 .collect();
420 diagnostics.extend(result.warnings.iter().map(|w| {
422 crate::native_proto::Diagnostic {
423 kind: crate::native_proto::DiagnosticKind::Warning,
424 span: None,
425 message: w.clone(),
426 }
427 }));
428
429 let cabi_exports = result.cabi_exports;
431
432 let closure_fns: std::collections::HashSet<String> =
434 std::collections::HashSet::new();
435
436 let fn_return_types: std::collections::HashMap<
438 String,
439 crate::native_proto::ZigType,
440 > = result
441 .var_types
442 .iter()
443 .map(|(k, v)| (k.clone(), v.clone()))
444 .collect();
445
446 let source_map = crate::sourcemap::SourceMap::new("");
448
449 (
450 result.zig_code,
451 diagnostics,
452 closure_fns,
453 fn_return_types,
454 cabi_exports,
455 source_map,
456 )
457 }
458 Err(e) => {
459 let diagnostics = vec![crate::native_proto::Diagnostic {
461 kind: crate::native_proto::DiagnosticKind::Error,
462 span: None,
463 message: e,
464 }];
465 (
466 String::new(),
467 diagnostics,
468 HashSet::new(),
469 HashMap::new(),
470 Vec::<crate::native_proto::NativeCabiExport>::new(),
471 crate::sourcemap::SourceMap::new(""),
472 )
473 }
474 };
475
476 let (hard_errors, soft_errors): (Vec<_>, Vec<_>) = diagnostics
477 .iter()
478 .filter(|d| d.kind == crate::native_proto::DiagnosticKind::Error)
479 .partition(|d| !d.message.contains("(Rule 8)"));
480 if !hard_errors.is_empty() {
481 let err_count = hard_errors.len();
482 eprintln!(" skip '{}': {} codegen error(s)", member, err_count);
483 for diag in &hard_errors {
484 eprintln!(" {}", diag.message.as_str());
485 file_diagnostics.push(format!("{}: ERROR - {}", member, diag.message));
486 }
487 for diag in &soft_errors {
489 eprintln!(" [Rule 8] {}", diag.message.as_str());
490 file_diagnostics.push(format!("{}: WARNING - {}", member, diag.message));
491 }
492 has_error = true;
493 continue;
496 }
497 if !soft_errors.is_empty() {
499 eprintln!(
500 " '{}': {} Rule 8 diagnostic(s) (non-blocking)",
501 member,
502 soft_errors.len()
503 );
504 for diag in &soft_errors {
505 eprintln!(" {}", diag.message.as_str());
506 file_diagnostics.push(format!("{}: WARNING - {}", member, diag.message));
507 }
508 }
509
510 if !diagnostics.is_empty() {
511 eprintln!(" '{}': {} diagnostic(s)", member, diagnostics.len());
512 for diag in &diagnostics {
513 eprintln!(" {}", diag.message.as_str());
514 file_diagnostics.push(format!("{}: {}", member, diag.message));
515 }
516 }
517
518 for exp in &exports_for_all_modules {
519 all_module_exports.push((exp.clone(), module_name.clone()));
520 }
521 for fn_name in scan_pub_functions(&zig_code) {
523 if !exports_for_all_modules.contains(&fn_name) {
524 all_module_exports.push((fn_name, module_name.clone()));
525 }
526 }
527
528 let dep_imports = build_dep_imports(member, group);
529
530 per_file_modules.push(crate::project::PerFileModule {
531 mod_name: module_name.clone(),
532 zig_code: zig_code.to_string(),
533 dep_imports,
534 });
535
536 combined_zig.push_str(&zig_code);
537 if !source_map.mappings.is_empty() {
538 all_source_maps.push(source_map);
539 }
540
541 all_cabi_exports.extend(cabi_exports);
543
544 if is_test_group {
545 let test_cases = crate::testgen::extract_test_cases(program, &src);
548 let closure_fn_refs: HashSet<&str> =
549 closure_fns.iter().map(|s| s.as_str()).collect();
550 let ret_type_map: HashMap<String, String> = fn_return_types
551 .iter()
552 .map(|(k, v)| (k.clone(), v.to_zig_type()))
553 .collect();
554 let file_test_code = crate::testgen::generate_test_code(
555 &test_cases,
556 &closure_fn_refs,
557 &ret_type_map,
558 );
559 all_test_code.push_str(&file_test_code);
560 }
561 }
562
563 if per_file_modules.is_empty() {
566 if has_error {
567 eprintln!(" skip: all files failed codegen");
568 } else {
569 eprintln!(" skip: no valid modules after codegen");
570 }
571 continue;
572 }
573
574 if has_error {
575 eprintln!(
576 " warning: {} file(s) had codegen errors, continuing with {} successful file(s)",
577 group.members.len() - per_file_modules.len(),
578 per_file_modules.len()
579 );
580 }
581
582 let mut name_to_module: HashMap<&str, &str> = HashMap::new();
584 for (exp_name, mod_name) in &all_module_exports {
585 name_to_module.entry(exp_name).or_insert(mod_name);
586 }
587 let mut name_to_cabi: HashMap<&str, &crate::native_proto::NativeCabiExport> =
588 HashMap::new();
589 for exp in &all_cabi_exports {
590 name_to_cabi.entry(&exp.name).or_insert(exp);
591 }
592 let cabi_wrapper_code = gen_cabi_wrappers(&name_to_module, &name_to_cabi);
593 let cabi_names: HashSet<String> = name_to_cabi.keys().map(|&k| k.to_string()).collect();
594
595 let project_opts = crate::project::ProjectOptions {
596 name: group.core_name.clone(),
597 out_dir: out_dir.clone(),
598 per_file_code: per_file_modules,
599 external_exports: all_module_exports,
600 cabi_wrapper_code,
601 cabi_names,
602 test_code: all_test_code,
603 runtime_dir: Some(runtime_dir.clone()),
604 host_header: if combined_zig.contains("host.") || !async_host_fn_names.is_empty() {
605 host_header.clone()
606 } else {
607 String::new()
608 },
609 async_host_fn_names: async_host_fn_names.clone(),
610 include_windows_stub: group_idx == 0,
611 };
612
613 match crate::project::generate(&project_opts) {
614 Ok(()) => println!(" Generated: {}/{}", out_dir, group.core_name),
615 Err(e) => {
616 eprintln!(" FAIL ({})", e);
617 continue;
618 }
619 }
620
621 if !host_fns.is_empty() {
623 let host_zig_path = Path::new(&out_dir).join(&group.core_name).join("host.zig");
624 let host_zig_content = host_fns.generate_zig_header();
625 if let Err(e) = fs::write(&host_zig_path, &host_zig_content) {
626 eprintln!(" warning: failed to write host.zig: {}", e);
627 } else {
628 println!(
629 " Generated: {}/{}",
630 out_dir,
631 host_zig_path.file_name().unwrap().to_string_lossy()
632 );
633 }
634 }
635
636 if !all_source_maps.is_empty() {
638 let sm_path = Path::new(&out_dir)
639 .join(&group.core_name)
640 .join("source_map.json");
641 let sm_json = serde_json::json!({
642 "version": 1,
643 "generator": "js2rustc",
644 "files": all_source_maps
645 .iter()
646 .map(|sm| serde_json::json!({
647 "source": sm.source_file,
648 "mappings": sm.mappings.iter().map(|m| serde_json::json!({
649 "zig_line": m.zig_line,
650 "js_file": m.js_file,
651 "js_line": m.js_line,
652 "js_col": m.js_col,
653 "kind": m.kind,
654 })).collect::<Vec<_>>()
655 }))
656 .collect::<Vec<_>>()
657 });
658 if let Ok(json_str) = serde_json::to_string_pretty(&sm_json) {
659 let _ = std::fs::write(&sm_path, json_str);
660 }
661 }
662
663 let include_init = !is_test_group && group_idx == 0;
666 write_cabi_metadata(
667 Path::new(&out_dir),
668 &group.core_name,
669 &all_cabi_exports,
670 &host_fns,
671 include_init,
672 );
673
674 let cabi_path = Path::new(&out_dir)
676 .join(&group.core_name)
677 .join("cabi_exports.json");
678 let cabi_json = fs::read_to_string(&cabi_path).unwrap_or_default();
679
680 group_results.push(crate::GroupResult {
681 name: group.core_name.clone(),
682 is_test: is_test_group,
683 cabi_exports_json: cabi_json,
684 diagnostics: file_diagnostics.clone(),
685 output_files: Vec::new(),
686 });
687
688 }
690
691 if !config.run_zig_build {
693 continue;
695 }
696
697 let project_path = Path::new(&out_dir).join(&group.core_name);
698 let mut build_ok = false;
699 let build_result = Command::new("zig")
700 .arg("build")
701 .current_dir(&project_path)
702 .output();
703 match build_result {
704 Ok(result) if result.status.success() => {
705 println!(" zig build: OK");
706 build_ok = true;
707 }
708 Ok(result) => {
709 let stderr = String::from_utf8_lossy(&result.stderr);
710 eprintln!(" zig build FAILED:\n{}", stderr);
711 return Err(format!(
712 "zig build failed for group '{}':\n{}",
713 group.core_name,
714 stderr.lines().take(20).collect::<Vec<_>>().join("\n")
715 ));
716 }
717 Err(_) => eprintln!(" warning: zig not found — skipping build"),
718 }
719
720 let mut test_ok = false;
722 let test_result = Command::new("zig")
723 .arg("build")
724 .arg("test")
725 .current_dir(&project_path)
726 .output();
727 match test_result {
728 Ok(result) if result.status.success() => {
729 println!(" zig test: PASSED");
730 test_ok = true;
731 }
732 Ok(result) => {
733 let stderr = String::from_utf8_lossy(&result.stderr);
734 eprintln!(" zig test FAILED:\n{}", stderr);
735 }
736 Err(_) => {}
737 }
738
739 if build_ok && test_ok {
741 build_cache.insert(group.core_name.clone(), current_hash.clone());
742 }
743 }
744
745 write_build_cache(Path::new(&out_dir), &build_cache);
747
748 let all_diagnostics: Vec<String> = group_results
749 .iter()
750 .flat_map(|g| g.diagnostics.clone())
751 .collect();
752
753 Ok(ProjectResult {
754 groups: group_results,
755 diagnostics: all_diagnostics,
756 })
757}
758
759pub fn gen_cabi_wrappers(
767 name_to_module: &HashMap<&str, &str>,
768 name_to_cabi: &HashMap<&str, &crate::native_proto::NativeCabiExport>,
769) -> String {
770 use std::collections::HashSet;
771
772 let mut out = String::new();
773 let mut emitted: HashSet<&str> = HashSet::new();
774
775 for (&name, exp) in name_to_cabi {
776 if !emitted.insert(name) {
777 continue;
778 }
779 let Some(&module) = name_to_module.get(name) else {
780 continue;
781 };
782 let module = format!("_{}", module);
784
785 let returns_string = exp.ret_type == crate::native_proto::ZigType::Str;
786 let ret_is_js_any = exp.ret_type == crate::native_proto::ZigType::Anytype;
787 let ret_is_arraylist = matches!(exp.ret_type, crate::native_proto::ZigType::ArrayList(_));
788
789 if ret_is_js_any || ret_is_arraylist {
792 out.push_str(&format!(
793 "pub const {name} = {mod}.{name};\n\n",
794 name = name,
795 mod = module,
796 ));
797 continue;
798 }
799
800 let has_js_obj_param = exp.params.iter().any(|(_, ty)| {
802 *ty == crate::native_proto::ZigType::Void
803 || *ty == crate::native_proto::ZigType::Anytype
804 });
805 if has_js_obj_param {
806 out.push_str(&format!(
808 "pub const {name} = {mod}.{name};\n\n",
809 name = name,
810 mod = module,
811 ));
812 continue;
813 }
814
815 let mut cabi_params: Vec<String> = Vec::new();
817 let mut zig_params: Vec<String> = Vec::new();
818 let mut arg_names: Vec<String> = Vec::new();
819 let mut cabi_to_zig_conversions: Vec<String> = Vec::new();
820
821 for (pname, ptype) in &exp.params {
822 arg_names.push(pname.clone());
823 if *ptype == crate::native_proto::ZigType::Str {
824 cabi_params.push(format!("{}: [*:0]const u8", pname));
825 zig_params.push(format!("{}: []const u8", pname));
826 cabi_to_zig_conversions.push(format!(
827 " const {p}_slice: []const u8 = std.mem.span({p});",
828 p = pname
829 ));
830 } else {
831 let zig_ty = ptype.to_zig_type();
832 cabi_params.push(format!("{}: {}", pname, zig_ty));
833 zig_params.push(format!("{}: {}", pname, zig_ty));
834 }
835 }
836
837 let zig_call_args: String = arg_names.join(", ");
839 let cabi_call_args: String = exp
840 .params
841 .iter()
842 .map(|(pname, ptype)| {
843 if *ptype == crate::native_proto::ZigType::Str {
844 format!("{}_slice", pname)
845 } else {
846 pname.clone()
847 }
848 })
849 .collect::<Vec<_>>()
850 .join(", ");
851
852 if exp.is_async {
854 let async_zig_args = if zig_call_args.is_empty() {
855 "js_runtime.getIo()".to_string()
856 } else {
857 format!("js_runtime.getIo(), {}", zig_call_args)
858 };
859 let async_cabi_args = if cabi_call_args.is_empty() {
860 "js_runtime.getIo()".to_string()
861 } else {
862 format!("js_runtime.getIo(), {}", cabi_call_args)
863 };
864
865 if returns_string {
866 out.push_str(&format!(
868 "pub fn {name}({params}) []const u8 {{\n return {mod}.{name}({args}) catch @panic(\"async error in {name}\");\n}}\n",
869 name = name,
870 params = zig_params.join(", "),
871 mod = module,
872 args = async_zig_args,
873 ));
874 let conversions = if cabi_to_zig_conversions.is_empty() {
876 String::new()
877 } else {
878 format!("{}\n", cabi_to_zig_conversions.join("\n"))
879 };
880 out.push_str(&format!(
881 "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",
882 name = name,
883 cabi_params = cabi_params.join(", "),
884 conv = conversions,
885 mod = module,
886 args = async_cabi_args,
887 ));
888 out.push_str(&format!(
889 "comptime {{ @export(&{name}_cabi, .{{ .name = \"{name}\", .linkage = .strong }}); }}\n",
890 name = name,
891 ));
892 } else if let crate::native_proto::ZigType::NamedStruct(ref sn) = exp.ret_type {
893 let struct_name = format!("host.{}", sn);
895 let conversions = if cabi_to_zig_conversions.is_empty() {
896 String::new()
897 } else {
898 format!("{}\n", cabi_to_zig_conversions.join("\n"))
899 };
900
901 out.push_str(&format!(
903 "pub fn {name}({params}) {struct_name} {{\n return {mod}.{name}({args}) catch @panic(\"async error in {name}\");\n}}\n",
904 name = name,
905 params = zig_params.join(", "),
906 struct_name = struct_name,
907 mod = module,
908 args = async_zig_args,
909 ));
910
911 let mut cabi_params_with_out = cabi_params.clone();
913 cabi_params_with_out.push(format!("result: *{}", struct_name));
914 let cabi_params_str = cabi_params_with_out.join(", ");
915
916 let cabi_call = format!(
917 "{mod}.{name}({args})",
918 mod = module,
919 name = name,
920 args = async_cabi_args,
921 );
922 out.push_str(&format!(
923 "pub export fn {name}_cabi({params}) void {{\n{conv} const _result = {cabi_call} catch @panic(\"async error in {name}\");\n result.* = _result;\n}}\n",
924 name = name,
925 params = cabi_params_str,
926 conv = conversions,
927 cabi_call = cabi_call,
928 ));
929 out.push_str(&format!(
930 "comptime {{ @export(&{name}_cabi, .{{ .name = \"{name}\", .linkage = .strong }}); }}\n",
931 name = name,
932 ));
933 } else {
934 let ret_zig = exp.ret_type.to_zig_type();
936 let conversions = if cabi_to_zig_conversions.is_empty() {
937 String::new()
938 } else {
939 format!("{}\n", cabi_to_zig_conversions.join("\n"))
940 };
941
942 out.push_str(&format!(
944 "pub fn {name}({params}) {ret} {{\n return {mod}.{name}({args}) catch @panic(\"async error in {name}\");\n}}\n",
945 name = name,
946 params = zig_params.join(", "),
947 ret = ret_zig,
948 mod = module,
949 args = async_zig_args,
950 ));
951
952 let cabi_params_with_runtime = {
954 let mut p = cabi_params.clone();
955 p.push("js_runtime: *JSRuntime".to_string());
956 p
957 };
958 let cabi_params_str = cabi_params_with_runtime.join(", ");
959
960 let cabi_call = format!(
961 "{mod}.{name}({args})",
962 mod = module,
963 name = name,
964 args = async_cabi_args,
965 );
966 out.push_str(&format!(
967 "pub export fn {name}_cabi({params}) {ret} {{\n{conv} return {cabi_call} catch @panic(\"async error in {name}\");\n}}\n",
968 name = name,
969 params = cabi_params_str,
970 ret = ret_zig,
971 conv = conversions,
972 cabi_call = cabi_call,
973 ));
974 out.push_str(&format!(
975 "comptime {{ @export(&{name}_cabi, .{{ .name = \"{name}\", .linkage = .strong }}); }}\n",
976 name = name,
977 ));
978 }
979
980 out.push('\n');
981 continue;
982 }
983
984 if returns_string {
985 let test_call = if exp.can_throw {
987 format!(
988 "{mod}.{name}({args}) catch @panic(\"error in {name}\")",
989 mod = module,
990 name = name,
991 args = zig_call_args,
992 )
993 } else {
994 format!("{mod}.{name}({args})", mod = module, name = name, args = zig_call_args)
995 };
996 out.push_str(&format!(
997 "pub fn {name}({params}) []const u8 {{\n return {test_call};\n}}\n",
998 name = name,
999 params = zig_params.join(", "),
1000 test_call = test_call,
1001 ));
1002
1003 let conversions = if cabi_to_zig_conversions.is_empty() {
1005 String::new()
1006 } else {
1007 format!("{}\n", cabi_to_zig_conversions.join("\n"))
1008 };
1009 let cabi_call = if exp.can_throw {
1010 format!(
1011 "{mod}.{name}({args}) catch |err| return StrRet.from_panic(err)",
1012 mod = module,
1013 name = name,
1014 args = cabi_call_args,
1015 )
1016 } else {
1017 format!(
1018 "{mod}.{name}({args})",
1019 mod = module,
1020 name = name,
1021 args = cabi_call_args,
1022 )
1023 };
1024 out.push_str(&format!(
1025 "pub export fn {name}_cabi({cabi_params}) StrRet {{\n{conv} return StrRet.from({cabi_call});\n}}\n",
1026 name = name,
1027 cabi_params = cabi_params.join(", "),
1028 conv = conversions,
1029 cabi_call = cabi_call,
1030 ));
1031 out.push_str(&format!(
1032 "comptime {{ @export(&{name}_cabi, .{{ .name = \"{name}\", .linkage = .strong }}); }}\n",
1033 name = name,
1034 ));
1035 } else {
1036 let ret_zig = exp.ret_type.to_cabi_str();
1037 let exp_ret_is_js_value = exp.ret_type == crate::native_proto::ZigType::Void;
1038
1039 let mut cabi_params_with_err = cabi_params.clone();
1041 if exp.can_throw {
1042 cabi_params_with_err.push("err_out: *?[*:0]const u8".to_string());
1043 }
1044 let cabi_params_str = cabi_params_with_err.join(", ");
1045
1046 let (call_expr, err_setup) = if exp.can_throw {
1048 let err_handle = if ret_zig == "void" {
1049 format!(
1051 " {mod}.{name}({args}) catch |err| {{\n err_out.* = @errorName(err);\n return;\n }};",
1052 mod = module,
1053 name = name,
1054 args = cabi_call_args,
1055 )
1056 } else {
1057 let ret_zero = if ret_zig == "bool" { "false" } else { "0" };
1059 format!(
1060 " const _result = {mod}.{name}({args}) catch |err| {{\n err_out.* = @errorName(err);\n return {ret_zero};\n }};",
1061 mod = module,
1062 name = name,
1063 args = cabi_call_args,
1064 ret_zero = ret_zero,
1065 )
1066 };
1067 let setup = if ret_zig == "void" {
1068 " err_out.* = null;\n".to_string()
1069 } else {
1070 String::new()
1071 };
1072 (err_handle, setup)
1073 } else {
1074 (
1075 format!(
1076 "{mod}.{name}({args})",
1077 mod = module,
1078 name = name,
1079 args = cabi_call_args,
1080 ),
1081 String::new(),
1082 )
1083 };
1084
1085 let conversions = if cabi_to_zig_conversions.is_empty() {
1086 String::new()
1087 } else {
1088 format!("{}\n", cabi_to_zig_conversions.join("\n"))
1089 };
1090
1091 if ret_zig == "void" {
1092 if exp.can_throw {
1093 out.push_str(&format!(
1094 "pub export fn {name}({params}) void {{\n{conv}{err_setup}{call_expr}\n}}\n",
1095 name = name,
1096 params = cabi_params_str,
1097 conv = conversions,
1098 err_setup = err_setup,
1099 call_expr = call_expr,
1100 ));
1101 } else {
1102 out.push_str(&format!(
1103 "pub export fn {name}({params}) void {{\n{conv} {mod}.{name}({args});\n}}\n",
1104 name = name,
1105 params = cabi_params_str,
1106 conv = conversions,
1107 mod = module,
1108 args = cabi_call_args,
1109 ));
1110 }
1111 } else if exp_ret_is_js_value {
1112 if exp.can_throw {
1114 out.push_str(&format!(
1115 "pub export fn {name}({params}) i64 {{\n{conv}{call_expr}\n return _result.int;\n}}\n",
1116 name = name,
1117 params = cabi_params_str,
1118 conv = conversions,
1119 call_expr = call_expr,
1120 ));
1121 } else {
1122 out.push_str(&format!(
1123 "pub export fn {name}({params}) i64 {{\n{conv} const _result = {mod}.{name}({args});\n return _result.int;\n}}\n",
1124 name = name,
1125 params = cabi_params_str,
1126 conv = conversions,
1127 mod = module,
1128 args = cabi_call_args,
1129 ));
1130 }
1131 } else {
1132 let rz = if ret_zig == "bool" { "false" } else { "0" };
1134 if exp.can_throw {
1135 out.push_str(&format!(
1136 "pub export fn {name}({params}) {ret} {{\n{conv}{call_expr}\n if (@TypeOf(_result) == void) {{\n return {rz};\n }} else {{\n return _result;\n }}\n}}\n",
1137 name = name,
1138 params = cabi_params_str,
1139 conv = conversions,
1140 ret = ret_zig,
1141 call_expr = call_expr,
1142 rz = rz,
1143 ));
1144 } else {
1145 out.push_str(&format!(
1146 "pub export fn {name}({params}) {ret} {{\n{conv} const _result = {mod}.{name}({args});\n if (@TypeOf(_result) == void) {{\n return {rz};\n }} else {{\n return _result;\n }}\n}}\n",
1147 name = name,
1148 params = cabi_params_str,
1149 ret = ret_zig,
1150 conv = conversions,
1151 mod = module,
1152 args = cabi_call_args,
1153 rz = rz,
1154 ));
1155 }
1156 }
1157 }
1158
1159 out.push('\n');
1160 }
1161
1162 out
1163}
1164
1165pub fn write_cabi_metadata(
1167 out_dir: &Path,
1168 group_name: &str,
1169 cabi_exports: &[crate::native_proto::NativeCabiExport],
1170 host_fns: &crate::host::HostFnRegistry,
1171 include_init: bool,
1172) {
1173 let project_dir = out_dir.join(group_name);
1174
1175 let exports_path = project_dir.join("cabi_exports.json");
1177 let mut exports_value: Vec<serde_json::Value> = cabi_exports
1178 .iter()
1179 .filter(|exp| exp.ret_type != crate::native_proto::ZigType::Anytype)
1180 .map(|exp| {
1181 let params: Vec<serde_json::Value> = exp
1183 .params
1184 .iter()
1185 .map(|(name, ty)| {
1186 serde_json::json!({
1187 "name": name,
1188 "zig_type": ty.to_zig_type() })
1190 })
1191 .collect();
1192
1193 let ret_type_str = exp.ret_type.to_cabi_str();
1195
1196 let (ret_struct_name, ret_struct_fields) =
1198 if let crate::native_proto::ZigType::NamedStruct(ref struct_name) = exp.ret_type {
1199 let struct_fields: Option<Vec<serde_json::Value>> = host_fns
1201 .structs
1202 .iter()
1203 .find(|s| &s.zig_name == struct_name)
1204 .map(|s| {
1205 s.fields
1206 .iter()
1207 .map(|f| {
1208 serde_json::json!({
1209 "name": f.name,
1210 "zig_type": f.zig_type,
1211 "cabi_type": f.c_type,
1212 })
1213 })
1214 .collect()
1215 });
1216 (Some(struct_name.clone()), struct_fields)
1217 } else {
1218 (None, None)
1219 };
1220
1221 let mut json_obj = serde_json::json!({
1222 "name": exp.name,
1223 "params": params,
1224 "ret_type": ret_type_str,
1225 "can_throw": exp.can_throw,
1226 });
1227
1228 if let Some(sn) = ret_struct_name {
1230 json_obj["ret_struct_name"] = serde_json::json!(sn);
1231 }
1232 if let Some(sf) = ret_struct_fields {
1233 json_obj["ret_struct_fields"] = serde_json::json!(sf);
1234 }
1235
1236 json_obj
1237 })
1238 .collect();
1239
1240 {
1245 let mut seen = std::collections::HashSet::new();
1246 exports_value.retain(|exp| {
1247 let name = exp["name"].as_str().unwrap_or("");
1248 seen.insert(name.to_string())
1249 });
1250 }
1251
1252 if include_init {
1254 exports_value.push(serde_json::json!({
1255 "name": "js2rust_init",
1256 "params": [],
1257 "ret_type": "void",
1258 }));
1259 exports_value.push(serde_json::json!({
1260 "name": "js2rust_deinit",
1261 "params": [],
1262 "ret_type": "void",
1263 }));
1264 }
1265
1266 if let Ok(json_str) = serde_json::to_string_pretty(&exports_value) {
1267 let _ = fs::write(&exports_path, &json_str);
1268 }
1269
1270 let imports_path = project_dir.join("cabi_imports.json");
1272 let imports_value = host_fns.to_json_value();
1273 if let Ok(json_str) = serde_json::to_string_pretty(&imports_value) {
1274 let _ = fs::write(&imports_path, &json_str);
1275 }
1276}