logcompact_builtins/diagnostics/python/
traceback.rs1use crate::{Diagnostic, DiagnosticClass, Location, Severity};
2
3use super::super::common::normalize_path;
4
5#[derive(Debug, Default)]
11pub struct PythonDiagnosticParser {
12 location: Option<Location>,
13}
14
15impl PythonDiagnosticParser {
16 pub fn observe_line(&mut self, line: &str) -> Option<Diagnostic> {
19 if line.trim() == "Traceback (most recent call last):" {
20 self.location = None;
21 return None;
22 }
23 if let Some(location) = parse_location(line) {
24 self.location = Some(location);
25 return None;
26 }
27 let message = exception_message(line)?;
28 let exception_type = message.split_once(':').map_or(message, |(name, _)| name);
29 Some(Diagnostic {
30 severity: if exception_type.ends_with("Warning") {
31 Severity::Warning
32 } else {
33 Severity::Error
34 },
35 class: DiagnosticClass::Compiler,
36 code: None,
37 provenance: None,
38 message: message.to_owned(),
39 location: self.location.take(),
40 quality: crate::EvidenceQuality::Structured,
41 repetition_count: 1,
42 })
43 }
44}
45
46pub(crate) fn parse_location(line: &str) -> Option<Location> {
47 let marker = "File \"";
48 let start = line.find(marker)? + marker.len();
49 let remainder = &line[start..];
50 let (path, remainder) = remainder.split_once("\", line ")?;
51 let synthetic_path = path.starts_with('<') && !path.contains("/");
52 if synthetic_path || path.ends_with("_stage2_bootstrap.py") {
53 return None;
54 }
55 let digits = remainder
56 .bytes()
57 .take_while(|byte| byte.is_ascii_digit())
58 .count();
59 if digits == 0 {
60 return None;
61 }
62 let line_number = remainder[..digits].parse::<u32>().ok()?;
63 Some(Location {
64 path: compact_path(path),
65 line: Some(line_number),
66 column: None,
67 end_line: None,
68 end_column: None,
69 })
70}
71
72pub(crate) fn exception_message(line: &str) -> Option<&str> {
73 let mut line = line.trim();
74 if let Some(remainder) = line.strip_prefix('E')
75 && remainder.chars().next().is_some_and(char::is_whitespace)
76 {
77 line = remainder.trim_start();
78 }
79 if line.contains("File \"") {
80 return None;
81 }
82 let exception_type = line.split_once(':').map_or(line, |(name, _)| name);
83 if exception_type.is_empty()
84 || exception_type
85 .bytes()
86 .any(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.')))
87 {
88 return None;
89 }
90 let class_name = exception_type.rsplit('.').next()?;
91 let recognized = class_name.ends_with("Error")
92 || class_name.ends_with("Exception")
93 || class_name.ends_with("Failure")
94 || class_name.ends_with("Warning")
95 || matches!(class_name, "Failed" | "KeyboardInterrupt" | "SystemExit");
96 recognized.then_some(line)
97}
98
99fn compact_path(path: &str) -> String {
100 normalize_path(path)
101}