oxeon-diagnostics 0.0.3

Source spans and diagnostics for the Oxeon compiler.
Documentation
//! Terminal rendering of diagnostics in the style of rustc:
//!
//! ```text
//! error: expected `;`, found `let`
//!  --> mods/regen.ox:2:15
//!   |
//! 2 |     let x = 1 let y = 2;
//!   |               ^^^
//! ```

use crate::{Diagnostic, Severity, Span, line_col};
use std::fmt::Write;

/// How to render a diagnostic.
#[derive(Debug, Clone, Copy, Default)]
pub struct RenderOptions {
    /// Use ANSI colors.
    pub color: bool,
}

const TAB_WIDTH: usize = 4;

struct Style {
    on: bool,
}

impl Style {
    fn paint(&self, code: &str, text: &str) -> String {
        if self.on {
            format!("\x1b[{code}m{text}\x1b[0m")
        } else {
            text.to_owned()
        }
    }
}

fn severity_color(severity: Severity) -> &'static str {
    match severity {
        Severity::Error => "1;31",
        Severity::Warning => "1;33",
        Severity::Note => "1;36",
    }
}

const GUTTER: &str = "1;34";
const BOLD: &str = "1";

/// One underlined region.
struct Mark<'a> {
    line: usize,
    /// Display columns (0-based), tabs expanded.
    start_col: usize,
    width: usize,
    primary: bool,
    message: Option<&'a str>,
}

/// The text of 1-based `line`, without its newline.
fn line_text(source: &str, line: usize) -> &str {
    source
        .split('\n')
        .nth(line - 1)
        .unwrap_or("")
        .trim_end_matches('\r')
}

fn display_width(text: &str) -> usize {
    text.chars()
        .map(|c| if c == '\t' { TAB_WIDTH } else { 1 })
        .sum()
}

fn expand_tabs(text: &str) -> String {
    text.replace('\t', &" ".repeat(TAB_WIDTH))
}

fn mark<'a>(source: &str, span: Span, primary: bool, message: Option<&'a str>) -> Mark<'a> {
    let start = (span.start as usize).min(source.len());
    let end = (span.end as usize).clamp(start, source.len());
    let (line, _) = line_col(source, start as u32);
    let line_start = source[..start].rfind('\n').map_or(0, |i| i + 1);
    let line_end = source[start..]
        .find('\n')
        .map_or(source.len(), |i| start + i);
    let start_col = display_width(&source[line_start..start]);
    // Spans running past the end of the line are underlined to the line's end.
    let width = display_width(&source[start..end.min(line_end)]).max(1);
    Mark {
        line,
        start_col,
        width,
        primary,
        message,
    }
}

