1use std::fmt;
2use std::path::{Path, PathBuf};
3use tracing::{error, info, warn};
4
5pub fn format_path(path: &Path) -> String {
16 let mut s = path.to_string_lossy().replace('\\', "/");
17 if let Ok(cwd) = std::env::current_dir() {
18 let cwd_norm = cwd.to_string_lossy().replace('\\', "/");
19 if let Some(rest) = s.strip_prefix(&format!("{}/", cwd_norm)) {
20 s = rest.to_string();
21 } else if s == cwd_norm {
22 s = ".".to_string();
23 }
24 }
25 s
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum Severity {
31 Error,
32 Warning,
33 Info,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Applicability {
40 MachineApplicable,
43 MaybeIncorrect,
47 HasPlaceholders,
50 Unspecified,
52}
53
54#[derive(Debug, Clone)]
61pub struct Suggestion {
62 pub file: PathBuf,
63 pub line_range: (usize, usize),
64 pub replacement: String,
65 pub label: Option<String>,
68}
69
70#[derive(Debug, Clone)]
73pub struct Help {
74 pub message: String,
75 pub suggestions: Vec<Suggestion>,
76 pub applicability: Applicability,
77}
78
79#[derive(Debug, Clone)]
81pub struct Diagnostic {
82 pub file: PathBuf,
83 pub line: usize,
84 pub column: usize,
85 pub message: String,
86 pub severity: Severity,
87 pub phase: Phase,
88 pub help: Vec<Help>,
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum Phase {
101 Lexing,
102 Parsing,
103 SymbolRegistration,
104 TypeChecking,
105 CodeGeneration,
106 PointerCheck,
107}
108
109impl fmt::Display for Diagnostic {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 let severity = match self.severity {
112 Severity::Error => "error",
113 Severity::Warning => "warning",
114 Severity::Info => "info",
115 };
116 if self.column > 0 {
121 write!(
122 f,
123 "{}: {}\n --> {}:{}:{}",
124 severity,
125 self.message,
126 format_path(&self.file),
127 self.line,
128 self.column,
129 )
130 } else {
131 write!(
132 f,
133 "{}: {}\n --> {}:{}",
134 severity,
135 self.message,
136 format_path(&self.file),
137 self.line,
138 )
139 }
140 }
141}
142
143#[derive(Debug, Clone)]
145pub struct DiagnosticsCollector {
146 diagnostics: Vec<Diagnostic>,
147}
148
149impl DiagnosticsCollector {
150 pub fn new() -> Self {
151 DiagnosticsCollector {
152 diagnostics: Vec::new(),
153 }
154 }
155
156 pub fn add(&mut self, diagnostic: Diagnostic) {
157 self.diagnostics.push(diagnostic);
158 }
159
160 pub fn error(
161 &mut self,
162 file: PathBuf,
163 line: usize,
164 column: usize,
165 message: String,
166 phase: Phase,
167 ) {
168 self.add(Diagnostic {
169 file,
170 line,
171 column,
172 message,
173 severity: Severity::Error,
174 phase,
175 help: Vec::new(),
176 });
177 }
178
179 pub fn warning(
180 &mut self,
181 file: PathBuf,
182 line: usize,
183 column: usize,
184 message: String,
185 phase: Phase,
186 ) {
187 self.add(Diagnostic {
188 file,
189 line,
190 column,
191 message,
192 severity: Severity::Warning,
193 phase,
194 help: Vec::new(),
195 });
196 }
197
198 pub fn has_errors(&self) -> bool {
199 self.diagnostics
200 .iter()
201 .any(|d| d.severity == Severity::Error)
202 }
203
204 pub fn has_errors_in_phase(&self, phase: Phase) -> bool {
205 self.diagnostics
206 .iter()
207 .any(|d| d.severity == Severity::Error && d.phase == phase)
208 }
209
210 pub fn error_count(&self) -> usize {
211 self.diagnostics
212 .iter()
213 .filter(|d| d.severity == Severity::Error)
214 .count()
215 }
216
217 pub fn warning_count(&self) -> usize {
218 self.diagnostics
219 .iter()
220 .filter(|d| d.severity == Severity::Warning)
221 .count()
222 }
223
224 pub fn diagnostics(&self) -> &[Diagnostic] {
225 &self.diagnostics
226 }
227
228 pub fn errors(&self) -> Vec<&Diagnostic> {
229 self.diagnostics
230 .iter()
231 .filter(|d| d.severity == Severity::Error)
232 .collect()
233 }
234
235 pub fn print_all(&self) {
236 for diag in &self.diagnostics {
237 let msg = format!("{}", diag);
238 let help = render_help_string(diag);
239 let full = if help.is_empty() {
240 msg
241 } else {
242 format!("{}\n{}", msg, help)
243 };
244 match diag.severity {
245 Severity::Error => error!(target: "runec", "{}", full),
246 Severity::Warning => warn!(target: "runec", "{}", full),
247 Severity::Info => info!(target: "runec", "{}", full),
248 }
249 }
250 let errors = self.error_count();
251 let warnings = self.warning_count();
252 if errors > 0 || warnings > 0 {
253 info!(target: "runec", "{} error(s), {} warning(s) generated.", errors, warnings);
254 }
255 }
256
257 pub fn clear(&mut self) {
258 self.diagnostics.clear();
259 }
260
261 pub fn merge(&mut self, other: DiagnosticsCollector) {
262 self.diagnostics.extend(other.diagnostics);
263 }
264}
265
266impl Default for DiagnosticsCollector {
267 fn default() -> Self {
268 Self::new()
269 }
270}
271
272fn render_help_string(diag: &Diagnostic) -> String {
284 if diag.help.is_empty() {
285 return String::new();
286 }
287 use std::fmt::Write;
288 let mut out = String::new();
289 for help in &diag.help {
290 let _ = writeln!(out, "help: {}", help.message);
291 for sug in &help.suggestions {
292 let path = format_path(&sug.file);
293 if let Some(label) = &sug.label {
294 let _ = writeln!(
295 out,
296 " ┌─ {} {}:{}-{}",
297 label, path, sug.line_range.0, sug.line_range.1
298 );
299 } else {
300 let _ = writeln!(
301 out,
302 " ┌─ {}:{}-{}",
303 path, sug.line_range.0, sug.line_range.1
304 );
305 }
306
307 let original = std::fs::read_to_string(&sug.file).ok().and_then(|src| {
308 let start = sug.line_range.0.saturating_sub(1);
309 let end = sug.line_range.1;
310 let lines: Vec<&str> = src.lines().collect();
311 if start < lines.len() && end <= lines.len() && start < end {
312 Some(lines[start..end].join("\n"))
313 } else if start < lines.len() {
314 Some(lines[start].to_string())
315 } else {
316 None
317 }
318 });
319
320 match original {
321 Some(orig) => {
322 for l in orig.lines() {
323 let _ = writeln!(out, " - {}", l);
324 }
325 for l in sug.replacement.lines() {
326 let _ = writeln!(out, " + {}", l);
327 }
328 }
329 None => {
330 for l in sug.replacement.lines() {
331 let _ = writeln!(out, " + {}", l);
332 }
333 }
334 }
335 }
336 let appl = match help.applicability {
337 Applicability::MachineApplicable => "MachineApplicable (safe to auto-apply)",
338 Applicability::MaybeIncorrect => "MaybeIncorrect (review before applying)",
339 Applicability::HasPlaceholders => "HasPlaceholders (fill in the <…> tokens)",
340 Applicability::Unspecified => "Unspecified",
341 };
342 let _ = writeln!(out, " = note: Applicability: {}", appl);
343 }
344 out.truncate(out.trim_end().len());
345 out
346}