Skip to main content

next_rust_core/
diagnostic.rs

1//! Structured diagnostics.
2//!
3//! Every user-facing error produced by scanning, validation or builds is a
4//! [`Diagnostic`] with a stable code (e.g. `NR0102`), a one-line title, an
5//! explanation, the source locations involved and an actionable hint.
6
7use std::fmt;
8use std::path::PathBuf;
9
10use serde::{Deserialize, Serialize};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum Severity {
15    Warning,
16    Error,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Diagnostic {
21    pub severity: Severity,
22    pub code: String,
23    pub title: String,
24    /// Longer explanation; may span multiple lines.
25    pub message: String,
26    /// Files involved, in the order they are relevant.
27    pub locations: Vec<PathBuf>,
28    pub help: Option<String>,
29}
30
31impl Diagnostic {
32    pub fn error(code: &str, title: impl Into<String>) -> Self {
33        Self::new(Severity::Error, code, title)
34    }
35
36    pub fn warning(code: &str, title: impl Into<String>) -> Self {
37        Self::new(Severity::Warning, code, title)
38    }
39
40    fn new(severity: Severity, code: &str, title: impl Into<String>) -> Self {
41        Self {
42            severity,
43            code: code.to_owned(),
44            title: title.into(),
45            message: String::new(),
46            locations: Vec::new(),
47            help: None,
48        }
49    }
50
51    pub fn message(mut self, message: impl Into<String>) -> Self {
52        self.message = message.into();
53        self
54    }
55
56    pub fn location(mut self, path: impl Into<PathBuf>) -> Self {
57        self.locations.push(path.into());
58        self
59    }
60
61    pub fn help(mut self, help: impl Into<String>) -> Self {
62        self.help = Some(help.into());
63        self
64    }
65
66    pub fn is_error(&self) -> bool {
67        self.severity == Severity::Error
68    }
69
70    /// Render with ANSI colours.
71    pub fn render(&self, color: bool) -> String {
72        let (red, yellow, bold, dim, cyan, reset) = if color {
73            ("\x1b[31m", "\x1b[33m", "\x1b[1m", "\x1b[2m", "\x1b[36m", "\x1b[0m")
74        } else {
75            ("", "", "", "", "", "")
76        };
77        let (label, col) = match self.severity {
78            Severity::Error => ("error", red),
79            Severity::Warning => ("warning", yellow),
80        };
81        let mut out = format!("{col}{bold}{label}[{}]{reset}{bold}: {}{reset}\n", self.code, self.title);
82        for loc in &self.locations {
83            out.push_str(&format!("  {cyan}-->{reset} {}\n", loc.display()));
84        }
85        if !self.message.is_empty() {
86            out.push('\n');
87            for line in self.message.lines() {
88                out.push_str("  ");
89                out.push_str(line);
90                out.push('\n');
91            }
92        }
93        if let Some(help) = &self.help {
94            out.push_str(&format!("\n  {dim}help:{reset} {help}\n"));
95        }
96        out
97    }
98}
99
100impl fmt::Display for Diagnostic {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        f.write_str(&self.render(false))
103    }
104}
105
106impl std::error::Error for Diagnostic {}
107
108/// A collection of diagnostics.
109#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
110pub struct Diagnostics(pub Vec<Diagnostic>);
111
112impl Diagnostics {
113    pub fn push(&mut self, d: Diagnostic) {
114        self.0.push(d);
115    }
116
117    pub fn has_errors(&self) -> bool {
118        self.0.iter().any(Diagnostic::is_error)
119    }
120
121    pub fn errors(&self) -> impl Iterator<Item = &Diagnostic> {
122        self.0.iter().filter(|d| d.is_error())
123    }
124
125    pub fn warnings(&self) -> impl Iterator<Item = &Diagnostic> {
126        self.0.iter().filter(|d| !d.is_error())
127    }
128
129    pub fn is_empty(&self) -> bool {
130        self.0.is_empty()
131    }
132
133    pub fn len(&self) -> usize {
134        self.0.len()
135    }
136
137    pub fn iter(&self) -> std::slice::Iter<'_, Diagnostic> {
138        self.0.iter()
139    }
140
141    pub fn render(&self, color: bool) -> String {
142        self.0.iter().map(|d| d.render(color)).collect::<Vec<_>>().join("\n")
143    }
144}
145
146impl fmt::Display for Diagnostics {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        f.write_str(&self.render(false))
149    }
150}
151
152impl std::error::Error for Diagnostics {}
153
154impl IntoIterator for Diagnostics {
155    type Item = Diagnostic;
156    type IntoIter = std::vec::IntoIter<Diagnostic>;
157    fn into_iter(self) -> Self::IntoIter {
158        self.0.into_iter()
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn renders() {
168        let d = Diagnostic::error("NR0001", "Route conflict detected")
169            .location("app/users/settings/page.rs")
170            .message("Static route:\n    /users/settings")
171            .help("rename one of the directories");
172        let s = d.render(false);
173        assert!(s.starts_with("error[NR0001]: Route conflict detected\n"));
174        assert!(s.contains("--> app/users/settings/page.rs"));
175        assert!(s.contains("    /users/settings"));
176        assert!(s.contains("help: rename"));
177    }
178}