Skip to main content

js2zig_core/
pipeline.rs

1use crate::analyzer::{analyze_project, 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, Stdio};
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 analysis
19/// and maps source filenames to sanitized Zig module names.
20fn build_dep_imports(
21    filename: &str,
22    analysis: &crate::analyzer::AnalysisResult,
23) -> Vec<(String, String)> {
24    let empty = Vec::new();
25    let raw_imports = analysis.imported_names.get(filename).unwrap_or(&empty);
26    raw_imports
27        .iter()
28        .map(|(imported_name, src_file)| {
29            let mod_name = analysis
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/// Compute a content hash for the project.
43/// Hashes all member JS files + runtime .zig files so any change triggers rebuild.
44fn compute_content_hash(
45    in_dir: &Path,
46    analysis: &crate::analyzer::AnalysisResult,
47    runtime_dir: &Path,
48) -> String {
49    let mut hasher = std::hash::DefaultHasher::new();
50
51    // Hash each member JS file content (sorted for determinism)
52    let mut members: Vec<&String> = analysis.members.iter().collect();
53    members.sort();
54    for member in &members {
55        member.hash(&mut hasher);
56        if let Ok(content) = fs::read(in_dir.join(member)) {
57            content.hash(&mut hasher);
58        }
59    }
60
61    // Hash runtime .zig files (changes here affect the output)
62    if let Ok(entries) = fs::read_dir(runtime_dir) {
63        let mut rt_files: Vec<PathBuf> = entries
64            .filter_map(|e| e.ok())
65            .map(|e| e.path())
66            .filter(|p| p.extension().is_some_and(|ext| ext == "zig"))
67            .collect();
68        rt_files.sort();
69        for rt_file in &rt_files {
70            if let Ok(content) = fs::read(rt_file) {
71                rt_file.file_name().hash(&mut hasher);
72                content.hash(&mut hasher);
73            }
74        }
75    }
76
77    format!("{:016x}", hasher.finish())
78}
79
80/// Read build cache from `out/.build_cache.json`.
81/// Returns project_name → hash_hex map.
82fn read_build_cache(out_dir: &Path) -> HashMap<String, String> {
83    let cache_path = out_dir.join(".build_cache.json");
84    if let Ok(data) = fs::read_to_string(&cache_path)
85        && let Ok(map) = serde_json::from_str(&data)
86    {
87        return map;
88    }
89    HashMap::new()
90}
91
92/// Write build cache to `out/.build_cache.json`.
93fn write_build_cache(out_dir: &Path, cache: &HashMap<String, String>) {
94    let cache_path = out_dir.join(".build_cache.json");
95    if let Ok(json) = serde_json::to_string_pretty(cache) {
96        let _ = fs::write(cache_path, json);
97    }
98}
99
100/// Save project diagnostics to `out/<project_name>/diagnostics.json`.
101/// On cache hit, these are loaded back so the caller always sees
102/// consistent diagnostic output without re-transpiling.
103fn save_diagnostics(out_dir: &Path, project_name: &str, diagnostics: &[String]) {
104    let path = Path::new(out_dir)
105        .join(project_name)
106        .join("diagnostics.json");
107    if let Ok(json) = serde_json::to_string_pretty(diagnostics) {
108        let _ = fs::write(path, json);
109    }
110}
111
112pub fn transpile_project(config: &ProjectConfig) -> Result<ProjectResult, String> {
113    let ws = workspace_dir();
114
115    // js_dir is the source directory; js_files[0] is the primary entry.
116    let in_dir = &config.js_dir;
117    let js_files = &config.js_files;
118    if js_files.is_empty() {
119        return Err("js2rust_bridge: project.js_files is empty in js2rust.toml".to_string());
120    }
121    let primary_root = &js_files[0];
122    let out_dir = config.out_dir.clone();
123    let force_rebuild = config.build.force_rebuild;
124    let verbose = config.build.is_build_script; // only print progress in build.rs context
125
126    // Ensure output directory exists.
127    fs::create_dir_all(&out_dir).map_err(|e| {
128        format!(
129            "cannot create output directory '{}': {}",
130            out_dir.display(),
131            e
132        )
133    })?;
134
135    // === Phase 1: Analyze project (entry file + transitive deps) ===
136    let analysis = analyze_project(in_dir, js_files)?;
137
138    // Emit cargo:rerun-if-changed for every JS file discovered by the analyzer
139    // (including transitive dependencies not listed in js2rust.toml).
140    // These directives take effect in subsequent builds — Cargo stores them
141    // and uses them to decide whether to re-run the build script.
142    // Only emit when called from build.rs (is_build_script=true);
143    // proc-macros cannot use these directives and their stdout would leak
144    // noise to the terminal.
145    if config.build.is_build_script {
146        for member in &analysis.members {
147            let member_path = in_dir.join(member);
148            println!("cargo:rerun-if-changed={}", member_path.display());
149        }
150    }
151
152    if analysis.members.is_empty() {
153        return Err(format!(
154            "no JS files discovered from primary root '{}'",
155            primary_root
156        ));
157    }
158
159    // === Load host function registry ===
160    let mut host_fns = crate::host::HostFnRegistry::new();
161
162    // If host_config is provided in ProjectConfig, use it
163    if let Some(ref host_config) = config.host_config {
164        // Convert HostFunction to HostFnDef and register
165        for f in &host_config.functions {
166            let params: Vec<(String, crate::types::ZigType)> = f
167                .params
168                .iter()
169                .enumerate()
170                .map(|(i, t)| (format!("arg{}", i), crate::types::ZigType::from(*t)))
171                .collect();
172
173            if f.is_async {
174                if f.async_return_fields.is_empty() {
175                    // Async with simple return type
176                    let return_type = f
177                        .return_type
178                        .map(crate::types::ZigType::from)
179                        .unwrap_or(crate::types::ZigType::Void);
180                    host_fns.register_async_simple(&f.name, &f.name, params, return_type);
181                } else {
182                    // Async with struct return type
183                    let zig_name = f.struct_zig_name();
184                    let c_name = f.struct_c_name();
185                    let fields: Vec<crate::host::HostStructField> = f
186                        .async_return_fields
187                        .iter()
188                        .map(|(name, ty)| crate::host::HostStructField {
189                            name: name.clone(),
190                            zig_type: ty.to_zig_field_type().to_string(),
191                            c_type: ty.to_c_field_type().to_string(),
192                        })
193                        .collect();
194                    let struct_def = crate::host::HostStructDef {
195                        zig_name,
196                        c_name,
197                        fields,
198                    };
199                    host_fns.register_async(&f.name, &f.name, params, struct_def);
200                }
201            } else {
202                let return_type = f.return_type.map(crate::types::ZigType::from);
203                host_fns.register(
204                    &f.name,
205                    params,
206                    return_type.unwrap_or(crate::types::ZigType::Void),
207                );
208            }
209        }
210    }
211
212    let host_header = host_fns.generate_zig_header();
213    let async_host_fn_names: Vec<String> = host_fns.async_fn_names();
214    let runtime_dir = ws.join("runtime");
215
216    // === Incremental compilation: load build cache ===
217    let build_cache = read_build_cache(&out_dir);
218    let project_name = analysis.entry_name.clone();
219    let is_test = project_name.starts_with("test_");
220
221    if verbose {
222        println!(
223            "\n=== {} ({} member{}) {}===",
224            project_name,
225            analysis.members.len(),
226            if analysis.members.len() == 1 { "" } else { "s" },
227            if is_test { "[test] " } else { "" }
228        );
229    }
230
231    // --- Incremental check ---
232    let current_hash = compute_content_hash(in_dir, &analysis, &runtime_dir);
233    if let Some((diagnostics, cabi_json)) = try_cache_hit(
234        &out_dir,
235        &project_name,
236        force_rebuild,
237        &build_cache,
238        &current_hash,
239        verbose,
240    ) {
241        return Ok(ProjectResult {
242            project_name,
243            is_test,
244            cabi_exports_json: cabi_json,
245            diagnostics,
246        });
247    }
248
249    // Cache miss — full transpile + build.
250    let (result_diagnostics, result_cabi_json) = transpile_cache_miss(
251        &out_dir,
252        &project_name,
253        is_test,
254        &analysis,
255        primary_root,
256        js_files,
257        &host_fns,
258        &host_header,
259        &async_host_fn_names,
260        &current_hash,
261        &build_cache,
262        config,
263        verbose,
264        &runtime_dir,
265    )?;
266
267    Ok(ProjectResult {
268        project_name,
269        is_test,
270        cabi_exports_json: result_cabi_json,
271        diagnostics: result_diagnostics,
272    })
273}
274
275/// Check the incremental build cache for a matching entry.
276///
277/// Returns `Some((diagnostics, cabi_json))` on cache hit, or `None` on miss.
278fn try_cache_hit(
279    out_dir: &Path,
280    project_name: &str,
281    force_rebuild: bool,
282    build_cache: &HashMap<String, String>,
283    current_hash: &str,
284    verbose: bool,
285) -> Option<(Vec<String>, String)> {
286    if force_rebuild {
287        return None;
288    }
289    let cached_hash = build_cache.get(project_name)?;
290    if *cached_hash != current_hash {
291        return None;
292    }
293
294    if verbose {
295        println!("  unchanged (cache hit)");
296    }
297    let cabi_path = out_dir.join(project_name).join("cabi_exports.json");
298    let cabi_json = fs::read_to_string(&cabi_path).unwrap_or_default();
299
300    // Load cached diagnostics so the caller always sees consistent output.
301    let diag_path = out_dir.join(project_name).join("diagnostics.json");
302    let diagnostics: Vec<String> = fs::read_to_string(&diag_path)
303        .ok()
304        .and_then(|s| serde_json::from_str(&s).ok())
305        .unwrap_or_default();
306
307    Some((diagnostics, cabi_json))
308}
309
310/// Full transpile + build (cache miss path).
311///
312/// Takes all analysis results and configuration, performs transpilation,
313/// writes output files, runs zig build/test, and persists the build cache.
314/// Returns `(diagnostics, cabi_json)` on success, or an error string on failure.
315#[allow(clippy::too_many_arguments)]
316fn transpile_cache_miss(
317    out_dir: &Path,
318    project_name: &str,
319    is_test: bool,
320    analysis: &crate::analyzer::AnalysisResult,
321    primary_root: &str,
322    js_files: &[String],
323    host_fns: &crate::host::HostFnRegistry,
324    host_header: &str,
325    async_host_fn_names: &[String],
326    current_hash: &str,
327    build_cache: &HashMap<String, String>,
328    config: &ProjectConfig,
329    verbose: bool,
330    runtime_dir: &Path,
331) -> Result<(Vec<String>, String), String> {
332    if config.build.force_rebuild {
333        if verbose {
334            println!("  force rebuild");
335        }
336    } else if verbose {
337        println!("  source changed, re-transpiling");
338    }
339
340    let mut per_file_modules: Vec<crate::project::PerFileModule> = Vec::new();
341    let mut all_module_exports: Vec<(String, String)> = Vec::new();
342    let mut all_test_code = String::new();
343    let mut all_cabi_exports: Vec<(String, crate::types::NativeCabiExport)> = Vec::new();
344    let mut file_diagnostics: Vec<String> = Vec::new();
345
346    // --- Transpile pass (all metadata from analysis, no source scanning) ---
347    let core_exports = analysis
348        .exported_names
349        .get(primary_root)
350        .cloned()
351        .unwrap_or_default();
352
353    // --- Compute re-exported names per dependency ---
354    let core_imports = analysis
355        .imported_names
356        .get(primary_root)
357        .cloned()
358        .unwrap_or_default();
359    let mut dep_re_exports: HashMap<String, HashSet<String>> = HashMap::new();
360    for (imported_name, source_file) in &core_imports {
361        if core_exports.contains(imported_name) {
362            dep_re_exports
363                .entry(source_file.clone())
364                .or_default()
365                .insert(imported_name.clone());
366        }
367    }
368
369    let mut has_any_error = false;
370
371    for member in &analysis.members {
372        let src = match analysis.file_sources.get(member) {
373            Some(s) => s.as_str(),
374            None => {
375                eprintln!("  skip '{}': no cached source", member);
376                continue;
377            }
378        };
379
380        if src.trim().is_empty() {
381            eprintln!("  skip '{}': empty source", member);
382            continue;
383        }
384
385        let module_name = analysis.name_map.get(member).cloned().unwrap_or_else(|| {
386            let stem = member.strip_suffix(".js").unwrap_or(member);
387            sanitize_module_name(stem)
388        });
389
390        // For test projects: ALL toplevel functions → C ABI.
391        // For normal projects: entry file's JS exports → C ABI;
392        //                     additional core files → C ABI (full exports);
393        //                     dependency file: only re-exported names → C ABI.
394        let transpile_exports: HashSet<String> = if is_test {
395            analysis
396                .all_fn_names
397                .get(member)
398                .cloned()
399                .unwrap_or_default()
400        } else if *member == *primary_root || js_files.iter().skip(1).any(|f| *f == *member) {
401            analysis
402                .exported_names
403                .get(member)
404                .cloned()
405                .unwrap_or_default()
406        } else {
407            dep_re_exports.get(member).cloned().unwrap_or_default()
408        };
409
410        let module_exports = transpile_exports.clone();
411
412        let program = match analysis.parsed_programs.get(member) {
413            Some(p) => p,
414            None => {
415                eprintln!("  skip '{}': no parsed program", member);
416                continue;
417            }
418        };
419
420        let transpile_result = crate::native_proto::transpile_js(
421            program,
422            src,
423            Some(transpile_exports),
424            Some(host_fns),
425            member,
426        );
427
428        let (zig_code, cabi_exports, has_error) = match transpile_result {
429            Ok(result) => {
430                // @compileError diagnostics (non-blocking)
431                if !result.compile_errors.is_empty() {
432                    eprintln!(
433                        "  '{}': {} unsupported feature(s):",
434                        member,
435                        result.compile_errors.len()
436                    );
437                    for msg in &result.compile_errors {
438                        eprintln!("    @compileError: {}", msg);
439                    }
440                    for msg in &result.compile_errors {
441                        file_diagnostics.push(format!("{}: COMPILE_ERROR - {}", member, msg));
442                    }
443                }
444
445                // Hard errors — block file generation
446                let hard_errors: Vec<&str> = result
447                    .errors
448                    .iter()
449                    .filter(|m| !m.contains("(Rule 8)"))
450                    .map(|s| s.as_str())
451                    .collect();
452                // Rule 8 soft errors — non-blocking warnings
453                let rule8_errors: Vec<&str> = result
454                    .errors
455                    .iter()
456                    .filter(|m| m.contains("(Rule 8)"))
457                    .map(|s| s.as_str())
458                    .collect();
459
460                if !hard_errors.is_empty() {
461                    eprintln!(
462                        "  skip '{}': {} transpile error(s)",
463                        member,
464                        hard_errors.len()
465                    );
466                    for msg in &hard_errors {
467                        eprintln!("    {}", msg);
468                    }
469                    for msg in &hard_errors {
470                        file_diagnostics.push(format!("{}: ERROR - {}", member, msg));
471                    }
472                    for msg in &rule8_errors {
473                        eprintln!("    [Rule 8] {}", msg);
474                    }
475                    for msg in &rule8_errors {
476                        file_diagnostics.push(format!("{}: WARNING - {}", member, msg));
477                    }
478                    for msg in &result.warnings {
479                        eprintln!("    {}", msg);
480                        file_diagnostics.push(format!("{}: {}", member, msg));
481                    }
482                    (String::new(), Vec::new(), true)
483                } else {
484                    if !rule8_errors.is_empty() {
485                        eprintln!(
486                            "  '{}': {} Rule 8 diagnostic(s) (non-blocking)",
487                            member,
488                            rule8_errors.len()
489                        );
490                        for msg in &rule8_errors {
491                            eprintln!("    {}", msg);
492                        }
493                        for msg in &rule8_errors {
494                            file_diagnostics.push(format!("{}: WARNING - {}", member, msg));
495                        }
496                    }
497                    if !result.warnings.is_empty() {
498                        eprintln!("  '{}': {} diagnostic(s)", member, result.warnings.len());
499                        for msg in &result.warnings {
500                            eprintln!("    {}", msg);
501                        }
502                        for msg in &result.warnings {
503                            file_diagnostics.push(format!("{}: {}", member, msg));
504                        }
505                    }
506
507                    let cabi_exports = result.cabi_exports;
508
509                    if is_test {
510                        let test_cases = crate::testgen::extract_test_cases(program, src);
511                        let ret_type_map: HashMap<String, String> = result
512                            .var_types
513                            .iter()
514                            .map(|(k, v)| (k.clone(), v.to_zig_type().into_owned()))
515                            .collect();
516                        let file_test_code = crate::testgen::generate_test_code(
517                            &test_cases,
518                            &HashSet::new(),
519                            &ret_type_map,
520                        );
521                        all_test_code.push_str(&file_test_code);
522                    }
523
524                    (result.zig_code, cabi_exports, false)
525                }
526            }
527            Err(e) => {
528                eprintln!("  skip '{}': transpile error", member);
529                file_diagnostics.push(format!("{}: ERROR - {}", member, e));
530                (String::new(), Vec::new(), true)
531            }
532        };
533
534        if has_error {
535            has_any_error = true;
536            continue;
537        }
538
539        for exp in &module_exports {
540            all_module_exports.push((exp.clone(), module_name.clone()));
541        }
542        for ce in &cabi_exports {
543            if !module_exports.contains(&ce.name) {
544                all_module_exports.push((ce.name.clone(), module_name.clone()));
545            }
546        }
547
548        let dep_imports = build_dep_imports(member, analysis);
549
550        per_file_modules.push(crate::project::PerFileModule {
551            mod_name: module_name.clone(),
552            zig_code,
553            dep_imports,
554        });
555
556        for export in cabi_exports {
557            all_cabi_exports.push((module_name.clone(), export));
558        }
559    }
560
561    // Only fail if NO files succeeded transpilation.
562    if per_file_modules.is_empty() {
563        if has_any_error {
564            eprintln!("  skip: all files failed transpilation");
565        } else {
566            eprintln!("  skip: no valid modules after transpilation");
567        }
568        write_build_cache(out_dir, build_cache);
569        return Ok((file_diagnostics, String::new()));
570    }
571
572    if has_any_error {
573        eprintln!(
574            "  warning: {} file(s) had transpile errors, continuing with {} successful file(s)",
575            analysis.members.len() - per_file_modules.len(),
576            per_file_modules.len()
577        );
578    }
579
580    // --- Detect export name collisions and build rename map ---
581    let bare_name_counts: HashMap<&str, usize> = {
582        let mut counts: HashMap<&str, usize> = HashMap::new();
583        for (exp_name, _) in &all_module_exports {
584            *counts.entry(exp_name.as_str()).or_insert(0) += 1;
585        }
586        counts
587    };
588    let is_colliding =
589        |name: &str| -> bool { bare_name_counts.get(name).copied().unwrap_or(0) > 1 };
590
591    let mut cabi_rename: HashMap<String, String> = HashMap::new();
592    let mut name_to_module: HashMap<String, String> = HashMap::new();
593    for (exp_name, mod_name) in &all_module_exports {
594        let cabi_name = disambiguate_name(exp_name, mod_name, |n| is_colliding(n));
595        cabi_rename
596            .entry(cabi_name.clone())
597            .or_insert_with(|| exp_name.clone());
598        name_to_module
599            .entry(cabi_name)
600            .or_insert_with(|| mod_name.clone());
601    }
602    let mut name_to_cabi: HashMap<String, &crate::types::NativeCabiExport> = HashMap::new();
603    for (mod_name, exp) in &all_cabi_exports {
604        let key = disambiguate_name(&exp.name, mod_name, |n| is_colliding(n));
605        name_to_cabi.entry(key).or_insert(exp);
606    }
607    let cabi_wrapper_code = gen_cabi_wrappers(&name_to_module, &name_to_cabi, &cabi_rename);
608    let cabi_names: HashSet<String> = name_to_cabi.keys().cloned().collect();
609
610    let disambiguated_exports: Vec<(String, String, String)> = all_module_exports
611        .iter()
612        .map(|(exp_name, mod_name)| {
613            let cabi_name = disambiguate_name(exp_name, mod_name, |n| is_colliding(n));
614            (cabi_name, mod_name.clone(), exp_name.clone())
615        })
616        .collect();
617
618    // Detect feature usage from emitted Zig code
619    let needs_regex = per_file_modules.iter().any(|m| {
620        m.zig_code.contains("host_regex.")
621            || m.zig_code.contains("js_regexp.")
622            || m.zig_code.contains("JsRegExp")
623            || m.zig_code.contains("js_string_regex.")
624    });
625
626    let needs_icu = per_file_modules.iter().any(|m| {
627        m.zig_code.contains("host_icu.")
628            || m.zig_code.contains("js_string_icu.localeCompare")
629            || m.zig_code.contains("js_string_icu.normalize")
630            || m.zig_code.contains("js_string_icu.toLocaleUpper")
631            || m.zig_code.contains("js_string_icu.toLocaleLower")
632    });
633
634    let project_opts = crate::project::ProjectOptions {
635        name: project_name.to_string(),
636        out_dir: out_dir.to_path_buf(),
637        per_file_code: per_file_modules,
638        external_exports: disambiguated_exports,
639        cabi_wrapper_code,
640        cabi_names,
641        test_code: all_test_code,
642        runtime_dir: Some(runtime_dir.to_path_buf()),
643        host_header: if !host_fns.is_empty() {
644            host_header.to_string()
645        } else {
646            String::new()
647        },
648        async_host_fn_names: async_host_fn_names.to_vec(),
649        needs_regex,
650        needs_icu,
651    };
652
653    match crate::project::generate(&project_opts) {
654        Ok(()) => {
655            if verbose {
656                println!("  Generated: {}/{}", out_dir.display(), project_name);
657            }
658        }
659        Err(e) => {
660            eprintln!("  FAIL ({})", e);
661            write_build_cache(out_dir, build_cache);
662            return Ok((file_diagnostics, String::new()));
663        }
664    }
665
666    // Write CABI metadata
667    let include_init = !is_test;
668    write_cabi_metadata(
669        out_dir,
670        project_name,
671        &all_cabi_exports,
672        host_fns,
673        include_init,
674        &cabi_rename,
675    );
676
677    // Collect cabi_exports_json
678    let cabi_path = out_dir.join(project_name).join("cabi_exports.json");
679    let result_cabi_json = fs::read_to_string(&cabi_path).unwrap_or_default();
680
681    // Persist diagnostics
682    save_diagnostics(out_dir, project_name, &file_diagnostics);
683
684    // Update build cache
685    let mut build_cache = build_cache.clone();
686    build_cache.insert(project_name.to_string(), current_hash.to_string());
687
688    // === Zig build ===
689    if config.build.run_zig_build {
690        let project_path = out_dir.join(project_name);
691        let mut build_cmd = Command::new("zig");
692        build_cmd.arg("build");
693        if let Some(ref opt) = config.build.zig_optimize {
694            build_cmd.arg(format!("-Doptimize={}", opt));
695        }
696        let build_result = build_cmd.current_dir(&project_path).output();
697        match build_result {
698            Ok(result) if result.status.success() => {
699                if verbose {
700                    println!("  zig build: OK");
701                }
702            }
703            Ok(result) => {
704                let stderr = String::from_utf8_lossy(&result.stderr);
705                eprintln!("  zig build FAILED:\n{}", stderr);
706                write_build_cache(out_dir, &build_cache);
707                return Err(format!(
708                    "zig build failed for project '{}':\n{}",
709                    project_name,
710                    stderr.lines().take(20).collect::<Vec<_>>().join("\n")
711                ));
712            }
713            Err(_) => {
714                eprintln!("  warning: zig not found — skipping build");
715            }
716        }
717
718        // === Zig tests ===
719        if !host_fns.is_empty() {
720            if verbose {
721                println!("  zig test: SKIPPED (project has host function dependencies)");
722            }
723        } else {
724            let test_result = Command::new("zig")
725                .arg("build")
726                .arg("test")
727                .current_dir(&project_path)
728                .stdout(Stdio::null())
729                .stderr(Stdio::null())
730                .status();
731            match test_result {
732                Ok(status) if status.success() => {
733                    if verbose {
734                        println!("  zig test: PASSED");
735                    }
736                }
737                Ok(_) => {
738                    eprintln!("  zig test FAILED");
739                }
740                Err(e) => {
741                    eprintln!("  zig test: failed to execute: {}", e);
742                }
743            }
744        }
745    }
746
747    // Write build cache on success
748    write_build_cache(out_dir, &build_cache);
749
750    Ok((file_diagnostics, result_cabi_json))
751}
752
753use crate::cabi::{disambiguate_name, gen_cabi_wrappers, write_cabi_metadata};