oxeon-diagnostics 0.0.1

Source spans and diagnostics for the Oxeon compiler.
Documentation
//! Source spans and diagnostics shared by every stage of the Oxeon compiler.
//!
//! Rendering (snippets, colors) is intentionally left out for now; the data
//! model is what the rest of the compiler depends on.

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>,
}

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)
    }

    fn new(severity: Severity, message: impl Into<String>, span: Span) -> Self {
        Self {
            severity,
            message: message.into(),
            span,
            labels: Vec::new(),
            notes: 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
    }

    /// 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}"));
        }
        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));
    }
}