Skip to main content

rust_anything/
error_paths.rs

1//! Error paths: where the original fails (`throw`, `raise`, an `error` result), whether a
2//! recorded case reaches each of them, and whether the port panics where the original failed
3//! politely.
4
5use std::collections::BTreeSet;
6use std::ops::Range;
7use std::path::Path;
8
9use regex::Regex;
10use serde_json::Value;
11
12use crate::bridge::{Manifest, snake_case};
13use crate::gate::Check;
14use crate::lang::Lang;
15
16/// The marker that allows a panic in `port.rs`: the original treats that state as impossible too.
17pub const INFALLIBLE: &str = "INFALLIBLE:";
18const PANICS: [&str; 5] = [
19    ".unwrap()",
20    ".expect(",
21    "panic!(",
22    "unreachable!(",
23    "todo!(",
24];
25
26/// An export whose original fails on some input, and where.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Raise {
29    pub export: String,
30    pub site: String,
31}
32
33/// A panic in `port.rs`.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct Panic {
36    pub function: String,
37    pub line: usize,
38    pub what: &'static str,
39}
40
41fn indent(line: &str) -> usize {
42    line.len() - line.trim_start().len()
43}
44
45fn is_comment(lang: Lang, line: &str) -> bool {
46    let t = line.trim_start();
47    t.starts_with("//")
48        || t.starts_with("/*")
49        || t.starts_with('*')
50        || (matches!(
51            lang,
52            Lang::Python | Lang::Ruby | Lang::Php | Lang::Powershell
53        ) && t.starts_with('#'))
54}
55
56/// The lines of the definition that starts at `start`.
57fn body(lang: Lang, lines: &[&str], start: usize) -> Range<usize> {
58    let Some(first) = lines.get(start) else {
59        return start..start;
60    };
61    match lang {
62        Lang::Python => {
63            let base = indent(first);
64            let mut end = start + 1;
65            while end < lines.len() && (lines[end].trim().is_empty() || indent(lines[end]) > base) {
66                end += 1;
67            }
68            start..end
69        }
70        Lang::Ruby => {
71            let base = indent(first);
72            let end = (start + 1..lines.len())
73                .find(|&i| lines[i].trim() == "end" && indent(lines[i]) == base)
74                .map_or(lines.len(), |i| i + 1);
75            start..end
76        }
77        _ => {
78            let mut depth = 0i32;
79            let mut opened = false;
80            for (i, line) in lines.iter().enumerate().skip(start) {
81                if is_comment(lang, line) {
82                    continue;
83                }
84                let mut in_string: Option<char> = None;
85                let mut prev = ' ';
86                for c in line.chars() {
87                    match in_string {
88                        Some(q) if c == q && prev != '\\' => in_string = None,
89                        Some(_) => {}
90                        None if c == '"' || c == '`' => in_string = Some(c),
91                        None if c == '{' => {
92                            depth += 1;
93                            opened = true;
94                        }
95                        None if c == '}' => depth -= 1,
96                        None => {}
97                    }
98                    prev = c;
99                }
100                if opened && depth <= 0 {
101                    return start..i + 1;
102                }
103                if !opened && i > start + 10 {
104                    break;
105                }
106            }
107            start..(start + 1).min(lines.len())
108        }
109    }
110}
111
112/// The line, inside `range`, where the function fails on purpose.
113fn raise_line(lang: Lang, lines: &[&str], range: Range<usize>) -> Option<usize> {
114    let word = |w: &str| Regex::new(&format!(r"\b{w}\b")).expect("valid regex");
115    let find = |re: &Regex| {
116        range
117            .clone()
118            .find(|&i| !is_comment(lang, lines[i]) && re.is_match(lines[i]))
119    };
120    match lang {
121        Lang::Ts | Lang::Java | Lang::Kotlin | Lang::Php | Lang::Csharp | Lang::Powershell => {
122            find(&word("throw"))
123        }
124        Lang::Python | Lang::Ruby => find(&word("raise")),
125        Lang::Go => {
126            let open = range
127                .clone()
128                .find(|&i| lines[i].contains('{'))
129                .unwrap_or(range.start);
130            let signature: String = lines[range.start..=open.min(lines.len() - 1)].join(" ");
131            let head = signature.split('{').next().unwrap_or_default();
132            let returns_error = Regex::new(r"\)\s*(?:\([^)]*\berror\s*\)|error)\s*$")
133                .expect("valid regex")
134                .is_match(head.trim_end());
135            returns_error.then(|| {
136                find(
137                    &Regex::new(r"errors\.New|fmt\.Errorf|return [^\n]*\berr\b")
138                        .expect("valid regex"),
139                )
140                .unwrap_or(range.start)
141            })
142        }
143        Lang::C => None,
144    }
145}
146
147/// Exports whose original fails on purpose somewhere, with the place.
148pub fn raises(lang: Lang, root: &Path, exports: &[(String, String, u32)]) -> Vec<Raise> {
149    let mut out = Vec::new();
150    for (name, file, line) in exports {
151        let Ok(text) = std::fs::read_to_string(root.join(file)) else {
152            continue;
153        };
154        let lines: Vec<&str> = text.lines().collect();
155        let start = (*line as usize).saturating_sub(1);
156        if let Some(at) = raise_line(lang, &lines, body(lang, &lines, start)) {
157            out.push(Raise {
158                export: name.clone(),
159                site: format!("{file}:{}", at + 1),
160            });
161        }
162    }
163    out
164}
165
166/// Names of the functions with at least one recorded case that failed.
167pub fn recorded_errors(cases: &str) -> BTreeSet<String> {
168    cases
169        .lines()
170        .filter_map(|l| serde_json::from_str::<Value>(l).ok())
171        .filter(|c| c.get("error").is_some() || c.get("panic").is_some())
172        .filter_map(|c| c["fn"].as_str().map(str::to_string))
173        .collect()
174}
175
176/// `unwrap`, `expect` and panicking macros in `port.rs`, by function, outside tests and not
177/// marked `// INFALLIBLE:` on the line or in the comment just above.
178pub fn panics(port: &str) -> Vec<Panic> {
179    let lines: Vec<&str> = port.lines().collect();
180    let fn_name =
181        Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)")
182            .expect("valid regex");
183    let mut out = Vec::new();
184    let mut current = String::new();
185    for (i, line) in lines.iter().enumerate() {
186        if line.trim_start().starts_with("#[cfg(test)]") {
187            break;
188        }
189        if let Some(c) = fn_name.captures(line) {
190            current = c[1].to_string();
191        }
192        let code = line.split("//").next().unwrap_or_default();
193        let Some(what) = PANICS.iter().find(|p| code.contains(*p)) else {
194            continue;
195        };
196        let marked = line.contains(INFALLIBLE)
197            || lines[..i]
198                .iter()
199                .rev()
200                .take_while(|l| l.trim_start().starts_with("//"))
201                .any(|l| l.contains(INFALLIBLE));
202        if !marked {
203            out.push(Panic {
204                function: current.clone(),
205                line: i + 1,
206                what,
207            });
208        }
209    }
210    out
211}
212
213/// The `error cases` and `panics` checks of `gate`.
214pub fn checks(crate_dir: &Path, manifest: &Manifest) -> Vec<Check> {
215    let exports: Vec<(String, String, u32)> = manifest
216        .exports
217        .iter()
218        .map(|f| (f.name.clone(), f.file.clone(), f.line))
219        .collect();
220    let raised = raises(manifest.language, &manifest.root, &exports);
221    let cases = std::fs::read_to_string(crate_dir.join(crate::harness::CASES)).unwrap_or_default();
222    let failed = recorded_errors(&cases);
223    let unreached: Vec<String> = raised
224        .iter()
225        .filter(|r| !failed.contains(&r.export))
226        .map(|r| format!("{} fails at {}", r.export, r.site))
227        .collect();
228    let error_cases = Check {
229        fix: None,
230        name: "error cases",
231        passed: unreached.is_empty(),
232        detail: if raised.is_empty() {
233            "the original fails on purpose nowhere".into()
234        } else if unreached.is_empty() {
235            format!(
236                "each of the {} functions that fail in the original has a recorded failing case",
237                raised.len()
238            )
239        } else {
240            format!(
241                "no recorded case reaches these error paths: add inputs that fail (record --inputs)\n{}",
242                unreached.join("\n")
243            )
244        },
245    };
246
247    let port = std::fs::read_to_string(crate_dir.join("src/port.rs")).unwrap_or_default();
248    let fails: BTreeSet<String> = manifest
249        .exports
250        .iter()
251        .filter(|f| failed.contains(&f.name) || raised.iter().any(|r| r.export == f.name))
252        .map(|f| snake_case(&f.name))
253        .collect();
254    let bad: Vec<String> = panics(&port)
255        .into_iter()
256        .filter(|p| fails.contains(&p.function))
257        .map(|p| format!("src/port.rs:{} `{}` in {}", p.line, p.what, p.function))
258        .collect();
259    let panics_check = Check {
260        fix: None,
261        name: "panics",
262        passed: bad.is_empty(),
263        detail: if bad.is_empty() {
264            "no unwrap, expect or panic where the original returns an error".into()
265        } else {
266            format!(
267                "the original returns an error here, so the port must too (return Err), or mark a state the original also treats as impossible with `// {INFALLIBLE} <why>`\n{}",
268                bad.join("\n")
269            )
270        },
271    };
272    vec![error_cases, panics_check]
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    fn check(lang: Lang, file: &str, source: &str, exports: &[(&str, u32)]) -> Vec<String> {
280        let dir = std::env::temp_dir().join(format!(
281            "rust-anything-raises-{}-{file}",
282            std::process::id()
283        ));
284        std::fs::create_dir_all(&dir).unwrap();
285        std::fs::write(dir.join(file), source).unwrap();
286        let exports: Vec<(String, String, u32)> = exports
287            .iter()
288            .map(|(n, l)| (n.to_string(), file.to_string(), *l))
289            .collect();
290        let found = raises(lang, &dir, &exports)
291            .into_iter()
292            .map(|r| format!("{} {}", r.export, r.site))
293            .collect();
294        std::fs::remove_dir_all(&dir).unwrap();
295        found
296    }
297
298    #[test]
299    fn finds_where_the_original_fails_in_each_language() {
300        assert_eq!(
301            check(
302                Lang::Ts,
303                "a.ts",
304                "export function ok(x: number) {\n  return x\n}\nexport function parse(s: string) {\n  // throw in a comment\n  if (!s) { throw new Error('empty') }\n  return s\n}\n",
305                &[("ok", 1), ("parse", 4)]
306            ),
307            ["parse a.ts:6"]
308        );
309        assert_eq!(
310            check(
311                Lang::Python,
312                "a.py",
313                "def ok(x):\n    return x\n\ndef parse(s):\n    if not s:\n        raise ValueError('empty')\n    return s\n",
314                &[("ok", 1), ("parse", 4)]
315            ),
316            ["parse a.py:6"]
317        );
318        assert_eq!(
319            check(
320                Lang::Ruby,
321                "a.rb",
322                "module M\n  def self.ok(x)\n    x\n  end\n\n  def self.parse(s)\n    raise ArgumentError, 'empty' if s.empty?\n    s\n  end\nend\n",
323                &[("ok", 2), ("parse", 6)]
324            ),
325            ["parse a.rb:7"]
326        );
327        assert_eq!(
328            check(
329                Lang::Go,
330                "a.go",
331                "package a\n\nfunc Ok(x int) int {\n\treturn x\n}\n\nfunc Parse(s string) (int, error) {\n\tif s == \"\" {\n\t\treturn 0, errors.New(\"empty\")\n\t}\n\treturn 1, nil\n}\n",
332                &[("Ok", 3), ("Parse", 7)]
333            ),
334            ["Parse a.go:9"]
335        );
336        assert_eq!(
337            check(
338                Lang::Java,
339                "A.java",
340                "class A {\n  public static int ok(int x) { return x; }\n  public static int parse(String s) {\n    if (s.isEmpty()) throw new IllegalArgumentException(\"{\");\n    return 1;\n  }\n}\n",
341                &[("ok", 2), ("parse", 3)]
342            ),
343            ["parse A.java:4"]
344        );
345        assert!(
346            check(
347                Lang::C,
348                "a.c",
349                "int parse(const char *s) { return s ? 1 : -1; }\n",
350                &[("parse", 1)]
351            )
352            .is_empty()
353        );
354    }
355
356    #[test]
357    fn panics_outside_tests_and_markers_are_found() {
358        let port = "pub fn parse_port(s: String) -> Result<i64, String> {\n    let n: i64 = s.parse().unwrap();\n    // INFALLIBLE: checked above\n    let m = Some(1).expect(\"one\");\n    Ok(n + m)\n}\n\nfn helper() -> i64 {\n    \"1\".parse().unwrap_or(0) + Some(2).unwrap() // INFALLIBLE: literal\n}\n\npub async fn later() {\n    todo!(\"x\")\n}\n\n#[cfg(test)]\nmod tests {\n    fn t() { None::<i32>.unwrap(); }\n}\n";
359        let found: Vec<(String, usize, &str)> = panics(port)
360            .into_iter()
361            .map(|p| (p.function, p.line, p.what))
362            .collect();
363        assert_eq!(
364            found,
365            [
366                ("parse_port".to_string(), 2, ".unwrap()"),
367                ("later".to_string(), 13, "todo!(")
368            ]
369        );
370        assert_eq!(
371            recorded_errors(
372                "{\"fn\":\"a\",\"args\":[],\"result\":1}\n{\"fn\":\"b\",\"args\":[],\"error\":{\"name\":\"E\"}}\n"
373            ),
374            BTreeSet::from(["b".to_string()])
375        );
376    }
377}