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