Skip to main content

logcompact_builtins/diagnostics/java/
junit.rs

1use std::collections::BTreeSet;
2
3use crate::{Diagnostic, DiagnosticClass, Location, Severity};
4
5pub(crate) fn reduce(
6    input: &str,
7    diagnostics: &mut Vec<Diagnostic>,
8    messages: &mut BTreeSet<String>,
9) {
10    let mut parser = JavaTestDiagnosticParser::default();
11    for line in input.lines() {
12        if let Some(diagnostic) = parser.observe_line(line) {
13            messages.insert(diagnostic.message.clone());
14            diagnostics.push(diagnostic);
15        }
16    }
17    if let Some(diagnostic) = parser.finish() {
18        messages.insert(diagnostic.message.clone());
19        diagnostics.push(diagnostic);
20    }
21}
22
23/// Stateful extractor for Java exceptions followed by JVM stack frames.
24#[derive(Debug, Default)]
25pub struct JavaTestDiagnosticParser {
26    pending: Option<Diagnostic>,
27    pending_is_explicit: bool,
28    frames_seen: usize,
29}
30
31impl JavaTestDiagnosticParser {
32    const MAX_STACK_FRAMES: usize = 64;
33
34    /// Observes one normalized test-log line and emits an exception once an
35    /// application frame, another exception, or the end of its stack is seen.
36    pub fn observe_line(&mut self, line: &str) -> Option<Diagnostic> {
37        if let Some((message, explicitly_java)) = parse_exception_line(line) {
38            let previous = self.take_confirmed();
39            self.pending = Some(Diagnostic {
40                severity: Severity::Error,
41                class: DiagnosticClass::Test,
42                code: None,
43                provenance: None,
44                message: message.to_owned(),
45                location: None,
46                quality: crate::EvidenceQuality::Structured,
47                repetition_count: 1,
48            });
49            self.pending_is_explicit = explicitly_java;
50            self.frames_seen = 0;
51            return previous;
52        }
53        self.pending.as_ref()?;
54        if let Some((location, framework_frame)) = parse_stack_frame(line) {
55            self.frames_seen = self.frames_seen.saturating_add(1);
56            if !framework_frame {
57                let mut diagnostic = self.pending.take()?;
58                diagnostic.location = Some(location);
59                self.pending_is_explicit = false;
60                self.frames_seen = 0;
61                return Some(diagnostic);
62            }
63            if self.frames_seen >= Self::MAX_STACK_FRAMES {
64                return self.take_confirmed();
65            }
66            return None;
67        }
68        if line.trim().is_empty() {
69            return None;
70        }
71        self.take_confirmed()
72    }
73
74    /// Emits an exception that reached end-of-file without an application frame.
75    pub fn finish(&mut self) -> Option<Diagnostic> {
76        self.take_confirmed()
77    }
78
79    fn take_confirmed(&mut self) -> Option<Diagnostic> {
80        let confirmed = self.pending_is_explicit || self.frames_seen > 0;
81        self.pending_is_explicit = false;
82        self.frames_seen = 0;
83        if confirmed {
84            self.pending.take()
85        } else {
86            self.pending = None;
87            None
88        }
89    }
90}
91
92pub(crate) fn exception_message(line: &str) -> Option<&str> {
93    parse_exception_line(line).map(|(message, _)| message)
94}
95
96fn parse_exception_line(line: &str) -> Option<(&str, bool)> {
97    let mut line = line.trim();
98    let mut explicitly_java = false;
99    if let Some(remainder) = line.strip_prefix("Exception in thread \"") {
100        let (_, remainder) = remainder.split_once("\" ")?;
101        line = remainder;
102        explicitly_java = true;
103    } else if let Some(remainder) = line.strip_prefix("Caused by: ") {
104        line = remainder;
105        explicitly_java = true;
106    }
107    let exception_type = line.split_once(':').map_or(line, |(name, _)| name);
108    if exception_type.is_empty()
109        || exception_type
110            .bytes()
111            .any(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'$')))
112    {
113        return None;
114    }
115    let class_name = exception_type.rsplit('.').next()?;
116    let recognized = class_name.ends_with("Error")
117        || class_name.ends_with("Exception")
118        || class_name.ends_with("Failure");
119    (recognized && (explicitly_java || exception_type.contains('.')))
120        .then_some((line, explicitly_java))
121}
122
123fn parse_stack_frame(line: &str) -> Option<(Location, bool)> {
124    let frame = line.trim().strip_prefix("at ")?;
125    let (callable, source) = frame.split_once('(')?;
126    let source = source.strip_suffix(')')?;
127    let (file, line_number) = source.rsplit_once(':')?;
128    if !file.ends_with(".java") {
129        return None;
130    }
131    let line_number = line_number.parse::<u32>().ok()?;
132    let callable = callable.rsplit_once('/').map_or(callable, |(_, name)| name);
133    let class_name = callable.rsplit_once('.')?.0;
134    let package = class_name.rsplit_once('.').map(|(package, _)| package);
135    let path = package.map_or_else(
136        || file.to_owned(),
137        |package| format!("{}/{}", package.replace('.', "/"), file),
138    );
139    let framework_frame = [
140        "java.",
141        "javax.",
142        "jdk.",
143        "sun.",
144        "junit.",
145        "org.junit.",
146        "org.hamcrest.",
147        "org.opentest4j.",
148        "com.google.testing.junit.",
149    ]
150    .iter()
151    .any(|prefix| callable.starts_with(prefix));
152    Some((
153        Location {
154            path,
155            line: Some(line_number),
156            column: None,
157            end_line: None,
158            end_column: None,
159        },
160        framework_frame,
161    ))
162}