Skip to main content

oxeon_diagnostics/
lib.rs

1//! Source spans and diagnostics shared by every stage of the Oxeon compiler.
2//!
3//! [`Diagnostic::render`] prints a diagnostic with the source lines it points
4//! at, rustc-style; [`Diagnostic::render_plain`] gives a one-line summary.
5
6mod render;
7
8pub use render::RenderOptions;
9
10use std::fmt;
11use std::ops::Range;
12
13/// A byte range in a single source file.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
15pub struct Span {
16    pub start: u32,
17    pub end: u32,
18}
19
20impl Span {
21    pub const fn new(start: u32, end: u32) -> Self {
22        Self { start, end }
23    }
24
25    pub const fn len(self) -> u32 {
26        self.end - self.start
27    }
28
29    pub const fn is_empty(self) -> bool {
30        self.start == self.end
31    }
32
33    /// The smallest span covering both `self` and `other`.
34    pub fn to(self, other: Span) -> Span {
35        Span::new(self.start.min(other.start), self.end.max(other.end))
36    }
37
38    pub fn range(self) -> Range<usize> {
39        self.start as usize..self.end as usize
40    }
41}
42
43impl From<Range<usize>> for Span {
44    fn from(range: Range<usize>) -> Self {
45        let start = u32::try_from(range.start).expect("source files are limited to 4 GiB");
46        let end = u32::try_from(range.end).expect("source files are limited to 4 GiB");
47        Span::new(start, end)
48    }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Severity {
53    Error,
54    Warning,
55    Note,
56}
57
58impl fmt::Display for Severity {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.write_str(match self {
61            Severity::Error => "error",
62            Severity::Warning => "warning",
63            Severity::Note => "note",
64        })
65    }
66}
67
68/// A secondary location attached to a diagnostic.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct Label {
71    pub span: Span,
72    pub message: String,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct Diagnostic {
77    pub severity: Severity,
78    pub message: String,
79    pub span: Span,
80    pub labels: Vec<Label>,
81    pub notes: Vec<String>,
82    /// Suggestions for fixing the problem, shown as `= help: ...`.
83    pub help: Vec<String>,
84    /// A stable identifier for the kind of problem, e.g. `unused_variables`.
85    pub code: Option<&'static str>,
86    /// Edits an editor can apply to fix the problem.
87    pub fixes: Vec<Fix>,
88}
89
90/// A machine-applicable fix: a set of text replacements.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct Fix {
93    pub title: String,
94    pub edits: Vec<Edit>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct Edit {
99    /// The text to replace; empty to insert at `span.start`.
100    pub span: Span,
101    pub text: String,
102}
103
104impl Diagnostic {
105    pub fn error(message: impl Into<String>, span: Span) -> Self {
106        Self::new(Severity::Error, message, span)
107    }
108
109    pub fn warning(message: impl Into<String>, span: Span) -> Self {
110        Self::new(Severity::Warning, message, span)
111    }
112
113    pub fn note(message: impl Into<String>, span: Span) -> Self {
114        Self::new(Severity::Note, message, span)
115    }
116
117    fn new(severity: Severity, message: impl Into<String>, span: Span) -> Self {
118        Self {
119            severity,
120            message: message.into(),
121            span,
122            labels: Vec::new(),
123            notes: Vec::new(),
124            help: Vec::new(),
125            code: None,
126            fixes: Vec::new(),
127        }
128    }
129
130    pub fn with_label(mut self, span: Span, message: impl Into<String>) -> Self {
131        self.labels.push(Label {
132            span,
133            message: message.into(),
134        });
135        self
136    }
137
138    pub fn with_note(mut self, note: impl Into<String>) -> Self {
139        self.notes.push(note.into());
140        self
141    }
142
143    pub fn with_help(mut self, help: impl Into<String>) -> Self {
144        self.help.push(help.into());
145        self
146    }
147
148    pub fn with_code(mut self, code: &'static str) -> Self {
149        self.code = Some(code);
150        self
151    }
152
153    /// Adds a fix that replaces `span` with `text`.
154    pub fn with_fix(
155        mut self,
156        title: impl Into<String>,
157        span: Span,
158        text: impl Into<String>,
159    ) -> Self {
160        self.fixes.push(Fix {
161            title: title.into(),
162            edits: vec![Edit {
163                span,
164                text: text.into(),
165            }],
166        });
167        self
168    }
169
170    /// Plain one-line rendering: `file:line:col: error: message`.
171    pub fn render_plain(&self, file_name: &str, source: &str) -> String {
172        let (line, col) = line_col(source, self.span.start);
173        let mut out = format!(
174            "{file_name}:{line}:{col}: {}: {}",
175            self.severity, self.message
176        );
177        for label in &self.labels {
178            let (line, col) = line_col(source, label.span.start);
179            out.push_str(&format!("\n  {file_name}:{line}:{col}: {}", label.message));
180        }
181        for note in &self.notes {
182            out.push_str(&format!("\n  note: {note}"));
183        }
184        for help in &self.help {
185            out.push_str(&format!("\n  help: {help}"));
186        }
187        out
188    }
189}
190
191/// 1-based line and column (in chars) of a byte offset.
192pub fn line_col(source: &str, offset: u32) -> (usize, usize) {
193    let offset = (offset as usize).min(source.len());
194    let before = &source[..offset];
195    let line = before.matches('\n').count() + 1;
196    let line_start = before.rfind('\n').map_or(0, |i| i + 1);
197    let col = before[line_start..].chars().count() + 1;
198    (line, col)
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn line_col_counts_from_one() {
207        let src = "fn a() {}\nfn b() {}";
208        assert_eq!(line_col(src, 0), (1, 1));
209        assert_eq!(line_col(src, 10), (2, 1));
210        assert_eq!(line_col(src, 13), (2, 4));
211    }
212
213    #[test]
214    fn span_to_covers_both() {
215        assert_eq!(Span::new(4, 6).to(Span::new(1, 3)), Span::new(1, 6));
216    }
217}