tokencompact_builtins/diagnostics/
java.rs1use std::collections::BTreeSet;
2
3use crate::{Diagnostic, DiagnosticClass, Location, Severity};
4
5use super::common::{normalize_path, split_u32_prefix};
6
7pub(super) fn reduce_compiler(input: &str, diagnostics: &mut Vec<Diagnostic>) {
8 diagnostics.extend(parse_compiler_diagnostics(input));
9}
10
11pub(super) fn reduce_tests(
12 input: &str,
13 diagnostics: &mut Vec<Diagnostic>,
14 messages: &mut BTreeSet<String>,
15) {
16 let mut parser = JavaTestDiagnosticParser::default();
17 for line in input.lines() {
18 if let Some(diagnostic) = parser.observe_line(line) {
19 messages.insert(diagnostic.message.clone());
20 diagnostics.push(diagnostic);
21 }
22 }
23 if let Some(diagnostic) = parser.finish() {
24 messages.insert(diagnostic.message.clone());
25 diagnostics.push(diagnostic);
26 }
27}
28
29fn parse_compiler_diagnostics(input: &str) -> Vec<Diagnostic> {
30 const MAX_CONTEXT_LINES: usize = 8;
31 let lines = input.lines().collect::<Vec<_>>();
32 let mut diagnostics = Vec::new();
33 for (index, line) in lines.iter().enumerate() {
34 let Some(mut diagnostic) = parse_compiler_diagnostic(line) else {
35 continue;
36 };
37 if diagnostic
38 .message
39 .eq_ignore_ascii_case("cannot find symbol")
40 {
41 for context in lines.iter().skip(index + 1).take(MAX_CONTEXT_LINES) {
42 if parse_compiler_diagnostic(context).is_some()
43 || context.trim_start().starts_with("ERROR:")
44 {
45 break;
46 }
47 if let Some(symbol) = context.trim().strip_prefix("symbol:") {
48 diagnostic.message = format!(
49 "cannot find symbol: {}",
50 symbol.split_whitespace().collect::<Vec<_>>().join(" ")
51 );
52 break;
53 }
54 }
55 }
56 diagnostics.push(diagnostic);
57 }
58 diagnostics
59}
60
61pub(super) fn parse_compiler_diagnostic(line: &str) -> Option<Diagnostic> {
62 let marker = line.rfind(".java:")?;
63 let path_end = marker + ".java".len();
64 let path = line[..path_end]
65 .trim()
66 .strip_prefix("ERROR: ")
67 .unwrap_or_else(|| line[..path_end].trim());
68 let (line_number, remainder) = split_u32_prefix(&line[path_end + 1..])?;
69 let (column, message) = split_u32_prefix(remainder)
70 .map_or((None, remainder), |(column, message)| {
71 (Some(column), message)
72 });
73 let message = message.trim();
74 let (severity, message) = if let Some(message) = message.strip_prefix("error:") {
75 (Severity::Error, message.trim())
76 } else {
77 let message = message.strip_prefix("warning:")?;
78 (Severity::Warning, message.trim())
79 };
80 if message.is_empty() {
81 return None;
82 }
83 Some(Diagnostic {
84 severity,
85 class: DiagnosticClass::Compiler,
86 code: None,
87 provenance: None,
88 message: message.to_owned(),
89 location: Some(Location {
90 path: compact_path(path),
91 line: Some(line_number),
92 column,
93 }),
94 quality: crate::EvidenceQuality::Located,
95 repetition_count: 1,
96 })
97}
98
99#[derive(Debug, Default)]
101pub struct JavaTestDiagnosticParser {
102 pending: Option<Diagnostic>,
103 pending_is_explicit: bool,
104 frames_seen: usize,
105}
106
107impl JavaTestDiagnosticParser {
108 const MAX_STACK_FRAMES: usize = 64;
109
110 pub fn observe_line(&mut self, line: &str) -> Option<Diagnostic> {
113 if let Some((message, explicitly_java)) = parse_exception_line(line) {
114 let previous = self.take_confirmed();
115 self.pending = Some(Diagnostic {
116 severity: Severity::Error,
117 class: DiagnosticClass::Test,
118 code: None,
119 provenance: None,
120 message: message.to_owned(),
121 location: None,
122 quality: crate::EvidenceQuality::Structured,
123 repetition_count: 1,
124 });
125 self.pending_is_explicit = explicitly_java;
126 self.frames_seen = 0;
127 return previous;
128 }
129 self.pending.as_ref()?;
130 if let Some((location, framework_frame)) = parse_stack_frame(line) {
131 self.frames_seen = self.frames_seen.saturating_add(1);
132 if !framework_frame {
133 let mut diagnostic = self.pending.take()?;
134 diagnostic.location = Some(location);
135 self.pending_is_explicit = false;
136 self.frames_seen = 0;
137 return Some(diagnostic);
138 }
139 if self.frames_seen >= Self::MAX_STACK_FRAMES {
140 return self.take_confirmed();
141 }
142 return None;
143 }
144 if line.trim().is_empty() {
145 return None;
146 }
147 self.take_confirmed()
148 }
149
150 pub fn finish(&mut self) -> Option<Diagnostic> {
152 self.take_confirmed()
153 }
154
155 fn take_confirmed(&mut self) -> Option<Diagnostic> {
156 let confirmed = self.pending_is_explicit || self.frames_seen > 0;
157 self.pending_is_explicit = false;
158 self.frames_seen = 0;
159 if confirmed {
160 self.pending.take()
161 } else {
162 self.pending = None;
163 None
164 }
165 }
166}
167
168pub(super) fn exception_message(line: &str) -> Option<&str> {
169 parse_exception_line(line).map(|(message, _)| message)
170}
171
172fn parse_exception_line(line: &str) -> Option<(&str, bool)> {
173 let mut line = line.trim();
174 let mut explicitly_java = false;
175 if let Some(remainder) = line.strip_prefix("Exception in thread \"") {
176 let (_, remainder) = remainder.split_once("\" ")?;
177 line = remainder;
178 explicitly_java = true;
179 } else if let Some(remainder) = line.strip_prefix("Caused by: ") {
180 line = remainder;
181 explicitly_java = true;
182 }
183 let exception_type = line.split_once(':').map_or(line, |(name, _)| name);
184 if exception_type.is_empty()
185 || exception_type
186 .bytes()
187 .any(|byte| !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'$')))
188 {
189 return None;
190 }
191 let class_name = exception_type.rsplit('.').next()?;
192 let recognized = class_name.ends_with("Error")
193 || class_name.ends_with("Exception")
194 || class_name.ends_with("Failure");
195 (recognized && (explicitly_java || exception_type.contains('.')))
196 .then_some((line, explicitly_java))
197}
198
199fn parse_stack_frame(line: &str) -> Option<(Location, bool)> {
200 let frame = line.trim().strip_prefix("at ")?;
201 let (callable, source) = frame.split_once('(')?;
202 let source = source.strip_suffix(')')?;
203 let (file, line_number) = source.rsplit_once(':')?;
204 if !file.ends_with(".java") {
205 return None;
206 }
207 let line_number = line_number.parse::<u32>().ok()?;
208 let callable = callable.rsplit_once('/').map_or(callable, |(_, name)| name);
209 let class_name = callable.rsplit_once('.')?.0;
210 let package = class_name.rsplit_once('.').map(|(package, _)| package);
211 let path = package.map_or_else(
212 || file.to_owned(),
213 |package| format!("{}/{}", package.replace('.', "/"), file),
214 );
215 let framework_frame = [
216 "java.",
217 "javax.",
218 "jdk.",
219 "sun.",
220 "junit.",
221 "org.junit.",
222 "org.hamcrest.",
223 "org.opentest4j.",
224 "com.google.testing.junit.",
225 ]
226 .iter()
227 .any(|prefix| callable.starts_with(prefix));
228 Some((
229 Location {
230 path,
231 line: Some(line_number),
232 column: None,
233 },
234 framework_frame,
235 ))
236}
237
238fn compact_path(path: &str) -> String {
239 normalize_path(path)
240}