Skip to main content

oxeon_diagnostics/
render.rs

1//! Terminal rendering of diagnostics in the style of rustc:
2//!
3//! ```text
4//! error: expected `;`, found `let`
5//!  --> mods/regen.ox:2:15
6//!   |
7//! 2 |     let x = 1 let y = 2;
8//!   |               ^^^
9//! ```
10
11use crate::{Diagnostic, Severity, Span, line_col};
12use std::fmt::Write;
13
14/// How to render a diagnostic.
15#[derive(Debug, Clone, Copy, Default)]
16pub struct RenderOptions {
17    /// Use ANSI colors.
18    pub color: bool,
19}
20
21const TAB_WIDTH: usize = 4;
22
23struct Style {
24    on: bool,
25}
26
27impl Style {
28    fn paint(&self, code: &str, text: &str) -> String {
29        if self.on {
30            format!("\x1b[{code}m{text}\x1b[0m")
31        } else {
32            text.to_owned()
33        }
34    }
35}
36
37fn severity_color(severity: Severity) -> &'static str {
38    match severity {
39        Severity::Error => "1;31",
40        Severity::Warning => "1;33",
41        Severity::Note => "1;36",
42    }
43}
44
45const GUTTER: &str = "1;34";
46const BOLD: &str = "1";
47
48/// One underlined region.
49struct Mark<'a> {
50    line: usize,
51    /// Display columns (0-based), tabs expanded.
52    start_col: usize,
53    width: usize,
54    primary: bool,
55    message: Option<&'a str>,
56}
57
58/// The text of 1-based `line`, without its newline.
59fn line_text(source: &str, line: usize) -> &str {
60    source
61        .split('\n')
62        .nth(line - 1)
63        .unwrap_or("")
64        .trim_end_matches('\r')
65}
66
67fn display_width(text: &str) -> usize {
68    text.chars()
69        .map(|c| if c == '\t' { TAB_WIDTH } else { 1 })
70        .sum()
71}
72
73fn expand_tabs(text: &str) -> String {
74    text.replace('\t', &" ".repeat(TAB_WIDTH))
75}
76
77fn mark<'a>(source: &str, span: Span, primary: bool, message: Option<&'a str>) -> Mark<'a> {
78    let start = (span.start as usize).min(source.len());
79    let end = (span.end as usize).clamp(start, source.len());
80    let (line, _) = line_col(source, start as u32);
81    let line_start = source[..start].rfind('\n').map_or(0, |i| i + 1);
82    let line_end = source[start..]
83        .find('\n')
84        .map_or(source.len(), |i| start + i);
85    let start_col = display_width(&source[line_start..start]);
86    // Spans running past the end of the line are underlined to the line's end.
87    let width = display_width(&source[start..end.min(line_end)]).max(1);
88    Mark {
89        line,
90        start_col,
91        width,
92        primary,
93        message,
94    }
95}
96
97impl Diagnostic {
98    /// Renders the diagnostic with the source lines it points at.
99    pub fn render(&self, file_name: &str, source: &str, options: RenderOptions) -> String {
100        let style = Style { on: options.color };
101        let sev = severity_color(self.severity);
102
103        let mut marks = vec![mark(source, self.span, true, None)];
104        marks.extend(
105            self.labels
106                .iter()
107                .map(|l| mark(source, l.span, false, Some(&l.message))),
108        );
109        marks.sort_by_key(|m| (m.line, !m.primary, m.start_col));
110
111        let max_line = marks.iter().map(|m| m.line).max().unwrap_or(1);
112        let pad = " ".repeat(max_line.to_string().len());
113        let bar = style.paint(GUTTER, "|");
114
115        let mut out = String::new();
116        let _ = writeln!(
117            out,
118            "{}{}",
119            style.paint(sev, &self.severity.to_string()),
120            style.paint(BOLD, &format!(": {}", self.message))
121        );
122        let (line, col) = line_col(source, self.span.start);
123        let _ = writeln!(
124            out,
125            "{pad}{} {file_name}:{line}:{col}",
126            style.paint(GUTTER, "-->")
127        );
128        let _ = writeln!(out, "{pad} {bar}");
129
130        let mut previous_line: Option<usize> = None;
131        for m in &marks {
132            if previous_line != Some(m.line) {
133                if previous_line.is_some_and(|p| m.line > p + 1) {
134                    let _ = writeln!(out, "{}", style.paint(GUTTER, "..."));
135                }
136                let number = style.paint(GUTTER, &format!("{:>width$}", m.line, width = pad.len()));
137                let text = expand_tabs(line_text(source, m.line));
138                if text.is_empty() {
139                    let _ = writeln!(out, "{number} {bar}");
140                } else {
141                    let _ = writeln!(out, "{number} {bar} {text}");
142                }
143                previous_line = Some(m.line);
144            }
145            let (symbol, color) = if m.primary { ("^", sev) } else { ("-", GUTTER) };
146            let underline = style.paint(color, &symbol.repeat(m.width));
147            let message = m
148                .message
149                .map(|msg| format!(" {}", style.paint(color, msg)))
150                .unwrap_or_default();
151            let _ = writeln!(
152                out,
153                "{pad} {bar} {}{underline}{message}",
154                " ".repeat(m.start_col)
155            );
156        }
157
158        if !self.notes.is_empty() || !self.help.is_empty() {
159            let _ = writeln!(out, "{pad} {bar}");
160            let lines = self
161                .notes
162                .iter()
163                .map(|n| ("note", n))
164                .chain(self.help.iter().map(|h| ("help", h)));
165            for (kind, text) in lines {
166                let _ = writeln!(
167                    out,
168                    "{pad} {} {}: {text}",
169                    style.paint(GUTTER, "="),
170                    style.paint(BOLD, kind)
171                );
172            }
173        }
174        out
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    fn plain(d: &Diagnostic, src: &str) -> String {
183        d.render("test.ox", src, RenderOptions { color: false })
184    }
185
186    #[test]
187    fn underlines_the_span() {
188        let src = "fn main() {\n    let x = 1 let y = 2;\n}\n";
189        let start = src.find("let y").unwrap() as u32;
190        let d = Diagnostic::error("expected `;`, found `let`", Span::new(start, start + 3));
191        assert_eq!(
192            plain(&d, src),
193            "error: expected `;`, found `let`\n \
194             --> test.ox:2:15\n  \
195             |\n\
196             2 |     let x = 1 let y = 2;\n  \
197             |               ^^^\n"
198        );
199    }
200
201    #[test]
202    fn labels_notes_and_line_gaps() {
203        let src = "struct S;\n\nfn f() {}\n\n\n\nstruct S;\n";
204        let second = src.rfind("S;").unwrap() as u32;
205        let d = Diagnostic::error("`S` is defined twice", Span::new(second, second + 1))
206            .with_label(Span::new(7, 8), "first defined here")
207            .with_note("names must be unique within a module")
208            .with_help("rename one of them");
209        assert_eq!(
210            plain(&d, src),
211            "error: `S` is defined twice\n \
212             --> test.ox:7:8\n  \
213             |\n\
214             1 | struct S;\n  \
215             |        - first defined here\n\
216             ...\n\
217             7 | struct S;\n  \
218             |        ^\n  \
219             |\n  \
220             = note: names must be unique within a module\n  \
221             = help: rename one of them\n"
222        );
223    }
224
225    #[test]
226    fn empty_span_at_end_of_file() {
227        let src = "fn f() {";
228        let d = Diagnostic::error("unclosed delimiter", Span::new(8, 8));
229        assert!(
230            plain(&d, src).ends_with("1 | fn f() {\n  |         ^\n"),
231            "{}",
232            plain(&d, src)
233        );
234    }
235
236    #[test]
237    fn tabs_are_expanded_consistently() {
238        let src = "\tlet x = ;";
239        let start = src.find(';').unwrap() as u32;
240        let d = Diagnostic::error("expected expression", Span::new(start, start + 1));
241        let out = plain(&d, src);
242        assert!(
243            out.contains("1 |     let x = ;\n  |             ^\n"),
244            "{out}"
245        );
246    }
247
248    #[test]
249    fn spans_past_the_line_end_stop_at_the_line() {
250        let src = "let s = \"abc\ndef\";";
251        let d = Diagnostic::error("bad string", Span::new(8, src.len() as u32));
252        assert!(plain(&d, src).contains("1 | let s = \"abc\n  |         ^^^^\n"));
253    }
254
255    #[test]
256    fn color_wraps_parts_in_ansi_codes() {
257        let d = Diagnostic::error("oops", Span::new(0, 1));
258        let out = d.render("t.ox", "x", RenderOptions { color: true });
259        assert!(out.starts_with("\x1b[1;31merror\x1b[0m"));
260        assert!(out.contains("\x1b[1;31m^\x1b[0m"));
261    }
262}