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