Skip to main content

js2zig_core/
pipeline.rs

1use crate::analyzer::{analyze_single_group, sanitize_module_name, strip_imports_extract_exports};
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
9/// Resolve paths relative to the workspace root (parent of core crate).
10fn 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
17/// Build the dependency import list for a per-file Zig module.
18/// Given a filename like "main.js", looks up its imported_names in the group
19/// and maps source filenames to sanitized Zig module names.
20fn build_dep_imports(
21    filename: &str,
22    group: &crate::analyzer::FileGroup,
23) -> Vec<(String, String)> {
24    let empty = Vec::new();
25    let raw_imports = group.imported_names.get(filename).unwrap_or(&empty);
26    raw_imports
27        .iter()
28        .map(|(imported_name, src_file)| {
29            let mod_name = group
30                .name_map
31                .get(src_file.as_str())
32                .cloned()
33                .unwrap_or_else(|| {
34                    let stem = src_file.strip_suffix(".js").unwrap_or(src_file);
35                    sanitize_module_name(stem)
36                });
37            (imported_name.clone(), mod_name)
38        })
39        .collect()
40}
41
42/// Extract all top-level function names from JS source text.
43/// Used for test groups where ALL functions should be CABI-exported (not just `export`-prefixed).
44fn extract_all_function_names(source: &str) -> HashSet<String> {
45    let mut names = HashSet::new();
46    for line in source.lines() {
47        let trimmed = line.trim();
48        let rest = if let Some(r) = trimmed.strip_prefix("export function ") {
49            r
50        } else if let Some(r) = trimmed.strip_prefix("function ") {
51            r
52        } else {
53            continue;
54        };
55        if let Some(paren) = rest.find('(') {
56            let name = rest[..paren].trim();
57            if !name.is_empty() {
58                names.insert(name.to_string());
59            }
60        }
61    }
62    names
63}
64
65/// Scan zig_code for all `pub fn xxx(` and `pub export fn xxx(` declarations.
66/// Returns the function names so the orchestrator can re-export them.
67fn scan_pub_functions(zig_code: &str) -> Vec<String> {
68    let mut fns = Vec::new();
69    for line in zig_code.lines() {
70        let trimmed = line.trim();
71        let rest = if let Some(r) = trimmed.strip_prefix("pub export fn ") {
72            r
73        } else if let Some(r) = trimmed.strip_prefix("pub fn ") {
74            r
75        } else {
76            continue;
77        };
78        if let Some(paren) = rest.find('(') {
79            let name = rest[..paren].trim().to_string();
80            // Skip infrastructure functions that shouldn't be re-exported
81            if name != "init_js2rust" && name != "deinit_js2rust" {
82                fns.push(name);
83            }
84        }
85    }
86    fns
87}
88
89/// Compute a content hash for a file group.
90/// Hashes all member JS files + runtime .zig files so any change triggers rebuild.
91fn compute_group_hash(
92    in_dir: &Path,
93    group: &crate::analyzer::FileGroup,
94    runtime_dir: &Path,
95) -> String {
96    let mut hasher = std::hash::DefaultHasher::new();
97
98    // Hash each member JS file content (sorted for determinism)
99    let mut members: Vec<&String> = group.members.iter().collect();
100    members.sort();
101    for member in &members {
102        member.hash(&mut hasher);
103        if let Ok(content) = fs::read(in_dir.join(member)) {
104            content.hash(&mut hasher);
105        }
106    }
107
108    // Hash runtime .zig files (changes here affect all groups)
109    if let Ok(entries) = fs::read_dir(runtime_dir) {
110        let mut rt_files: Vec<PathBuf> = entries
111            .filter_map(|e| e.ok())
112            .map(|e| e.path())
113            .filter(|p| p.extension().is_some_and(|ext| ext == "zig"))
114            .collect();
115        rt_files.sort();
116        for rt_file in &rt_files {
117            if let Ok(content) = fs::read(rt_file) {
118                rt_file.file_name().hash(&mut hasher);
119                content.hash(&mut hasher);
120            }
121        }
122    }
123
124    format!("{:016x}", hasher.finish())
125}
126
127/// Read build cache from `out/.build_cache.json`.
128/// Returns group_name → hash_hex map.
129fn read_build_cache(out_dir: &Path) -> HashMap<String, String> {
130    let cache_path = out_dir.join(".build_cache.json");
131    if let Ok(data) = fs::read_to_string(&cache_path)
132        && let Ok(map) = serde_json::from_str(&data)
133    {
134        return map;
135    }
136    HashMap::new()
137}
138
139/// Write build cache to `out/.build_cache.json`.
140fn write_build_cache(out_dir: &Path, cache: &HashMap<String, String>) {
141    let cache_path = out_dir.join(".build_cache.json");
142    if let Ok(json) = serde_json::to_string_pretty(cache) {
143        let _ = fs::write(cache_path, json);
144    }
145}
146
147pub fn transpile_project(config: &ProjectConfig) -> Result<ProjectResult, String> {
148    let ws = workspace_dir();
149
150    // Derive input directory and core file name from js_file path.
151    let js_file = &config.js_file;
152    let in_path = js_file
153        .parent()
154        .ok_or_else(|| format!("cannot get parent directory of '{}'", js_file.display()))?
155        .to_path_buf();
156    let core_file = js_file
157        .file_name()
158        .and_then(|n| n.to_str())
159        .ok_or_else(|| format!("invalid file name in '{}'", js_file.display()))?
160        .to_string();
161
162    let in_dir = in_path.to_string_lossy().to_string();
163    let out_dir: String = config.out_dir.to_string_lossy().to_string();
164    let force_rebuild = config.force_rebuild;
165
166    // Ensure output directory exists.
167    fs::create_dir_all(&out_dir).map_err(|e| {
168        format!("cannot create output directory '{}': {}", out_dir, e)
169    })?;
170
171    // === Phase 1: Analyze file groups (single core file + transitive deps) ===
172    let (groups, groups_json) = analyze_single_group(&in_dir, &core_file);
173
174    let groups_json_path = Path::new(&out_dir).join("groups.json");
175    if let Err(e) = fs::write(&groups_json_path, &groups_json) {
176        eprintln!(
177            "warning: could not write '{}': {}",
178            groups_json_path.display(),
179            e
180        );
181    } else {
182        println!("Wrote: {}/groups.json", out_dir);
183    }
184
185    if groups.is_empty() {
186        return Err(format!("no groups derived from core file '{}'", core_file));
187    }
188
189    // === Load host function registry ===
190    let mut host_fns = crate::host::HostFnRegistry::new();
191
192    // If host_config is provided in ProjectConfig, use it
193    if let Some(ref host_config) = config.host_config {
194        // Convert HostFunction to HostFnDef and register
195        for f in &host_config.functions {
196            let params: Vec<(String, crate::infer::ZigType)> = f.params.iter().enumerate().map(|(i, t)| {
197                (format!("arg{}", i), crate::infer::ZigType::from(*t))
198            }).collect();
199
200            if f.is_async {
201                if f.async_return_fields.is_empty() {
202                    // Async with simple return type
203                    let return_type = f.return_type
204                        .map(crate::infer::ZigType::from)
205                        .unwrap_or(crate::infer::ZigType::Void);
206                    host_fns.register_async_simple(&f.name, &f.name, params, return_type);
207                } else {
208                    // Async with struct return type
209                    let zig_name = f.struct_zig_name();
210                    let c_name = f.struct_c_name();
211                    let fields: Vec<crate::host::HostStructField> = f.async_return_fields.iter()
212                        .map(|(name, ty)| {
213                            crate::host::HostStructField {
214                                name: name.clone(),
215                                zig_type: ty.to_zig_field_type().to_string(),
216                                c_type: ty.to_c_field_type().to_string(),
217                            }
218                        })
219                        .collect();
220                    let struct_def = crate::host::HostStructDef {
221                        zig_name,
222                        c_name,
223                        fields,
224                    };
225                    host_fns.register_async(&f.name, &f.name, params, struct_def);
226                }
227            } else {
228                let return_type = f.return_type.map(crate::infer::ZigType::from);
229                host_fns.register(&f.name, params, return_type.unwrap_or(crate::infer::ZigType::Void));
230            }
231        }
232    } else {
233        // Fallback: load from host_config.json file
234        let config_path = ws.join("host_config.json");
235        if config_path.exists() {
236            match crate::host::HostFnRegistry::load_from_file(&config_path) {
237                Ok(registry) => {
238                    host_fns = registry;
239                }
240                Err(e) => {
241                    return Err(e);
242                }
243            }
244        } else {
245            eprintln!(
246                "warning: '{}' not found — no host functions registered",
247                config_path.display()
248            );
249        }
250    };
251
252    let mut builtins = crate::builtins::BuiltinRegistry::new();
253    builtins.register_host_fns(&host_fns);
254    let host_header = host_fns.generate_zig_header();
255    let async_host_fn_names: Vec<String> = host_fns.async_fn_names();
256    let runtime_dir = ws.join("runtime").to_string_lossy().to_string();
257
258    // === Incremental compilation: load build cache ===
259    let mut build_cache = read_build_cache(Path::new(&out_dir));
260    let runtime_path = ws.join("runtime");
261    let mut group_results: Vec<crate::GroupResult> = Vec::new();
262
263    // === Phase 2: Generate Zig project per group ===
264    // Always uses multi-file mode: one .zig per JS file + orchestrator lib.zig.
265    for (group_idx, group) in groups.iter().enumerate() {
266        let is_test_group = group.core_name.starts_with("test_");
267        println!(
268            "\n=== {} ({} member{}) {}===",
269            group.core_name,
270            group.members.len(),
271            if group.members.len() == 1 { "" } else { "s" },
272            if is_test_group { "[test] " } else { "" }
273        );
274
275        // --- Incremental check ---
276        let current_hash = compute_group_hash(&in_path, group, &runtime_path);
277        if !force_rebuild
278            && let Some(cached_hash) = build_cache.get(&group.core_name)
279            && *cached_hash == current_hash
280        {
281            println!("  unchanged, skipping (use --force to rebuild)");
282            // Still collect the cabi_exports_json for the result
283            let cabi_path = Path::new(&out_dir)
284                .join(&group.core_name)
285                .join("cabi_exports.json");
286            let cabi_json = fs::read_to_string(&cabi_path).unwrap_or_default();
287            group_results.push(crate::GroupResult {
288                name: group.core_name.clone(),
289                is_test: is_test_group,
290                cabi_exports_json: cabi_json,
291                diagnostics: Vec::new(),
292                output_files: Vec::new(),
293            });
294            continue;
295        }
296
297        {
298            let mut per_file_modules: Vec<crate::project::PerFileModule> = Vec::new();
299            let mut all_module_exports: Vec<(String, String)> = Vec::new();
300            let mut all_test_code = String::new();
301            let mut combined_zig = String::new();
302            let mut all_cabi_exports: Vec<crate::codegen::CabiExport> = Vec::new();
303            let mut all_source_maps: Vec<crate::sourcemap::SourceMap> = Vec::new();
304            let mut has_error = false;
305
306            // --- Pre-scan: collect source, exports, and module names ---
307            struct MemberMeta {
308                stripped: String,
309                exports: HashSet<String>,
310                module_name: String,
311            }
312            let mut member_metas: Vec<MemberMeta> = Vec::new();
313            let mut core_exports: HashSet<String> = HashSet::new();
314
315            for member in &group.members {
316                let src = match fs::read_to_string(in_path.join(member)) {
317                    Ok(s) => s,
318                    Err(e) => {
319                        eprintln!("  warning: cannot read '{}': {}", member, e);
320                        continue;
321                    }
322                };
323                let (stripped, exports) = strip_imports_extract_exports(&src);
324
325                let module_name = group
326                    .name_map
327                    .get(member)
328                    .cloned()
329                    .unwrap_or_else(|| {
330                        let stem = member.strip_suffix(".js").unwrap_or(member);
331                        sanitize_module_name(stem)
332                    });
333
334                if *member == group.core_file {
335                    core_exports = exports.clone();
336                }
337
338                member_metas.push(MemberMeta {
339                    stripped,
340                    exports,
341                    module_name,
342                });
343            }
344
345            // --- Compute re-exported names per dependency ---
346            // Names that the core file re-exports from a dependency file should
347            // also get `pub export fn` in that dependency module.
348            let core_imports = group
349                .imported_names
350                .get(&group.core_file)
351                .cloned()
352                .unwrap_or_default();
353            let mut dep_re_exports: HashMap<String, HashSet<String>> = HashMap::new();
354            for (imported_name, source_file) in &core_imports {
355                if core_exports.contains(imported_name) {
356                    dep_re_exports
357                        .entry(source_file.clone())
358                        .or_default()
359                        .insert(imported_name.clone());
360                }
361            }
362
363
364            // --- Codegen pass ---
365            for (member, meta) in group.members.iter().zip(member_metas.iter()) {
366                let MemberMeta {
367                    ref stripped,
368                    ref exports,
369                    ref module_name,
370                } = *meta;
371
372                if stripped.trim().is_empty() {
373                    eprintln!("  skip '{}': empty after stripping imports", member);
374                    continue;
375                }
376
377                // For test groups: export ALL functions for CABI bridge testing.
378                // For normal groups: core file's JS exports → C ABI;
379                //                    dependency file: only re-exported names → C ABI.
380                let codegen_exports: HashSet<String> = if is_test_group {
381                    extract_all_function_names(stripped)
382                } else if *member == group.core_file {
383                    exports.clone()
384                } else {
385                    dep_re_exports.get(member).cloned().unwrap_or_default()
386                };
387
388                let allocator = oxc_allocator::Allocator::default();
389                let program = crate::parser::parse(&allocator, stripped);
390
391                // Collect host function return types and param types for type inference
392                let mut host_return_types: std::collections::HashMap<String, crate::infer::ZigType> =
393                    std::collections::HashMap::new();
394                let mut host_param_types: std::collections::HashMap<String, Vec<crate::infer::ZigType>> =
395                    std::collections::HashMap::new();
396                for def in host_fns.iter() {
397                    host_return_types.insert(def.name.clone(), def.ret_type.clone());
398                    host_param_types.insert(
399                        def.name.clone(),
400                        def.params.iter().map(|(_, t)| t.clone()).collect(),
401                    );
402                }
403                let host_struct_fields = host_fns.struct_fields_map();
404
405                let async_fns: std::collections::HashSet<String> =
406                    host_fns.async_fn_names().into_iter().collect();
407
408                let host_info = crate::codegen::HostTypeInfo {
409                    return_types: &host_return_types,
410                    param_types: &host_param_types,
411                    struct_fields: &host_struct_fields,
412                    async_fns: &async_fns,
413                };
414
415                let (zig_code, diagnostics, closure_fns, fn_return_types, cabi_exports, source_map) =
416                    crate::codegen::generate(&program, &builtins, &codegen_exports, stripped, member, &host_info);
417
418                let has_file_error = diagnostics
419                    .iter()
420                    .any(|d| d.kind == crate::infer::DiagnosticKind::Error);
421                if has_file_error {
422                    let err_count = diagnostics
423                        .iter()
424                        .filter(|d| d.kind == crate::infer::DiagnosticKind::Error)
425                        .count();
426                    eprintln!("  skip '{}': {} codegen error(s)", member, err_count);
427                    for diag in &diagnostics {
428                        if diag.kind == crate::infer::DiagnosticKind::Error {
429                            eprintln!("    {}", diag.format_with_source(stripped));
430                        }
431                    }
432                    has_error = true;
433                    break;
434                }
435
436                if !diagnostics.is_empty() {
437                    eprintln!("  '{}': {} diagnostic(s)", member, diagnostics.len());
438                    for diag in &diagnostics {
439                        eprintln!("    {}", diag.format_with_source(stripped));
440                    }
441                }
442
443                for exp in exports {
444                    all_module_exports.push((exp.clone(), module_name.clone()));
445                }
446                // Also scan all pub fn / pub export fn for test re-export
447                for fn_name in scan_pub_functions(&zig_code) {
448                    if !exports.contains(&fn_name) {
449                        all_module_exports.push((fn_name, module_name.clone()));
450                    }
451                }
452
453                let dep_imports = build_dep_imports(member, group);
454
455                per_file_modules.push(crate::project::PerFileModule {
456                    mod_name: module_name.clone(),
457                    zig_code: zig_code.clone(),
458                    dep_imports,
459                });
460
461                combined_zig.push_str(&zig_code);
462                if !source_map.mappings.is_empty() {
463                    all_source_maps.push(source_map);
464                }
465
466                // Always collect CABI exports for all groups
467                all_cabi_exports.extend(cabi_exports);
468
469                if is_test_group {
470                    // Test groups: also generate Zig test code
471                    let test_cases = crate::testgen::extract_test_cases(&program, stripped);
472                    let closure_fn_refs: HashSet<&str> =
473                        closure_fns.iter().map(|s| s.as_str()).collect();
474                    let ret_type_map: HashMap<String, String> = fn_return_types
475                        .iter()
476                        .map(|(k, v)| (k.clone(), v.to_zig_str()))
477                        .collect();
478                    let file_test_code =
479                        crate::testgen::generate_test_code(&test_cases, &closure_fn_refs, &ret_type_map);
480                    all_test_code.push_str(&file_test_code);
481                }
482            }
483
484            if has_error {
485                continue;
486            }
487
488            if per_file_modules.is_empty() {
489                eprintln!("  skip: no valid modules after codegen");
490                continue;
491            }
492
493            // --- Generate C ABI wrapper code for lib.zig ---
494            let mut name_to_module: HashMap<&str, &str> = HashMap::new();
495            for (exp_name, mod_name) in &all_module_exports {
496                name_to_module.entry(exp_name).or_insert(mod_name);
497            }
498            let mut name_to_cabi: HashMap<&str, &crate::codegen::CabiExport> = HashMap::new();
499            for exp in &all_cabi_exports {
500                name_to_cabi.entry(&exp.name).or_insert(exp);
501            }
502            let cabi_wrapper_code = gen_cabi_wrappers(&name_to_module, &name_to_cabi);
503            let cabi_names: HashSet<String> =
504                name_to_cabi.keys().map(|&k| k.to_string()).collect();
505
506            let project_opts = crate::project::ProjectOptions {
507                name: group.core_name.clone(),
508                out_dir: out_dir.clone(),
509                per_file_code: per_file_modules,
510                external_exports: all_module_exports,
511                cabi_wrapper_code,
512                cabi_names,
513                test_code: all_test_code,
514                runtime_dir: Some(runtime_dir.clone()),
515                host_header: if combined_zig.contains("host.") || !async_host_fn_names.is_empty() {
516                    host_header.clone()
517                } else {
518                    String::new()
519                },
520                async_host_fn_names: async_host_fn_names.clone(),
521                include_windows_stub: group_idx == 0,
522            };
523
524            match crate::project::generate(&project_opts) {
525                Ok(()) => println!("  Generated: {}/{}", out_dir, group.core_name),
526                Err(e) => {
527                    eprintln!("  FAIL ({})", e);
528                    continue;
529                }
530            }
531
532            // Generate host.zig if host functions are registered
533            if !host_fns.is_empty() {
534                let host_zig_path = Path::new(&out_dir)
535                    .join(&group.core_name)
536                    .join("host.zig");
537                let host_zig_content = host_fns.generate_zig_header();
538                if let Err(e) = fs::write(&host_zig_path, &host_zig_content) {
539                    eprintln!("  warning: failed to write host.zig: {}", e);
540                } else {
541                    println!("  Generated: {}/{}", out_dir, host_zig_path.file_name().unwrap().to_string_lossy());
542                }
543            }
544
545            // Write source map JSON
546            if !all_source_maps.is_empty() {
547                let sm_path = Path::new(&out_dir)
548                    .join(&group.core_name)
549                    .join("source_map.json");
550                let sm_json = serde_json::json!({
551                    "version": 1,
552                    "generator": "js2rustc",
553                    "files": all_source_maps
554                        .iter()
555                        .map(|sm| serde_json::json!({
556                            "source": sm.source_file,
557                            "mappings": sm.mappings.iter().map(|m| serde_json::json!({
558                                "zig_line": m.zig_line,
559                                "js_file": m.js_file,
560                                "js_line": m.js_line,
561                                "js_col": m.js_col,
562                                "kind": m.kind,
563                            })).collect::<Vec<_>>()
564                        }))
565                        .collect::<Vec<_>>()
566                });
567                if let Ok(json_str) = serde_json::to_string_pretty(&sm_json) {
568                    let _ = std::fs::write(&sm_path, json_str);
569                }
570            }
571
572            // Write CABI metadata for all groups
573            // Only include init/deinit for the first non-test group
574            let include_init = !is_test_group && group_idx == 0;
575            write_cabi_metadata(Path::new(&out_dir), &group.core_name, &all_cabi_exports, &host_fns, include_init);
576
577            // Collect cabi_exports_json for the result
578            let cabi_path = Path::new(&out_dir)
579                .join(&group.core_name)
580                .join("cabi_exports.json");
581            let cabi_json = fs::read_to_string(&cabi_path).unwrap_or_default();
582
583            group_results.push(crate::GroupResult {
584                name: group.core_name.clone(),
585                is_test: is_test_group,
586                cabi_exports_json: cabi_json,
587                diagnostics: Vec::new(),
588                output_files: Vec::new(),
589            });
590
591            // Write test_cases.json for test groups (used by bridge test generation)
592        }
593
594        // === Zig build ===
595        if !config.run_zig_build {
596            // Skip zig build/test — caller handles compilation (e.g. proc-macro)
597            continue;
598        }
599
600        let project_path = Path::new(&out_dir).join(&group.core_name);
601        let mut build_ok = false;
602        let build_result = Command::new("zig")
603            .arg("build")
604            .current_dir(&project_path)
605            .output();
606        match build_result {
607            Ok(result) if result.status.success() => {
608                println!("  zig build: OK");
609                build_ok = true;
610            }
611            Ok(result) => {
612                let stderr = String::from_utf8_lossy(&result.stderr);
613                eprintln!("  zig build FAILED:\n{}", stderr);
614            }
615            Err(_) => eprintln!("  warning: zig not found — skipping build"),
616        }
617
618        // === Zig tests ===
619        let mut test_ok = false;
620        let test_result = Command::new("zig")
621            .arg("build")
622            .arg("test")
623            .current_dir(&project_path)
624            .output();
625        match test_result {
626            Ok(result) if result.status.success() => {
627                println!("  zig test: PASSED");
628                test_ok = true;
629            }
630            Ok(result) => {
631                let stderr = String::from_utf8_lossy(&result.stderr);
632                eprintln!("  zig test FAILED:\n{}", stderr);
633            }
634            Err(_) => {}
635        }
636
637        // === Update build cache on success ===
638        if build_ok && test_ok {
639            build_cache.insert(group.core_name.clone(), current_hash.clone());
640        }
641    }
642
643    // === Write build cache ===
644    write_build_cache(Path::new(&out_dir), &build_cache);
645
646    Ok(ProjectResult {
647        groups: group_results,
648        diagnostics: Vec::new(),
649    })
650}
651
652/// Generate `pub export fn` wrapper code for lib.zig.
653/// Each wrapper calls the per-file module function and lives in the root lib.zig,
654/// so Zig correctly propagates the symbols into the final .lib.
655///
656/// For string-returning functions, ALSO generate a Zig-friendly adapter
657/// (`pub fn greet(s: []const u8) []const u8`) so test code can call
658/// the function with idiomatic Zig string types.
659pub fn gen_cabi_wrappers(
660    name_to_module: &HashMap<&str, &str>,
661    name_to_cabi: &HashMap<&str, &crate::codegen::CabiExport>,
662) -> String {
663    use std::collections::HashSet;
664
665    let mut out = String::new();
666    let mut emitted: HashSet<&str> = HashSet::new();
667
668    for (&name, exp) in name_to_cabi {
669        if !emitted.insert(name) {
670            continue;
671        }
672        let Some(&module) = name_to_module.get(name) else {
673            continue;
674        };
675
676        let returns_string = exp.ret_type == crate::infer::ZigType::String;
677        let ret_is_js_any = exp.ret_type == crate::infer::ZigType::JsAny;
678
679        // JsAny returns: re-export as const alias (no CABI export).
680        // This lets Zig test code call the function, but no C ABI symbol is emitted.
681        if ret_is_js_any {
682            out.push_str(&format!(
683                "pub const {name} = {mod}.{name};\n\n",
684                name = name,
685                mod = module,
686            ));
687            continue;
688        }
689
690        // Build parameter lists for all function types
691        let mut cabi_params: Vec<String> = Vec::new();
692        let mut zig_params: Vec<String> = Vec::new();
693        let mut arg_names: Vec<String> = Vec::new();
694        let mut cabi_to_zig_conversions: Vec<String> = Vec::new();
695
696        for (pname, ptype) in &exp.params {
697            arg_names.push(pname.clone());
698            if *ptype == crate::infer::ZigType::String {
699                cabi_params.push(format!("{}: [*:0]const u8", pname));
700                zig_params.push(format!("{}: []const u8", pname));
701                cabi_to_zig_conversions.push(format!(
702                    "    const {p}_slice: []const u8 = std.mem.span({p});",
703                    p = pname
704                ));
705            } else {
706                let zig_ty = ptype.to_zig_str();
707                cabi_params.push(format!("{}: {}", pname, zig_ty));
708                zig_params.push(format!("{}: {}", pname, zig_ty));
709            }
710        }
711
712        // Build call args: for CABI wrapper, string params use _slice version
713        let zig_call_args: String = arg_names.join(", ");
714        let cabi_call_args: String = exp.params.iter().map(|(pname, ptype)| {
715            if *ptype == crate::infer::ZigType::String {
716                format!("{}_slice", pname)
717            } else {
718                pname.clone()
719            }
720        }).collect::<Vec<_>>().join(", ");
721
722        // ── Async exports: call _impl with js_runtime.getIo(), catch errors ──
723        if exp.is_async {
724            let async_zig_args = if zig_call_args.is_empty() {
725                "js_runtime.getIo()".to_string()
726            } else {
727                format!("js_runtime.getIo(), {}", zig_call_args)
728            };
729            let async_cabi_args = if cabi_call_args.is_empty() {
730                "js_runtime.getIo()".to_string()
731            } else {
732                format!("js_runtime.getIo(), {}", cabi_call_args)
733            };
734
735            if returns_string {
736                // Zig-friendly adapter (for tests) — calls _impl directly
737                out.push_str(&format!(
738                    "pub fn {name}({params}) []const u8 {{\n    return {mod}.{name}_impl({args}) catch @panic(\"async error\");\n}}\n",
739                    name = name,
740                    params = zig_params.join(", "),
741                    mod = module,
742                    args = async_zig_args,
743                ));
744                // C ABI wrapper
745                let conversions = if cabi_to_zig_conversions.is_empty() {
746                    String::new()
747                } else {
748                    format!("{}\n", cabi_to_zig_conversions.join("\n"))
749                };
750                out.push_str(&format!(
751                    "pub export fn {name}_cabi({params}) [*:0]const u8 {{\n{conv}    const _result = {mod}.{name}_impl({args}) catch @panic(\"async error\");\n    return @ptrCast(_result.ptr);\n}}\n",
752                    name = name,
753                    params = cabi_params.join(", "),
754                    conv = conversions,
755                    mod = module,
756                    args = async_cabi_args,
757                ));
758                out.push_str(&format!(
759                    "comptime {{ @export(&{name}_cabi, .{{ .name = \"{name}\", .linkage = .strong }}); }}\n",
760                    name = name,
761                ));
762            } else {
763                let ret_zig = if exp.ret_type == crate::infer::ZigType::Void {
764                    "void".to_string()
765                } else {
766                    exp.ret_type.to_zig_str()
767                };
768                let exp_ret_is_js_value = exp.ret_type == crate::infer::ZigType::JsValue;
769                let conversions = if cabi_to_zig_conversions.is_empty() {
770                    String::new()
771                } else {
772                    format!("{}\n", cabi_to_zig_conversions.join("\n"))
773                };
774
775                if ret_zig == "void" {
776                    out.push_str(&format!(
777                        "pub export fn {name}({params}) void {{\n{conv}    {mod}.{name}_impl({args}) catch @panic(\"async error\");\n}}\n",
778                        name = name,
779                        params = cabi_params.join(", "),
780                        conv = conversions,
781                        mod = module,
782                        args = async_cabi_args,
783                    ));
784                } else if exp_ret_is_js_value {
785                    out.push_str(&format!(
786                        "pub export fn {name}({params}) i64 {{\n{conv}    const _result = {mod}.{name}_impl({args}) catch @panic(\"async error\");\n    return _result.int;\n}}\n",
787                        name = name,
788                        params = cabi_params.join(", "),
789                        conv = conversions,
790                        mod = module,
791                        args = async_cabi_args,
792                    ));
793                } else {
794                    out.push_str(&format!(
795                        "pub export fn {name}({params}) {ret} {{\n{conv}    return {mod}.{name}_impl({args}) catch @panic(\"async error\");\n}}\n",
796                        name = name,
797                        params = cabi_params.join(", "),
798                        conv = conversions,
799                        ret = ret_zig,
800                        mod = module,
801                        args = async_cabi_args,
802                    ));
803                }
804            }
805
806            // free_xxx wrapper (C ABI, always _cabi suffix for string returns)
807            if exp.has_free_func {
808                let free_fn = format!("free_{}", name);
809                if returns_string {
810                    out.push_str(&format!(
811                        "pub export fn {free_fn}_cabi(ptr: [*:0]const u8) void {{
812    {mod}.free_{name}(ptr);
813}}\n",
814                        free_fn = free_fn,
815                        name = name,
816                        mod = module,
817                    ));
818                    out.push_str(&format!(
819                        "comptime {{ @export(&{free_fn}_cabi, .{{ .name = \"{free_fn}\", .linkage = .strong }}); }}\n",
820                        free_fn = free_fn,
821                    ));
822                }
823            }
824
825            out.push('\n');
826            continue;
827        }
828
829        if returns_string {
830            // ── Zig-friendly adapter (for tests) — calls _impl directly, no conversion ──
831            out.push_str(&format!(
832                "pub fn {name}({params}) []const u8 {{\n    return {mod}.{name}_impl({args});\n}}\n",
833                name = name,
834                params = zig_params.join(", "),
835                mod = module,
836                args = zig_call_args,
837            ));
838
839            // ── C ABI wrapper — converts string params and return value ──
840            let conversions = if cabi_to_zig_conversions.is_empty() {
841                String::new()
842            } else {
843                format!("{}\n", cabi_to_zig_conversions.join("\n"))
844            };
845            out.push_str(&format!(
846                "pub export fn {name}_cabi({params}) [*:0]const u8 {{\n{conv}    const _result = {mod}.{name}_impl({args});\n    return @ptrCast(_result.ptr);\n}}\n",
847                name = name,
848                params = cabi_params.join(", "),
849                conv = conversions,
850                mod = module,
851                args = cabi_call_args,
852            ));
853            out.push_str(&format!(
854                "comptime {{ @export(&{name}_cabi, .{{ .name = \"{name}\", .linkage = .strong }}); }}\n",
855                name = name,
856            ));
857        } else {
858            let ret_zig = if exp.ret_type == crate::infer::ZigType::Void {
859                "void".to_string()
860            } else {
861                exp.ret_type.to_zig_str()
862            };
863            let exp_ret_is_js_value = exp.ret_type == crate::infer::ZigType::JsValue;
864
865            if ret_zig == "void" {
866                out.push_str(&format!(
867                    "pub export fn {name}({params}) void {{\n    {mod}.{name}({args});\n}}\n",
868                    name = name,
869                    params = cabi_params.join(", "),
870                    mod = module,
871                    args = zig_call_args,
872                ));
873            } else if exp_ret_is_js_value {
874                // JsValue: extract .int for C ABI (i64)
875                out.push_str(&format!(
876                    "pub export fn {name}({params}) i64 {{\n    const _result = {mod}.{name}({args});\n    return _result.int;\n}}\n",
877                    name = name,
878                    params = cabi_params.join(", "),
879                    mod = module,
880                    args = zig_call_args,
881                ));
882            } else {
883                out.push_str(&format!(
884                    "pub export fn {name}({params}) {ret} {{\n    return {mod}.{name}({args});\n}}\n",
885                    name = name,
886                    params = cabi_params.join(", "),
887                    ret = ret_zig,
888                    mod = module,
889                    args = zig_call_args,
890                ));
891            }
892        }
893
894        // ── free_xxx wrapper (C ABI, always _cabi suffix) ──
895        if exp.has_free_func {
896            let free_fn = format!("free_{}", name);
897            if returns_string {
898                out.push_str(&format!(
899                    "pub export fn {free_fn}_cabi(ptr: [*:0]const u8) void {{
900    {mod}.free_{name}(ptr);
901}}\n",
902                    free_fn = free_fn,
903                    name = name,
904                    mod = module,
905                ));
906                out.push_str(&format!(
907                "comptime {{ @export(&{free_fn}_cabi, .{{ .name = \"{free_fn}\", .linkage = .strong }}); }}\n",
908                    free_fn = free_fn,
909                ));
910            } else {
911                // Closure return: free takes *anyopaque
912                out.push_str(&format!(
913                    "pub export fn {free_fn}(ptr: *anyopaque) void {{
914    {mod}.{free_fn}(ptr);
915}}\n",
916                    free_fn = free_fn,
917                    mod = module,
918                ));
919            }
920        }
921
922        out.push('\n');
923    }
924
925    out
926}
927
928/// Write C ABI exports/imports JSON metadata for a single group project.
929pub fn write_cabi_metadata(
930    out_dir: &Path,
931    group_name: &str,
932    cabi_exports: &[crate::codegen::CabiExport],
933    host_fns: &crate::host::HostFnRegistry,
934    include_init: bool,
935) {
936    let project_dir = out_dir.join(group_name);
937
938    // cabi_exports.json — filter out JsAny returns (no C ABI export generated)
939    let exports_path = project_dir.join("cabi_exports.json");
940    let mut exports_value: Vec<serde_json::Value> = cabi_exports
941        .iter()
942        .filter(|exp| exp.ret_type != crate::infer::ZigType::JsAny)
943        .map(|exp| {
944            let params: Vec<serde_json::Value> = exp
945                .params
946                .iter()
947                .map(|(name, ty)| {
948                    serde_json::json!({
949                        "name": name,
950                        "zig_type": ty.to_zig_str()
951                    })
952                })
953                .collect();
954            serde_json::json!({
955                "name": exp.name,
956                "params": params,
957                "ret_type": exp.ret_type.to_cabi_str(),
958                "has_free_func": exp.has_free_func
959            })
960        })
961        .collect();
962
963    // Only include js2rust_init and js2rust_deinit for the first non-test group
964    if include_init {
965        exports_value.push(serde_json::json!({
966            "name": "js2rust_init",
967            "params": [],
968            "ret_type": "void",
969            "has_free_func": false
970        }));
971        exports_value.push(serde_json::json!({
972            "name": "js2rust_deinit",
973            "params": [],
974            "ret_type": "void",
975            "has_free_func": false
976        }));
977    }
978
979    if let Ok(json_str) = serde_json::to_string_pretty(&exports_value) {
980        let _ = fs::write(&exports_path, &json_str);
981    }
982
983    // cabi_imports.json
984    let imports_path = project_dir.join("cabi_imports.json");
985    let imports_value = host_fns.to_json_value();
986    if let Ok(json_str) = serde_json::to_string_pretty(&imports_value) {
987        let _ = fs::write(&imports_path, &json_str);
988    }
989}