oxeon-diagnostics 0.0.5

Source spans and diagnostics for the Oxeon compiler.
Documentation
//! Source spans and diagnostics shared by every stage of the Oxeon compiler.
//!
//! [`Diagnostic::render`] prints a diagnostic with the source lines it points
//! at, rustc-style; [`Diagnostic::render_plain`] gives a one-line summary.

mod render;

pub use render::RenderOptions;

use std::fmt;
use std::ops::Range;

/// A byte range in a single source file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Span {
    pub start: u32,
    pub end: u32,
}

impl Span {
    pub const fn new(start: u32, end: u32) -> Self {
        Self { start, end }
    }

    pub const fn len(self) -> u32 {
        self.end - self.start
    }

    pub const fn is_empty(self) -> bool {
        self.start == self.end
    }

    /// The smallest span covering both `self` and `other`.
    pub fn to(self, other: Span) -> Span {
        Span::new(self.start.min(other.start), self.end.max(other.end))
    }

    pub fn range(self) -> Range<usize> {
        self.start as usize..self.end as usize
    }
}

impl From<Range<usize>> for Span {
    fn from(range: Range<usize>) -> Self {
        let start = u32::try_from(range.start).expect("source files are limited to 4 GiB");
        let end = u32::try_from(range.end).expect("source files are limited to 4 GiB");
        Span::new(start, end)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Error,
    Warning,
    Note,
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Note => "note",
        })
    }
}

/// A secondary location attached to a diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Label {
    pub span: Span,
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    pub severity: Severity,
    pub message: String,
    pub span: Span,
    pub labels: Vec<Label>,
    pub notes: Vec<String>,
    /// Suggestions for fixing the problem, shown as `= help: ...`.
    pub help: Vec<String>,
    /// A stable identifier for the kind of problem, e.g. `unused_variables`.
    pub code: Option<&'static str>,
    /// Edits an editor can apply to fix the problem.
    pub fixes: Vec<Fix>,
}

/// A machine-applicable fix: a set of text replacements.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fix {
    pub title: String,
    pub edits: Vec<Edit>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Edit {
    /// The text to replace; empty to insert at `span.start`.
    pub span: Span,
    pub text: String,
}

impl Diagnostic {
    pub fn error(message: impl Into<String>, span: Span) -> Self {
        Self::new(Severity::Error, message, span)
    }

    pub fn warning(message: impl Into<String>, span: Span) -> Self {
        Self::new(Severity::Warning, message, span)
    }

    pub fn note(message: impl Into<String>, span: Span) -> Self {
        Self::new(Severity::Note, message, span)
    }

    fn new(severity: Severity, message: impl Into<String>, span: Span) -> Self {
        Self {
            severity,
            message: message.into(),
            span,
            labels: Vec::new(),
            notes: Vec::new(),
            help: Vec::new(),
            code: None,
            fixes: Vec::new(),
        }
    }

    pub fn with_label(mut self, span: Span, message: impl Into<String>) -> Self {
        self.labels.push(Label {
            span,
            message: message.into(),
        });
        self
    }

    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }

    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help.push(help.into());
        self
    }

    pub fn with_code(mut self, code: &'static str) -> Self {
        self.code = Some(code);
        self
    }

    /// Adds a fix that replaces `span` with `text`.
    pub fn with_fix(
        mut self,
        title: impl Into<String>,
        span: Span,
        text: impl Into<String>,
    ) -> Self {
        self.fixes.push(Fix {
            title: title.into(),
            edits: vec![Edit {
                span,
                text: text.into(),
            }],
        });
        self
    }

    /// Plain one-line rendering: `file:line:col: error: message`.
    pub fn render_plain(&self, file_name: &str, source: &str) -> String {
        let (line, col) = line_col(source, self.span.start);
        let mut out = format!(
            "{file_name}:{line}:{col}: {}: {}",
            self.severity, self.message
        );
        for label in &self.labels {
            let (line, col) = line_col(source, label.span.start);
            out.push_str(&format!("\n  {file_name}:{line}:{col}: {}", label.message));
        }
        for note in &self.notes {
            out.push_str(&format!("\n  note: {note}"));
        }
        for help in &self.help {
            out.push_str(&format!("\n  help: {help}"));
        }
        out
    }
}

/// 1-based line and column (in chars) of a byte offset.
pub fn line_col(source: &str, offset: u32) -> (usize, usize) {
    let offset = (offset as usize).min(source.len());
    let before = &source[..offset];
    let line = before.matches('\n').count() + 1;
    let line_start = before.rfind('\n').map_or(0, |i| i + 1);
    let col = before[line_start..].chars().count() + 1;
    (line, col)
}

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

    #[test]
    fn line_col_counts_from_one() {
        let src = "fn a() {}\nfn b() {}";
        assert_eq!(line_col(src, 0), (1, 1));
        assert_eq!(line_col(src, 10), (2, 1));
        assert_eq!(line_col(src, 13), (2, 4));
    }

    #[test]
    fn span_to_covers_both() {
        assert_eq!(Span::new(4, 6).to(Span::new(1, 3)), Span::new(1, 6));
    }
}