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