Skip to main content

parsec_base/
render.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! [`Diagnostic::render`]: a diagnostic as a code frame, the lines it
5//! points at with a gutter of line numbers and carets under the place.
6
7use std::fmt::Write;
8
9use crate::{Diagnostic, LineIndex};
10
11/// How [`Diagnostic::render`] lays a code frame out.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13pub struct RenderOptions<'a> {
14    /// A name for the source, like a file's path, shown before the line
15    /// and column.
16    pub path: Option<&'a str>,
17    /// A tab moves to the next multiple of this many columns.
18    pub tab_width: u32,
19    /// The most columns of a line shown. A longer line, like a minified
20    /// script's, is cut to a window around what's marked on it, with `…`
21    /// where it's cut.
22    pub max_width: u32,
23}
24
25impl Default for RenderOptions<'_> {
26    fn default() -> Self {
27        RenderOptions {
28            path: None,
29            tab_width: 4,
30            max_width: 100,
31        }
32    }
33}
34
35/// A place to underline on one line: bytes `start..end` of the source.
36struct Mark<'d> {
37    line: u32,
38    start: usize,
39    end: usize,
40    primary: bool,
41    message: Option<&'d str>,
42}
43
44/// A line laid out in columns: each character's byte offset in the line,
45/// its column and what's shown for it.
46struct Laid {
47    cells: Vec<(usize, u32, u32)>,
48    shown: Vec<String>,
49    width: u32,
50}
51
52impl Laid {
53    fn new(text: &str, tab_width: u32) -> Laid {
54        let tab_width = tab_width.max(1);
55        let (mut cells, mut shown) = (Vec::new(), Vec::new());
56        let mut col = 0;
57        for (i, c) in text.char_indices() {
58            let (w, s) = if c == '\t' {
59                let w = tab_width - col % tab_width;
60                (w, " ".repeat(w as usize))
61            } else if is_hidden(c) {
62                // Control characters and bidirectional overrides would act
63                // on the terminal, or reorder the line, rather than show.
64                (1, "\u{FFFD}".into())
65            } else {
66                (char_width(c), c.to_string())
67            };
68            cells.push((i, col, w));
69            shown.push(s);
70            col += w;
71        }
72        Laid {
73            cells,
74            shown,
75            width: col,
76        }
77    }
78
79    /// The column byte `offset` of the line starts at; inside a character
80    /// counts as after it.
81    fn col(&self, offset: usize) -> u32 {
82        let i = self.cells.partition_point(|&(b, ..)| b < offset);
83        self.cells.get(i).map_or(self.width, |&(_, c, _)| c)
84    }
85}
86
87/// Characters a code frame shouldn't print as they are.
88fn is_hidden(c: char) -> bool {
89    c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
90}
91
92/// Columns a character takes in a terminal: East Asian wide and
93/// fullwidth characters and most emoji take two, combining marks and
94/// joiners none, the rest one.
95///
96/// shortcut: a few ranges, not Unicode's EastAsianWidth table, so some
97/// rare characters are measured wrong; use the table if one matters.
98fn char_width(c: char) -> u32 {
99    match c as u32 {
100        0x0300..=0x036F
101        | 0x1AB0..=0x1AFF
102        | 0x1DC0..=0x1DFF
103        | 0x200B..=0x200F
104        | 0x2060..=0x2064
105        | 0x20D0..=0x20FF
106        | 0xFE00..=0xFE0F
107        | 0xFE20..=0xFE2F
108        | 0xFEFF
109        | 0xE0100..=0xE01EF => 0,
110        0x1100..=0x115F
111        | 0x2E80..=0x303E
112        | 0x3041..=0x33FF
113        | 0x3400..=0x4DBF
114        | 0x4E00..=0x9FFF
115        | 0xA000..=0xA4CF
116        | 0xAC00..=0xD7A3
117        | 0xF900..=0xFAFF
118        | 0xFE30..=0xFE4F
119        | 0xFF00..=0xFF60
120        | 0xFFE0..=0xFFE6
121        | 0x1F300..=0x1F64F
122        | 0x1F680..=0x1F6FF
123        | 0x1F900..=0x1F9FF
124        | 0x1FA70..=0x1FAFF
125        | 0x20000..=0x2FFFD
126        | 0x30000..=0x3FFFD => 2,
127        _ => 1,
128    }
129}
130
131impl Diagnostic {
132    /// The diagnostic as a code frame: a header with its severity, code
133    /// and message, where it is, and each line it or a label points at,
134    /// carets under its own span and dashes under each label's.
135    ///
136    /// `lines` is an index of `src`. Columns are counted as a terminal
137    /// shows them: tabs expanded, and East Asian wide characters two
138    /// columns.
139    ///
140    /// ```
141    /// use parsec_base::{Diagnostic, LineIndex, RenderOptions, Span};
142    ///
143    /// let src = "if (ready {\n  go();\n}\n";
144    /// let d = Diagnostic::error("unexpected-token", Span::new(10, 11), "`{` can't go here")
145    ///     .with_label(Span::new(3, 4), "this `(` is still open");
146    /// let frame = d.render(src, &LineIndex::new(src), &RenderOptions::default());
147    /// assert_eq!(frame, "\
148    /// error[unexpected-token]: `{` can't go here
149    ///  --> 1:11
150    ///   |
151    /// 1 | if (ready {
152    ///   |    -      ^
153    ///   |    |
154    ///   |    this `(` is still open
155    /// ");
156    /// ```
157    pub fn render(&self, src: &str, lines: &LineIndex<'_>, options: &RenderOptions<'_>) -> String {
158        let mut marks = Vec::new();
159        push_marks(&mut marks, src, lines, self.span, true, None);
160        for l in &self.labels {
161            push_marks(&mut marks, src, lines, l.span, false, Some(&l.message));
162        }
163        let mut shown: Vec<u32> = marks.iter().map(|m| m.line).collect();
164        shown.sort_unstable();
165        shown.dedup();
166        // A single line between two shown ones is shown too; it's no
167        // longer than the `...` that would stand for it.
168        let mut all = Vec::with_capacity(shown.len());
169        for (i, &l) in shown.iter().enumerate() {
170            if i > 0 && l == shown[i - 1] + 2 {
171                all.push(l - 1);
172            }
173            all.push(l);
174        }
175        let gutter = all.last().map_or(1, |l| l.to_string().len());
176        let pad = " ".repeat(gutter);
177
178        let mut out = String::new();
179        let _ = writeln!(out, "{}[{}]: {}", self.severity, self.code, self.message);
180        let at = lines.line_col(self.span.start.min(src.len() as u32));
181        match options.path {
182            Some(p) => {
183                let _ = writeln!(out, "{pad}--> {p}:{at}");
184            }
185            None => {
186                let _ = writeln!(out, "{pad}--> {at}");
187            }
188        }
189        let _ = writeln!(out, "{pad} |");
190        for (i, &line) in all.iter().enumerate() {
191            if i > 0 && line > all[i - 1] + 1 {
192                out.push_str("...\n");
193            }
194            let (start, text) = line_text(src, lines, line);
195            let laid = Laid::new(text, options.tab_width);
196            let mut on: Vec<&Mark> = marks.iter().filter(|m| m.line == line).collect();
197            on.sort_by_key(|m| (m.start, !m.primary));
198            // Each mark's columns, start and end, on the line.
199            let cols: Vec<(u32, u32)> = on
200                .iter()
201                .map(|m| {
202                    let a = laid.col(m.start - start);
203                    (a, laid.col(m.end - start).max(a + 1))
204                })
205                .collect();
206            let (body, shift, lo, hi) = window(&laid, &cols, options.max_width);
207            let _ = writeln!(out, "{line:>gutter$} | {body}");
208            if on.is_empty() {
209                continue;
210            }
211            // Columns in the shown line, clipped to the window.
212            let place = |c: u32| c.clamp(lo, hi) - lo + shift;
213            let spans: Vec<(u32, u32)> = cols
214                .iter()
215                .map(|&(a, b)| (place(a), place(b).max(place(a) + 1)))
216                .collect();
217            let mut row: Vec<char> = Vec::new();
218            for primary in [false, true] {
219                for (m, &(a, b)) in on.iter().zip(&spans) {
220                    if m.primary != primary {
221                        continue;
222                    }
223                    let fill = if primary { '^' } else { '-' };
224                    if row.len() < b as usize {
225                        row.resize(b as usize, ' ');
226                    }
227                    for c in &mut row[a as usize..b as usize] {
228                        *c = fill;
229                    }
230                }
231            }
232            let mut first: String = row.into_iter().collect();
233            // The rightmost mark's message goes on the underline; the
234            // others hang below, rightmost first.
235            let mut hanging: Vec<usize> =
236                (0..on.len()).filter(|&k| on[k].message.is_some()).collect();
237            let last = (0..on.len()).max_by_key(|&k| (spans[k].0, k));
238            if let Some(k) = last.filter(|&k| hanging.last() == Some(&k)) {
239                let _ = write!(first, " {}", on[k].message.unwrap_or(""));
240                hanging.pop();
241            }
242            let _ = writeln!(out, "{pad} | {}", first.trim_end());
243            while let Some(k) = hanging.pop() {
244                let left: Vec<u32> = hanging.iter().map(|&j| spans[j].0).collect();
245                let mut both = left.clone();
246                both.push(spans[k].0);
247                let _ = writeln!(out, "{pad} | {}", pipes(&both, None));
248                let _ = writeln!(
249                    out,
250                    "{pad} | {}",
251                    pipes(&left, Some((spans[k].0, on[k].message.unwrap_or(""))))
252                );
253            }
254        }
255        out
256    }
257}
258
259/// A `|` at each of `cols`, and a message starting at a column.
260fn pipes(cols: &[u32], message: Option<(u32, &str)>) -> String {
261    let mut r: Vec<char> = Vec::new();
262    for &c in cols {
263        if r.len() <= c as usize {
264            r.resize(c as usize + 1, ' ');
265        }
266        r[c as usize] = '|';
267    }
268    let mut s: String = r.into_iter().collect();
269    if let Some((c, m)) = message {
270        let w = s.chars().count();
271        s.push_str(&" ".repeat((c as usize).saturating_sub(w)));
272        s.push_str(m);
273    }
274    s
275}
276
277/// The marks for `span`: one on its line, or for a span over several
278/// lines, one at its start and one at its end, which has the message.
279fn push_marks<'d>(
280    marks: &mut Vec<Mark<'d>>,
281    src: &str,
282    lines: &LineIndex<'_>,
283    span: crate::Span,
284    primary: bool,
285    message: Option<&'d str>,
286) {
287    let start = (span.start as usize).min(src.len());
288    let end = (span.end as usize).clamp(start, src.len());
289    let first = lines.line(start as u32);
290    // A span that ends with a line terminator ends on that line.
291    let last = lines.line(end.saturating_sub(1).max(start) as u32);
292    if first == last {
293        marks.push(Mark {
294            line: first,
295            start,
296            end,
297            primary,
298            message,
299        });
300        return;
301    }
302    let (s, text) = line_text(src, lines, first);
303    marks.push(Mark {
304        line: first,
305        start,
306        end: s + text.len(),
307        primary,
308        message: None,
309    });
310    let (s, _) = line_text(src, lines, last);
311    marks.push(Mark {
312        line: last,
313        start: s,
314        end,
315        primary,
316        message,
317    });
318}
319
320/// Where line `line` starts, and its text without its terminator.
321fn line_text<'s>(src: &'s str, lines: &LineIndex<'_>, line: u32) -> (usize, &'s str) {
322    let start = lines.line_start(line).map_or(src.len(), |s| s as usize);
323    let end = lines.line_start(line + 1).map_or(src.len(), |s| s as usize);
324    let text = src.get(start..end).unwrap_or("");
325    let text = text
326        .strip_suffix("\r\n")
327        .or_else(|| text.strip_suffix(['\n', '\r', '\u{2028}', '\u{2029}']))
328        .unwrap_or(text);
329    (start, text)
330}
331
332/// The line as shown, cut to `max` columns around the marks if it's
333/// longer: the text, the columns a leading `…` adds, and the window of
334/// the line's columns shown.
335fn window(laid: &Laid, cols: &[(u32, u32)], max: u32) -> (String, u32, u32, u32) {
336    let all = |laid: &Laid| laid.shown.concat();
337    if laid.width <= max || max < 3 {
338        return (all(laid), 0, 0, laid.width.max(1) + 1);
339    }
340    let inner = max - 2;
341    let lo_m = cols.iter().map(|c| c.0).min().unwrap_or(0);
342    let hi_m = cols.iter().map(|c| c.1).max().unwrap_or(0);
343    // Every mark if they fit, or else the first.
344    let (a, b) = if hi_m - lo_m <= inner {
345        (lo_m, hi_m)
346    } else {
347        cols.first().map_or((0, 1), |&(a, _)| (a, a + 1))
348    };
349    let centre = (a + b) / 2;
350    let lo = centre.saturating_sub(inner / 2).min(laid.width - inner);
351    let hi = lo + inner;
352    let mut s = String::new();
353    if lo > 0 {
354        s.push('…');
355    }
356    for (k, &(_, c, w)) in laid.cells.iter().enumerate() {
357        if c >= lo && c + w <= hi {
358            s.push_str(&laid.shown[k]);
359        }
360    }
361    if hi < laid.width {
362        s.push('…');
363    }
364    (s, u32::from(lo > 0), lo, hi)
365}
366
367#[cfg(test)]
368mod tests {
369    use crate::{Diagnostic, LineIndex, RenderOptions, Span};
370
371    fn render(src: &str, d: &Diagnostic) -> String {
372        d.render(src, &LineIndex::new(src), &RenderOptions::default())
373    }
374
375    #[test]
376    fn caret_under_the_span() {
377        let src = "let x = ;\n";
378        let d = Diagnostic::error("unexpected-token", Span::new(8, 9), "`;` can't go here");
379        assert_eq!(
380            render(src, &d),
381            "error[unexpected-token]: `;` can't go here\n --> 1:9\n  |\n1 | let x = ;\n  |         ^\n"
382        );
383    }
384
385    #[test]
386    fn path_and_warning() {
387        let src = "a";
388        let d = Diagnostic::warning("odd", Span::new(0, 1), "odd");
389        let o = RenderOptions {
390            path: Some("src/app.js"),
391            ..RenderOptions::default()
392        };
393        assert_eq!(
394            d.render(src, &LineIndex::new(src), &o),
395            "warning[odd]: odd\n --> src/app.js:1:1\n  |\n1 | a\n  | ^\n"
396        );
397    }
398
399    #[test]
400    fn empty_span_and_end_of_input() {
401        // An empty span, at the end, gets one caret after the last
402        // character.
403        let src = "f(a, b";
404        let d = Diagnostic::error("unexpected-end", Span::at(6), "the input ends")
405            .with_label(Span::new(1, 2), "this `(` is still open");
406        assert_eq!(
407            render(src, &d),
408            "error[unexpected-end]: the input ends\n --> 1:7\n  |\n1 | f(a, b\n  |  -    ^\n  |  |\n  |  this `(` is still open\n"
409        );
410    }
411
412    #[test]
413    fn labels_on_other_lines() {
414        let src = "let a = 1;\nlet b;\nlet c;\nlet d;\nlet a = 2;\n";
415        let d = Diagnostic::error(
416            "duplicate-declaration",
417            Span::new(36, 37),
418            "`a` is declared twice",
419        )
420        .with_label(Span::new(4, 5), "declared here first");
421        assert_eq!(
422            render(src, &d),
423            "error[duplicate-declaration]: `a` is declared twice\n --> 5:5\n  |\n1 | let a = 1;\n  |     - declared here first\n...\n5 | let a = 2;\n  |     ^\n"
424        );
425        // One line between is shown, not elided.
426        let src = "let a;\nx;\nlet a;\n";
427        let d = Diagnostic::error("dup", Span::new(14, 15), "twice")
428            .with_label(Span::new(4, 5), "first");
429        assert_eq!(
430            render(src, &d),
431            "error[dup]: twice\n --> 3:5\n  |\n1 | let a;\n  |     - first\n2 | x;\n3 | let a;\n  |     ^\n"
432        );
433    }
434
435    #[test]
436    fn rightmost_message_inline_others_hang() {
437        let src = "f(a, [b, c";
438        let d = Diagnostic::error("e", Span::at(10), "ends")
439            .with_label(Span::new(1, 2), "this `(` is still open")
440            .with_label(Span::new(5, 6), "this `[` is still open");
441        assert_eq!(
442            render(src, &d),
443            "error[e]: ends\n --> 1:11\n  |\n1 | f(a, [b, c\n  |  -   -    ^\n  |  |   |\n  |  |   this `[` is still open\n  |  |\n  |  this `(` is still open\n"
444        );
445        // A label right of the primary has its message on the underline.
446        let d =
447            Diagnostic::error("e", Span::new(0, 1), "here").with_label(Span::new(5, 6), "there");
448        assert!(render(src, &d).contains("  | ^    - there\n"));
449    }
450
451    #[test]
452    fn tabs_expand() {
453        let src = "\tx\t= ;";
454        let d = Diagnostic::error("e", Span::new(5, 6), "m");
455        // The tab to column 4, `x`, the tab to 8, `=` and a space.
456        assert!(render(src, &d).ends_with("1 |     x   = ;\n  |           ^\n"));
457        let o = RenderOptions {
458            tab_width: 2,
459            ..RenderOptions::default()
460        };
461        let out = d.render(src, &LineIndex::new(src), &o);
462        assert!(out.ends_with("1 |   x = ;\n  |       ^\n"), "{out}");
463    }
464
465    #[test]
466    fn wide_and_combining_characters() {
467        // 名前 is two columns a character; é as e and a combining accent
468        // is one.
469        let src = "let 名前 = e\u{301} +;";
470        let at = src.find(';').unwrap() as u32;
471        let d = Diagnostic::error("e", Span::new(at, at + 1), "m");
472        let out = render(src, &d);
473        assert!(out.contains(&format!("  | {}^\n", " ".repeat(14))), "{out}");
474        // A span over a wide character is two carets.
475        let d = Diagnostic::error("e", Span::new(4, 7), "m");
476        assert!(render(src, &d).contains("  |     ^^\n"));
477        // The column in the header is in characters.
478        assert!(out.contains(" --> 1:14\n"), "{out}");
479    }
480
481    #[test]
482    fn control_and_bidi_characters_are_replaced() {
483        let src = "a\u{1b}[2J\u{202E}b";
484        let d = Diagnostic::error("e", Span::new(0, 1), "m");
485        let out = render(src, &d);
486        assert!(!out.contains('\u{1b}') && !out.contains('\u{202E}'));
487        assert!(out.contains("1 | a\u{FFFD}[2J\u{FFFD}b\n"));
488    }
489
490    #[test]
491    fn long_lines_are_windowed() {
492        let src = format!("{}let x = ;{}", "a".repeat(500), "b".repeat(500));
493        let d = Diagnostic::error("e", Span::new(508, 509), "m");
494        let out = render(&src, &d);
495        let lines: Vec<&str> = out.lines().collect();
496        let body = lines[3].strip_prefix("1 | ").unwrap();
497        assert!(body.starts_with('…') && body.ends_with('…'), "{body}");
498        assert_eq!(body.chars().count(), 100);
499        assert!(body.contains("let x = ;"));
500        // The caret is still under the `;`.
501        let caret = lines[4].strip_prefix("  | ").unwrap();
502        let col = caret.find('^').unwrap();
503        assert_eq!(body.chars().nth(col), Some(';'));
504        // Near the start, nothing is cut there.
505        let d = Diagnostic::error("e", Span::new(2, 3), "m");
506        let out = render(&src, &d);
507        let body = out.lines().nth(3).unwrap().strip_prefix("1 | ").unwrap();
508        assert!(body.starts_with("aaa") && body.ends_with('…'));
509        assert!(out.lines().nth(4).unwrap().ends_with("  ^"));
510        // Marks too far apart to share a window: it's around the first.
511        let d = Diagnostic::error("e", Span::new(990, 991), "m").with_label(Span::new(3, 4), "far");
512        let out = render(&src, &d);
513        assert!(out.contains("far"));
514    }
515
516    #[test]
517    fn spans_over_several_lines() {
518        let src = "f(function () {\n  a;\n  b;\n});\n";
519        let d = Diagnostic::error("e", Span::new(2, 27), "m");
520        let out = render(src, &d);
521        assert_eq!(
522            out,
523            "error[e]: m\n --> 1:3\n  |\n1 | f(function () {\n  |   ^^^^^^^^^^^^^\n...\n4 | });\n  | ^\n"
524        );
525    }
526
527    #[test]
528    fn line_terminators_and_gutter_width() {
529        let src = "a\r\nb\rc\n".repeat(4) + "bad";
530        let at = src.len() as u32 - 3;
531        let d =
532            Diagnostic::error("e", Span::new(at, at + 3), "m").with_label(Span::new(0, 1), "first");
533        let out = render(&src, &d);
534        assert!(out.contains("\n  --> 13:1\n"), "{out}");
535        assert!(out.contains("\n 1 | a\n   | - first\n"), "{out}");
536        assert!(out.contains("\n13 | bad\n   | ^^^\n"), "{out}");
537        assert!(!out.contains('\r'));
538        // ECMAScript's separators end lines too, with that index.
539        let src = "a\u{2028}b;";
540        let d = Diagnostic::error("e", Span::new(4, 5), "m");
541        let out = d.render(src, &LineIndex::ecmascript(src), &RenderOptions::default());
542        assert!(out.contains("2 | b;\n  | ^\n"), "{out}");
543    }
544
545    #[test]
546    fn spans_out_of_range_are_clamped() {
547        let src = "ab";
548        let d = Diagnostic::error("e", Span::new(40, 50), "m");
549        assert!(render(src, &d).ends_with("1 | ab\n  |   ^\n"));
550        assert!(render("", &Diagnostic::error("e", Span::at(0), "m")).ends_with("1 | \n  | ^\n"));
551    }
552}