Skip to main content

rust_anything/
gate.rs

1//! Step 5: the definition of done for one port.
2//!
3//! fmt, clippy (warnings are errors), cargo tests, no unexplained `unsafe`, every function
4//! ported, the built module exposes the original API, and the recorded behavior replays cleanly.
5
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use anyhow::Result;
10use serde::Serialize;
11
12use crate::bridge::Manifest;
13use crate::harness::{self, CASES, DiffOptions};
14
15#[derive(Debug, Serialize)]
16pub struct Check {
17    pub name: &'static str,
18    pub passed: bool,
19    pub detail: String,
20    /// The next command or edit that clears a failed check.
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub fix: Option<String>,
23}
24
25/// Recovery guidance when an outside tool failed to start (structured `SpawnError`).
26fn spawn_fix(err: &anyhow::Error) -> Option<String> {
27    let spawn = err.downcast_ref::<crate::process::SpawnError>()?;
28    Some(if spawn.missing {
29        match crate::doctor::missing_command(&spawn.program) {
30            Some(install) if !install.contains('\n') => {
31                format!(
32                    "install `{}` with `{install}`, or run `rust-anything doctor`",
33                    spawn.program
34                )
35            }
36            _ => format!(
37                "run `rust-anything doctor` for how to install `{}`",
38                spawn.program
39            ),
40        }
41    } else {
42        "run `rust-anything doctor` and check that the build tool can run".into()
43    })
44}
45
46/// The fix for a failed check, by its name.
47fn fix_for(check: &Check, crate_dir: &Path) -> Option<String> {
48    let c = crate_dir.display();
49    let manifest = format!("--manifest-path {c}/Cargo.toml");
50    Some(match check.name {
51        "fmt" => format!("cargo fmt {manifest}"),
52        "clippy" => {
53            format!("cargo clippy --all-targets {manifest} -- -D warnings, then fix each warning")
54        }
55        "cargo test" => format!("cargo test {manifest}"),
56        "unsafe" => "add a `// SAFETY:` comment above each listed `unsafe`, or remove it".into(),
57        "ported" => {
58            "port the functions still stubbed in src/port.rs, then `rust-anything gate` again"
59                .into()
60        }
61        "size" => "use the crates `rust-anything analyze` lists and fold repeated code".into(),
62        "build" => format!("fix the compile error above, then `rust-anything build {c}`"),
63        "recording" => format!("rust-anything record {c}"),
64        "behavior" if check.detail.contains("no recorded cases") => {
65            format!("rust-anything record {c}")
66        }
67        "behavior" => format!(
68            "rust-anything diff {c} to see each mismatch; fix the port, or list an intended difference in {}",
69            crate::recording::KNOWN_DIFFS
70        ),
71        "known diffs" => format!(
72            "remove the entries that no longer happen from {c}/{}",
73            crate::recording::KNOWN_DIFFS
74        ),
75        "api" => {
76            format!("export the missing functions from src/port.rs, then `rust-anything build {c}`")
77        }
78        "error cases" | "panics" => {
79            format!("rust-anything diff {c} to see the cases where the port's errors differ")
80        }
81        _ => return None,
82    })
83}
84
85/// Bindings `bridge` writes into `src/`; everything else there is the port.
86const GENERATED: [&str; 8] = [
87    "lib.rs",
88    "js.rs",
89    "pinned.rs",
90    "pyconv.rs",
91    "pynum.rs",
92    "rbconv.rs",
93    "utf16.rs",
94    "wire.rs",
95];
96
97/// How many times the source's lines the port may take before `gate` calls it bloated, plus a
98/// fixed allowance for the imports and signatures every port has.
99pub const MAX_GROWTH: f64 = 3.0;
100const ALLOWANCE: f64 = 50.0;
101
102fn files_under(path: &Path, extensions: &[&str]) -> Vec<std::path::PathBuf> {
103    if path.is_file() {
104        return vec![path.to_path_buf()];
105    }
106    crate::walk::builder(path)
107        .build()
108        .flatten()
109        .map(ignore::DirEntry::into_path)
110        .filter(|p| {
111            p.extension()
112                .is_some_and(|e| extensions.contains(&e.to_string_lossy().as_ref()))
113        })
114        .collect()
115}
116
117/// Lines of Rust in the port against lines of the source unit: a port several times larger
118/// usually re-implements what a crate already does.
119/// The unit's files and the repository files they import, directly or not: a port stands in
120/// for all of them.
121pub(crate) fn with_local_imports(root: &Path, files: Vec<PathBuf>) -> Vec<PathBuf> {
122    const TRIES: &[&str] = &[
123        "",
124        ".ts",
125        ".tsx",
126        ".mts",
127        ".cts",
128        ".js",
129        ".mjs",
130        ".cjs",
131        "/index.ts",
132        "/index.tsx",
133        "/index.js",
134        "/index.mjs",
135    ];
136    let resolve = |from: &Path, spec: &str| -> Option<PathBuf> {
137        let base = from.parent()?.join(spec);
138        let stem = base.with_extension("");
139        let js_to_ts = matches!(
140            base.extension().and_then(|e| e.to_str()),
141            Some("js" | "mjs" | "cjs")
142        );
143        TRIES
144            .iter()
145            .map(|t| PathBuf::from(format!("{}{t}", base.display())))
146            .chain(js_to_ts.then(|| stem.with_extension("ts")))
147            .find(|p| p.is_file())
148    };
149    let mut seen: std::collections::BTreeSet<PathBuf> = files.into_iter().collect();
150    let mut todo: Vec<PathBuf> = seen.iter().cloned().collect();
151    while let Some(file) = todo.pop() {
152        let Ok(text) = std::fs::read_to_string(&file) else {
153            continue;
154        };
155        for import in crate::ts::scan::scan(&file.to_string_lossy(), &text).imports {
156            if !import.specifier.starts_with('.') || import.type_only {
157                continue;
158            }
159            if let Some(found) = resolve(&file, &import.specifier)
160                && found.starts_with(root)
161                && !found.components().any(|c| c.as_os_str() == "node_modules")
162                && seen.insert(found.clone())
163            {
164                todo.push(found);
165            }
166        }
167    }
168    seen.into_iter().collect()
169}
170
171fn size_check(crate_dir: &Path, manifest: &Manifest) -> Option<Check> {
172    let mut files = files_under(
173        &manifest.root.join(&manifest.unit),
174        manifest.language.extensions(),
175    );
176    if manifest.language == crate::lang::Lang::Ts {
177        files = with_local_imports(&manifest.root, files);
178    }
179    if manifest.language == crate::lang::Lang::C {
180        let ported: Vec<&str> = manifest.exports.iter().map(|f| f.name.as_str()).collect();
181        files.extend(crate::lang::c::called_implementations(
182            &manifest.root,
183            &manifest.unit,
184            &ported,
185        ));
186    }
187    let source: usize = files
188        .iter()
189        .filter_map(|p| std::fs::read_to_string(p).ok())
190        .map(|t| crate::lang::syntax::loc(&t, manifest.language))
191        .sum();
192    if source == 0 {
193        return None;
194    }
195    let rust: usize = files_under(&crate_dir.join("src"), &["rs"])
196        .iter()
197        .filter(|p| {
198            p.file_name()
199                .is_none_or(|n| !GENERATED.contains(&n.to_string_lossy().as_ref()))
200        })
201        .filter_map(|p| std::fs::read_to_string(p).ok())
202        .map(|t| crate::lang::syntax::code_lines(&t, &["//"]))
203        .sum();
204    let growth = rust as f64 / source as f64;
205    let passed = rust as f64 <= MAX_GROWTH * source as f64 + ALLOWANCE;
206    Some(Check {
207        fix: None,
208        name: "size",
209        passed,
210        detail: format!(
211            "{} of Rust for {} of {} ({growth:.1}x){}",
212            crate::report::count(rust, "line"),
213            crate::report::count(source, "line"),
214            manifest.language.name(),
215            if passed {
216                String::new()
217            } else {
218                format!(
219                    "; over {MAX_GROWTH}x usually means code a crate already provides, or a case \
220                     handled one by one: use the crates `analyze` lists and fold repeated code"
221                )
222            }
223        ),
224    })
225}
226
227#[derive(Debug, Serialize)]
228pub struct GateOutcome {
229    pub passed: bool,
230    pub checks: Vec<Check>,
231}
232
233pub fn gate(crate_dir: &Path, node_args: &[String]) -> Result<GateOutcome> {
234    let manifest = Manifest::load(crate_dir)?;
235    let lockfile = lockfile_check(crate_dir);
236    let mut checks = rust_checks(crate_dir, &crate::cache::target_for(crate_dir)?.dir);
237    checks.extend(lockfile);
238    checks.extend(advisories_check(crate_dir));
239    checks.push(ported_check(crate_dir));
240
241    checks.extend(size_check(crate_dir, &manifest));
242    checks.extend(crate::error_paths::checks(crate_dir, &manifest));
243    let built = harness::build(crate_dir);
244    let built_ok = built.is_ok();
245    let (build_detail, build_fix) = match built {
246        Ok(path) => (format!("built {}", path.display()), None),
247        Err(e) => (last_lines(&format!("{e:#}"), 15), spawn_fix(&e)),
248    };
249    checks.push(Check {
250        fix: build_fix,
251        name: "build",
252        passed: built_ok,
253        detail: build_detail,
254    });
255
256    if let Some(why) = crate::recording::stale(crate_dir, &manifest) {
257        checks.push(Check {
258            fix: None,
259            name: "recording",
260            passed: false,
261            detail: why,
262        });
263    }
264
265    if let Some(line) = crate::recording::saved_coverage(crate_dir)
266        .and_then(|c| crate::recording::coverage_line(&c))
267    {
268        checks.push(Check {
269            fix: None,
270            name: "coverage",
271            passed: true,
272            detail: line,
273        });
274    }
275
276    if !crate_dir.join(CASES).exists() {
277        checks.push(Check {
278            fix: None,
279            name: "behavior",
280            passed: false,
281            detail: "no recorded cases: run `rust-anything record` first".into(),
282        });
283    } else if built_ok {
284        match harness::diff(&DiffOptions {
285            crate_dir,
286            module: None,
287            ignore_key_order: false,
288            float_tolerance: None,
289            node_args,
290        }) {
291            Ok(d) => {
292                checks.push(Check {
293                    fix: None,
294                    name: "api",
295                    passed: d.missing.is_empty(),
296                    detail: if d.missing.is_empty() {
297                        format!(
298                            "exports {}",
299                            manifest
300                                .exports
301                                .iter()
302                                .map(|f| f.name.clone())
303                                .chain(manifest.classes.iter().map(|c| format!("class {}", c.name)))
304                                .collect::<Vec<_>>()
305                                .join(", ")
306                        )
307                    } else {
308                        format!("missing exports: {}", d.missing.join(", "))
309                    },
310                });
311                checks.push(Check {
312                    fix: None,
313                    name: "behavior",
314                    passed: d.failed == 0,
315                    detail: if d.accepted > 0 {
316                        format!(
317                            "{}/{} recorded cases match ({} by {})",
318                            d.passed,
319                            d.total,
320                            d.accepted,
321                            crate::recording::KNOWN_DIFFS
322                        )
323                    } else {
324                        format!("{}/{} recorded cases match", d.passed, d.total)
325                    },
326                });
327                if !d.stale_known.is_empty() {
328                    checks.push(Check {
329                        fix: None,
330                        name: "known diffs",
331                        passed: false,
332                        detail: format!(
333                            "{} entr{} of {} no longer differ{}: remove {}",
334                            d.stale_known.len(),
335                            if d.stale_known.len() == 1 { "y" } else { "ies" },
336                            crate::recording::KNOWN_DIFFS,
337                            if d.stale_known.len() == 1 { "s" } else { "" },
338                            d.stale_known
339                                .iter()
340                                .map(|e| format!(
341                                    "{}({})",
342                                    e["fn"].as_str().unwrap_or("?"),
343                                    e["args"]
344                                ))
345                                .collect::<Vec<_>>()
346                                .join(", ")
347                        ),
348                    });
349                }
350            }
351            Err(e) => checks.push(Check {
352                fix: None,
353                name: "behavior",
354                passed: false,
355                detail: format!("{e:#}"),
356            }),
357        }
358    }
359
360    for check in checks.iter_mut().filter(|c| !c.passed && c.fix.is_none()) {
361        check.fix = fix_for(check, crate_dir);
362    }
363    Ok(GateOutcome {
364        passed: checks.iter().all(|c| c.passed),
365        checks,
366    })
367}
368
369fn lockfile_check(crate_dir: &Path) -> Option<Check> {
370    if !crate_dir.join("Cargo.lock").exists() {
371        return Some(Check {
372            fix: None,
373            name: "lockfile",
374            passed: true,
375            detail: "warning: no Cargo.lock yet; keep the one the build writes, so builds are reproducible".into(),
376        });
377    }
378    let mut cmd = Command::new("cargo");
379    cmd.args([
380        "metadata",
381        "--locked",
382        "--offline",
383        "--format-version",
384        "1",
385        "--manifest-path",
386    ])
387    .arg(crate_dir.join("Cargo.toml"));
388    let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
389    let stderr = String::from_utf8_lossy(&out.stderr);
390    let stale = !out.status.success() && stderr.contains("--locked");
391    Some(Check {
392        fix: None,
393        name: "lockfile",
394        passed: true,
395        detail: if stale {
396            "warning: Cargo.lock is out of date with Cargo.toml; keep the refreshed one the build wrote".into()
397        } else {
398            "Cargo.lock matches Cargo.toml".into()
399        },
400    })
401}
402
403fn advisories_check(crate_dir: &Path) -> Option<Check> {
404    let manifest = crate_dir.join("Cargo.toml");
405    let attempts: [(&str, Vec<std::ffi::OsString>); 2] = [
406        (
407            "cargo-deny",
408            vec![
409                "deny".into(),
410                "--manifest-path".into(),
411                manifest.clone().into(),
412                "check".into(),
413                "advisories".into(),
414            ],
415        ),
416        (
417            "cargo-audit",
418            vec![
419                "audit".into(),
420                "--file".into(),
421                crate_dir.join("Cargo.lock").into(),
422            ],
423        ),
424    ];
425    for (tool, args) in attempts {
426        if !crate::setup::on_path(tool) {
427            continue;
428        }
429        let mut cmd = Command::new("cargo");
430        cmd.args(&args);
431        let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
432        let text = format!(
433            "{}{}",
434            String::from_utf8_lossy(&out.stdout),
435            String::from_utf8_lossy(&out.stderr)
436        );
437        return Some(Check {
438            fix: None,
439            name: "advisories",
440            passed: true,
441            detail: if out.status.success() {
442                format!("no known advisories ({tool})")
443            } else {
444                format!(
445                    "warning: {tool} reports advisories\n{}",
446                    last_lines(&text, 15)
447                )
448            },
449        });
450    }
451    None
452}
453
454/// The checks that hold for any Rust crate, bindings or not: fmt, clippy (warnings are errors),
455/// cargo test, and `unsafe` only with a `// SAFETY:` comment.
456pub fn rust_checks(crate_dir: &Path, target_dir: &Path) -> Vec<Check> {
457    let cargo = |args: &[&str]| -> (bool, String, Option<String>) {
458        let mut cmd = Command::new("cargo");
459        cmd.args(args)
460            .arg("--manifest-path")
461            .arg(crate_dir.join("Cargo.toml"))
462            .env("CARGO_TARGET_DIR", target_dir);
463        // Lint arguments go after `--`, so the manifest path must come before them.
464        match crate::process::output(&mut cmd, crate::process::BUILD) {
465            Ok(o) => (
466                o.status.success(),
467                last_lines(&String::from_utf8_lossy(&o.stderr), 15),
468                None,
469            ),
470            Err(e) => (false, format!("{e:#}"), spawn_fix(&e)),
471        }
472    };
473    let mut checks = Vec::new();
474
475    let (ok, out, fix) = cargo(&["fmt", "--check"]);
476    checks.push(Check {
477        name: "fmt",
478        passed: ok,
479        detail: if ok {
480            "formatted".into()
481        } else if fix.is_some() {
482            out
483        } else {
484            format!("run `cargo fmt`\n{out}")
485        },
486        fix,
487    });
488
489    let mut clippy = Command::new("cargo");
490    clippy
491        .args(["clippy", "--all-targets", "--manifest-path"])
492        .arg(crate_dir.join("Cargo.toml"))
493        .args(["--", "-D", "warnings"])
494        .env("CARGO_TARGET_DIR", target_dir);
495    let (ok, out, fix) = match crate::process::output(&mut clippy, crate::process::BUILD) {
496        Ok(o) => (
497            o.status.success(),
498            last_lines(&String::from_utf8_lossy(&o.stderr), 15),
499            None,
500        ),
501        Err(e) => (false, format!("{e:#}"), spawn_fix(&e)),
502    };
503    checks.push(Check {
504        fix,
505        name: "clippy",
506        passed: ok,
507        detail: if ok { "no warnings".into() } else { out },
508    });
509
510    let (ok, out, fix) = cargo(&["test", "--quiet"]);
511    checks.push(Check {
512        fix,
513        name: "cargo test",
514        passed: ok,
515        detail: if ok { "passed".into() } else { out },
516    });
517
518    let (unexplained, explained) = unsafe_blocks(&crate_dir.join("src"));
519    checks.push(Check {
520        fix: None,
521        name: "unsafe",
522        passed: unexplained.is_empty(),
523        detail: if unexplained.is_empty() {
524            format!("{explained} unsafe uses, each with a `// SAFETY:` comment")
525        } else {
526            format!(
527                "unsafe without a `// SAFETY:` comment: {}",
528                unexplained.join(", ")
529            )
530        },
531    });
532
533    checks
534}
535
536/// No function in `src/port.rs` is still `unimplemented!`.
537pub fn ported_check(crate_dir: &Path) -> Check {
538    let path = crate_dir.join("src/port.rs");
539    let port = match std::fs::read_to_string(&path) {
540        Ok(port) => port,
541        Err(error) => {
542            return Check {
543                fix: None,
544                name: "ported",
545                passed: false,
546                detail: format!("cannot read {}: {error}", path.display()),
547            };
548        }
549    };
550    let todo = stubs(&port);
551    Check {
552        fix: None,
553        name: "ported",
554        passed: todo == 0,
555        detail: if todo == 0 {
556            "nothing in port.rs is `unimplemented!`, `todo!` or only a `panic!`".into()
557        } else {
558            format!(
559                "{todo} place(s) in port.rs still `unimplemented!`, `todo!` or a function that only panics"
560            )
561        },
562    }
563}
564
565/// Stubs left in a port: `unimplemented!`, `todo!`, and functions whose whole body is a `panic!`.
566fn stubs(port: &str) -> usize {
567    let code: String = port
568        .lines()
569        .map(|l| l.split("//").next().unwrap_or_default())
570        .collect::<Vec<_>>()
571        .join("\n");
572    let macros = code.matches("unimplemented!(").count() + code.matches("todo!(").count();
573    let panics = regex::Regex::new(r"\bfn\s+\w+[^{;]*\{\s*panic!\([^;{}]*\)\s*;?\s*\}")
574        .map(|re| re.find_iter(&code).count())
575        .unwrap_or(0);
576    macros + panics
577}
578
579/// `unsafe` uses in Rust sources, split into those without and with a `// SAFETY:` comment just above.
580fn unsafe_blocks(src: &Path) -> (Vec<String>, usize) {
581    let mut unexplained = Vec::new();
582    let mut explained = 0;
583    let mut stack = vec![src.to_path_buf()];
584    while let Some(dir) = stack.pop() {
585        let Ok(entries) = std::fs::read_dir(&dir) else {
586            continue;
587        };
588        for entry in entries.flatten() {
589            let path = entry.path();
590            if path.is_dir() {
591                stack.push(path);
592                continue;
593            }
594            if path.extension().is_none_or(|e| e != "rs") {
595                continue;
596            }
597            let text = std::fs::read_to_string(&path).unwrap_or_default();
598            let lines: Vec<&str> = text.lines().collect();
599            for (i, line) in lines.iter().enumerate() {
600                let code = line.split("//").next().unwrap_or("");
601                let uses_unsafe = code
602                    .split(|c: char| !(c.is_alphanumeric() || c == '_'))
603                    .any(|word| word == "unsafe");
604                if !uses_unsafe {
605                    continue;
606                }
607                let has_safety = lines[..i]
608                    .iter()
609                    .rev()
610                    .take_while(|l| l.trim_start().starts_with("//"))
611                    .any(|l| l.contains("SAFETY:"));
612                if has_safety {
613                    explained += 1;
614                } else {
615                    unexplained.push(format!("{}:{}", path.display(), i + 1));
616                }
617            }
618        }
619    }
620    (unexplained, explained)
621}
622
623fn last_lines(text: &str, n: usize) -> String {
624    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
625    lines[lines.len().saturating_sub(n)..].join("\n")
626}
627
628#[cfg(test)]
629mod tests {
630    use super::{Check, fix_for, spawn_fix, stubs, unsafe_blocks};
631
632    #[test]
633    fn counts_every_kind_of_stub() {
634        let port = "pub fn a() -> u8 { todo!() }\n\
635                    pub fn b() -> u8 { unimplemented!(\"later\") }\n\
636                    pub fn c(x: u8) -> u8 {\n    panic!(\"not ported\")\n}\n\
637                    pub fn d(x: u8) -> u8 { if x > 1 { panic!(\"big\") } x }\n\
638                    // todo!() in a comment\n";
639        assert_eq!(stubs(port), 3);
640        assert_eq!(stubs("pub fn ok() -> u8 { 1 }"), 0);
641    }
642
643    #[test]
644    fn failed_checks_say_what_to_run() {
645        let check = |name, detail: &str| Check {
646            fix: None,
647            name,
648            passed: false,
649            detail: detail.into(),
650        };
651        let dir = std::path::Path::new("port");
652        assert_eq!(
653            fix_for(&check("recording", "changed"), dir).as_deref(),
654            Some("rust-anything record port")
655        );
656        assert_eq!(
657            fix_for(&check("behavior", "no recorded cases: run"), dir).as_deref(),
658            Some("rust-anything record port")
659        );
660        assert!(fix_for(&check("fmt", ""), dir).is_some_and(|f| f.starts_with("cargo fmt")));
661        assert_eq!(fix_for(&check("coverage", ""), dir), None);
662
663        let mut missing_cmd = std::process::Command::new("cargo");
664        missing_cmd.env_remove("PATH");
665        let missing_err = crate::process::spawn_error(
666            &missing_cmd,
667            "cargo build",
668            std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
669        );
670        let missing_fix = spawn_fix(&missing_err).unwrap();
671        assert!(
672            !missing_fix.contains("fix the compile error above"),
673            "{missing_fix}"
674        );
675        assert!(missing_fix.contains("cargo"), "{missing_fix}");
676        assert!(
677            missing_fix.contains("rust-anything doctor"),
678            "{missing_fix}"
679        );
680        assert!(!missing_fix.contains('\n'), "{missing_fix}");
681
682        let denied_err = crate::process::spawn_error(
683            &std::process::Command::new("cargo"),
684            "cargo build",
685            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"),
686        );
687        let spawn_hint = spawn_fix(&denied_err).unwrap();
688        assert!(
689            !spawn_hint.contains("fix the compile error above"),
690            "{spawn_hint}"
691        );
692        assert!(spawn_hint.contains("rust-anything doctor"), "{spawn_hint}");
693
694        let compile_err =
695            anyhow::anyhow!("cargo build failed (exit status: 101)\n\"not found on PATH\"");
696        assert!(spawn_fix(&compile_err).is_none());
697        let compile_fix = fix_for(&check("build", &compile_err.to_string()), dir).unwrap();
698        assert!(
699            compile_fix.starts_with("fix the compile error above"),
700            "{compile_fix}"
701        );
702    }
703
704    #[test]
705    fn requires_safety_comments() {
706        let dir = std::env::temp_dir().join(format!("rust-anything-gate-{}", std::process::id()));
707        std::fs::create_dir_all(&dir).unwrap();
708        std::fs::write(
709            dir.join("a.rs"),
710            "#![forbid(unsafe_code)]\n// SAFETY: checked above\nunsafe { x() }\nlet y = unsafe { z() };\n// unsafe in a comment\n",
711        )
712        .unwrap();
713        let (unexplained, explained) = unsafe_blocks(&dir);
714        std::fs::remove_dir_all(&dir).unwrap();
715        assert_eq!(explained, 1);
716        assert_eq!(unexplained.len(), 1);
717        assert!(unexplained[0].ends_with("a.rs:4"));
718    }
719
720    #[test]
721    fn missing_port_source_fails_the_ported_check() {
722        let dir = crate::app::temp_dir("gate-port").unwrap();
723        let check = super::ported_check(&dir);
724        std::fs::remove_dir(dir).unwrap();
725        assert!(!check.passed);
726        assert!(check.detail.contains("cannot read"));
727        assert!(check.detail.contains("port.rs"));
728    }
729
730    #[test]
731    fn size_check_says_1_line_for_singular_source() {
732        let dir = crate::app::temp_dir("gate-size").unwrap();
733        let src_dir = dir.join("src");
734        std::fs::create_dir_all(&src_dir).unwrap();
735        std::fs::write(src_dir.join("add.ts"), "export const add = 1;\n").unwrap();
736        std::fs::write(src_dir.join("port.rs"), "pub fn add() -> i32 { 1 }\n").unwrap();
737        let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
738            "schema": crate::bridge::SCHEMA,
739            "root": dir,
740            "unit": "src",
741            "crate_name": "demo",
742            "kind": "napi",
743            "exports": [],
744        }))
745        .unwrap();
746        let check = super::size_check(&dir, &manifest).unwrap();
747        std::fs::remove_dir_all(dir).unwrap();
748        assert!(
749            check
750                .detail
751                .contains("1 line of Rust for 1 line of TypeScript/JavaScript"),
752            "{}",
753            check.detail
754        );
755    }
756}