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 start >= lines.len() {
157            continue;
158        }
159        if let Some(at) = raise_line(lang, &lines, body(lang, &lines, start)) {
160            out.push(Raise {
161                export: name.clone(),
162                site: format!("{file}:{}", at + 1),
163            });
164        }
165    }
166    out
167}
168
169/// Names of the functions with at least one recorded case that failed.
170pub fn recorded_errors(cases: &str) -> BTreeSet<String> {
171    cases
172        .lines()
173        .filter_map(|l| serde_json::from_str::<Value>(l).ok())
174        .filter(|c| c.get("error").is_some() || c.get("panic").is_some())
175        .filter_map(|c| c["fn"].as_str().map(str::to_string))
176        .collect()
177}
178
179/// `unwrap`, `expect` and panicking macros in `port.rs`, by function, outside tests and not
180/// marked `// INFALLIBLE:` on the line or in the comment just above.
181pub fn panics(port: &str) -> Vec<Panic> {
182    let lines: Vec<&str> = port.lines().collect();
183    let fn_name =
184        Regex::new(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)")
185            .expect("valid regex");
186    let mut out = Vec::new();
187    let mut current = String::new();
188    for (i, line) in lines.iter().enumerate() {
189        if line.trim_start().starts_with("#[cfg(test)]") {
190            break;
191        }
192        if let Some(c) = fn_name.captures(line) {
193            current = c[1].to_string();
194        }
195        let code = line.split("//").next().unwrap_or_default();
196        let Some(what) = PANICS.iter().find(|p| code.contains(*p)) else {
197            continue;
198        };
199        let marked = line.contains(INFALLIBLE)
200            || lines[..i]
201                .iter()
202                .rev()
203                .take_while(|l| l.trim_start().starts_with("//"))
204                .any(|l| l.contains(INFALLIBLE));
205        if !marked {
206            out.push(Panic {
207                function: current.clone(),
208                line: i + 1,
209                what,
210            });
211        }
212    }
213    out
214}
215
216/// The `error cases` and `panics` checks of `gate`.
217pub fn checks(crate_dir: &Path, manifest: &Manifest) -> Vec<Check> {
218    let exports: Vec<(String, String, u32)> = manifest
219        .exports
220        .iter()
221        .map(|f| (f.name.clone(), f.file.clone(), f.line))
222        .collect();
223    let raised = raises(manifest.language, &manifest.root, &exports);
224    let cases = std::fs::read_to_string(crate_dir.join(crate::harness::CASES)).unwrap_or_default();
225    let failed = recorded_errors(&cases);
226    let unreached: Vec<String> = raised
227        .iter()
228        .filter(|r| !failed.contains(&r.export))
229        .map(|r| format!("{} fails at {}", r.export, r.site))
230        .collect();
231    let error_cases = Check {
232        fix: None,
233        name: "error cases",
234        passed: unreached.is_empty(),
235        detail: if raised.is_empty() {
236            "the original fails on purpose nowhere".into()
237        } else if unreached.is_empty() {
238            if raised.len() == 1 {
239                "the 1 function that fails in the original has a recorded failing case".into()
240            } else {
241                format!(
242                    "each of the {} functions that fail in the original has a recorded failing case",
243                    raised.len()
244                )
245            }
246        } else {
247            format!(
248                "no recorded case reaches these error paths: add inputs that fail (record --inputs)\n{}",
249                unreached.join("\n")
250            )
251        },
252    };
253
254    let port = std::fs::read_to_string(crate_dir.join("src/port.rs")).unwrap_or_default();
255    let fails: BTreeSet<String> = manifest
256        .exports
257        .iter()
258        .filter(|f| failed.contains(&f.name) || raised.iter().any(|r| r.export == f.name))
259        .map(|f| snake_case(&f.name))
260        .collect();
261    let bad: Vec<String> = panics(&port)
262        .into_iter()
263        .filter(|p| fails.contains(&p.function))
264        .map(|p| format!("src/port.rs:{} `{}` in {}", p.line, p.what, p.function))
265        .collect();
266    let panics_check = Check {
267        fix: None,
268        name: "panics",
269        passed: bad.is_empty(),
270        detail: if bad.is_empty() {
271            "no unwrap, expect or panic where the original returns an error".into()
272        } else {
273            format!(
274                "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{}",
275                bad.join("\n")
276            )
277        },
278    };
279    vec![error_cases, panics_check]
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    fn check(lang: Lang, file: &str, source: &str, exports: &[(&str, u32)]) -> Vec<String> {
287        let dir = std::env::temp_dir().join(format!(
288            "rust-anything-raises-{}-{file}",
289            std::process::id()
290        ));
291        std::fs::create_dir_all(&dir).unwrap();
292        std::fs::write(dir.join(file), source).unwrap();
293        let exports: Vec<(String, String, u32)> = exports
294            .iter()
295            .map(|(n, l)| (n.to_string(), file.to_string(), *l))
296            .collect();
297        let found = raises(lang, &dir, &exports)
298            .into_iter()
299            .map(|r| format!("{} {}", r.export, r.site))
300            .collect();
301        std::fs::remove_dir_all(&dir).unwrap();
302        found
303    }
304
305    #[test]
306    fn a_line_past_the_end_of_an_edited_file_is_skipped() {
307        let source = "package textkit\n\nfunc Abbrev(s string) string {\n\treturn s\n}\n";
308        for lang in [Lang::Go, Lang::Ts, Lang::Python] {
309            assert!(check(lang, "short.go", source, &[("Humanize", 12)]).is_empty());
310        }
311    }
312
313    #[test]
314    fn finds_where_the_original_fails_in_each_language() {
315        assert_eq!(
316            check(
317                Lang::Ts,
318                "a.ts",
319                "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",
320                &[("ok", 1), ("parse", 4)]
321            ),
322            ["parse a.ts:6"]
323        );
324        assert_eq!(
325            check(
326                Lang::Python,
327                "a.py",
328                "def ok(x):\n    return x\n\ndef parse(s):\n    if not s:\n        raise ValueError('empty')\n    return s\n",
329                &[("ok", 1), ("parse", 4)]
330            ),
331            ["parse a.py:6"]
332        );
333        assert_eq!(
334            check(
335                Lang::Ruby,
336                "a.rb",
337                "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",
338                &[("ok", 2), ("parse", 6)]
339            ),
340            ["parse a.rb:7"]
341        );
342        assert_eq!(
343            check(
344                Lang::Go,
345                "a.go",
346                "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",
347                &[("Ok", 3), ("Parse", 7)]
348            ),
349            ["Parse a.go:9"]
350        );
351        assert_eq!(
352            check(
353                Lang::Java,
354                "A.java",
355                "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",
356                &[("ok", 2), ("parse", 3)]
357            ),
358            ["parse A.java:4"]
359        );
360        assert!(
361            check(
362                Lang::C,
363                "a.c",
364                "int parse(const char *s) { return s ? 1 : -1; }\n",
365                &[("parse", 1)]
366            )
367            .is_empty()
368        );
369    }
370
371    #[test]
372    fn panics_outside_tests_and_markers_are_found() {
373        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";
374        let found: Vec<(String, usize, &str)> = panics(port)
375            .into_iter()
376            .map(|p| (p.function, p.line, p.what))
377            .collect();
378        assert_eq!(
379            found,
380            [
381                ("parse_port".to_string(), 2, ".unwrap()"),
382                ("later".to_string(), 13, "todo!(")
383            ]
384        );
385        assert_eq!(
386            recorded_errors(
387                "{\"fn\":\"a\",\"args\":[],\"result\":1}\n{\"fn\":\"b\",\"args\":[],\"error\":{\"name\":\"E\"}}\n"
388            ),
389            BTreeSet::from(["b".to_string()])
390        );
391    }
392
393    #[test]
394    fn error_cases_detail_singular_and_plural() {
395        let dir =
396            std::env::temp_dir().join(format!("rust-anything-error-detail-{}", std::process::id()));
397        let root = dir.join("root");
398        let _ = std::fs::remove_dir_all(&dir);
399        std::fs::create_dir_all(&root).unwrap();
400        std::fs::write(
401            root.join("test.ts"),
402            "export function parse(s: string) {\n  if (!s) throw new Error('err');\n  return s;\n}\nexport function second(s: string) {\n  if (!s) throw new Error('err2');\n  return s;\n}\n",
403        )
404        .unwrap();
405
406        let mut manifest = Manifest {
407            schema: String::new(),
408            root: root.clone(),
409            root_written: None,
410            unit: "test.ts".into(),
411            language: Lang::Ts,
412            kind: crate::bridge::Kind::Napi,
413            crate_name: "test-rs".into(),
414            exports: vec![crate::ts::exports::ExportedFn {
415                name: "parse".into(),
416                file: "test.ts".into(),
417                line: 1,
418                ..Default::default()
419            }],
420            classes: Vec::new(),
421            js_only: Vec::new(),
422            batches: Vec::new(),
423            allocator: Default::default(),
424            float_tolerance: None,
425            ignore_key_order: false,
426            end_state: None,
427        };
428
429        // 1 function that fails: recorded
430        std::fs::write(
431            dir.join("cases.jsonl"),
432            "{\"fn\":\"parse\",\"args\":[\"\"],\"error\":{\"name\":\"Error\"}}\n",
433        )
434        .unwrap();
435
436        let checks_one = checks(&dir, &manifest);
437        assert_eq!(checks_one[0].name, "error cases");
438        assert!(checks_one[0].passed);
439        assert_eq!(
440            checks_one[0].detail,
441            "the 1 function that fails in the original has a recorded failing case"
442        );
443
444        // 2 functions that fail: recorded
445        manifest.exports.push(crate::ts::exports::ExportedFn {
446            name: "second".into(),
447            file: "test.ts".into(),
448            line: 5,
449            ..Default::default()
450        });
451        std::fs::write(
452            dir.join("cases.jsonl"),
453            "{\"fn\":\"parse\",\"args\":[\"\"],\"error\":{\"name\":\"Error\"}}\n{\"fn\":\"second\",\"args\":[\"\"],\"error\":{\"name\":\"Error\"}}\n",
454        )
455        .unwrap();
456
457        let checks_two = checks(&dir, &manifest);
458        assert_eq!(checks_two[0].name, "error cases");
459        assert!(checks_two[0].passed);
460        assert_eq!(
461            checks_two[0].detail,
462            "each of the 2 functions that fail in the original has a recorded failing case"
463        );
464
465        std::fs::remove_dir_all(&dir).unwrap();
466    }
467}