1use std::cell::RefCell;
2
3use crate::span::{Span, Spanned};
4
5thread_local! {
6 pub static DIAGNOSTICS: RefCell<Vec<Diag>> = RefCell::default();
7}
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10pub enum Level {
11 Info,
12 Warning,
13 Error,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17#[must_use]
18pub struct Diag {
19 pub level: Level,
20 pub text: Spanned<String>,
21 pub notes: Vec<Spanned<String>>,
22}
23
24impl Diag {
25 pub fn new(level: Level, span: Span, text: impl ToString) -> Diag {
26 Diag { level, text: Spanned(span, text.to_string()), notes: Vec::new() }
27 }
28
29 pub fn error(span: Span, text: impl ToString) -> Diag {
30 Self::new(Level::Error, span, text)
31 }
32
33 pub fn warn(span: Span, text: impl ToString) -> Diag {
34 Self::new(Level::Warning, span, text)
35 }
36
37 pub fn info(span: Span, text: impl ToString) -> Diag {
38 Self::new(Level::Info, span, text)
39 }
40
41 pub fn note(mut self, span: Span, text: impl ToString) -> Diag {
42 self.notes.push(Spanned(span, text.to_string()));
43 self
44 }
45
46 pub fn emit(self) {
47 DIAGNOSTICS.with(|d| d.borrow_mut().push(self));
48 }
49
50 pub fn is_fatal(&self) -> bool {
51 self.level >= Level::Error
52 }
53}
54
55pub fn diagnose<A>(f: impl FnOnce() -> A) -> (A, Vec<Diag>) {
58 let prev = DIAGNOSTICS.with(|a| a.take());
59 let v = f();
60 let diag = DIAGNOSTICS.with(|a| a.replace(prev));
61 (v, diag)
62}
63
64#[cfg(test)]
65pub fn print_diags(filename: &str, source: &str, diags: &[Diag]) {
66 use codespan_reporting::diagnostic::{Diagnostic, Label};
67 use codespan_reporting::files::SimpleFiles;
68 use codespan_reporting::term::termcolor::{ColorChoice, StandardStream};
69
70 let writer = StandardStream::stderr(ColorChoice::Always);
71 let config = codespan_reporting::term::Config::default();
72 let mut files = SimpleFiles::new();
73 let file_id = files.add(filename, source);
74
75 let mut diags = diags.to_owned();
76 diags.sort_by_key(|a| (a.text.0.start, a.text.0.end));
77
78 for d in diags {
79 let mut l = vec![
80 Label::primary(file_id, d.text.0.as_range()).with_message(&d.text.1),
81 ];
82 for n in &d.notes {
83 l.push(Label::secondary(file_id, n.0.as_range()).with_message(&n.1));
84 }
85 let d = match d.level {
86 Level::Error => Diagnostic::error(),
87 Level::Warning => Diagnostic::warning(),
88 Level::Info => Diagnostic::help(),
89 };
90 let d = d.with_labels(l);
91 codespan_reporting::term::emit(&mut writer.lock(), &config, &files, &d).unwrap();
92 }
93}