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        _ => &["//", "/*", "*"],
162    };
163    let mut files = files_under(
164        &manifest.root.join(&manifest.unit),
165        manifest.language.extensions(),
166    );
167    if manifest.language == crate::lang::Lang::Ts {
168        files = with_local_imports(&manifest.root, files);
169    }
170    if manifest.language == crate::lang::Lang::C {
171        let ported: Vec<&str> = manifest.exports.iter().map(|f| f.name.as_str()).collect();
172        files.extend(crate::lang::c::called_implementations(
173            &manifest.root,
174            &manifest.unit,
175            &ported,
176        ));
177    }
178    let source: usize = files
179        .iter()
180        .filter_map(|p| std::fs::read_to_string(p).ok())
181        .map(|t| code_lines(&t, source_comments))
182        .sum();
183    if source == 0 {
184        return None;
185    }
186    let rust: usize = files_under(&crate_dir.join("src"), &["rs"])
187        .iter()
188        .filter(|p| {
189            p.file_name()
190                .is_none_or(|n| !GENERATED.contains(&n.to_string_lossy().as_ref()))
191        })
192        .filter_map(|p| std::fs::read_to_string(p).ok())
193        .map(|t| code_lines(&t, &["//"]))
194        .sum();
195    let growth = rust as f64 / source as f64;
196    let passed = rust as f64 <= MAX_GROWTH * source as f64 + ALLOWANCE;
197    Some(Check {
198        fix: None,
199        name: "size",
200        passed,
201        detail: format!(
202            "{rust} lines of Rust for {source} lines of {} ({growth:.1}x){}",
203            manifest.language.name(),
204            if passed {
205                String::new()
206            } else {
207                format!(
208                    "; over {MAX_GROWTH}x usually means code a crate already provides, or a case \
209                     handled one by one: use the crates `analyze` lists and fold repeated code"
210                )
211            }
212        ),
213    })
214}
215
216#[derive(Debug, Serialize)]
217pub struct GateOutcome {
218    pub passed: bool,
219    pub checks: Vec<Check>,
220}
221
222pub fn gate(crate_dir: &Path, node_args: &[String]) -> Result<GateOutcome> {
223    let manifest = Manifest::load(crate_dir)?;
224    let lockfile = lockfile_check(crate_dir);
225    let mut checks = rust_checks(crate_dir, &crate::cache::target_for(crate_dir)?.dir);
226    checks.extend(lockfile);
227    checks.extend(advisories_check(crate_dir));
228    checks.push(ported_check(crate_dir));
229
230    checks.extend(size_check(crate_dir, &manifest));
231    checks.extend(crate::error_paths::checks(crate_dir, &manifest));
232    let built = harness::build(crate_dir);
233    let built_ok = built.is_ok();
234    checks.push(Check {
235        fix: None,
236        name: "build",
237        passed: built_ok,
238        detail: match built {
239            Ok(path) => format!("built {}", path.display()),
240            Err(e) => last_lines(&format!("{e:#}"), 15),
241        },
242    });
243
244    if let Some(why) = crate::recording::stale(crate_dir, &manifest) {
245        checks.push(Check {
246            fix: None,
247            name: "recording",
248            passed: false,
249            detail: why,
250        });
251    }
252
253    if let Some(line) = crate::recording::saved_coverage(crate_dir)
254        .and_then(|c| crate::recording::coverage_line(&c))
255    {
256        checks.push(Check {
257            fix: None,
258            name: "coverage",
259            passed: true,
260            detail: line,
261        });
262    }
263
264    if !crate_dir.join(CASES).exists() {
265        checks.push(Check {
266            fix: None,
267            name: "behavior",
268            passed: false,
269            detail: "no recorded cases: run `rust-anything record` first".into(),
270        });
271    } else if built_ok {
272        match harness::diff(&DiffOptions {
273            crate_dir,
274            module: None,
275            ignore_key_order: false,
276            float_tolerance: None,
277            node_args,
278        }) {
279            Ok(d) => {
280                checks.push(Check {
281                    fix: None,
282                    name: "api",
283                    passed: d.missing.is_empty(),
284                    detail: if d.missing.is_empty() {
285                        format!(
286                            "exports {}",
287                            manifest
288                                .exports
289                                .iter()
290                                .map(|f| f.name.clone())
291                                .chain(manifest.classes.iter().map(|c| format!("class {}", c.name)))
292                                .collect::<Vec<_>>()
293                                .join(", ")
294                        )
295                    } else {
296                        format!("missing exports: {}", d.missing.join(", "))
297                    },
298                });
299                checks.push(Check {
300                    fix: None,
301                    name: "behavior",
302                    passed: d.failed == 0,
303                    detail: if d.accepted > 0 {
304                        format!(
305                            "{}/{} recorded cases match ({} by {})",
306                            d.passed,
307                            d.total,
308                            d.accepted,
309                            crate::recording::KNOWN_DIFFS
310                        )
311                    } else {
312                        format!("{}/{} recorded cases match", d.passed, d.total)
313                    },
314                });
315                if !d.stale_known.is_empty() {
316                    checks.push(Check {
317                        fix: None,
318                        name: "known diffs",
319                        passed: false,
320                        detail: format!(
321                            "{} entr{} of {} no longer differ{}: remove {}",
322                            d.stale_known.len(),
323                            if d.stale_known.len() == 1 { "y" } else { "ies" },
324                            crate::recording::KNOWN_DIFFS,
325                            if d.stale_known.len() == 1 { "s" } else { "" },
326                            d.stale_known
327                                .iter()
328                                .map(|e| format!(
329                                    "{}({})",
330                                    e["fn"].as_str().unwrap_or("?"),
331                                    e["args"]
332                                ))
333                                .collect::<Vec<_>>()
334                                .join(", ")
335                        ),
336                    });
337                }
338            }
339            Err(e) => checks.push(Check {
340                fix: None,
341                name: "behavior",
342                passed: false,
343                detail: format!("{e:#}"),
344            }),
345        }
346    }
347
348    for check in checks.iter_mut().filter(|c| !c.passed && c.fix.is_none()) {
349        check.fix = fix_for(check, crate_dir);
350    }
351    Ok(GateOutcome {
352        passed: checks.iter().all(|c| c.passed),
353        checks,
354    })
355}
356
357fn lockfile_check(crate_dir: &Path) -> Option<Check> {
358    if !crate_dir.join("Cargo.lock").exists() {
359        return Some(Check {
360            fix: None,
361            name: "lockfile",
362            passed: true,
363            detail: "warning: no Cargo.lock yet; keep the one the build writes, so builds are reproducible".into(),
364        });
365    }
366    let mut cmd = Command::new("cargo");
367    cmd.args([
368        "metadata",
369        "--locked",
370        "--offline",
371        "--format-version",
372        "1",
373        "--manifest-path",
374    ])
375    .arg(crate_dir.join("Cargo.toml"));
376    let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
377    let stderr = String::from_utf8_lossy(&out.stderr);
378    let stale = !out.status.success() && stderr.contains("--locked");
379    Some(Check {
380        fix: None,
381        name: "lockfile",
382        passed: true,
383        detail: if stale {
384            "warning: Cargo.lock is out of date with Cargo.toml; keep the refreshed one the build wrote".into()
385        } else {
386            "Cargo.lock matches Cargo.toml".into()
387        },
388    })
389}
390
391fn advisories_check(crate_dir: &Path) -> Option<Check> {
392    let manifest = crate_dir.join("Cargo.toml");
393    let attempts: [(&str, Vec<std::ffi::OsString>); 2] = [
394        (
395            "cargo-deny",
396            vec![
397                "deny".into(),
398                "--manifest-path".into(),
399                manifest.clone().into(),
400                "check".into(),
401                "advisories".into(),
402            ],
403        ),
404        (
405            "cargo-audit",
406            vec![
407                "audit".into(),
408                "--file".into(),
409                crate_dir.join("Cargo.lock").into(),
410            ],
411        ),
412    ];
413    for (tool, args) in attempts {
414        if !crate::setup::on_path(tool) {
415            continue;
416        }
417        let mut cmd = Command::new("cargo");
418        cmd.args(&args);
419        let out = crate::process::output(&mut cmd, crate::process::BUILD).ok()?;
420        let text = format!(
421            "{}{}",
422            String::from_utf8_lossy(&out.stdout),
423            String::from_utf8_lossy(&out.stderr)
424        );
425        return Some(Check {
426            fix: None,
427            name: "advisories",
428            passed: true,
429            detail: if out.status.success() {
430                format!("no known advisories ({tool})")
431            } else {
432                format!(
433                    "warning: {tool} reports advisories\n{}",
434                    last_lines(&text, 15)
435                )
436            },
437        });
438    }
439    None
440}
441
442/// The checks that hold for any Rust crate, bindings or not: fmt, clippy (warnings are errors),
443/// cargo test, and `unsafe` only with a `// SAFETY:` comment.
444pub fn rust_checks(crate_dir: &Path, target_dir: &Path) -> Vec<Check> {
445    let cargo = |args: &[&str]| -> (bool, String) {
446        let mut cmd = Command::new("cargo");
447        cmd.args(args)
448            .arg("--manifest-path")
449            .arg(crate_dir.join("Cargo.toml"))
450            .env("CARGO_TARGET_DIR", target_dir);
451        // Lint arguments go after `--`, so the manifest path must come before them.
452        match crate::process::output(&mut cmd, crate::process::BUILD) {
453            Ok(o) => (
454                o.status.success(),
455                last_lines(&String::from_utf8_lossy(&o.stderr), 15),
456            ),
457            Err(e) => (false, e.to_string()),
458        }
459    };
460    let mut checks = Vec::new();
461
462    let (ok, out) = cargo(&["fmt", "--check"]);
463    checks.push(Check {
464        fix: None,
465        name: "fmt",
466        passed: ok,
467        detail: if ok {
468            "formatted".into()
469        } else {
470            format!("run `cargo fmt`\n{out}")
471        },
472    });
473
474    let mut clippy = Command::new("cargo");
475    clippy
476        .args(["clippy", "--all-targets", "--manifest-path"])
477        .arg(crate_dir.join("Cargo.toml"))
478        .args(["--", "-D", "warnings"])
479        .env("CARGO_TARGET_DIR", target_dir);
480    let (ok, out) = match crate::process::output(&mut clippy, crate::process::BUILD) {
481        Ok(o) => (
482            o.status.success(),
483            last_lines(&String::from_utf8_lossy(&o.stderr), 15),
484        ),
485        Err(e) => (false, e.to_string()),
486    };
487    checks.push(Check {
488        fix: None,
489        name: "clippy",
490        passed: ok,
491        detail: if ok { "no warnings".into() } else { out },
492    });
493
494    let (ok, out) = cargo(&["test", "--quiet"]);
495    checks.push(Check {
496        fix: None,
497        name: "cargo test",
498        passed: ok,
499        detail: if ok { "passed".into() } else { out },
500    });
501
502    let (unexplained, explained) = unsafe_blocks(&crate_dir.join("src"));
503    checks.push(Check {
504        fix: None,
505        name: "unsafe",
506        passed: unexplained.is_empty(),
507        detail: if unexplained.is_empty() {
508            format!("{explained} unsafe uses, each with a `// SAFETY:` comment")
509        } else {
510            format!(
511                "unsafe without a `// SAFETY:` comment: {}",
512                unexplained.join(", ")
513            )
514        },
515    });
516
517    checks
518}
519
520/// No function in `src/port.rs` is still `unimplemented!`.
521pub fn ported_check(crate_dir: &Path) -> Check {
522    let path = crate_dir.join("src/port.rs");
523    let port = match std::fs::read_to_string(&path) {
524        Ok(port) => port,
525        Err(error) => {
526            return Check {
527                fix: None,
528                name: "ported",
529                passed: false,
530                detail: format!("cannot read {}: {error}", path.display()),
531            };
532        }
533    };
534    let todo = stubs(&port);
535    Check {
536        fix: None,
537        name: "ported",
538        passed: todo == 0,
539        detail: if todo == 0 {
540            "nothing in port.rs is `unimplemented!`, `todo!` or only a `panic!`".into()
541        } else {
542            format!(
543                "{todo} place(s) in port.rs still `unimplemented!`, `todo!` or a function that only panics"
544            )
545        },
546    }
547}
548
549/// Stubs left in a port: `unimplemented!`, `todo!`, and functions whose whole body is a `panic!`.
550fn stubs(port: &str) -> usize {
551    let code: String = port
552        .lines()
553        .map(|l| l.split("//").next().unwrap_or_default())
554        .collect::<Vec<_>>()
555        .join("\n");
556    let macros = code.matches("unimplemented!(").count() + code.matches("todo!(").count();
557    let panics = regex::Regex::new(r"\bfn\s+\w+[^{;]*\{\s*panic!\([^;{}]*\)\s*;?\s*\}")
558        .map(|re| re.find_iter(&code).count())
559        .unwrap_or(0);
560    macros + panics
561}
562
563/// `unsafe` uses in Rust sources, split into those without and with a `// SAFETY:` comment just above.
564fn unsafe_blocks(src: &Path) -> (Vec<String>, usize) {
565    let mut unexplained = Vec::new();
566    let mut explained = 0;
567    let mut stack = vec![src.to_path_buf()];
568    while let Some(dir) = stack.pop() {
569        let Ok(entries) = std::fs::read_dir(&dir) else {
570            continue;
571        };
572        for entry in entries.flatten() {
573            let path = entry.path();
574            if path.is_dir() {
575                stack.push(path);
576                continue;
577            }
578            if path.extension().is_none_or(|e| e != "rs") {
579                continue;
580            }
581            let text = std::fs::read_to_string(&path).unwrap_or_default();
582            let lines: Vec<&str> = text.lines().collect();
583            for (i, line) in lines.iter().enumerate() {
584                let code = line.split("//").next().unwrap_or("");
585                let uses_unsafe = code
586                    .split(|c: char| !(c.is_alphanumeric() || c == '_'))
587                    .any(|word| word == "unsafe");
588                if !uses_unsafe {
589                    continue;
590                }
591                let has_safety = lines[..i]
592                    .iter()
593                    .rev()
594                    .take_while(|l| l.trim_start().starts_with("//"))
595                    .any(|l| l.contains("SAFETY:"));
596                if has_safety {
597                    explained += 1;
598                } else {
599                    unexplained.push(format!("{}:{}", path.display(), i + 1));
600                }
601            }
602        }
603    }
604    (unexplained, explained)
605}
606
607fn last_lines(text: &str, n: usize) -> String {
608    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
609    lines[lines.len().saturating_sub(n)..].join("\n")
610}
611
612#[cfg(test)]
613mod tests {
614    use super::{Check, fix_for, stubs, unsafe_blocks};
615
616    #[test]
617    fn counts_every_kind_of_stub() {
618        let port = "pub fn a() -> u8 { todo!() }\n\
619                    pub fn b() -> u8 { unimplemented!(\"later\") }\n\
620                    pub fn c(x: u8) -> u8 {\n    panic!(\"not ported\")\n}\n\
621                    pub fn d(x: u8) -> u8 { if x > 1 { panic!(\"big\") } x }\n\
622                    // todo!() in a comment\n";
623        assert_eq!(stubs(port), 3);
624        assert_eq!(stubs("pub fn ok() -> u8 { 1 }"), 0);
625    }
626
627    #[test]
628    fn failed_checks_say_what_to_run() {
629        let check = |name, detail: &str| Check {
630            fix: None,
631            name,
632            passed: false,
633            detail: detail.into(),
634        };
635        let dir = std::path::Path::new("port");
636        assert_eq!(
637            fix_for(&check("recording", "changed"), dir).as_deref(),
638            Some("rust-anything record port")
639        );
640        assert_eq!(
641            fix_for(&check("behavior", "no recorded cases: run"), dir).as_deref(),
642            Some("rust-anything record port")
643        );
644        assert!(fix_for(&check("fmt", ""), dir).is_some_and(|f| f.starts_with("cargo fmt")));
645        assert_eq!(fix_for(&check("coverage", ""), dir), None);
646    }
647
648    #[test]
649    fn requires_safety_comments() {
650        let dir = std::env::temp_dir().join(format!("rust-anything-gate-{}", std::process::id()));
651        std::fs::create_dir_all(&dir).unwrap();
652        std::fs::write(
653            dir.join("a.rs"),
654            "#![forbid(unsafe_code)]\n// SAFETY: checked above\nunsafe { x() }\nlet y = unsafe { z() };\n// unsafe in a comment\n",
655        )
656        .unwrap();
657        let (unexplained, explained) = unsafe_blocks(&dir);
658        std::fs::remove_dir_all(&dir).unwrap();
659        assert_eq!(explained, 1);
660        assert_eq!(unexplained.len(), 1);
661        assert!(unexplained[0].ends_with("a.rs:4"));
662    }
663
664    #[test]
665    fn missing_port_source_fails_the_ported_check() {
666        let dir = crate::app::temp_dir("gate-port").unwrap();
667        let check = super::ported_check(&dir);
668        std::fs::remove_dir(dir).unwrap();
669        assert!(!check.passed);
670        assert!(check.detail.contains("cannot read"));
671        assert!(check.detail.contains("port.rs"));
672    }
673}