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 mut checks = rust_checks(crate_dir, &crate_dir.join("target"));
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
345/// The checks that hold for any Rust crate, bindings or not: fmt, clippy (warnings are errors),
346/// cargo test, and `unsafe` only with a `// SAFETY:` comment.
347pub fn rust_checks(crate_dir: &Path, target_dir: &Path) -> Vec<Check> {
348    let cargo = |args: &[&str]| -> (bool, String) {
349        let mut cmd = Command::new("cargo");
350        cmd.args(args)
351            .arg("--manifest-path")
352            .arg(crate_dir.join("Cargo.toml"))
353            .env("CARGO_TARGET_DIR", target_dir);
354        // Lint arguments go after `--`, so the manifest path must come before them.
355        match crate::process::output(&mut cmd, crate::process::BUILD) {
356            Ok(o) => (
357                o.status.success(),
358                last_lines(&String::from_utf8_lossy(&o.stderr), 15),
359            ),
360            Err(e) => (false, e.to_string()),
361        }
362    };
363    let mut checks = Vec::new();
364
365    let (ok, out) = cargo(&["fmt", "--check"]);
366    checks.push(Check {
367        fix: None,
368        name: "fmt",
369        passed: ok,
370        detail: if ok {
371            "formatted".into()
372        } else {
373            format!("run `cargo fmt`\n{out}")
374        },
375    });
376
377    let mut clippy = Command::new("cargo");
378    clippy
379        .args(["clippy", "--all-targets", "--manifest-path"])
380        .arg(crate_dir.join("Cargo.toml"))
381        .args(["--", "-D", "warnings"])
382        .env("CARGO_TARGET_DIR", target_dir);
383    let (ok, out) = match crate::process::output(&mut clippy, crate::process::BUILD) {
384        Ok(o) => (
385            o.status.success(),
386            last_lines(&String::from_utf8_lossy(&o.stderr), 15),
387        ),
388        Err(e) => (false, e.to_string()),
389    };
390    checks.push(Check {
391        fix: None,
392        name: "clippy",
393        passed: ok,
394        detail: if ok { "no warnings".into() } else { out },
395    });
396
397    let (ok, out) = cargo(&["test", "--quiet"]);
398    checks.push(Check {
399        fix: None,
400        name: "cargo test",
401        passed: ok,
402        detail: if ok { "passed".into() } else { out },
403    });
404
405    let (unexplained, explained) = unsafe_blocks(&crate_dir.join("src"));
406    checks.push(Check {
407        fix: None,
408        name: "unsafe",
409        passed: unexplained.is_empty(),
410        detail: if unexplained.is_empty() {
411            format!("{explained} unsafe uses, each with a `// SAFETY:` comment")
412        } else {
413            format!(
414                "unsafe without a `// SAFETY:` comment: {}",
415                unexplained.join(", ")
416            )
417        },
418    });
419
420    checks
421}
422
423/// No function in `src/port.rs` is still `unimplemented!`.
424pub fn ported_check(crate_dir: &Path) -> Check {
425    let path = crate_dir.join("src/port.rs");
426    let port = match std::fs::read_to_string(&path) {
427        Ok(port) => port,
428        Err(error) => {
429            return Check {
430                fix: None,
431                name: "ported",
432                passed: false,
433                detail: format!("cannot read {}: {error}", path.display()),
434            };
435        }
436    };
437    let todo = stubs(&port);
438    Check {
439        fix: None,
440        name: "ported",
441        passed: todo == 0,
442        detail: if todo == 0 {
443            "nothing in port.rs is `unimplemented!`, `todo!` or only a `panic!`".into()
444        } else {
445            format!(
446                "{todo} place(s) in port.rs still `unimplemented!`, `todo!` or a function that only panics"
447            )
448        },
449    }
450}
451
452/// Stubs left in a port: `unimplemented!`, `todo!`, and functions whose whole body is a `panic!`.
453fn stubs(port: &str) -> usize {
454    let code: String = port
455        .lines()
456        .map(|l| l.split("//").next().unwrap_or_default())
457        .collect::<Vec<_>>()
458        .join("\n");
459    let macros = code.matches("unimplemented!(").count() + code.matches("todo!(").count();
460    let panics = regex::Regex::new(r"\bfn\s+\w+[^{;]*\{\s*panic!\([^;{}]*\)\s*;?\s*\}")
461        .map(|re| re.find_iter(&code).count())
462        .unwrap_or(0);
463    macros + panics
464}
465
466/// `unsafe` uses in Rust sources, split into those without and with a `// SAFETY:` comment just above.
467fn unsafe_blocks(src: &Path) -> (Vec<String>, usize) {
468    let mut unexplained = Vec::new();
469    let mut explained = 0;
470    let mut stack = vec![src.to_path_buf()];
471    while let Some(dir) = stack.pop() {
472        let Ok(entries) = std::fs::read_dir(&dir) else {
473            continue;
474        };
475        for entry in entries.flatten() {
476            let path = entry.path();
477            if path.is_dir() {
478                stack.push(path);
479                continue;
480            }
481            if path.extension().is_none_or(|e| e != "rs") {
482                continue;
483            }
484            let text = std::fs::read_to_string(&path).unwrap_or_default();
485            let lines: Vec<&str> = text.lines().collect();
486            for (i, line) in lines.iter().enumerate() {
487                let code = line.split("//").next().unwrap_or("");
488                let uses_unsafe = code
489                    .split(|c: char| !(c.is_alphanumeric() || c == '_'))
490                    .any(|word| word == "unsafe");
491                if !uses_unsafe {
492                    continue;
493                }
494                let has_safety = lines[..i]
495                    .iter()
496                    .rev()
497                    .take_while(|l| l.trim_start().starts_with("//"))
498                    .any(|l| l.contains("SAFETY:"));
499                if has_safety {
500                    explained += 1;
501                } else {
502                    unexplained.push(format!("{}:{}", path.display(), i + 1));
503                }
504            }
505        }
506    }
507    (unexplained, explained)
508}
509
510fn last_lines(text: &str, n: usize) -> String {
511    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
512    lines[lines.len().saturating_sub(n)..].join("\n")
513}
514
515#[cfg(test)]
516mod tests {
517    use super::{Check, fix_for, stubs, unsafe_blocks};
518
519    #[test]
520    fn counts_every_kind_of_stub() {
521        let port = "pub fn a() -> u8 { todo!() }\n\
522                    pub fn b() -> u8 { unimplemented!(\"later\") }\n\
523                    pub fn c(x: u8) -> u8 {\n    panic!(\"not ported\")\n}\n\
524                    pub fn d(x: u8) -> u8 { if x > 1 { panic!(\"big\") } x }\n\
525                    // todo!() in a comment\n";
526        assert_eq!(stubs(port), 3);
527        assert_eq!(stubs("pub fn ok() -> u8 { 1 }"), 0);
528    }
529
530    #[test]
531    fn failed_checks_say_what_to_run() {
532        let check = |name, detail: &str| Check {
533            fix: None,
534            name,
535            passed: false,
536            detail: detail.into(),
537        };
538        let dir = std::path::Path::new("port");
539        assert_eq!(
540            fix_for(&check("recording", "changed"), dir).as_deref(),
541            Some("rust-anything record port")
542        );
543        assert_eq!(
544            fix_for(&check("behavior", "no recorded cases: run"), dir).as_deref(),
545            Some("rust-anything record port")
546        );
547        assert!(fix_for(&check("fmt", ""), dir).is_some_and(|f| f.starts_with("cargo fmt")));
548        assert_eq!(fix_for(&check("coverage", ""), dir), None);
549    }
550
551    #[test]
552    fn requires_safety_comments() {
553        let dir = std::env::temp_dir().join(format!("rust-anything-gate-{}", std::process::id()));
554        std::fs::create_dir_all(&dir).unwrap();
555        std::fs::write(
556            dir.join("a.rs"),
557            "#![forbid(unsafe_code)]\n// SAFETY: checked above\nunsafe { x() }\nlet y = unsafe { z() };\n// unsafe in a comment\n",
558        )
559        .unwrap();
560        let (unexplained, explained) = unsafe_blocks(&dir);
561        std::fs::remove_dir_all(&dir).unwrap();
562        assert_eq!(explained, 1);
563        assert_eq!(unexplained.len(), 1);
564        assert!(unexplained[0].ends_with("a.rs:4"));
565    }
566
567    #[test]
568    fn missing_port_source_fails_the_ported_check() {
569        let dir = crate::app::temp_dir("gate-port").unwrap();
570        let check = super::ported_check(&dir);
571        std::fs::remove_dir(dir).unwrap();
572        assert!(!check.passed);
573        assert!(check.detail.contains("cannot read"));
574        assert!(check.detail.contains("port.rs"));
575    }
576}