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::collections::{BTreeSet, HashSet};
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10use anyhow::Result;
11use serde::{Deserialize, Serialize};
12
13use crate::bridge::Manifest;
14use crate::harness::{self, CASES, DiffOptions};
15
16#[derive(Debug, Serialize)]
17pub struct Check {
18    pub name: &'static str,
19    pub passed: bool,
20    pub detail: String,
21    /// The next command or edit that clears a failed check.
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub fix: Option<String>,
24}
25
26/// Recovery guidance when an outside tool failed to start (structured `SpawnError`).
27fn spawn_fix(err: &anyhow::Error) -> Option<String> {
28    let spawn = err.downcast_ref::<crate::process::SpawnError>()?;
29    Some(if spawn.missing {
30        match crate::doctor::missing_command(&spawn.program) {
31            Some(install) if !install.contains('\n') => {
32                format!(
33                    "install `{}` with `{install}`, or run `rust-anything doctor`",
34                    spawn.program
35                )
36            }
37            _ => format!(
38                "run `rust-anything doctor` for how to install `{}`",
39                spawn.program
40            ),
41        }
42    } else {
43        "run `rust-anything doctor` and check that the build tool can run".into()
44    })
45}
46
47/// The fix for a failed check, by its name.
48fn fix_for(check: &Check, crate_dir: &Path) -> Option<String> {
49    let c = crate_dir.display();
50    let manifest = format!("--manifest-path {c}/Cargo.toml");
51    Some(match check.name {
52        "fmt" => format!("cargo fmt {manifest}"),
53        "clippy" => {
54            format!("cargo clippy --all-targets {manifest} -- -D warnings, then fix each warning")
55        }
56        "cargo test" => format!("cargo test {manifest}"),
57        "unsafe" => "add a `// SAFETY:` comment above each listed `unsafe`, or remove it".into(),
58        "ported" => {
59            "port the functions still stubbed in src/port.rs, then `rust-anything gate` again"
60                .into()
61        }
62        "size" => "use the crates `rust-anything analyze` lists and fold repeated code".into(),
63        "literals" => "compute these values the way the original does; a constant the original \
64                       takes from a library can stay with a `// recorded-literal:` comment"
65            .into(),
66        "tests" => format!(
67            "restore the removed tests or assertions; if the change is intended, delete \
68             `{c}/{TESTS_BASELINE}` and run gate again"
69        ),
70        "build" => format!("fix the compile error above, then `rust-anything build {c}`"),
71        "recording" => format!("rust-anything record {c}"),
72        "behavior" if check.detail.contains("no recorded cases") => {
73            format!("rust-anything record {c}")
74        }
75        "behavior" => format!(
76            "rust-anything diff {c} to see each mismatch; fix the port, or list an intended difference in {}",
77            crate::recording::KNOWN_DIFFS
78        ),
79        "known diffs" => format!(
80            "remove the entries that no longer happen from {c}/{}",
81            crate::recording::KNOWN_DIFFS
82        ),
83        "api" => {
84            format!("export the missing functions from src/port.rs, then `rust-anything build {c}`")
85        }
86        "error cases" | "panics" => {
87            format!("rust-anything diff {c} to see the cases where the port's errors differ")
88        }
89        _ => return None,
90    })
91}
92
93/// Bindings `bridge` writes into `src/`; everything else there is the port.
94const GENERATED: [&str; 8] = [
95    "lib.rs",
96    "js.rs",
97    "pinned.rs",
98    "pyconv.rs",
99    "pynum.rs",
100    "rbconv.rs",
101    "utf16.rs",
102    "wire.rs",
103];
104
105/// How many times the source's lines the port may take before `gate` calls it bloated, plus a
106/// fixed allowance for the imports and signatures every port has.
107pub const MAX_GROWTH: f64 = 3.0;
108const ALLOWANCE: f64 = 50.0;
109
110fn files_under(path: &Path, extensions: &[&str]) -> Vec<std::path::PathBuf> {
111    if path.is_file() {
112        return vec![path.to_path_buf()];
113    }
114    crate::walk::builder(path)
115        .build()
116        .flatten()
117        .map(ignore::DirEntry::into_path)
118        .filter(|p| {
119            p.extension()
120                .is_some_and(|e| extensions.contains(&e.to_string_lossy().as_ref()))
121        })
122        .collect()
123}
124
125/// Lines of Rust in the port against lines of the source unit: a port several times larger
126/// usually re-implements what a crate already does.
127/// The unit's files and the repository files they import, directly or not: a port stands in
128/// for all of them.
129pub(crate) fn with_local_imports(root: &Path, files: Vec<PathBuf>) -> Vec<PathBuf> {
130    const TRIES: &[&str] = &[
131        "",
132        ".ts",
133        ".tsx",
134        ".mts",
135        ".cts",
136        ".js",
137        ".mjs",
138        ".cjs",
139        "/index.ts",
140        "/index.tsx",
141        "/index.js",
142        "/index.mjs",
143    ];
144    let resolve = |from: &Path, spec: &str| -> Option<PathBuf> {
145        let base = from.parent()?.join(spec);
146        let stem = base.with_extension("");
147        let js_to_ts = matches!(
148            base.extension().and_then(|e| e.to_str()),
149            Some("js" | "mjs" | "cjs")
150        );
151        TRIES
152            .iter()
153            .map(|t| PathBuf::from(format!("{}{t}", base.display())))
154            .chain(js_to_ts.then(|| stem.with_extension("ts")))
155            .find(|p| p.is_file())
156    };
157    let mut seen: std::collections::BTreeSet<PathBuf> = files.into_iter().collect();
158    let mut todo: Vec<PathBuf> = seen.iter().cloned().collect();
159    while let Some(file) = todo.pop() {
160        let Ok(text) = std::fs::read_to_string(&file) else {
161            continue;
162        };
163        for import in crate::ts::scan::scan(&file.to_string_lossy(), &text).imports {
164            if !import.specifier.starts_with('.') || import.type_only {
165                continue;
166            }
167            if let Some(found) = resolve(&file, &import.specifier)
168                && found.starts_with(root)
169                && !found.components().any(|c| c.as_os_str() == "node_modules")
170                && seen.insert(found.clone())
171            {
172                todo.push(found);
173            }
174        }
175    }
176    seen.into_iter().collect()
177}
178
179/// The original's files a port stands for: the unit, plus what it imports (TS) or calls (C).
180fn source_files(manifest: &Manifest) -> Vec<PathBuf> {
181    let mut files = files_under(
182        &manifest.root.join(&manifest.unit),
183        manifest.language.extensions(),
184    );
185    if manifest.language == crate::lang::Lang::Ts {
186        files = with_local_imports(&manifest.root, files);
187    }
188    if manifest.language == crate::lang::Lang::C {
189        let ported: Vec<&str> = manifest.exports.iter().map(|f| f.name.as_str()).collect();
190        files.extend(crate::lang::c::called_implementations(
191            &manifest.root,
192            &manifest.unit,
193            &ported,
194        ));
195    }
196    files
197}
198
199/// The port's own Rust files under `src/`: everything but the generated bindings.
200fn port_files(crate_dir: &Path) -> Vec<PathBuf> {
201    files_under(&crate_dir.join("src"), &["rs"])
202        .into_iter()
203        .filter(|p| {
204            p.file_name()
205                .is_none_or(|n| !GENERATED.contains(&n.to_string_lossy().as_ref()))
206        })
207        .collect()
208}
209
210fn size_check(crate_dir: &Path, manifest: &Manifest) -> Option<Check> {
211    let source: usize = source_files(manifest)
212        .iter()
213        .filter_map(|p| std::fs::read_to_string(p).ok())
214        .map(|t| crate::lang::syntax::loc(&t, manifest.language))
215        .sum();
216    if source == 0 {
217        return None;
218    }
219    let rust: usize = port_files(crate_dir)
220        .iter()
221        .filter_map(|p| std::fs::read_to_string(p).ok())
222        .map(|t| crate::lang::syntax::code_lines(&t, &["//"]))
223        .sum();
224    let growth = rust as f64 / source as f64;
225    let passed = rust as f64 <= MAX_GROWTH * source as f64 + ALLOWANCE;
226    Some(Check {
227        fix: None,
228        name: "size",
229        passed,
230        detail: format!(
231            "{} of Rust for {} of {} ({growth:.1}x){}",
232            crate::report::count(rust, "line"),
233            crate::report::count(source, "line"),
234            manifest.language.name(),
235            if passed {
236                String::new()
237            } else {
238                format!(
239                    "; over {MAX_GROWTH}x usually means code a crate already provides, or a case \
240                     handled one by one: use the crates `analyze` lists and fold repeated code"
241                )
242            }
243        ),
244    })
245}
246
247/// Files a port must never read: what it is checked against.
248const RECORDING_FILES: [&str; 3] = [
249    CASES,
250    crate::recording::KNOWN_DIFFS,
251    crate::recording::RECORDED_FROM,
252];
253/// Shorter strings (`"error"`, `"none"`) are too common to say anything.
254const MIN_STRING: usize = 8;
255/// Numbers with fewer significant digits are too common to say anything.
256const MIN_DIGITS: usize = 5;
257/// Recorded values hard-coded in the port before `literals` fails.
258const LITERALS_FAIL: usize = 3;
259/// Where `gate` keeps the test counts of the last passing run.
260const TESTS_BASELINE: &str = ".rust-anything/tests.json";
261
262/// Rust source without comments, string literals emptied, with the literals it holds.
263#[derive(Default)]
264struct Scan {
265    code: String,
266    strings: Vec<(usize, String)>,
267    numbers: Vec<(usize, String)>,
268    /// Lines with a `// recorded-literal: <reason>` comment.
269    marked: BTreeSet<usize>,
270}
271
272fn starts(chars: &[char], i: usize, s: &str) -> bool {
273    s.chars()
274        .enumerate()
275        .all(|(k, c)| chars.get(i + k) == Some(&c))
276}
277
278/// Splits Rust source into code, string literals (unescaped) and number literals (without `_`
279/// or a type suffix); with `stop_at_tests`, everything from the first `#[cfg(test)]` on is left
280/// out.
281fn scan_rust(text: &str, stop_at_tests: bool) -> Scan {
282    let chars: Vec<char> = text.chars().collect();
283    let ident = |c: char| c.is_alphanumeric() || c == '_';
284    let digits = |chars: &[char], mut i: usize| {
285        while chars
286            .get(i)
287            .is_some_and(|c| c.is_ascii_digit() || *c == '_')
288        {
289            i += 1;
290        }
291        i
292    };
293    let mut scan = Scan::default();
294    let mut line = 1;
295    let mut i = 0;
296    while i < chars.len() {
297        let c = chars[i];
298        let free = i == 0 || !ident(chars[i - 1]);
299        if stop_at_tests && starts(&chars, i, "#[cfg(test)]") {
300            break;
301        }
302        if starts(&chars, i, "//") {
303            let end = chars[i..]
304                .iter()
305                .position(|&c| c == '\n')
306                .map_or(chars.len(), |p| i + p);
307            if chars[i..end]
308                .iter()
309                .collect::<String>()
310                .contains("recorded-literal:")
311            {
312                scan.marked.insert(line);
313            }
314            i = end;
315            continue;
316        }
317        if starts(&chars, i, "/*") {
318            let mut depth = 0usize;
319            while i < chars.len() {
320                if starts(&chars, i, "/*") {
321                    depth += 1;
322                    i += 2;
323                } else if starts(&chars, i, "*/") {
324                    depth -= 1;
325                    i += 2;
326                    if depth == 0 {
327                        break;
328                    }
329                } else {
330                    if chars[i] == '\n' {
331                        line += 1;
332                        scan.code.push('\n');
333                    }
334                    i += 1;
335                }
336            }
337            continue;
338        }
339        let raw = match c {
340            'r' if free => Some(i + 1),
341            'b' | 'c' if free && chars.get(i + 1) == Some(&'r') => Some(i + 2),
342            _ => None,
343        }
344        .and_then(|j| {
345            let hashes = chars[j..].iter().take_while(|&&h| h == '#').count();
346            (chars.get(j + hashes) == Some(&'"')).then_some((j + hashes + 1, hashes))
347        });
348        if let Some((start, hashes)) = raw {
349            let close = format!("\"{}", "#".repeat(hashes));
350            let end = (start..chars.len())
351                .find(|&k| starts(&chars, k, &close))
352                .unwrap_or(chars.len());
353            let value: String = chars[start..end].iter().collect();
354            scan.strings.push((line, value.clone()));
355            line += value.matches('\n').count();
356            scan.code.push_str("\"\"");
357            i = end + close.len();
358            continue;
359        }
360        let quoted = if c == '"' {
361            Some(i + 1)
362        } else if free && matches!(c, 'b' | 'c') && chars.get(i + 1) == Some(&'"') {
363            Some(i + 2)
364        } else {
365            None
366        };
367        if let Some(mut j) = quoted {
368            let at = line;
369            let mut value = String::new();
370            while j < chars.len() && chars[j] != '"' {
371                if chars[j] != '\\' {
372                    if chars[j] == '\n' {
373                        line += 1;
374                    }
375                    value.push(chars[j]);
376                    j += 1;
377                    continue;
378                }
379                let escaped = chars.get(j + 1).copied().unwrap_or('\\');
380                j += 2;
381                match escaped {
382                    'n' => value.push('\n'),
383                    't' => value.push('\t'),
384                    'r' => value.push('\r'),
385                    '0' => value.push('\0'),
386                    'x' => {
387                        let hex: String = chars[j..(j + 2).min(chars.len())].iter().collect();
388                        value.extend(u8::from_str_radix(&hex, 16).ok().map(char::from));
389                        j += 2;
390                    }
391                    'u' if chars.get(j) == Some(&'{') => {
392                        let end = (j..chars.len())
393                            .find(|&k| chars[k] == '}')
394                            .unwrap_or(chars.len());
395                        let hex: String = chars[j + 1..end].iter().filter(|c| **c != '_').collect();
396                        value.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32));
397                        j = end + 1;
398                    }
399                    '\n' => {
400                        line += 1;
401                        while j < chars.len() && chars[j].is_whitespace() {
402                            if chars[j] == '\n' {
403                                line += 1;
404                            }
405                            j += 1;
406                        }
407                    }
408                    other => value.push(other),
409                }
410            }
411            scan.strings.push((at, value));
412            scan.code.push_str("\"\"");
413            i = j + 1;
414            continue;
415        }
416        if c == '\'' {
417            let end = if chars.get(i + 1) == Some(&'\\') {
418                (i + 3..chars.len()).find(|&k| chars[k] == '\'')
419            } else {
420                (chars.get(i + 2) == Some(&'\'')).then_some(i + 2)
421            };
422            if let Some(end) = end {
423                scan.code.push_str("' '");
424                i = end + 1;
425                continue;
426            }
427        }
428        let after_range = i >= 2 && chars[i - 1] == '.' && chars[i - 2] == '.';
429        if c.is_ascii_digit() && free && (i == 0 || chars[i - 1] != '.' || after_range) {
430            let start = i;
431            if c == '0' && matches!(chars.get(i + 1), Some('x' | 'o' | 'b')) {
432                while i < chars.len() && ident(chars[i]) {
433                    i += 1;
434                }
435                scan.code.extend(&chars[start..i]);
436                continue;
437            }
438            i = digits(&chars, i);
439            if chars.get(i) == Some(&'.') && chars.get(i + 1).is_some_and(char::is_ascii_digit) {
440                i = digits(&chars, i + 1);
441            }
442            if matches!(chars.get(i), Some('e' | 'E')) {
443                let sign = usize::from(matches!(chars.get(i + 1), Some('+' | '-')));
444                if chars.get(i + 1 + sign).is_some_and(char::is_ascii_digit) {
445                    i = digits(&chars, i + 1 + sign);
446                }
447            }
448            let number: String = chars[start..i].iter().filter(|c| **c != '_').collect();
449            while i < chars.len() && ident(chars[i]) {
450                i += 1;
451            }
452            scan.code.extend(&chars[start..i]);
453            scan.numbers.push((line, number));
454            continue;
455        }
456        if c == '\n' {
457            line += 1;
458        }
459        scan.code.push(c);
460        i += 1;
461    }
462    scan
463}
464
465/// Digits of a number literal that carry information: no leading or trailing zeros.
466fn significant_digits(number: &str) -> usize {
467    let mantissa = number.split(['e', 'E']).next().unwrap_or(number);
468    let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
469    digits.trim_start_matches('0').trim_end_matches('0').len()
470}
471
472/// Numbers any program may spell out: powers of two (and one off them), powers of ten, and the
473/// float limits.
474fn well_known(number: &str) -> bool {
475    if number.chars().all(|c| c.is_ascii_digit()) {
476        let Ok(n) = number.parse::<u128>() else {
477            return false;
478        };
479        let mut ten = n;
480        while ten >= 10 && ten % 10 == 0 {
481            ten /= 10;
482        }
483        return ten == 1
484            || n == u128::MAX
485            || [Some(n), n.checked_add(1), n.checked_sub(1)]
486                .into_iter()
487                .flatten()
488                .any(u128::is_power_of_two);
489    }
490    let Ok(v) = number.parse::<f64>() else {
491        return false;
492    };
493    [
494        f64::MAX,
495        f64::MIN_POSITIVE,
496        f64::EPSILON,
497        f64::from(f32::MAX),
498        f64::from(f32::MIN_POSITIVE),
499        f64::from(f32::EPSILON),
500    ]
501    .iter()
502    .any(|k| ((v - k) / k).abs() < 1e-6)
503}
504
505/// Strings and numbers the recording holds, arguments and results alike.
506#[derive(Default)]
507struct Recorded {
508    strings: HashSet<String>,
509    numbers: HashSet<u64>,
510}
511
512impl Recorded {
513    fn add(&mut self, value: &serde_json::Value) {
514        match value {
515            serde_json::Value::String(s) if s.chars().count() >= MIN_STRING => {
516                self.strings.insert(s.clone());
517            }
518            serde_json::Value::Number(n) => {
519                if let Some(f) = n.as_f64() {
520                    self.numbers.insert((f + 0.0).to_bits());
521                }
522            }
523            serde_json::Value::Array(items) => items.iter().for_each(|v| self.add(v)),
524            serde_json::Value::Object(o) => o
525                .iter()
526                .filter(|(k, _)| !matches!(k.as_str(), "error" | "error_type"))
527                .for_each(|(_, v)| self.add(v)),
528            _ => {}
529        }
530    }
531}
532
533fn recorded_values(crate_dir: &Path) -> Option<Recorded> {
534    let text = std::fs::read_to_string(crate_dir.join(CASES)).ok()?;
535    let mut recorded = Recorded::default();
536    for line in text.lines().filter(|l| !l.trim().is_empty()) {
537        let Ok(serde_json::Value::Object(case)) = serde_json::from_str(line) else {
538            continue;
539        };
540        for (key, value) in &case {
541            if !matches!(
542                key.as_str(),
543                "fn" | "class" | "module" | "error" | "error_type"
544            ) {
545                recorded.add(value);
546            }
547        }
548    }
549    Some(recorded)
550}
551
552/// Recorded values written into the port as literals although the original never spells them
553/// out: a port that answers the recorded cases from a table passes `diff` without porting
554/// anything. Fails on `LITERALS_FAIL` or more, or on any read of the recording itself; fewer
555/// pass with their names. A literal on a line with `// recorded-literal: <reason>` is left out.
556/// Recorded error text is left out too: the runtime often writes it (`division by zero`), and the
557/// port has to reproduce it.
558pub fn literals_check(crate_dir: &Path, manifest: &Manifest) -> Option<Check> {
559    let recorded = recorded_values(crate_dir)?;
560    let original: String = source_files(manifest)
561        .iter()
562        .filter_map(|p| std::fs::read_to_string(p).ok())
563        .collect::<Vec<_>>()
564        .join("\n");
565    let in_original = |text: &str| {
566        original.contains(text)
567            || serde_json::to_string(text)
568                .is_ok_and(|j| original.contains(&j[1..j.len().saturating_sub(1)]))
569    };
570    let mut found: Vec<(String, String, String)> = Vec::new();
571    let mut reads = Vec::new();
572    for file in port_files(crate_dir) {
573        let Ok(text) = std::fs::read_to_string(&file) else {
574            continue;
575        };
576        let scan = scan_rust(&text, true);
577        let name = file
578            .strip_prefix(crate_dir)
579            .unwrap_or(&file)
580            .to_string_lossy()
581            .replace('\\', "/");
582        let mut note = |key: String, shown: String, line: usize| {
583            if !found.iter().any(|(k, _, _)| *k == key) {
584                found.push((key, shown, format!("{name}:{line}")));
585            }
586        };
587        for (line, s) in &scan.strings {
588            if RECORDING_FILES.iter().any(|f| s.contains(f)) {
589                reads.push(format!("{name}:{line}"));
590            }
591            if scan.marked.contains(line) || !recorded.strings.contains(s) || in_original(s) {
592                continue;
593            }
594            let shown: String = if s.chars().count() > 40 {
595                s.chars().take(37).chain("...".chars()).collect()
596            } else {
597                s.clone()
598            };
599            note(
600                format!("s{s}"),
601                serde_json::to_string(&shown).unwrap_or_default(),
602                *line,
603            );
604        }
605        for (line, n) in &scan.numbers {
606            if scan.marked.contains(line) || significant_digits(n) < MIN_DIGITS || well_known(n) {
607                continue;
608            }
609            let Ok(v) = n.parse::<f64>() else {
610                continue;
611            };
612            let bits = (v + 0.0).to_bits();
613            if recorded.numbers.contains(&bits) && !original.contains(n.as_str()) {
614                note(format!("n{bits}"), n.clone(), *line);
615            }
616        }
617    }
618    let listed = found
619        .iter()
620        .take(5)
621        .map(|(_, shown, at)| format!("{shown} ({at})"))
622        .chain((found.len() > 5).then(|| format!("{} more", found.len() - 5)))
623        .collect::<Vec<_>>()
624        .join(", ");
625    let (passed, detail) = if !reads.is_empty() {
626        (
627            false,
628            format!(
629                "the port names the recording ({}) at {}: compute results, never look them up",
630                RECORDING_FILES.join(", "),
631                reads.join(", ")
632            ),
633        )
634    } else if found.len() >= LITERALS_FAIL {
635        (
636            false,
637            format!(
638                "{} recorded values are written into the port, and the original spells out none \
639                 of them: {listed}",
640                found.len()
641            ),
642        )
643    } else if !found.is_empty() {
644        (
645            true,
646            format!(
647                "{} written into the port that the original never spells out: {listed}; compute \
648                 {} unless the original takes {} from a library (then mark the line \
649                 `// recorded-literal: <reason>`)",
650                crate::report::count(found.len(), "recorded value"),
651                if found.len() == 1 { "it" } else { "them" },
652                if found.len() == 1 { "it" } else { "them" },
653            ),
654        )
655    } else {
656        (true, "no recorded values written into the port".into())
657    };
658    Some(Check {
659        fix: None,
660        name: "literals",
661        passed,
662        detail,
663    })
664}
665
666/// Tests and assertions in the crate (`src/` without the bindings, and `tests/`).
667#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
668pub struct TestCounts {
669    #[serde(default)]
670    pub tests: usize,
671    #[serde(default)]
672    pub asserts: usize,
673    #[serde(default)]
674    pub ignored: usize,
675    #[serde(default)]
676    pub should_panic: usize,
677    /// Entries of `known-diffs.jsonl`; `None` in a baseline saved before they were counted.
678    #[serde(default, skip_serializing_if = "Option::is_none")]
679    pub known_diffs: Option<usize>,
680}
681
682pub fn test_counts(crate_dir: &Path) -> TestCounts {
683    let patterns = [
684        r"#\[\s*(?:\w+::)*test\s*\]",
685        r"\b(?:debug_)?assert(?:_\w+)?!",
686        r"#\[\s*ignore\b",
687        r"#\[\s*should_panic\b",
688    ]
689    .map(|p| regex::Regex::new(p).ok());
690    let tests = crate_dir.join("tests");
691    let mut files = port_files(crate_dir);
692    if tests.is_dir() {
693        files.extend(files_under(&tests, &["rs"]));
694    }
695    let mut n = [0usize; 4];
696    for file in files {
697        let Ok(text) = std::fs::read_to_string(&file) else {
698            continue;
699        };
700        let code = scan_rust(&text, false).code;
701        for (count, re) in n.iter_mut().zip(&patterns) {
702            *count += re.as_ref().map_or(0, |re| re.find_iter(&code).count());
703        }
704    }
705    let [tests, asserts, ignored, should_panic] = n;
706    TestCounts {
707        tests,
708        asserts,
709        ignored,
710        should_panic,
711        known_diffs: Some(known_diff_entries(crate_dir)),
712    }
713}
714
715fn known_diff_entries(crate_dir: &Path) -> usize {
716    crate::recording::known_diffs(crate_dir).map_or(0, |e| e.len())
717}
718
719fn tests_baseline(crate_dir: &Path) -> Option<TestCounts> {
720    std::fs::read_to_string(crate_dir.join(TESTS_BASELINE))
721        .ok()
722        .and_then(|t| serde_json::from_str(&t).ok())
723}
724
725/// Entries added to `known-diffs.jsonl` since the last passing gate: each one is a behavior
726/// change, which reviewers can only tell from a regression when it lands apart from the port.
727fn known_diffs_added(crate_dir: &Path) -> usize {
728    tests_baseline(crate_dir)
729        .and_then(|b| b.known_diffs)
730        .map_or(0, |before| {
731            known_diff_entries(crate_dir).saturating_sub(before)
732        })
733}
734
735fn behavior_detail(passed: usize, total: usize, accepted: usize, added: usize) -> String {
736    let matched = format!("{passed}/{total} recorded cases match");
737    match (accepted, added) {
738        (0, 0) => matched,
739        (_, 0) => format!(
740            "{matched} ({accepted} by {})",
741            crate::recording::KNOWN_DIFFS
742        ),
743        _ => format!(
744            "{matched} ({accepted} by {}, {} added since the last passing gate: land behavior \
745             changes apart from the port)",
746            crate::recording::KNOWN_DIFFS,
747            if added == 1 {
748                "1 entry".to_string()
749            } else {
750                format!("{added} entries")
751            }
752        ),
753    }
754}
755
756/// Saves the crate's test counts as the baseline the next `tests` check compares with.
757pub fn save_tests_baseline(crate_dir: &Path) -> Result<()> {
758    let path = crate_dir.join(TESTS_BASELINE);
759    if let Some(dir) = path.parent() {
760        std::fs::create_dir_all(dir)?;
761    }
762    std::fs::write(
763        &path,
764        serde_json::to_string_pretty(&test_counts(crate_dir))? + "\n",
765    )?;
766    Ok(())
767}
768
769/// Fails when tests or assertions were removed, or tests ignored, since the last passing gate:
770/// weakening the tests is not a way to pass.
771pub fn tests_check(crate_dir: &Path) -> Check {
772    let now = test_counts(crate_dir);
773    let counts = format!(
774        "{}, {}",
775        crate::report::count(now.tests, "test"),
776        crate::report::count(now.asserts, "assertion")
777    );
778    let Some(before) = tests_baseline(crate_dir) else {
779        return Check {
780            fix: None,
781            name: "tests",
782            passed: true,
783            detail: format!("{counts}; saved as the baseline once gate passes"),
784        };
785    };
786    let mut worse = Vec::new();
787    if now.tests < before.tests {
788        worse.push(format!("tests {} -> {}", before.tests, now.tests));
789    }
790    if now.asserts < before.asserts {
791        worse.push(format!("assertions {} -> {}", before.asserts, now.asserts));
792    }
793    if now.ignored > before.ignored {
794        worse.push(format!("ignored {} -> {}", before.ignored, now.ignored));
795    }
796    Check {
797        fix: None,
798        name: "tests",
799        passed: worse.is_empty(),
800        detail: if worse.is_empty() {
801            format!("{counts}, none removed since the last passing gate")
802        } else {
803            format!("{} since the last passing gate", worse.join(", "))
804        },
805    }
806}
807
808#[derive(Debug, Serialize)]
809pub struct GateOutcome {
810    pub passed: bool,
811    pub checks: Vec<Check>,
812}
813
814/// Format the text output for a `GateOutcome`. Every check's detail begins in the same
815/// column by padding check names to the longest check name.
816pub fn text(outcome: &GateOutcome) -> String {
817    use std::fmt::Write as _;
818    let mut out = String::new();
819    let width = outcome
820        .checks
821        .iter()
822        .map(|c| c.name.len())
823        .max()
824        .unwrap_or(0);
825    for check in &outcome.checks {
826        let mark = if check.passed { "pass" } else { "FAIL" };
827        let first = check.detail.lines().next().unwrap_or_default();
828        let _ = writeln!(out, "{mark}  {:<width$} {first}", check.name);
829        if !check.passed {
830            // Continuation lines start in the detail's column: the mark, two spaces, the
831            // padded name and one space.
832            let indent = " ".repeat(mark.len() + 2 + width + 1);
833            for line in check.detail.lines().skip(1) {
834                let _ = writeln!(out, "{indent}{line}");
835            }
836            if let Some(fix) = &check.fix {
837                let _ = writeln!(out, "{indent}fix: {fix}");
838            }
839        }
840    }
841    let _ = writeln!(
842        out,
843        "{}",
844        if outcome.passed {
845            "Gate passed."
846        } else {
847            "Gate failed."
848        }
849    );
850    out
851}
852
853pub fn gate(crate_dir: &Path, node_args: &[String]) -> Result<GateOutcome> {
854    let manifest = Manifest::load(crate_dir)?;
855    let lockfile = lockfile_check(crate_dir);
856    let mut checks = rust_checks(crate_dir, &crate::cache::target_for(crate_dir)?.dir);
857    checks.extend(lockfile);
858    checks.extend(advisories_check(crate_dir));
859    checks.push(ported_check(crate_dir));
860
861    checks.extend(size_check(crate_dir, &manifest));
862    checks.extend(literals_check(crate_dir, &manifest));
863    checks.push(tests_check(crate_dir));
864    checks.extend(crate::error_paths::checks(crate_dir, &manifest));
865    let built = harness::build(crate_dir);
866    let built_ok = built.is_ok();
867    let (build_detail, build_fix) = match built {
868        Ok(path) => (format!("built {}", path.display()), None),
869        Err(e) => (last_lines(&format!("{e:#}"), 15), spawn_fix(&e)),
870    };
871    checks.push(Check {
872        fix: build_fix,
873        name: "build",
874        passed: built_ok,
875        detail: build_detail,
876    });
877
878    if let Some(why) = crate::recording::stale(crate_dir, &manifest) {
879        checks.push(Check {
880            fix: None,
881            name: "recording",
882            passed: false,
883            detail: why,
884        });
885    }
886    if let Some(why) = crate::recording::cases_tampered(crate_dir) {
887        checks.push(Check {
888            fix: None,
889            name: "recording",
890            passed: false,
891            detail: why,
892        });
893    }
894
895    if let Some(line) = crate::recording::saved_coverage(crate_dir)
896        .and_then(|c| crate::recording::coverage_line(&c))
897    {
898        checks.push(Check {
899            fix: None,
900            name: "coverage",
901            passed: true,
902            detail: line,
903        });
904    }
905
906    if !crate_dir.join(CASES).exists() {
907        checks.push(Check {
908            fix: None,
909            name: "behavior",
910            passed: false,
911            detail: "no recorded cases: run `rust-anything record` first".into(),
912        });
913    } else if built_ok {
914        match harness::diff(&DiffOptions {
915            crate_dir,
916            module: None,
917            ignore_key_order: false,
918            float_tolerance: None,
919            node_args,
920        }) {
921            Ok(d) => {
922                checks.push(Check {
923                    fix: None,
924                    name: "api",
925                    passed: d.missing.is_empty(),
926                    detail: if d.missing.is_empty() {
927                        format!(
928                            "exports {}",
929                            manifest
930                                .exports
931                                .iter()
932                                .map(|f| f.name.clone())
933                                .chain(manifest.classes.iter().map(|c| format!("class {}", c.name)))
934                                .collect::<Vec<_>>()
935                                .join(", ")
936                        )
937                    } else {
938                        format!("missing exports: {}", d.missing.join(", "))
939                    },
940                });
941                checks.push(Check {
942                    fix: None,
943                    name: "behavior",
944                    passed: d.failed == 0,
945                    detail: behavior_detail(
946                        d.passed,
947                        d.total,
948                        d.accepted,
949                        known_diffs_added(crate_dir),
950                    ),
951                });
952                if !d.stale_known.is_empty() {
953                    checks.push(Check {
954                        fix: None,
955                        name: "known diffs",
956                        passed: false,
957                        detail: format!(
958                            "{} entr{} of {} no longer differ{}: remove {}",
959                            d.stale_known.len(),
960                            if d.stale_known.len() == 1 { "y" } else { "ies" },
961                            crate::recording::KNOWN_DIFFS,
962                            if d.stale_known.len() == 1 { "s" } else { "" },
963                            d.stale_known
964                                .iter()
965                                .map(|e| format!(
966                                    "{}({})",
967                                    e["fn"].as_str().unwrap_or("?"),
968                                    e["args"]
969                                ))
970                                .collect::<Vec<_>>()
971                                .join(", ")
972                        ),
973                    });
974                }
975            }
976            Err(e) => checks.push(Check {
977                fix: None,
978                name: "behavior",
979                passed: false,
980                detail: format!("{e:#}"),
981            }),
982        }
983    }
984
985    for check in checks.iter_mut().filter(|c| !c.passed && c.fix.is_none()) {
986        check.fix = fix_for(check, crate_dir);
987    }
988    let passed = checks.iter().all(|c| c.passed);
989    if passed {
990        save_tests_baseline(crate_dir)?;
991    }
992    Ok(GateOutcome { passed, checks })
993}
994
995fn lockfile_check(crate_dir: &Path) -> Option<Check> {
996    if !crate_dir.join("Cargo.lock").exists() {
997        return Some(Check {
998            fix: None,
999            name: "lockfile",
1000            passed: true,
1001            detail: "warning: no Cargo.lock yet; keep the one the build writes, so builds are reproducible".into(),
1002        });
1003    }
1004    let mut cmd = Command::new("cargo");
1005    cmd.args([
1006        "metadata",
1007        "--locked",
1008        "--offline",
1009        "--format-version",
1010        "1",
1011        "--manifest-path",
1012    ])
1013    .arg(crate_dir.join("Cargo.toml"));
1014    let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
1015    let stderr = String::from_utf8_lossy(&out.stderr);
1016    let stale = !out.status.success() && stderr.contains("--locked");
1017    Some(Check {
1018        fix: None,
1019        name: "lockfile",
1020        passed: true,
1021        detail: if stale {
1022            "warning: Cargo.lock is out of date with Cargo.toml; keep the refreshed one the build wrote".into()
1023        } else {
1024            "Cargo.lock matches Cargo.toml".into()
1025        },
1026    })
1027}
1028
1029fn advisories_check(crate_dir: &Path) -> Option<Check> {
1030    let manifest = crate_dir.join("Cargo.toml");
1031    let attempts: [(&str, Vec<std::ffi::OsString>); 2] = [
1032        (
1033            "cargo-deny",
1034            vec![
1035                "deny".into(),
1036                "--manifest-path".into(),
1037                manifest.clone().into(),
1038                "check".into(),
1039                "advisories".into(),
1040            ],
1041        ),
1042        (
1043            "cargo-audit",
1044            vec![
1045                "audit".into(),
1046                "--file".into(),
1047                crate_dir.join("Cargo.lock").into(),
1048            ],
1049        ),
1050    ];
1051    for (tool, args) in attempts {
1052        if !crate::setup::on_path(tool) {
1053            continue;
1054        }
1055        let mut cmd = Command::new("cargo");
1056        cmd.args(&args);
1057        let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
1058        let text = format!(
1059            "{}{}",
1060            String::from_utf8_lossy(&out.stdout),
1061            String::from_utf8_lossy(&out.stderr)
1062        );
1063        return Some(Check {
1064            fix: None,
1065            name: "advisories",
1066            passed: true,
1067            detail: if out.status.success() {
1068                format!("no known advisories ({tool})")
1069            } else {
1070                format!(
1071                    "warning: {tool} reports advisories\n{}",
1072                    last_lines(&text, 15)
1073                )
1074            },
1075        });
1076    }
1077    None
1078}
1079
1080/// The checks that hold for any Rust crate, bindings or not: fmt, clippy (warnings are errors),
1081/// cargo test, and `unsafe` only with a `// SAFETY:` comment.
1082pub fn rust_checks(crate_dir: &Path, target_dir: &Path) -> Vec<Check> {
1083    let cargo = |args: &[&str]| -> (bool, String, Option<String>) {
1084        let mut cmd = Command::new("cargo");
1085        cmd.args(args)
1086            .arg("--manifest-path")
1087            .arg(crate_dir.join("Cargo.toml"))
1088            .env("CARGO_TARGET_DIR", target_dir);
1089        // Lint arguments go after `--`, so the manifest path must come before them.
1090        match crate::process::output(&mut cmd, crate::process::BUILD) {
1091            Ok(o) => (
1092                o.status.success(),
1093                last_lines(&String::from_utf8_lossy(&o.stderr), 15),
1094                None,
1095            ),
1096            Err(e) => (false, format!("{e:#}"), spawn_fix(&e)),
1097        }
1098    };
1099    let mut checks = Vec::new();
1100
1101    let (ok, out, fix) = cargo(&["fmt", "--check"]);
1102    checks.push(Check {
1103        name: "fmt",
1104        passed: ok,
1105        detail: if ok {
1106            "formatted".into()
1107        } else if fix.is_some() {
1108            out
1109        } else {
1110            format!("run `cargo fmt`\n{out}")
1111        },
1112        fix,
1113    });
1114
1115    let mut clippy = Command::new("cargo");
1116    clippy
1117        .args(["clippy", "--all-targets", "--manifest-path"])
1118        .arg(crate_dir.join("Cargo.toml"))
1119        .args(["--", "-D", "warnings"])
1120        .env("CARGO_TARGET_DIR", target_dir);
1121    let (ok, out, fix) = match crate::process::output(&mut clippy, crate::process::BUILD) {
1122        Ok(o) => (
1123            o.status.success(),
1124            last_lines(&String::from_utf8_lossy(&o.stderr), 15),
1125            None,
1126        ),
1127        Err(e) => (false, format!("{e:#}"), spawn_fix(&e)),
1128    };
1129    checks.push(Check {
1130        fix,
1131        name: "clippy",
1132        passed: ok,
1133        detail: if ok { "no warnings".into() } else { out },
1134    });
1135
1136    let (ok, out, fix) = cargo(&["test", "--quiet"]);
1137    checks.push(Check {
1138        fix,
1139        name: "cargo test",
1140        passed: ok,
1141        detail: if ok { "passed".into() } else { out },
1142    });
1143
1144    let (unexplained, explained) = unsafe_blocks(&crate_dir.join("src"));
1145    checks.push(Check {
1146        fix: None,
1147        name: "unsafe",
1148        passed: unexplained.is_empty(),
1149        detail: if unexplained.is_empty() {
1150            format!("{explained} unsafe uses, each with a `// SAFETY:` comment")
1151        } else {
1152            format!(
1153                "unsafe without a `// SAFETY:` comment: {}",
1154                unexplained.join(", ")
1155            )
1156        },
1157    });
1158
1159    checks
1160}
1161
1162/// No function in `src/port.rs` is still `unimplemented!`.
1163pub fn ported_check(crate_dir: &Path) -> Check {
1164    let path = crate_dir.join("src/port.rs");
1165    let port = match std::fs::read_to_string(&path) {
1166        Ok(port) => port,
1167        Err(error) => {
1168            return Check {
1169                fix: None,
1170                name: "ported",
1171                passed: false,
1172                detail: format!("cannot read {}: {error}", path.display()),
1173            };
1174        }
1175    };
1176    let todo = stubs(&port);
1177    Check {
1178        fix: None,
1179        name: "ported",
1180        passed: todo == 0,
1181        detail: if todo == 0 {
1182            "nothing in port.rs is `unimplemented!`, `todo!` or only a `panic!`".into()
1183        } else {
1184            format!(
1185                "{} in port.rs still `unimplemented!`, `todo!` or a function that only panics",
1186                crate::report::count(todo, "place")
1187            )
1188        },
1189    }
1190}
1191
1192/// Stubs left in a port: `unimplemented!`, `todo!`, and functions whose whole body is a `panic!`.
1193fn stubs(port: &str) -> usize {
1194    let code: String = port
1195        .lines()
1196        .map(|l| l.split("//").next().unwrap_or_default())
1197        .collect::<Vec<_>>()
1198        .join("\n");
1199    let macros = code.matches("unimplemented!(").count() + code.matches("todo!(").count();
1200    let panics = regex::Regex::new(r"\bfn\s+\w+[^{;]*\{\s*panic!\([^;{}]*\)\s*;?\s*\}")
1201        .map(|re| re.find_iter(&code).count())
1202        .unwrap_or(0);
1203    macros + panics
1204}
1205
1206/// `unsafe` uses in Rust sources, split into those without and with a `// SAFETY:` comment just above.
1207fn unsafe_blocks(src: &Path) -> (Vec<String>, usize) {
1208    let mut unexplained = Vec::new();
1209    let mut explained = 0;
1210    let mut stack = vec![src.to_path_buf()];
1211    while let Some(dir) = stack.pop() {
1212        let Ok(entries) = std::fs::read_dir(&dir) else {
1213            continue;
1214        };
1215        for entry in entries.flatten() {
1216            let path = entry.path();
1217            if path.is_dir() {
1218                stack.push(path);
1219                continue;
1220            }
1221            if path.extension().is_none_or(|e| e != "rs") {
1222                continue;
1223            }
1224            let text = std::fs::read_to_string(&path).unwrap_or_default();
1225            let lines: Vec<&str> = text.lines().collect();
1226            for (i, line) in lines.iter().enumerate() {
1227                let code = strip_code(line);
1228                let uses_unsafe = code
1229                    .split(|c: char| !(c.is_alphanumeric() || c == '_'))
1230                    .any(|word| word == "unsafe");
1231                if !uses_unsafe {
1232                    continue;
1233                }
1234                let has_safety = lines[..i]
1235                    .iter()
1236                    .rev()
1237                    .take_while(|l| l.trim_start().starts_with("//"))
1238                    .any(|l| l.contains("SAFETY:"));
1239                if has_safety {
1240                    explained += 1;
1241                } else {
1242                    unexplained.push(format!("{}:{}", path.display(), i + 1));
1243                }
1244            }
1245        }
1246    }
1247    (unexplained, explained)
1248}
1249
1250fn last_lines(text: &str, n: usize) -> String {
1251    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
1252    lines[lines.len().saturating_sub(n)..].join("\n")
1253}
1254
1255/// Strips string and char literals and comments from a line of Rust source code so keyword
1256/// searches (like `unsafe`) only match real code, not strings or comments.
1257fn strip_code(line: &str) -> String {
1258    let bytes = line.as_bytes();
1259    let mut out = String::with_capacity(line.len());
1260    let mut i = 0;
1261    while i < bytes.len() {
1262        // Line comment: everything from here to end of line is ignored.
1263        if bytes[i..].starts_with(b"//") {
1264            break;
1265        }
1266
1267        // Block comment: /* ... */
1268        if bytes[i..].starts_with(b"/*") {
1269            i += 2;
1270            while i < bytes.len() && !bytes[i..].starts_with(b"*/") {
1271                i += 1;
1272            }
1273            if i < bytes.len() {
1274                i += 2;
1275            }
1276            out.push(' ');
1277            continue;
1278        }
1279
1280        // Raw string: optional 'b' or 'c', then 'r', zero or more '#', then '"'.
1281        let prev_is_ident = i > 0 && (bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
1282        let mut j = i;
1283        if !prev_is_ident
1284            && (bytes[j] == b'b' || bytes[j] == b'c')
1285            && j + 1 < bytes.len()
1286            && bytes[j + 1] == b'r'
1287        {
1288            j += 1;
1289        }
1290        if !prev_is_ident && bytes[j] == b'r' {
1291            let mut k = j + 1;
1292            while k < bytes.len() && bytes[k] == b'#' {
1293                k += 1;
1294            }
1295            if k < bytes.len() && bytes[k] == b'"' {
1296                let hashes = k - (j + 1);
1297                i = k + 1;
1298                while i < bytes.len() {
1299                    if bytes[i] == b'"' {
1300                        let rest = &bytes[i + 1..];
1301                        if rest.len() >= hashes && rest[..hashes].iter().all(|&b| b == b'#') {
1302                            i += 1 + hashes;
1303                            break;
1304                        }
1305                    }
1306                    i += 1;
1307                }
1308                out.push(' ');
1309                continue;
1310            }
1311        }
1312
1313        // Standard string: optional 'b' or 'c', then '"'.
1314        let is_byte_or_c_str = !prev_is_ident
1315            && (bytes[i] == b'b' || bytes[i] == b'c')
1316            && i + 1 < bytes.len()
1317            && bytes[i + 1] == b'"';
1318        if bytes[i] == b'"' || is_byte_or_c_str {
1319            if is_byte_or_c_str {
1320                i += 1;
1321            }
1322            i += 1; // skip opening '"'
1323            while i < bytes.len() {
1324                if bytes[i] == b'\\' {
1325                    i += if i + 1 < bytes.len() { 2 } else { 1 };
1326                } else if bytes[i] == b'"' {
1327                    i += 1;
1328                    break;
1329                } else {
1330                    i += 1;
1331                }
1332            }
1333            out.push(' ');
1334            continue;
1335        }
1336
1337        // Char literal: 'x', '\n', '\'', etc.
1338        let is_byte_char =
1339            !prev_is_ident && bytes[i] == b'b' && i + 1 < bytes.len() && bytes[i + 1] == b'\'';
1340        if bytes[i] == b'\'' || is_byte_char {
1341            let quote_pos = if is_byte_char { i + 1 } else { i };
1342            let rest = &line[quote_pos + 1..];
1343            if let Some(close_rel) = rest.find('\'')
1344                && close_rel <= 8
1345                && !rest[..close_rel].contains(' ')
1346            {
1347                i = quote_pos + 1 + close_rel + 1;
1348                out.push(' ');
1349                continue;
1350            }
1351        }
1352
1353        out.push(bytes[i] as char);
1354        i += 1;
1355    }
1356    out
1357}
1358
1359#[cfg(test)]
1360mod tests {
1361    use super::{
1362        CASES, Check, GateOutcome, TESTS_BASELINE, behavior_detail, fix_for, known_diffs_added,
1363        spawn_fix, stubs, unsafe_blocks,
1364    };
1365
1366    #[test]
1367    fn the_behavior_line_names_known_diffs_added_since_the_last_pass() {
1368        assert_eq!(behavior_detail(10, 10, 0, 0), "10/10 recorded cases match");
1369        assert_eq!(
1370            behavior_detail(10, 10, 3, 0),
1371            "10/10 recorded cases match (3 by known-diffs.jsonl)"
1372        );
1373        assert_eq!(
1374            behavior_detail(10, 10, 3, 2),
1375            "10/10 recorded cases match (3 by known-diffs.jsonl, 2 entries added since the \
1376             last passing gate: land behavior changes apart from the port)"
1377        );
1378        assert_eq!(
1379            behavior_detail(10, 10, 1, 1),
1380            "10/10 recorded cases match (1 by known-diffs.jsonl, 1 entry added since the \
1381             last passing gate: land behavior changes apart from the port)"
1382        );
1383    }
1384
1385    #[test]
1386    fn known_diffs_added_counts_from_the_last_passing_gate_only() {
1387        let dir = std::env::temp_dir().join(format!("ra-known-added-{}", std::process::id()));
1388        std::fs::create_dir_all(dir.join(".rust-anything")).unwrap();
1389        let entry = r#"{"fn":"f","args":[1],"actual":2,"reason":"rounding"}"#;
1390        std::fs::write(
1391            dir.join("known-diffs.jsonl"),
1392            format!("{entry}\n{entry}\n{entry}\n"),
1393        )
1394        .unwrap();
1395        assert_eq!(known_diffs_added(&dir), 0, "no baseline yet");
1396        std::fs::write(dir.join(TESTS_BASELINE), r#"{"tests":1,"asserts":1}"#).unwrap();
1397        assert_eq!(
1398            known_diffs_added(&dir),
1399            0,
1400            "a baseline from before the count"
1401        );
1402        std::fs::write(
1403            dir.join(TESTS_BASELINE),
1404            r#"{"tests":1,"asserts":1,"known_diffs":1}"#,
1405        )
1406        .unwrap();
1407        assert_eq!(known_diffs_added(&dir), 2);
1408        std::fs::remove_dir_all(&dir).unwrap();
1409    }
1410
1411    #[test]
1412    fn counts_every_kind_of_stub() {
1413        let port = "pub fn a() -> u8 { todo!() }\n\
1414                    pub fn b() -> u8 { unimplemented!(\"later\") }\n\
1415                    pub fn c(x: u8) -> u8 {\n    panic!(\"not ported\")\n}\n\
1416                    pub fn d(x: u8) -> u8 { if x > 1 { panic!(\"big\") } x }\n\
1417                    // todo!() in a comment\n";
1418        assert_eq!(stubs(port), 3);
1419        assert_eq!(stubs("pub fn ok() -> u8 { 1 }"), 0);
1420    }
1421
1422    #[test]
1423    fn failed_checks_say_what_to_run() {
1424        let check = |name, detail: &str| Check {
1425            fix: None,
1426            name,
1427            passed: false,
1428            detail: detail.into(),
1429        };
1430        let dir = std::path::Path::new("port");
1431        assert_eq!(
1432            fix_for(&check("recording", "changed"), dir).as_deref(),
1433            Some("rust-anything record port")
1434        );
1435        assert_eq!(
1436            fix_for(&check("behavior", "no recorded cases: run"), dir).as_deref(),
1437            Some("rust-anything record port")
1438        );
1439        assert!(fix_for(&check("fmt", ""), dir).is_some_and(|f| f.starts_with("cargo fmt")));
1440        assert_eq!(fix_for(&check("coverage", ""), dir), None);
1441
1442        let mut missing_cmd = std::process::Command::new("cargo");
1443        missing_cmd.env_remove("PATH");
1444        let missing_err = crate::process::spawn_error(
1445            &missing_cmd,
1446            "cargo build",
1447            std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
1448        );
1449        let missing_fix = spawn_fix(&missing_err).unwrap();
1450        assert!(
1451            !missing_fix.contains("fix the compile error above"),
1452            "{missing_fix}"
1453        );
1454        assert!(missing_fix.contains("cargo"), "{missing_fix}");
1455        assert!(
1456            missing_fix.contains("rust-anything doctor"),
1457            "{missing_fix}"
1458        );
1459        assert!(!missing_fix.contains('\n'), "{missing_fix}");
1460
1461        let denied_err = crate::process::spawn_error(
1462            &std::process::Command::new("cargo"),
1463            "cargo build",
1464            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"),
1465        );
1466        let spawn_hint = spawn_fix(&denied_err).unwrap();
1467        assert!(
1468            !spawn_hint.contains("fix the compile error above"),
1469            "{spawn_hint}"
1470        );
1471        assert!(spawn_hint.contains("rust-anything doctor"), "{spawn_hint}");
1472
1473        let compile_err =
1474            anyhow::anyhow!("cargo build failed (exit status: 101)\n\"not found on PATH\"");
1475        assert!(spawn_fix(&compile_err).is_none());
1476        let compile_fix = fix_for(&check("build", &compile_err.to_string()), dir).unwrap();
1477        assert!(
1478            compile_fix.starts_with("fix the compile error above"),
1479            "{compile_fix}"
1480        );
1481    }
1482
1483    #[test]
1484    fn requires_safety_comments() {
1485        let dir = std::env::temp_dir().join(format!("rust-anything-gate-{}", std::process::id()));
1486        std::fs::create_dir_all(&dir).unwrap();
1487        std::fs::write(
1488            dir.join("a.rs"),
1489            "#![forbid(unsafe_code)]\n\
1490             // SAFETY: checked above\n\
1491             unsafe { x() }\n\
1492             let y = unsafe { z() };\n\
1493             // unsafe in a comment\n\
1494             let _err = Err(\"RangeError: unsafe input\".into());\n\
1495             let _raw = r#\"unsafe \"quoted\" string\"#;\n\
1496             let _with_real = \"a string with unsafe\"; unsafe { real_work() };\n",
1497        )
1498        .unwrap();
1499        let (unexplained, explained) = unsafe_blocks(&dir);
1500        std::fs::remove_dir_all(&dir).unwrap();
1501        assert_eq!(explained, 1);
1502        assert_eq!(unexplained.len(), 2);
1503        assert!(unexplained[0].ends_with("a.rs:4"), "{}", unexplained[0]);
1504        assert!(unexplained[1].ends_with("a.rs:8"), "{}", unexplained[1]);
1505    }
1506
1507    #[test]
1508    fn strip_code_removes_strings_chars_and_comments() {
1509        assert_eq!(super::strip_code("// unsafe comment").trim(), "");
1510        assert_eq!(
1511            super::strip_code("let s = \"unsafe inside string\";"),
1512            "let s =  ;"
1513        );
1514        assert_eq!(
1515            super::strip_code("let s = r#\"unsafe in raw\"#;"),
1516            "let s =  ;"
1517        );
1518        assert_eq!(
1519            super::strip_code("let s = \"unsafe\"; unsafe { }"),
1520            "let s =  ; unsafe { }"
1521        );
1522        assert_eq!(
1523            super::strip_code("let s = \"http://example.com\"; unsafe { }"),
1524            "let s =  ; unsafe { }"
1525        );
1526    }
1527
1528    #[test]
1529    fn missing_port_source_fails_the_ported_check() {
1530        let dir = crate::app::temp_dir("gate-port").unwrap();
1531        let check = super::ported_check(&dir);
1532        std::fs::remove_dir(dir).unwrap();
1533        assert!(!check.passed);
1534        assert!(check.detail.contains("cannot read"));
1535        assert!(check.detail.contains("port.rs"));
1536    }
1537
1538    #[test]
1539    fn ported_check_counts_one_place_and_several_places() {
1540        let detail = |port: &str| {
1541            let dir = crate::app::temp_dir("gate-ported").unwrap();
1542            std::fs::create_dir_all(dir.join("src")).unwrap();
1543            std::fs::write(dir.join("src/port.rs"), port).unwrap();
1544            let check = super::ported_check(&dir);
1545            std::fs::remove_dir_all(dir).unwrap();
1546            assert!(!check.passed);
1547            check.detail
1548        };
1549        let one = detail("pub fn a() -> i32 { todo!() }\n");
1550        assert!(one.starts_with("1 place in port.rs "), "{one}");
1551        let two = detail("pub fn a() -> i32 { todo!() }\npub fn b() -> i32 { unimplemented!() }\n");
1552        assert!(two.starts_with("2 places in port.rs "), "{two}");
1553    }
1554
1555    #[test]
1556    fn scan_finds_literals_outside_comments_and_tests() {
1557        let port = "// \"a comment string\" 123456\n\
1558                    /* 987654 /* nested */ \"no\" */\n\
1559                    pub fn f(x: &str) -> u64 { if x == \"tab\\there\\u{e9}\" { 1_234_567u64 } else { 0x123456 } }\n\
1560                    pub fn g<'a>(c: char) -> &'a str { if c == '\"' { r#\"say \"hi\" now\"# } else { b\"bytes!!!\"; \"x\" } }\n\
1561                    pub fn h() -> f64 { 3.14159e-2 + (0..100000).count() as f64 } // recorded-literal: pi\n\
1562                    pub fn i() -> f64 { t.0 + 2.5f32 as f64 }\n\
1563                    #[cfg(test)]\nmod tests { const X: &str = \"only in tests\"; }\n";
1564        let scan = super::scan_rust(port, true);
1565        let strings: Vec<(usize, &str)> =
1566            scan.strings.iter().map(|(l, s)| (*l, s.as_str())).collect();
1567        assert_eq!(
1568            strings,
1569            [
1570                (3, "tab\there\u{e9}"),
1571                (4, "say \"hi\" now"),
1572                (4, "bytes!!!"),
1573                (4, "x")
1574            ]
1575        );
1576        let numbers: Vec<(usize, &str)> =
1577            scan.numbers.iter().map(|(l, n)| (*l, n.as_str())).collect();
1578        assert_eq!(
1579            numbers,
1580            [
1581                (3, "1234567"),
1582                (5, "3.14159e-2"),
1583                (5, "0"),
1584                (5, "100000"),
1585                (6, "2.5")
1586            ]
1587        );
1588        assert!(scan.marked.contains(&5) && scan.marked.len() == 1);
1589        assert!(!scan.code.contains("comment") && !scan.code.contains("only in tests"));
1590        let all = super::scan_rust(port, false);
1591        assert_eq!(all.strings.last().unwrap().1, "only in tests");
1592    }
1593
1594    #[test]
1595    fn common_numbers_are_never_suspicious() {
1596        use super::{significant_digits, well_known};
1597        assert_eq!(significant_digits("1234500"), 5);
1598        assert_eq!(significant_digits("0.00012345"), 5);
1599        assert_eq!(significant_digits("1.25e10"), 3);
1600        for n in [
1601            "65536",
1602            "65535",
1603            "4294967295",
1604            "2147483647",
1605            "9007199254740991",
1606            "18446744073709551615",
1607            "1000000",
1608            "1.7976931348623157e308",
1609            "3.4028235e38",
1610            "2.220446049250313e-16",
1611        ] {
1612            assert!(well_known(n), "{n}");
1613        }
1614        for n in ["12345", "4294967299", "3.14159", "99999"] {
1615            assert!(!well_known(n), "{n}");
1616        }
1617    }
1618
1619    #[test]
1620    fn literals_leave_out_recorded_error_text() {
1621        let dir = crate::app::temp_dir("gate-literals-errors").unwrap();
1622        std::fs::create_dir_all(dir.join("src")).unwrap();
1623        std::fs::write(dir.join("words.py"), "def ratio(a, b):\n    return a / b\n").unwrap();
1624        std::fs::write(
1625            dir.join(CASES),
1626            "{\"fn\":\"ratio\",\"args\":[1,0],\"error\":\"ZeroDivisionError: division by zero\",\"error_type\":\"ZeroDivisionError\"}\n\
1627             {\"class\":\"Ratio\",\"ctor\":[0],\"calls\":[],\"results\":[{\"error\":\"OverflowError: stack is full\"}]}\n",
1628        )
1629        .unwrap();
1630        std::fs::write(
1631            dir.join("src/port.rs"),
1632            "pub fn ratio(a: f64, b: f64) -> Result<f64, String> {\n    if b == 0.0 { return Err(\"ZeroDivisionError: division by zero\".into()) }\n    if a > 1e9 { return Err(\"OverflowError: stack is full\".into()) }\n    Ok(a / b)\n}\n",
1633        )
1634        .unwrap();
1635        let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
1636            "schema": crate::bridge::SCHEMA,
1637            "root": dir,
1638            "unit": "words.py",
1639            "crate_name": "demo",
1640            "kind": "pyo3",
1641            "exports": [],
1642        }))
1643        .unwrap();
1644        let check = super::literals_check(&dir, &manifest).unwrap();
1645        assert!(check.passed, "{check:?}");
1646        assert_eq!(check.detail, "no recorded values written into the port");
1647    }
1648
1649    #[test]
1650    fn literals_fail_from_three_recorded_values_the_original_does_not_spell() {
1651        let dir = crate::app::temp_dir("gate-literals").unwrap();
1652        std::fs::create_dir_all(dir.join("src")).unwrap();
1653        std::fs::write(
1654            dir.join("lib.ts"),
1655            "export const greet = (n: string) => `hello there, ${n}` + \"spelled out\" + 31337\n",
1656        )
1657        .unwrap();
1658        std::fs::write(
1659            dir.join(CASES),
1660            "{\"fn\":\"greet\",\"args\":[\"somebody else\"],\"ok\":\"hello there, somebody else\"}\n\
1661             {\"fn\":\"greet\",\"args\":[\"x\"],\"ok\":[\"spelled out\",\"second answer\",31337,271828,\"third answer\"]}\n",
1662        )
1663        .unwrap();
1664        let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
1665            "schema": crate::bridge::SCHEMA,
1666            "root": dir,
1667            "unit": "lib.ts",
1668            "crate_name": "demo",
1669            "kind": "napi",
1670            "exports": [],
1671        }))
1672        .unwrap();
1673        let check = |port: &str| {
1674            std::fs::write(dir.join("src/port.rs"), port).unwrap();
1675            super::literals_check(&dir, &manifest).unwrap()
1676        };
1677        let honest = check(
1678            "pub fn greet(n: &str) -> String { format!(\"hello there, {n}\") + \"spelled out\" }\n",
1679        );
1680        assert!(honest.passed, "{honest:?}");
1681        assert_eq!(honest.detail, "no recorded values written into the port");
1682
1683        let two = check(
1684            "pub fn greet(n: &str) -> String {\n    if n == \"somebody else\" { return \"second answer\".into() }\n    String::new()\n}\n",
1685        );
1686        assert!(two.passed, "{two:?}");
1687        assert!(
1688            two.detail.starts_with("2 recorded values"),
1689            "{}",
1690            two.detail
1691        );
1692        assert!(
1693            two.detail.contains("\"somebody else\" (src/port.rs:2)"),
1694            "{}",
1695            two.detail
1696        );
1697
1698        let three = check(
1699            "pub fn greet(n: &str) -> String {\n    if n == \"somebody else\" { return \"second answer\".into() }\n    let _ = 271_828;\n    String::new()\n}\n",
1700        );
1701        assert!(!three.passed, "{three:?}");
1702        assert!(
1703            three.detail.contains("271828 (src/port.rs:3)"),
1704            "{}",
1705            three.detail
1706        );
1707
1708        let marked = check(
1709            "pub fn greet(n: &str) -> String {\n    if n == \"somebody else\" { return \"second answer\".into() }\n    let _ = 271_828; // recorded-literal: e from a table\n    String::new()\n}\n",
1710        );
1711        assert!(marked.passed, "{marked:?}");
1712
1713        let reads = check("const C: &str = include_str!(\"../cases.jsonl\");\n");
1714        assert!(!reads.passed, "{reads:?}");
1715        assert!(reads.detail.contains("src/port.rs:1"), "{}", reads.detail);
1716        std::fs::remove_dir_all(dir).unwrap();
1717    }
1718
1719    #[test]
1720    fn size_check_says_1_line_for_singular_source() {
1721        let dir = crate::app::temp_dir("gate-size").unwrap();
1722        let src_dir = dir.join("src");
1723        std::fs::create_dir_all(&src_dir).unwrap();
1724        std::fs::write(src_dir.join("add.ts"), "export const add = 1;\n").unwrap();
1725        std::fs::write(src_dir.join("port.rs"), "pub fn add() -> i32 { 1 }\n").unwrap();
1726        let manifest: crate::bridge::Manifest = serde_json::from_value(serde_json::json!({
1727            "schema": crate::bridge::SCHEMA,
1728            "root": dir,
1729            "unit": "src",
1730            "crate_name": "demo",
1731            "kind": "napi",
1732            "exports": [],
1733        }))
1734        .unwrap();
1735        let check = super::size_check(&dir, &manifest).unwrap();
1736        std::fs::remove_dir_all(dir).unwrap();
1737        assert!(
1738            check
1739                .detail
1740                .contains("1 line of Rust for 1 line of TypeScript/JavaScript"),
1741            "{}",
1742            check.detail
1743        );
1744    }
1745
1746    #[test]
1747    fn text_aligns_all_check_details_including_error_cases_and_known_diffs() {
1748        let outcome = GateOutcome {
1749            passed: true,
1750            checks: vec![
1751                Check {
1752                    name: "tests",
1753                    passed: true,
1754                    detail: "0 tests, 0 assertions; saved as the baseline once gate passes".into(),
1755                    fix: None,
1756                },
1757                Check {
1758                    name: "error cases",
1759                    passed: true,
1760                    detail: "the 1 function that fails in the original has a recorded failing case"
1761                        .into(),
1762                    fix: None,
1763                },
1764                Check {
1765                    name: "panics",
1766                    passed: true,
1767                    detail: "no unwrap, expect or panic where the original returns an error".into(),
1768                    fix: None,
1769                },
1770                Check {
1771                    name: "known diffs",
1772                    passed: true,
1773                    detail: "all recorded diffs match".into(),
1774                    fix: None,
1775                },
1776            ],
1777        };
1778        let text = super::text(&outcome);
1779        let lines: Vec<&str> = text.lines().take(4).collect();
1780        // Column where the detail starts (after "pass  " (6 chars) + 11-char name + " " (1 char) = 18 chars)
1781        let col = "pass  error cases ".len();
1782        assert_eq!(col, 18);
1783        for line in &lines {
1784            assert!(line.len() > col, "line too short: {line}");
1785            assert_eq!(
1786                &line[col..col + 2],
1787                match line.split_whitespace().nth(1).unwrap() {
1788                    "tests" => "0 ",
1789                    "error" => "th",
1790                    "panics" => "no",
1791                    "known" => "al",
1792                    other => panic!("unexpected check: {other}"),
1793                }
1794            );
1795        }
1796        assert!(text.contains("Gate passed."));
1797    }
1798
1799    #[test]
1800    fn text_aligns_continuation_and_fix_lines_with_the_detail() {
1801        let outcome = GateOutcome {
1802            passed: false,
1803            checks: vec![
1804                Check {
1805                    name: "ported",
1806                    passed: false,
1807                    detail: "1 place in port.rs still `todo!`\nsecond line of the detail".into(),
1808                    fix: Some("port the functions still stubbed in src/port.rs".into()),
1809                },
1810                Check {
1811                    name: "error cases",
1812                    passed: true,
1813                    detail: "every failing function has a recorded failing case".into(),
1814                    fix: None,
1815                },
1816            ],
1817        };
1818        let text = super::text(&outcome);
1819        let col = "FAIL  error cases ".len();
1820        let lines: Vec<&str> = text.lines().collect();
1821        assert_eq!(&lines[0][col..], "1 place in port.rs still `todo!`");
1822        assert_eq!(
1823            lines[1],
1824            format!("{}second line of the detail", " ".repeat(col))
1825        );
1826        assert_eq!(
1827            lines[2],
1828            format!(
1829                "{}fix: port the functions still stubbed in src/port.rs",
1830                " ".repeat(col)
1831            )
1832        );
1833        assert_eq!(
1834            &lines[3][col..],
1835            "every failing function has a recorded failing case"
1836        );
1837        assert_eq!(lines[4], "Gate failed.");
1838    }
1839}