Skip to main content

tokencompact_builtins/diagnostics/
python.rs

1use crate::{Diagnostic, DiagnosticClass, Location, Severity};
2
3use super::common::normalize_path;
4
5/// Stateful extractor for standard Python traceback and syntax-error output.
6///
7/// Python reports source locations on a `File "...", line N` frame before the
8/// terminal exception. Keeping only the latest frame is bounded and matches
9/// traceback semantics, where the innermost frame is printed last.
10#[derive(Debug, Default)]
11pub struct PythonDiagnosticParser {
12    location: Option<Location>,
13}
14
15impl PythonDiagnosticParser {
16    /// Observes one normalized output line and returns a diagnostic when the
17    /// line terminates a Python exception block.
18    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}