Skip to main content

js2zig_core/
pipeline.rs

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
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(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
39/// Extract all top-level function names from JS source text.
40/// Scan zig_code for all `pub fn xxx(` and `pub export fn xxx(` declarations.
41/// Returns the function names so the orchestrator can re-export them.
42fn 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            // Skip infrastructure functions that shouldn't be re-exported
56            if name != "init_js2rust" && name != "deinit_js2rust" {
57                fns.push(name);
58            }
59        }
60    }
61    fns
62}
63
64/// Compute a content hash for a file group.
65/// Hashes all member JS files + runtime .zig files so any change triggers rebuild.
66fn 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    // Hash each member JS file content (sorted for determinism)
74    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    // Hash runtime .zig files (changes here affect all groups)
84    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
102/// Read build cache from `out/.build_cache.json`.
103/// Returns group_name → hash_hex map.
104fn 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
114/// Write build cache to `out/.build_cache.json`.
115fn 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    // Derive input directory and core file name from js_file path.
126    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    // Ensure output directory exists.
142    fs::create_dir_all(&out_dir)
143        .map_err(|e| format!("cannot create output directory '{}': {}", out_dir, e))?;
144
145    // === Phase 1: Analyze file groups (single or multi-root core files + transitive deps) ===
146    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    // === Load host function registry ===
173    let mut host_fns = crate::host::HostFnRegistry::new();
174
175    // If host_config is provided in ProjectConfig, use it
176    if let Some(ref host_config) = config.host_config {
177        // Convert HostFunction to HostFnDef and register
178        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                    // Async with simple return type
189                    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                    // Async with struct return type
196                    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        // Fallback: load from host_config.json file
225        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            // No host_config.json found — this is normal for projects that don't use host functions.
237        }
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    // === Incremental compilation: load build cache ===
247    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    // === Phase 2: Generate Zig project per group ===
252    // Always uses multi-file mode: one .zig per JS file + orchestrator lib.zig.
253    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        // --- Incremental check ---
264        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            // Still collect the cabi_exports_json for the result
271            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(), // incremental cache — no diagnostics needed
280                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            // --- Codegen pass (all metadata from group AST, no source scanning) ---
296            let core_exports = group
297                .exported_names
298                .get(&group.core_file)
299                .cloned()
300                .unwrap_or_default();
301
302            // --- Compute re-exported names per dependency ---
303            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            // Additional core files (multi-root): treat their exports as CABI-exportable too.
319            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                // For test groups: ALL toplevel functions → C ABI.
342                // For normal groups: core file's JS exports → C ABI;
343                //                    additional core files → C ABI (full exports);
344                //                    dependency file: only re-exported names → C ABI.
345                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                // Collect host function return types and param types for type inference
358                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                // Use native_proto (strict static type system) — pre-parsed AST
379                // from analyze_single_group, no re-parsing of source text.
380                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                            // Convert errors to diagnostics
397                            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                            // Convert warnings to diagnostics (non-fatal)
407                            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                            // Extract cabi_exports from result
416                            let cabi_exports = result.cabi_exports;
417
418                            // closure_fns: not supported in native_proto yet, use empty
419                            let closure_fns: std::collections::HashSet<String> =
420                                std::collections::HashSet::new();
421
422                            // fn_return_types: use var_types (native_proto::ZigType)
423                            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                            // source_map: not generated by native_proto yet
433                            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                            // Return error as diagnostic
446                            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                // Also scan all pub fn / pub export fn for test re-export
493                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                // Always collect CABI exports for all groups
513                all_cabi_exports.extend(cabi_exports);
514
515                if is_test_group {
516                    // Test groups: also generate Zig test code
517                    // (reuses the already-parsed program from group.parsed_programs)
518                    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            // --- Generate C ABI wrapper code for lib.zig ---
544            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            // Generate host.zig if host functions are registered
583            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            // Write source map JSON
598            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            // Write CABI metadata for all groups
625            // Only include init/deinit for the first non-test group
626            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            // Collect cabi_exports_json for the result
636            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            // Write test_cases.json for test groups (used by bridge test generation)
650        }
651
652        // === Zig build ===
653        if !config.run_zig_build {
654            // Skip zig build/test — caller handles compilation (e.g. proc-macro)
655            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        // === Zig tests ===
677        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        // === Update build cache on success ===
696        if build_ok && test_ok {
697            build_cache.insert(group.core_name.clone(), current_hash.clone());
698        }
699    }
700
701    // === Write build cache ===
702    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
715/// Generate `pub export fn` wrapper code for lib.zig.
716/// Each wrapper calls the per-file module function and lives in the root lib.zig,
717/// so Zig correctly propagates the symbols into the final .lib.
718///
719/// For string-returning functions, ALSO generate a Zig-friendly adapter
720/// (`pub fn greet(s: []const u8) []const u8`) so test code can call
721/// the function with idiomatic Zig string types.
722pub 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        // JsAny returns: re-export as const alias (no CABI export).
743        // This lets Zig test code call the function, but no C ABI symbol is emitted.
744        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        // Skip functions with JsValue/JsAny parameters (C ABI doesn't support unions)
754        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            // Re-export as const alias (no C ABI export)
760            out.push_str(&format!(
761                "pub const {name} = {mod}.{name};\n\n",
762                name = name,
763                mod = module,
764            ));
765            continue;
766        }
767
768        // Build parameter lists for all function types
769        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        // Build call args: for CABI wrapper, string params use _slice version
791        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        // ── Async exports: call _impl with js_runtime.getIo(), catch errors ──
806        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                // Zig-friendly adapter (for tests) — calls _impl directly
820                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                // C ABI wrapper (StrRet — zero-copy, panic via negative len)
828                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                // Async non-string: add _err out-param for can_throw exports
859                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            // ── Zig-friendly adapter (for tests) — calls _impl directly, no conversion ──
921            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            // ── C ABI wrapper (StrRet — zero-copy, error via sign-bit) ──
939            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            // Build C ABI param list: add _err out-param for can_throw non-string exports
979            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            // Build the call expression with error handling for can_throw
986            let (call_expr, err_setup) = if exp.can_throw {
987                let err_handle = if ret_zig == "void" {
988                    // Void: call without assignment
989                    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                // JsValue: extract .int for C ABI (i64)
1046                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
1094/// Write C ABI exports/imports JSON metadata for a single group project.
1095pub 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    // cabi_exports.json — filter out JsAny returns (no C ABI export generated)
1105    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            // Build params list
1111            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            // StrRet-returning functions: no result_len parameter needed
1123
1124            // Determine ret_type string for C ABI
1125            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    // Only include js2rust_init and js2rust_deinit for the first non-test group
1137    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    // cabi_imports.json
1155    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}