1use colored::Colorize;
7use std::fmt;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
11pub enum Severity {
12 Note,
14 Warning,
16 Error,
18 Fatal,
20}
21
22impl Severity {
23 pub fn tag(&self) -> &'static str {
25 match self {
26 Self::Note => "note",
27 Self::Warning => "warning",
28 Self::Error => "error",
29 Self::Fatal => "fatal",
30 }
31 }
32}
33
34impl fmt::Display for Severity {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 write!(f, "{}", self.tag())
37 }
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum ErrorCategory {
43 Parse,
45 Type,
47 Semantic,
49 Io,
51 Transpile,
53 Internal,
55}
56
57impl fmt::Display for ErrorCategory {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 match self {
60 Self::Parse => write!(f, "parse"),
61 Self::Type => write!(f, "type"),
62 Self::Semantic => write!(f, "semantic"),
63 Self::Io => write!(f, "io"),
64 Self::Transpile => write!(f, "transpile"),
65 Self::Internal => write!(f, "internal"),
66 }
67 }
68}
69
70#[derive(Debug, Clone)]
75pub struct Diagnostic {
76 pub severity: Severity,
78 pub message: String,
80 pub file: Option<String>,
82 pub line: Option<u32>,
84 pub column: Option<u32>,
86 pub category: Option<String>,
88 pub fix_its: Vec<String>,
90 pub snippet: Option<String>,
92 pub note: Option<String>,
94 pub help: Option<String>,
96}
97
98impl Diagnostic {
99 pub fn new(severity: Severity, message: impl Into<String>) -> Self {
101 Self {
102 severity,
103 message: message.into(),
104 file: None,
105 line: None,
106 column: None,
107 category: None,
108 fix_its: Vec::new(),
109 snippet: None,
110 note: None,
111 help: None,
112 }
113 }
114
115 pub fn error_category(&self) -> ErrorCategory {
117 if let Some(ref cat) = self.category {
118 let cat_lower = cat.to_lowercase();
119 if cat_lower.contains("parse") || cat_lower.contains("syntax") {
120 return ErrorCategory::Parse;
121 }
122 if cat_lower.contains("type") {
123 return ErrorCategory::Type;
124 }
125 if cat_lower.contains("semantic") {
126 return ErrorCategory::Semantic;
127 }
128 }
129
130 let msg = self.message.to_lowercase();
131 if msg.contains("expected") || msg.contains("unterminated") || msg.contains("extraneous") {
132 ErrorCategory::Parse
133 } else if msg.contains("incompatible") || msg.contains("implicit conversion") {
134 ErrorCategory::Type
135 } else if msg.contains("undeclared") || msg.contains("redefinition") {
136 ErrorCategory::Semantic
137 } else {
138 ErrorCategory::Parse
139 }
140 }
141
142 pub fn build_snippet(source: &str, line: u32, column: Option<u32>) -> Option<String> {
144 let lines: Vec<&str> = source.lines().collect();
145 let line_idx = line.checked_sub(1)? as usize;
146 if line_idx >= lines.len() {
147 return None;
148 }
149
150 let mut out = String::new();
151 let gutter_width = format!("{}", line_idx + 2).len().max(2);
152
153 if line_idx > 0 {
155 out.push_str(&format!(
156 "{:>width$}| {}\n",
157 line_idx,
158 lines[line_idx - 1],
159 width = gutter_width
160 ));
161 }
162
163 out.push_str(&format!(
165 "{:>width$}| {}\n",
166 line_idx + 1,
167 lines[line_idx],
168 width = gutter_width
169 ));
170
171 if let Some(col) = column {
173 let col_idx = (col as usize).saturating_sub(1);
174 let padding = " ".repeat(col_idx);
175 out.push_str(&format!("{:>width$}| {}^\n", "", padding, width = gutter_width));
176 }
177
178 if line_idx + 1 < lines.len() {
180 out.push_str(&format!(
181 "{:>width$}| {}\n",
182 line_idx + 2,
183 lines[line_idx + 1],
184 width = gutter_width
185 ));
186 }
187
188 Some(out)
189 }
190
191 pub fn infer_note_and_help(&mut self) {
193 let msg = self.message.to_lowercase();
194
195 if msg.contains("expected ')'") {
196 self.note = Some("Unclosed parenthesis in expression or function call.".into());
197 self.help = Some("Add the missing ')' to close the expression.".into());
198 } else if msg.contains("expected ';'") {
199 self.note = Some("Missing semicolon after statement.".into());
200 self.help = Some("Add ';' at the end of the statement.".into());
201 } else if msg.contains("use of undeclared identifier")
202 || msg.contains("undeclared identifier")
203 {
204 self.note = Some("Variable or function not declared in this scope.".into());
205 self.help =
206 Some("Declare the variable before use, or check for typos in the name.".into());
207 } else if msg.contains("implicit declaration of function") {
208 self.note = Some("Function called before it is declared.".into());
209 self.help = Some(
210 "Add a #include for the header that declares this function, or add a forward declaration.".into(),
211 );
212 } else if msg.contains("incompatible") && msg.contains("type") {
213 self.note = Some("Type mismatch in assignment or return value.".into());
214 self.help =
215 Some("Ensure the types match, or add an explicit cast if intentional.".into());
216 } else if msg.contains("expected '}'") {
217 self.note = Some("Unclosed brace in block or struct definition.".into());
218 self.help = Some("Add the missing '}' to close the block.".into());
219 } else if msg.contains("redefinition of") {
220 self.note = Some("This name was already defined earlier in the same scope.".into());
221 self.help = Some("Rename one of the definitions, or use a different scope.".into());
222 } else if msg.contains("expected expression") {
223 self.note =
224 Some("The parser expected a value or expression but found something else.".into());
225 self.help = Some("Check for missing operands or misplaced punctuation.".into());
226 } else if !self.fix_its.is_empty() {
227 self.help = Some(self.fix_its.join("; "));
228 }
229 }
230}
231
232impl fmt::Display for Diagnostic {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 let category = self.error_category();
236 let header = format!("{}[{}]", self.severity.tag(), category);
237 let colored_header = match self.severity {
238 Severity::Error | Severity::Fatal => header.red().bold().to_string(),
239 Severity::Warning => header.yellow().bold().to_string(),
240 Severity::Note => header.cyan().bold().to_string(),
241 };
242 writeln!(f, "{}: {}", colored_header, self.message.bold())?;
243
244 if let Some(ref file) = self.file {
246 let loc = match (self.line, self.column) {
247 (Some(l), Some(c)) => format!("{}:{}:{}", file, l, c),
248 (Some(l), None) => format!("{}:{}", file, l),
249 _ => file.clone(),
250 };
251 writeln!(f, " {} {}", "-->".blue().bold(), loc)?;
252 }
253
254 if let Some(ref snippet) = self.snippet {
256 for line in snippet.lines() {
258 if let Some(pipe_pos) = line.find('|') {
259 let gutter = &line[..=pipe_pos];
260 let rest = &line[pipe_pos + 1..];
261 if rest.trim() == "^" || rest.contains('^') {
262 writeln!(f, " {}{}", gutter.blue(), rest.red())?;
264 } else {
265 writeln!(f, " {}{}", gutter.blue(), rest)?;
266 }
267 } else {
268 writeln!(f, " {}", line)?;
269 }
270 }
271 }
272
273 if let Some(ref note) = self.note {
275 writeln!(f, " {}: {}", "note".cyan().bold(), note)?;
276 }
277
278 if let Some(ref help) = self.help {
280 writeln!(f, " {}: {}", "help".green().bold(), help)?;
281 }
282
283 Ok(())
284 }
285}
286
287#[derive(Debug)]
292pub struct DiagnosticError {
293 pub diagnostics: Vec<Diagnostic>,
295}
296
297impl DiagnosticError {
298 pub fn new(diagnostics: Vec<Diagnostic>) -> Self {
300 Self { diagnostics }
301 }
302}
303
304impl fmt::Display for DiagnosticError {
305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306 for diag in &self.diagnostics {
307 write!(f, "{}", diag)?;
308 }
309 let error_count = self.diagnostics.iter().filter(|d| d.severity >= Severity::Error).count();
310 if error_count > 0 {
311 write!(
312 f,
313 "{}",
314 format!(
315 "aborting due to {} previous error{}",
316 error_count,
317 if error_count == 1 { "" } else { "s" }
318 )
319 .red()
320 .bold()
321 )?;
322 }
323 Ok(())
324 }
325}
326
327impl std::error::Error for DiagnosticError {}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332
333 #[test]
334 fn test_severity_ordering() {
335 assert!(Severity::Note < Severity::Warning);
336 assert!(Severity::Warning < Severity::Error);
337 assert!(Severity::Error < Severity::Fatal);
338 }
339
340 #[test]
341 fn test_severity_tags() {
342 assert_eq!(Severity::Note.tag(), "note");
343 assert_eq!(Severity::Warning.tag(), "warning");
344 assert_eq!(Severity::Error.tag(), "error");
345 assert_eq!(Severity::Fatal.tag(), "fatal");
346 }
347
348 #[test]
349 fn test_error_category_from_clang_category() {
350 let mut d = Diagnostic::new(Severity::Error, "expected ')'");
351 d.category = Some("Parse Issue".into());
352 assert_eq!(d.error_category(), ErrorCategory::Parse);
353
354 d.category = Some("Semantic Issue".into());
355 assert_eq!(d.error_category(), ErrorCategory::Semantic);
356 }
357
358 #[test]
359 fn test_error_category_from_message() {
360 let d = Diagnostic::new(Severity::Error, "expected ';' after expression");
361 assert_eq!(d.error_category(), ErrorCategory::Parse);
362
363 let d = Diagnostic::new(Severity::Error, "use of undeclared identifier 'x'");
364 assert_eq!(d.error_category(), ErrorCategory::Semantic);
365
366 let d = Diagnostic::new(Severity::Error, "incompatible pointer types");
367 assert_eq!(d.error_category(), ErrorCategory::Type);
368 }
369
370 #[test]
371 fn test_display_contains_header() {
372 let d = Diagnostic::new(Severity::Error, "expected ')'");
373 let output = format!("{}", d);
374 assert!(output.contains("error[parse]"));
375 assert!(output.contains("expected ')'"));
376 }
377
378 #[test]
379 fn test_display_contains_location() {
380 let mut d = Diagnostic::new(Severity::Error, "expected ')'");
381 d.file = Some("test.c".into());
382 d.line = Some(15);
383 d.column = Some(22);
384 let output = format!("{}", d);
385 assert!(output.contains("-->"));
386 assert!(output.contains("test.c:15:22"));
387 }
388
389 #[test]
390 fn test_display_contains_snippet() {
391 let mut d = Diagnostic::new(Severity::Error, "expected ')'");
392 d.snippet = Some("14| int y = 10;\n15| int x = foo(bar;\n | ^\n16| return 0;\n".into());
393 let output = format!("{}", d);
394 assert!(output.contains("|"));
395 assert!(output.contains("^"));
396 }
397
398 #[test]
399 fn test_display_contains_note_and_help() {
400 let mut d = Diagnostic::new(Severity::Error, "expected ')'");
401 d.note = Some("Unclosed parenthesis.".into());
402 d.help = Some("Add ')' to close.".into());
403 let output = format!("{}", d);
404 assert!(output.contains("note:"));
405 assert!(output.contains("help:"));
406 assert!(output.contains("Unclosed parenthesis."));
407 assert!(output.contains("Add ')' to close."));
408 }
409
410 #[test]
411 fn test_build_snippet_middle_of_file() {
412 let source = "line 1\nline 2\nline 3\nline 4\nline 5";
413 let snippet = Diagnostic::build_snippet(source, 3, Some(4)).unwrap();
414 assert!(snippet.contains("line 2")); assert!(snippet.contains("line 3")); assert!(snippet.contains("line 4")); assert!(snippet.contains("^")); }
419
420 #[test]
421 fn test_build_snippet_first_line() {
422 let source = "int x = foo(bar;\nint y = 10;";
423 let snippet = Diagnostic::build_snippet(source, 1, Some(16)).unwrap();
424 assert!(snippet.contains("int x = foo(bar;"));
425 assert!(snippet.contains("^"));
426 }
428
429 #[test]
430 fn test_build_snippet_last_line() {
431 let source = "int y = 10;\nint x = foo(bar;";
432 let snippet = Diagnostic::build_snippet(source, 2, Some(16)).unwrap();
433 assert!(snippet.contains("int x = foo(bar;"));
434 assert!(snippet.contains("^"));
435 }
437
438 #[test]
439 fn test_build_snippet_no_column() {
440 let source = "line 1\nline 2\nline 3";
441 let snippet = Diagnostic::build_snippet(source, 2, None).unwrap();
442 assert!(snippet.contains("line 2"));
443 assert!(!snippet.contains("^")); }
445
446 #[test]
447 fn test_build_snippet_out_of_bounds() {
448 let source = "line 1\nline 2";
449 assert!(Diagnostic::build_snippet(source, 99, Some(1)).is_none());
450 assert!(Diagnostic::build_snippet(source, 0, Some(1)).is_none());
451 }
452
453 #[test]
454 fn test_infer_note_expected_paren() {
455 let mut d = Diagnostic::new(Severity::Error, "expected ')'");
456 d.infer_note_and_help();
457 assert!(d.note.is_some());
458 assert!(d.help.is_some());
459 assert!(d.note.unwrap().contains("parenthesis"));
460 }
461
462 #[test]
463 fn test_infer_note_expected_semicolon() {
464 let mut d = Diagnostic::new(Severity::Error, "expected ';' after expression");
465 d.infer_note_and_help();
466 assert!(d.note.unwrap().contains("semicolon"));
467 }
468
469 #[test]
470 fn test_infer_note_undeclared() {
471 let mut d = Diagnostic::new(Severity::Error, "use of undeclared identifier 'foo'");
472 d.infer_note_and_help();
473 assert!(d.note.unwrap().contains("not declared"));
474 }
475
476 #[test]
477 fn test_infer_note_falls_back_to_fix_its() {
478 let mut d = Diagnostic::new(Severity::Error, "some unusual error");
479 d.fix_its = vec!["insert ';'".into()];
480 d.infer_note_and_help();
481 assert!(d.help.unwrap().contains("insert ';'"));
482 }
483
484 #[test]
485 fn test_diagnostic_error_display() {
486 let d1 = Diagnostic::new(Severity::Error, "first error");
487 let d2 = Diagnostic::new(Severity::Error, "second error");
488 let err = DiagnosticError::new(vec![d1, d2]);
489 let output = format!("{}", err);
490 assert!(output.contains("first error"));
491 assert!(output.contains("second error"));
492 assert!(output.contains("2 previous errors"));
493 }
494
495 #[test]
496 fn test_diagnostic_error_single() {
497 let d = Diagnostic::new(Severity::Error, "only error");
498 let err = DiagnosticError::new(vec![d]);
499 let output = format!("{}", err);
500 assert!(output.contains("1 previous error"));
501 assert!(!output.contains("1 previous errors"));
503 }
504
505 #[test]
506 fn test_diagnostic_error_is_std_error() {
507 let err: Box<dyn std::error::Error> =
508 Box::new(DiagnosticError::new(vec![Diagnostic::new(Severity::Error, "test")]));
509 assert!(!err.to_string().is_empty());
510 }
511
512 #[test]
513 fn test_warning_severity_display() {
514 let d = Diagnostic::new(Severity::Warning, "implicit conversion loses precision");
515 let output = format!("{}", d);
516 assert!(output.contains("warning"));
517 }
518}