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;
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}
21
22/// Bindings `bridge` writes into `src/`; everything else there is the port.
23const GENERATED: [&str; 7] = [
24    "lib.rs",
25    "js.rs",
26    "pyconv.rs",
27    "pynum.rs",
28    "rbconv.rs",
29    "utf16.rs",
30    "wire.rs",
31];
32
33/// How many times the source's lines the port may take before `gate` calls it bloated, plus a
34/// fixed allowance for the imports and signatures every port has.
35pub const MAX_GROWTH: f64 = 3.0;
36const ALLOWANCE: f64 = 50.0;
37
38fn code_lines(text: &str, comment: &[&str]) -> usize {
39    text.lines()
40        .map(str::trim)
41        .filter(|l| !l.is_empty() && !comment.iter().any(|c| l.starts_with(c)))
42        .count()
43}
44
45fn files_under(path: &Path, extensions: &[&str]) -> Vec<std::path::PathBuf> {
46    if path.is_file() {
47        return vec![path.to_path_buf()];
48    }
49    crate::walk::builder(path)
50        .build()
51        .flatten()
52        .map(ignore::DirEntry::into_path)
53        .filter(|p| {
54            p.extension()
55                .is_some_and(|e| extensions.contains(&e.to_string_lossy().as_ref()))
56        })
57        .collect()
58}
59
60/// Lines of Rust in the port against lines of the source unit: a port several times larger
61/// usually re-implements what a crate already does.
62fn size_check(crate_dir: &Path, manifest: &Manifest) -> Option<Check> {
63    let source_comments: &[&str] = match manifest.language {
64        crate::lang::Lang::Python | crate::lang::Lang::Ruby => &["#"],
65        crate::lang::Lang::Php => &["//", "#", "/*", "*"],
66        _ => &["//", "/*", "*"],
67    };
68    let source: usize = files_under(
69        &manifest.root.join(&manifest.unit),
70        manifest.language.extensions(),
71    )
72    .iter()
73    .filter_map(|p| std::fs::read_to_string(p).ok())
74    .map(|t| code_lines(&t, source_comments))
75    .sum();
76    if source == 0 {
77        return None;
78    }
79    let rust: usize = files_under(&crate_dir.join("src"), &["rs"])
80        .iter()
81        .filter(|p| {
82            p.file_name()
83                .is_none_or(|n| !GENERATED.contains(&n.to_string_lossy().as_ref()))
84        })
85        .filter_map(|p| std::fs::read_to_string(p).ok())
86        .map(|t| code_lines(&t, &["//"]))
87        .sum();
88    let growth = rust as f64 / source as f64;
89    let passed = rust as f64 <= MAX_GROWTH * source as f64 + ALLOWANCE;
90    Some(Check {
91        name: "size",
92        passed,
93        detail: format!(
94            "{rust} lines of Rust for {source} lines of {} ({growth:.1}x){}",
95            manifest.language.name(),
96            if passed {
97                String::new()
98            } else {
99                format!(
100                    "; over {MAX_GROWTH}x usually means code a crate already provides, or a case \
101                     handled one by one: use the crates `analyze` lists and fold repeated code"
102                )
103            }
104        ),
105    })
106}
107
108#[derive(Debug, Serialize)]
109pub struct GateOutcome {
110    pub passed: bool,
111    pub checks: Vec<Check>,
112}
113
114pub fn gate(crate_dir: &Path, node_args: &[String]) -> Result<GateOutcome> {
115    let manifest = Manifest::load(crate_dir)?;
116    let mut checks = rust_checks(crate_dir, &crate_dir.join("target"));
117    checks.push(ported_check(crate_dir));
118
119    checks.extend(size_check(crate_dir, &manifest));
120    checks.extend(crate::error_paths::checks(crate_dir, &manifest));
121    let built = harness::build(crate_dir);
122    let built_ok = built.is_ok();
123    checks.push(Check {
124        name: "build",
125        passed: built_ok,
126        detail: match built {
127            Ok(path) => format!("built {}", path.display()),
128            Err(e) => last_lines(&format!("{e:#}"), 15),
129        },
130    });
131
132    if !crate_dir.join(CASES).exists() {
133        checks.push(Check {
134            name: "behavior",
135            passed: false,
136            detail: "no recorded cases: run `rust-anything record` first".into(),
137        });
138    } else if built_ok {
139        match harness::diff(&DiffOptions {
140            crate_dir,
141            module: None,
142            ignore_key_order: false,
143            float_tolerance: None,
144            node_args,
145        }) {
146            Ok(d) => {
147                checks.push(Check {
148                    name: "api",
149                    passed: d.missing.is_empty(),
150                    detail: if d.missing.is_empty() {
151                        format!(
152                            "exports {}",
153                            manifest
154                                .exports
155                                .iter()
156                                .map(|f| f.name.clone())
157                                .chain(manifest.classes.iter().map(|c| format!("class {}", c.name)))
158                                .collect::<Vec<_>>()
159                                .join(", ")
160                        )
161                    } else {
162                        format!("missing exports: {}", d.missing.join(", "))
163                    },
164                });
165                checks.push(Check {
166                    name: "behavior",
167                    passed: d.failed == 0,
168                    detail: format!("{}/{} recorded cases match", d.passed, d.total),
169                });
170            }
171            Err(e) => checks.push(Check {
172                name: "behavior",
173                passed: false,
174                detail: format!("{e:#}"),
175            }),
176        }
177    }
178
179    Ok(GateOutcome {
180        passed: checks.iter().all(|c| c.passed),
181        checks,
182    })
183}
184
185/// The checks that hold for any Rust crate, bindings or not: fmt, clippy (warnings are errors),
186/// cargo test, and `unsafe` only with a `// SAFETY:` comment.
187pub fn rust_checks(crate_dir: &Path, target_dir: &Path) -> Vec<Check> {
188    let cargo = |args: &[&str]| -> (bool, String) {
189        let mut cmd = Command::new("cargo");
190        cmd.args(args)
191            .arg("--manifest-path")
192            .arg(crate_dir.join("Cargo.toml"))
193            .env("CARGO_TARGET_DIR", target_dir);
194        // Lint arguments go after `--`, so the manifest path must come before them.
195        match cmd.output() {
196            Ok(o) => (
197                o.status.success(),
198                last_lines(&String::from_utf8_lossy(&o.stderr), 15),
199            ),
200            Err(e) => (false, e.to_string()),
201        }
202    };
203    let mut checks = Vec::new();
204
205    let (ok, out) = cargo(&["fmt", "--check"]);
206    checks.push(Check {
207        name: "fmt",
208        passed: ok,
209        detail: if ok {
210            "formatted".into()
211        } else {
212            format!("run `cargo fmt`\n{out}")
213        },
214    });
215
216    let mut clippy = Command::new("cargo");
217    clippy
218        .args(["clippy", "--all-targets", "--manifest-path"])
219        .arg(crate_dir.join("Cargo.toml"))
220        .args(["--", "-D", "warnings"])
221        .env("CARGO_TARGET_DIR", target_dir);
222    let (ok, out) = match clippy.output() {
223        Ok(o) => (
224            o.status.success(),
225            last_lines(&String::from_utf8_lossy(&o.stderr), 15),
226        ),
227        Err(e) => (false, e.to_string()),
228    };
229    checks.push(Check {
230        name: "clippy",
231        passed: ok,
232        detail: if ok { "no warnings".into() } else { out },
233    });
234
235    let (ok, out) = cargo(&["test", "--quiet"]);
236    checks.push(Check {
237        name: "cargo test",
238        passed: ok,
239        detail: if ok { "passed".into() } else { out },
240    });
241
242    let (unexplained, explained) = unsafe_blocks(&crate_dir.join("src"));
243    checks.push(Check {
244        name: "unsafe",
245        passed: unexplained.is_empty(),
246        detail: if unexplained.is_empty() {
247            format!("{explained} unsafe uses, each with a `// SAFETY:` comment")
248        } else {
249            format!(
250                "unsafe without a `// SAFETY:` comment: {}",
251                unexplained.join(", ")
252            )
253        },
254    });
255
256    checks
257}
258
259/// No function in `src/port.rs` is still `unimplemented!`.
260pub fn ported_check(crate_dir: &Path) -> Check {
261    let path = crate_dir.join("src/port.rs");
262    let port = match std::fs::read_to_string(&path) {
263        Ok(port) => port,
264        Err(error) => {
265            return Check {
266                name: "ported",
267                passed: false,
268                detail: format!("cannot read {}: {error}", path.display()),
269            };
270        }
271    };
272    let todo = port.matches("unimplemented!(").count();
273    Check {
274        name: "ported",
275        passed: todo == 0,
276        detail: if todo == 0 {
277            "nothing `unimplemented!` in port.rs".into()
278        } else {
279            format!("{todo} functions in port.rs still `unimplemented!`")
280        },
281    }
282}
283
284/// `unsafe` uses in Rust sources, split into those without and with a `// SAFETY:` comment just above.
285fn unsafe_blocks(src: &Path) -> (Vec<String>, usize) {
286    let mut unexplained = Vec::new();
287    let mut explained = 0;
288    let mut stack = vec![src.to_path_buf()];
289    while let Some(dir) = stack.pop() {
290        let Ok(entries) = std::fs::read_dir(&dir) else {
291            continue;
292        };
293        for entry in entries.flatten() {
294            let path = entry.path();
295            if path.is_dir() {
296                stack.push(path);
297                continue;
298            }
299            if path.extension().is_none_or(|e| e != "rs") {
300                continue;
301            }
302            let text = std::fs::read_to_string(&path).unwrap_or_default();
303            let lines: Vec<&str> = text.lines().collect();
304            for (i, line) in lines.iter().enumerate() {
305                let code = line.split("//").next().unwrap_or("");
306                let uses_unsafe = code
307                    .split(|c: char| !(c.is_alphanumeric() || c == '_'))
308                    .any(|word| word == "unsafe");
309                if !uses_unsafe {
310                    continue;
311                }
312                let has_safety = lines[..i]
313                    .iter()
314                    .rev()
315                    .take_while(|l| l.trim_start().starts_with("//"))
316                    .any(|l| l.contains("SAFETY:"));
317                if has_safety {
318                    explained += 1;
319                } else {
320                    unexplained.push(format!("{}:{}", path.display(), i + 1));
321                }
322            }
323        }
324    }
325    (unexplained, explained)
326}
327
328fn last_lines(text: &str, n: usize) -> String {
329    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
330    lines[lines.len().saturating_sub(n)..].join("\n")
331}
332
333#[cfg(test)]
334mod tests {
335    use super::unsafe_blocks;
336
337    #[test]
338    fn requires_safety_comments() {
339        let dir = std::env::temp_dir().join(format!("rust-anything-gate-{}", std::process::id()));
340        std::fs::create_dir_all(&dir).unwrap();
341        std::fs::write(
342            dir.join("a.rs"),
343            "#![forbid(unsafe_code)]\n// SAFETY: checked above\nunsafe { x() }\nlet y = unsafe { z() };\n// unsafe in a comment\n",
344        )
345        .unwrap();
346        let (unexplained, explained) = unsafe_blocks(&dir);
347        std::fs::remove_dir_all(&dir).unwrap();
348        assert_eq!(explained, 1);
349        assert_eq!(unexplained.len(), 1);
350        assert!(unexplained[0].ends_with("a.rs:4"));
351    }
352
353    #[test]
354    fn missing_port_source_fails_the_ported_check() {
355        let dir = crate::app::temp_dir("gate-port").unwrap();
356        let check = super::ported_check(&dir);
357        std::fs::remove_dir(dir).unwrap();
358        assert!(!check.passed);
359        assert!(check.detail.contains("cannot read"));
360        assert!(check.detail.contains("port.rs"));
361    }
362}