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#[derive(Debug, Serialize)]
23pub struct GateOutcome {
24    pub passed: bool,
25    pub checks: Vec<Check>,
26}
27
28pub fn gate(crate_dir: &Path, node_args: &[String]) -> Result<GateOutcome> {
29    let manifest = Manifest::load(crate_dir)?;
30    let mut checks = rust_checks(crate_dir, &crate_dir.join("target"));
31    let port = std::fs::read_to_string(crate_dir.join("src/port.rs")).unwrap_or_default();
32    let todo = port.matches("unimplemented!(").count();
33    checks.push(Check {
34        name: "ported",
35        passed: todo == 0,
36        detail: if todo == 0 {
37            format!("all {} functions ported", manifest.exports.len())
38        } else {
39            format!(
40                "{todo} of {} functions still `unimplemented!`",
41                manifest.exports.len()
42            )
43        },
44    });
45
46    checks.extend(crate::error_paths::checks(crate_dir, &manifest));
47    let built = harness::build(crate_dir);
48    let built_ok = built.is_ok();
49    checks.push(Check {
50        name: "build",
51        passed: built_ok,
52        detail: match built {
53            Ok(path) => format!("built {}", path.display()),
54            Err(e) => last_lines(&format!("{e:#}"), 15),
55        },
56    });
57
58    if !crate_dir.join(CASES).exists() {
59        checks.push(Check {
60            name: "behavior",
61            passed: false,
62            detail: "no recorded cases: run `rust-anything record` first".into(),
63        });
64    } else if built_ok {
65        match harness::diff(&DiffOptions {
66            crate_dir,
67            module: None,
68            ignore_key_order: false,
69            float_tolerance: None,
70            node_args,
71        }) {
72            Ok(d) => {
73                checks.push(Check {
74                    name: "api",
75                    passed: d.missing.is_empty(),
76                    detail: if d.missing.is_empty() {
77                        format!(
78                            "exports {}",
79                            manifest
80                                .exports
81                                .iter()
82                                .map(|f| f.name.clone())
83                                .chain(manifest.classes.iter().map(|c| format!("class {}", c.name)))
84                                .collect::<Vec<_>>()
85                                .join(", ")
86                        )
87                    } else {
88                        format!("missing exports: {}", d.missing.join(", "))
89                    },
90                });
91                checks.push(Check {
92                    name: "behavior",
93                    passed: d.failed == 0,
94                    detail: format!("{}/{} recorded cases match", d.passed, d.total),
95                });
96            }
97            Err(e) => checks.push(Check {
98                name: "behavior",
99                passed: false,
100                detail: format!("{e:#}"),
101            }),
102        }
103    }
104
105    Ok(GateOutcome {
106        passed: checks.iter().all(|c| c.passed),
107        checks,
108    })
109}
110
111/// The checks that hold for any Rust crate, bindings or not: fmt, clippy (warnings are errors),
112/// cargo test, and `unsafe` only with a `// SAFETY:` comment.
113pub fn rust_checks(crate_dir: &Path, target_dir: &Path) -> Vec<Check> {
114    let cargo = |args: &[&str]| -> (bool, String) {
115        let mut cmd = Command::new("cargo");
116        cmd.args(args)
117            .arg("--manifest-path")
118            .arg(crate_dir.join("Cargo.toml"))
119            .env("CARGO_TARGET_DIR", target_dir);
120        // Lint arguments go after `--`, so the manifest path must come before them.
121        match cmd.output() {
122            Ok(o) => (
123                o.status.success(),
124                last_lines(&String::from_utf8_lossy(&o.stderr), 15),
125            ),
126            Err(e) => (false, e.to_string()),
127        }
128    };
129    let mut checks = Vec::new();
130
131    let (ok, out) = cargo(&["fmt", "--check"]);
132    checks.push(Check {
133        name: "fmt",
134        passed: ok,
135        detail: if ok {
136            "formatted".into()
137        } else {
138            format!("run `cargo fmt`\n{out}")
139        },
140    });
141
142    let mut clippy = Command::new("cargo");
143    clippy
144        .args(["clippy", "--all-targets", "--manifest-path"])
145        .arg(crate_dir.join("Cargo.toml"))
146        .args(["--", "-D", "warnings"])
147        .env("CARGO_TARGET_DIR", target_dir);
148    let (ok, out) = match clippy.output() {
149        Ok(o) => (
150            o.status.success(),
151            last_lines(&String::from_utf8_lossy(&o.stderr), 15),
152        ),
153        Err(e) => (false, e.to_string()),
154    };
155    checks.push(Check {
156        name: "clippy",
157        passed: ok,
158        detail: if ok { "no warnings".into() } else { out },
159    });
160
161    let (ok, out) = cargo(&["test", "--quiet"]);
162    checks.push(Check {
163        name: "cargo test",
164        passed: ok,
165        detail: if ok { "passed".into() } else { out },
166    });
167
168    let (unexplained, explained) = unsafe_blocks(&crate_dir.join("src"));
169    checks.push(Check {
170        name: "unsafe",
171        passed: unexplained.is_empty(),
172        detail: if unexplained.is_empty() {
173            format!("{explained} unsafe uses, each with a `// SAFETY:` comment")
174        } else {
175            format!(
176                "unsafe without a `// SAFETY:` comment: {}",
177                unexplained.join(", ")
178            )
179        },
180    });
181
182    checks
183}
184
185/// No function in `src/port.rs` is still `unimplemented!`.
186pub fn ported_check(crate_dir: &Path) -> Check {
187    let port = std::fs::read_to_string(crate_dir.join("src/port.rs")).unwrap_or_default();
188    let todo = port.matches("unimplemented!(").count();
189    Check {
190        name: "ported",
191        passed: todo == 0,
192        detail: if todo == 0 {
193            "nothing `unimplemented!` in port.rs".into()
194        } else {
195            format!("{todo} functions in port.rs still `unimplemented!`")
196        },
197    }
198}
199
200/// `unsafe` uses in Rust sources, split into those without and with a `// SAFETY:` comment just above.
201fn unsafe_blocks(src: &Path) -> (Vec<String>, usize) {
202    let mut unexplained = Vec::new();
203    let mut explained = 0;
204    let mut stack = vec![src.to_path_buf()];
205    while let Some(dir) = stack.pop() {
206        let Ok(entries) = std::fs::read_dir(&dir) else {
207            continue;
208        };
209        for entry in entries.flatten() {
210            let path = entry.path();
211            if path.is_dir() {
212                stack.push(path);
213                continue;
214            }
215            if path.extension().is_none_or(|e| e != "rs") {
216                continue;
217            }
218            let text = std::fs::read_to_string(&path).unwrap_or_default();
219            let lines: Vec<&str> = text.lines().collect();
220            for (i, line) in lines.iter().enumerate() {
221                let code = line.split("//").next().unwrap_or("");
222                let uses_unsafe = code
223                    .split(|c: char| !(c.is_alphanumeric() || c == '_'))
224                    .any(|word| word == "unsafe");
225                if !uses_unsafe {
226                    continue;
227                }
228                let has_safety = lines[..i]
229                    .iter()
230                    .rev()
231                    .take_while(|l| l.trim_start().starts_with("//"))
232                    .any(|l| l.contains("SAFETY:"));
233                if has_safety {
234                    explained += 1;
235                } else {
236                    unexplained.push(format!("{}:{}", path.display(), i + 1));
237                }
238            }
239        }
240    }
241    (unexplained, explained)
242}
243
244fn last_lines(text: &str, n: usize) -> String {
245    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
246    lines[lines.len().saturating_sub(n)..].join("\n")
247}
248
249#[cfg(test)]
250mod tests {
251    use super::unsafe_blocks;
252
253    #[test]
254    fn requires_safety_comments() {
255        let dir = std::env::temp_dir().join(format!("rust-anything-gate-{}", std::process::id()));
256        std::fs::create_dir_all(&dir).unwrap();
257        std::fs::write(
258            dir.join("a.rs"),
259            "#![forbid(unsafe_code)]\n// SAFETY: checked above\nunsafe { x() }\nlet y = unsafe { z() };\n// unsafe in a comment\n",
260        )
261        .unwrap();
262        let (unexplained, explained) = unsafe_blocks(&dir);
263        std::fs::remove_dir_all(&dir).unwrap();
264        assert_eq!(explained, 1);
265        assert_eq!(unexplained.len(), 1);
266        assert!(unexplained[0].ends_with("a.rs:4"));
267    }
268}