tokencompact_builtins/diagnostics/
python.rs1use crate::{Diagnostic, DiagnosticClass, Location, Severity};
2
3use 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(super) 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 })
68}
69
70pub(super) fn exception_message(line: &str) -> Option<&str> {
71 let mut line = line.trim();
72 if let Some(remainder) = line.strip_prefix('E')
73 && remainder.chars().next().is_some_and(char::is_whitespace)
74 {
75 line = remainder.trim_start();
76 }
77 if line.contains("File \"") {
78 return None;
79 }
80 let exception_type = line.split_once(':').map_or(line, |(name, _)| name);
81 if exception_type.is_empty()
82 || exception_type
83 .bytes()
84 .any(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.')))
85 {
86 return None;
87 }
88 let class_name = exception_type.rsplit('.').next()?;
89 let recognized = class_name.ends_with("Error")
90 || class_name.ends_with("Exception")
91 || class_name.ends_with("Failure")
92 || class_name.ends_with("Warning")
93 || matches!(class_name, "Failed" | "KeyboardInterrupt" | "SystemExit");
94 recognized.then_some(line)
95}
96
97fn compact_path(path: &str) -> String {
98 normalize_path(path)
99}