Skip to main content

flow_span/
span.rs

1//! Byte extents within a source file.
2
3use crate::newtype_index;
4
5newtype_index! {
6    /// One source file within a [`SourceMap`](crate::SourceMap).
7    pub struct FileId;
8}
9
10/// A half-open byte range `[lo, lo + len)` within one source file.
11///
12/// A span carries its [`FileId`], which costs four bytes and buys one thing
13/// worth paying for: a span from any file of a compilation reads back
14/// through one [`SourceMap`](crate::SourceMap) without a file beside it.
15/// Every span names a real position; a value that may have none holds an
16/// `Option<Span>`.
17///
18/// Extents are measured in **UTF-8 bytes**, matching
19/// `docs/language/spec/grammar.md`'s lexical contract, where token extents
20/// partition the file and their byte lengths sum to its length. Line and column
21/// are a rendering concern and are computed on demand by
22/// [`SourceFile::line_col`](crate::SourceFile::line_col).
23#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub struct Span {
25    file: FileId,
26    lo: u32,
27    len: u32,
28}
29
30impl Span {
31    /// Returns the span covering `len` bytes from `lo` in `file`.
32    ///
33    /// # Panics
34    ///
35    /// Panics when `lo + len` would exceed the `u32` range.
36    pub fn new(file: FileId, lo: u32, len: u32) -> Self {
37        assert!(
38            lo.checked_add(len).is_some(),
39            "span {lo}+{len} overflows the u32 offset range"
40        );
41        Self { file, lo, len }
42    }
43
44    /// Returns the span covering `[lo, hi)` in `file`.
45    ///
46    /// # Panics
47    ///
48    /// Panics when `hi` precedes `lo`.
49    pub fn from_bounds(file: FileId, lo: u32, hi: u32) -> Self {
50        assert!(lo <= hi, "span bounds {lo}..{hi} are inverted");
51        Self {
52            file,
53            lo,
54            len: hi - lo,
55        }
56    }
57
58    /// Returns the file this span names a position in.
59    pub const fn file(self) -> FileId {
60        self.file
61    }
62
63    /// Returns the byte offset the span starts at.
64    pub const fn lo(self) -> u32 {
65        self.lo
66    }
67
68    /// Returns the byte offset one past the span's last byte.
69    pub const fn hi(self) -> u32 {
70        self.lo + self.len
71    }
72
73    /// Returns the span's length in bytes.
74    pub const fn len(self) -> u32 {
75        self.len
76    }
77
78    /// Returns whether the span covers no bytes.
79    pub const fn is_empty(self) -> bool {
80        self.len == 0
81    }
82
83    /// Returns the empty span at this one's start.
84    #[must_use]
85    pub const fn shrink_to_lo(self) -> Self {
86        Self {
87            file: self.file,
88            lo: self.lo,
89            len: 0,
90        }
91    }
92
93    /// Returns the empty span at this one's end.
94    #[must_use]
95    pub const fn shrink_to_hi(self) -> Self {
96        Self {
97            file: self.file,
98            lo: self.hi(),
99            len: 0,
100        }
101    }
102
103    /// Returns the smallest span covering both.
104    ///
105    /// # Panics
106    ///
107    /// Panics when the spans name different files. One span names one file,
108    /// so there is no honest answer to give instead.
109    #[must_use]
110    pub fn merge(self, other: Self) -> Self {
111        assert_eq!(
112            self.file, other.file,
113            "spans of different files have no common extent"
114        );
115        Self::from_bounds(self.file, self.lo.min(other.lo), self.hi().max(other.hi()))
116    }
117
118    /// Returns whether this span covers every byte `other` covers.
119    pub fn contains(self, other: Self) -> bool {
120        self.file == other.file && self.lo <= other.lo && other.hi() <= self.hi()
121    }
122
123    /// Returns the byte range this span names.
124    pub const fn range(self) -> std::ops::Range<usize> {
125        crate::widen(self.lo)..crate::widen(self.hi())
126    }
127}
128
129impl std::fmt::Debug for Span {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        write!(f, "Span({}:{}..{})", self.file.as_u32(), self.lo, self.hi())
132    }
133}
134
135/// A one-based line and column, for rendering only.
136///
137/// The column counts **Unicode scalar values**, not bytes, because it exists to
138/// place a caret under a character a reader can see.
139#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
140pub struct LineCol {
141    /// The one-based line number.
142    pub line: u32,
143    /// The one-based column, in Unicode scalar values.
144    pub column: u32,
145}
146
147#[cfg(test)]
148#[cfg_attr(coverage, coverage(off))]
149mod tests {
150    use super::{FileId, LineCol, Span};
151    use crate::Idx as _;
152
153    fn file(position: usize) -> FileId {
154        FileId::from_usize(position)
155    }
156
157    fn span(lo: u32, hi: u32) -> Span {
158        Span::from_bounds(file(0), lo, hi)
159    }
160
161    #[test]
162    fn a_span_reports_the_extent_it_was_built_from() {
163        let extent = Span::new(file(2), 10, 5);
164        assert_eq!(extent.file(), file(2));
165        assert_eq!(extent.lo(), 10);
166        assert_eq!(extent.hi(), 15);
167        assert_eq!(extent.len(), 5);
168        assert!(!extent.is_empty());
169        assert_eq!(extent.range(), 10..15);
170        assert_eq!(Span::from_bounds(file(2), 10, 15), extent);
171    }
172
173    #[test]
174    fn an_empty_span_still_names_a_position() {
175        let empty = span(7, 7);
176        assert!(empty.is_empty());
177        assert_eq!(empty.lo(), 7);
178        assert_eq!(empty.hi(), 7);
179    }
180
181    #[test]
182    fn a_span_debugs_as_its_file_and_extent() {
183        assert_eq!(format!("{:?}", Span::new(file(3), 4, 2)), "Span(3:4..6)");
184    }
185
186    #[test]
187    fn shrinking_keeps_the_chosen_end() {
188        let extent = span(4, 9);
189        assert_eq!(extent.shrink_to_lo(), span(4, 4));
190        assert_eq!(extent.shrink_to_hi(), span(9, 9));
191    }
192
193    #[test]
194    fn merging_covers_both_extents() {
195        assert_eq!(span(2, 4).merge(span(8, 9)), span(2, 9));
196        assert_eq!(span(8, 9).merge(span(2, 4)), span(2, 9));
197        assert_eq!(span(2, 9).merge(span(4, 5)), span(2, 9));
198    }
199
200    #[test]
201    fn containment_needs_one_file() {
202        assert!(span(2, 9).contains(span(4, 5)));
203        assert!(span(2, 9).contains(span(2, 9)));
204        assert!(!span(2, 9).contains(span(1, 5)));
205        assert!(!span(2, 9).contains(span(5, 10)));
206        assert!(!span(2, 9).contains(Span::from_bounds(file(1), 4, 5)));
207    }
208
209    #[test]
210    fn spans_order_and_hash_by_their_components() {
211        let mut sorted = [span(4, 5), span(2, 9), span(2, 3)];
212        sorted.sort_unstable();
213        assert_eq!(sorted, [span(2, 3), span(2, 9), span(4, 5)]);
214
215        let unique: std::collections::HashSet<Span> =
216            [span(2, 3), span(2, 3)].into_iter().collect();
217        assert_eq!(unique.len(), 1);
218    }
219
220    #[test]
221    fn a_line_and_column_render_for_a_reader() {
222        let position = LineCol {
223            line: 3,
224            column: 12,
225        };
226        assert_eq!(format!("{position:?}"), "LineCol { line: 3, column: 12 }");
227        assert!(LineCol { line: 3, column: 1 } < position);
228    }
229
230    #[test]
231    #[should_panic(expected = "overflows the u32 offset range")]
232    fn a_span_past_the_offset_range_is_a_defect() {
233        let _ = Span::new(file(0), u32::MAX, 1);
234    }
235
236    #[test]
237    #[should_panic(expected = "bounds 9..2 are inverted")]
238    fn inverted_bounds_are_a_defect() {
239        let _ = Span::from_bounds(file(0), 9, 2);
240    }
241
242    #[test]
243    #[should_panic(expected = "different files have no common extent")]
244    fn merging_across_files_is_a_defect() {
245        let _ = span(2, 4).merge(Span::from_bounds(file(1), 2, 4));
246    }
247}