flow-span 0.1.0-rc.5

Source positions, source files, the identifier interner, and the places in a run.
Documentation
//! Byte extents within a source file.

use crate::newtype_index;

newtype_index! {
    /// One source file within a [`SourceMap`](crate::SourceMap).
    pub struct FileId;
}

/// A half-open byte range `[lo, lo + len)` within one source file.
///
/// A span carries its [`FileId`], which costs four bytes and buys one thing
/// worth paying for: a span from any file of a compilation reads back
/// through one [`SourceMap`](crate::SourceMap) without a file beside it.
/// Every span names a real position; a value that may have none holds an
/// `Option<Span>`.
///
/// Extents are measured in **UTF-8 bytes**, matching
/// `docs/language/spec/grammar.md`'s lexical contract, where token extents
/// partition the file and their byte lengths sum to its length. Line and column
/// are a rendering concern and are computed on demand by
/// [`SourceFile::line_col`](crate::SourceFile::line_col).
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Span {
    file: FileId,
    lo: u32,
    len: u32,
}

impl Span {
    /// Returns the span covering `len` bytes from `lo` in `file`.
    ///
    /// # Panics
    ///
    /// Panics when `lo + len` would exceed the `u32` range.
    pub fn new(file: FileId, lo: u32, len: u32) -> Self {
        assert!(
            lo.checked_add(len).is_some(),
            "span {lo}+{len} overflows the u32 offset range"
        );
        Self { file, lo, len }
    }

    /// Returns the span covering `[lo, hi)` in `file`.
    ///
    /// # Panics
    ///
    /// Panics when `hi` precedes `lo`.
    pub fn from_bounds(file: FileId, lo: u32, hi: u32) -> Self {
        assert!(lo <= hi, "span bounds {lo}..{hi} are inverted");
        Self {
            file,
            lo,
            len: hi - lo,
        }
    }

    /// Returns the file this span names a position in.
    pub const fn file(self) -> FileId {
        self.file
    }

    /// Returns the byte offset the span starts at.
    pub const fn lo(self) -> u32 {
        self.lo
    }

    /// Returns the byte offset one past the span's last byte.
    pub const fn hi(self) -> u32 {
        self.lo + self.len
    }

    /// Returns the span's length in bytes.
    pub const fn len(self) -> u32 {
        self.len
    }

    /// Returns whether the span covers no bytes.
    pub const fn is_empty(self) -> bool {
        self.len == 0
    }

    /// Returns the empty span at this one's start.
    #[must_use]
    pub const fn shrink_to_lo(self) -> Self {
        Self {
            file: self.file,
            lo: self.lo,
            len: 0,
        }
    }

    /// Returns the empty span at this one's end.
    #[must_use]
    pub const fn shrink_to_hi(self) -> Self {
        Self {
            file: self.file,
            lo: self.hi(),
            len: 0,
        }
    }

    /// Returns the smallest span covering both.
    ///
    /// # Panics
    ///
    /// Panics when the spans name different files. One span names one file,
    /// so there is no honest answer to give instead.
    #[must_use]
    pub fn merge(self, other: Self) -> Self {
        assert_eq!(
            self.file, other.file,
            "spans of different files have no common extent"
        );
        Self::from_bounds(self.file, self.lo.min(other.lo), self.hi().max(other.hi()))
    }

    /// Returns whether this span covers every byte `other` covers.
    pub fn contains(self, other: Self) -> bool {
        self.file == other.file && self.lo <= other.lo && other.hi() <= self.hi()
    }

    /// Returns the byte range this span names.
    pub const fn range(self) -> std::ops::Range<usize> {
        crate::widen(self.lo)..crate::widen(self.hi())
    }
}

impl std::fmt::Debug for Span {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Span({}:{}..{})", self.file.as_u32(), self.lo, self.hi())
    }
}

/// A one-based line and column, for rendering only.
///
/// The column counts **Unicode scalar values**, not bytes, because it exists to
/// place a caret under a character a reader can see.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct LineCol {
    /// The one-based line number.
    pub line: u32,
    /// The one-based column, in Unicode scalar values.
    pub column: u32,
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::{FileId, LineCol, Span};
    use crate::Idx as _;

    fn file(position: usize) -> FileId {
        FileId::from_usize(position)
    }

    fn span(lo: u32, hi: u32) -> Span {
        Span::from_bounds(file(0), lo, hi)
    }

    #[test]
    fn a_span_reports_the_extent_it_was_built_from() {
        let extent = Span::new(file(2), 10, 5);
        assert_eq!(extent.file(), file(2));
        assert_eq!(extent.lo(), 10);
        assert_eq!(extent.hi(), 15);
        assert_eq!(extent.len(), 5);
        assert!(!extent.is_empty());
        assert_eq!(extent.range(), 10..15);
        assert_eq!(Span::from_bounds(file(2), 10, 15), extent);
    }

    #[test]
    fn an_empty_span_still_names_a_position() {
        let empty = span(7, 7);
        assert!(empty.is_empty());
        assert_eq!(empty.lo(), 7);
        assert_eq!(empty.hi(), 7);
    }

    #[test]
    fn a_span_debugs_as_its_file_and_extent() {
        assert_eq!(format!("{:?}", Span::new(file(3), 4, 2)), "Span(3:4..6)");
    }

    #[test]
    fn shrinking_keeps_the_chosen_end() {
        let extent = span(4, 9);
        assert_eq!(extent.shrink_to_lo(), span(4, 4));
        assert_eq!(extent.shrink_to_hi(), span(9, 9));
    }

    #[test]
    fn merging_covers_both_extents() {
        assert_eq!(span(2, 4).merge(span(8, 9)), span(2, 9));
        assert_eq!(span(8, 9).merge(span(2, 4)), span(2, 9));
        assert_eq!(span(2, 9).merge(span(4, 5)), span(2, 9));
    }

    #[test]
    fn containment_needs_one_file() {
        assert!(span(2, 9).contains(span(4, 5)));
        assert!(span(2, 9).contains(span(2, 9)));
        assert!(!span(2, 9).contains(span(1, 5)));
        assert!(!span(2, 9).contains(span(5, 10)));
        assert!(!span(2, 9).contains(Span::from_bounds(file(1), 4, 5)));
    }

    #[test]
    fn spans_order_and_hash_by_their_components() {
        let mut sorted = [span(4, 5), span(2, 9), span(2, 3)];
        sorted.sort_unstable();
        assert_eq!(sorted, [span(2, 3), span(2, 9), span(4, 5)]);

        let unique: std::collections::HashSet<Span> =
            [span(2, 3), span(2, 3)].into_iter().collect();
        assert_eq!(unique.len(), 1);
    }

    #[test]
    fn a_line_and_column_render_for_a_reader() {
        let position = LineCol {
            line: 3,
            column: 12,
        };
        assert_eq!(format!("{position:?}"), "LineCol { line: 3, column: 12 }");
        assert!(LineCol { line: 3, column: 1 } < position);
    }

    #[test]
    #[should_panic(expected = "overflows the u32 offset range")]
    fn a_span_past_the_offset_range_is_a_defect() {
        let _ = Span::new(file(0), u32::MAX, 1);
    }

    #[test]
    #[should_panic(expected = "bounds 9..2 are inverted")]
    fn inverted_bounds_are_a_defect() {
        let _ = Span::from_bounds(file(0), 9, 2);
    }

    #[test]
    #[should_panic(expected = "different files have no common extent")]
    fn merging_across_files_is_a_defect() {
        let _ = span(2, 4).merge(Span::from_bounds(file(1), 2, 4));
    }
}