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