impl Diagnostic {
    /// Renders the diagnostic with the source lines it points at.
    pub fn render(&self, file_name: &str, source: &str, options: RenderOptions) -> String {
        let style = Style { on: options.color };
        let sev = severity_color(self.severity);

        let mut marks = vec![mark(source, self.span, true, None)];
        marks.extend(
            self.labels
                .iter()
                .map(|l| mark(source, l.span, false, Some(&l.message))),
        );
        marks.sort_by_key(|m| (m.line, !m.primary, m.start_col));

        let max_line = marks.iter().map(|m| m.line).max().unwrap_or(1);
        let pad = " ".repeat(max_line.to_string().len());
        let bar = style.paint(GUTTER, "|");

        let mut out = String::new();
        let _ = writeln!(
            out,
            "{}{}",
            style.paint(sev, &self.severity.to_string()),
            style.paint(BOLD, &format!(": {}", self.message))
        );
        let (line, col) = line_col(source, self.span.start);
        let _ = writeln!(
            out,
            "{pad}{} {file_name}:{line}:{col}",
            style.paint(GUTTER, "-->")
        );
        let _ = writeln!(out, "{pad} {bar}");

        let mut previous_line: Option<usize> = None;
        for m in &marks {
            if previous_line != Some(m.line) {
                if previous_line.is_some_and(|p| m.line > p + 1) {
                    let _ = writeln!(out, "{}", style.paint(GUTTER, "..."));
                }
                let number = style.paint(GUTTER, &format!("{:>width$}", m.line, width = pad.len()));
                let text = expand_tabs(line_text(source, m.line));
                if text.is_empty() {
                    let _ = writeln!(out, "{number} {bar}");
                } else {
                    let _ = writeln!(out, "{number} {bar} {text}");
                }
                previous_line = Some(m.line);
            }
            let (symbol, color) = if m.primary { ("^", sev) } else { ("-", GUTTER) };
            let underline = style.paint(color, &symbol.repeat(m.width));
            let message = m
                .message
                .map(|msg| format!(" {}", style.paint(color, msg)))
                .unwrap_or_default();
            let _ = writeln!(
                out,
                "{pad} {bar} {}{underline}{message}",
                " ".repeat(m.start_col)
            );
        }

        if !self.notes.is_empty() || !self.help.is_empty() {
            let _ = writeln!(out, "{pad} {bar}");
            let lines = self
                .notes
                .iter()
                .map(|n| ("note", n))
                .chain(self.help.iter().map(|h| ("help", h)));
            for (kind, text) in lines {
                let _ = writeln!(
                    out,
                    "{pad} {} {}: {text}",
                    style.paint(GUTTER, "="),
                    style.paint(BOLD, kind)
                );
            }
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn plain(d: &Diagnostic, src: &str) -> String {
        d.render("test.ox", src, RenderOptions { color: false })
    }

    #[test]
    fn underlines_the_span() {
        let src = "fn main() {\n    let x = 1 let y = 2;\n}\n";
        let start = src.find("let y").unwrap() as u32;
        let d = Diagnostic::error("expected `;`, found `let`", Span::new(start, start + 3));
        assert_eq!(
            plain(&d, src),
            "error: expected `;`, found `let`\n \
             --> test.ox:2:15\n  \
             |\n\
             2 |     let x = 1 let y = 2;\n  \
             |               ^^^\n"
        );
    }

    #[test]
    fn labels_notes_and_line_gaps() {
        let src = "struct S;\n\nfn f() {}\n\n\n\nstruct S;\n";
        let second = src.rfind("S;").unwrap() as u32;
        let d = Diagnostic::error("`S` is defined twice", Span::new(second, second + 1))
            .with_label(Span::new(7, 8), "first defined here")
            .with_note("names must be unique within a module")
            .with_help("rename one of them");
        assert_eq!(
            plain(&d, src),
            "error: `S` is defined twice\n \
             --> test.ox:7:8\n  \
             |\n\
             1 | struct S;\n  \
             |        - first defined here\n\
             ...\n\
             7 | struct S;\n  \
             |        ^\n  \
             |\n  \
             = note: names must be unique within a module\n  \
             = help: rename one of them\n"
        );
    }

    #[test]
    fn empty_span_at_end_of_file() {
        let src = "fn f() {";
        let d = Diagnostic::error("unclosed delimiter", Span::new(8, 8));
        assert!(
            plain(&d, src).ends_with("1 | fn f() {\n  |         ^\n"),
            "{}",
            plain(&d, src)
        );
    }

    #[test]
    fn tabs_are_expanded_consistently() {
        let src = "\tlet x = ;";
        let start = src.find(';').unwrap() as u32;
        let d = Diagnostic::error("expected expression", Span::new(start, start + 1));
        let out = plain(&d, src);
        assert!(
            out.contains("1 |     let x = ;\n  |             ^\n"),
            "{out}"
        );
    }

    #[test]
    fn spans_past_the_line_end_stop_at_the_line() {
        let src = "let s = \"abc\ndef\";";
        let d = Diagnostic::error("bad string", Span::new(8, src.len() as u32));
        assert!(plain(&d, src).contains("1 | let s = \"abc\n  |         ^^^^\n"));
    }

    #[test]
    fn color_wraps_parts_in_ansi_codes() {
        let d = Diagnostic::error("oops", Span::new(0, 1));
        let out = d.render("t.ox", "x", RenderOptions { color: true });
        assert!(out.starts_with("\x1b[1;31merror\x1b[0m"));
        assert!(out.contains("\x1b[1;31m^\x1b[0m"));
    }
}