Skip to main content

flow_span/
source_map.rs

1//! Source files and the map that owns them.
2
3use camino::Utf8PathBuf;
4
5use crate::IndexVec;
6use crate::span::{FileId, LineCol, Span};
7
8/// Where a source file came from.
9#[derive(Clone, PartialEq, Eq, Hash, Debug)]
10pub enum SourceName {
11    /// A file on disk.
12    Real(Utf8PathBuf),
13    /// A source with no path: a test fixture, a string a host supplied.
14    Anon(String),
15}
16
17impl std::fmt::Display for SourceName {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match self {
20            SourceName::Real(path) => write!(f, "{path}"),
21            SourceName::Anon(label) => write!(f, "<{label}>"),
22        }
23    }
24}
25
26/// One source file, with the line index a caret needs.
27///
28/// Line starts are computed once at construction. Every later question about a
29/// position is a binary search over that vector rather than a rescan, which
30/// matters because a diagnostic-heavy run asks the question many times per file.
31#[derive(Clone, Debug)]
32pub struct SourceFile {
33    id: FileId,
34    name: SourceName,
35    text: String,
36    line_starts: Vec<u32>,
37}
38
39impl SourceFile {
40    /// Returns this file's identity within its map.
41    pub const fn id(&self) -> FileId {
42        self.id
43    }
44
45    /// Returns where this file came from.
46    pub const fn name(&self) -> &SourceName {
47        &self.name
48    }
49
50    /// Returns the whole source text.
51    pub fn text(&self) -> &str {
52        &self.text
53    }
54
55    /// Returns the source length in bytes.
56    ///
57    /// # Panics
58    ///
59    /// Never for a file a [`SourceMap`] holds: [`SourceMap::add`] refuses text
60    /// whose length does not fit in a `u32` offset.
61    pub fn len(&self) -> u32 {
62        u32::try_from(self.text.len()).expect("source length fits in u32")
63    }
64
65    /// Returns whether the source is empty.
66    pub fn is_empty(&self) -> bool {
67        self.text.is_empty()
68    }
69
70    /// Returns how many lines the file has.
71    ///
72    /// A file always has at least one line, and a trailing newline does not
73    /// open an extra one.
74    pub fn line_count(&self) -> usize {
75        self.line_starts.len()
76    }
77
78    /// Returns the one-based line and column of `offset`.
79    ///
80    /// # Panics
81    ///
82    /// Panics when `offset` lies past the end of the file, or inside a
83    /// multi-byte character. Both are defects in whatever produced the offset:
84    /// spans come from a lexer whose token extents partition the file.
85    pub fn line_col(&self, offset: u32) -> LineCol {
86        let position = crate::widen(offset);
87        assert!(
88            position <= self.text.len(),
89            "offset {position} lies past the end of {} ({} bytes)",
90            self.name,
91            self.text.len(),
92        );
93
94        let line_index = self.line_index(offset);
95        let line_start = crate::widen(self.line_starts[line_index]);
96        let prefix = self
97            .text
98            .get(line_start..position)
99            .unwrap_or_else(|| panic!("offset {position} is not a character boundary"));
100
101        LineCol {
102            line: u32::try_from(line_index + 1).expect("line number fits in u32"),
103            column: u32::try_from(prefix.chars().count() + 1).expect("column fits in u32"),
104        }
105    }
106
107    /// Returns the offset `at` names, the inverse of [`SourceFile::line_col`]:
108    /// `None` when the file has no such line, or the line no such column. A
109    /// line's columns end at its line break, or one past the file's last
110    /// character on its last line.
111    pub fn offset(&self, at: LineCol) -> Option<u32> {
112        let index = crate::widen(at.line).checked_sub(1)?;
113        let column = crate::widen(at.column).checked_sub(1)?;
114        let start = crate::widen(*self.line_starts.get(index)?);
115        let end = self
116            .line_starts
117            .get(index + 1)
118            .map_or(self.text.len(), |next| crate::widen(*next));
119        let line = &self.text[start..end];
120        let within = line
121            .char_indices()
122            .map(|(at, _)| at)
123            .chain((end == self.text.len()).then_some(line.len()))
124            .nth(column)?;
125        u32::try_from(start + within).ok()
126    }
127
128    /// Returns the zero-based index of the line containing `offset`.
129    pub fn line_index(&self, offset: u32) -> usize {
130        match self.line_starts.binary_search(&offset) {
131            Ok(exact) => exact,
132            Err(next) => next - 1,
133        }
134    }
135
136    /// Returns the text of the zero-based line `index`, without its newline.
137    ///
138    /// # Panics
139    ///
140    /// Panics when `index` names no line.
141    pub fn line_text(&self, index: usize) -> &str {
142        let start = crate::widen(self.line_starts[index]);
143        let end = self
144            .line_starts
145            .get(index + 1)
146            .map_or(self.text.len(), |next| crate::widen(*next));
147
148        let line = &self.text[start..end];
149        let line = line.strip_suffix('\n').unwrap_or(line);
150        line.strip_suffix('\r').unwrap_or(line)
151    }
152
153    /// Returns the text `span` covers.
154    ///
155    /// # Panics
156    ///
157    /// Panics when the span names another file, lies past the end, or does not
158    /// land on character boundaries.
159    pub fn snippet(&self, span: Span) -> &str {
160        assert_eq!(span.file(), self.id, "span names another file");
161        self.text.get(span.range()).unwrap_or_else(|| {
162            panic!(
163                "span {span:?} does not cover whole characters of {}",
164                self.name
165            )
166        })
167    }
168
169    fn new(id: FileId, name: SourceName, text: String) -> Self {
170        let mut line_starts = vec![0_u32];
171        for (offset, byte) in text.bytes().enumerate() {
172            if byte == b'\n' && offset + 1 < text.len() {
173                line_starts.push(u32::try_from(offset + 1).expect("line start offset fits in u32"));
174            }
175        }
176        Self {
177            id,
178            name,
179            text,
180            line_starts,
181        }
182    }
183}
184
185/// Every source file one compilation reads.
186///
187/// A [`Span`] carries only a [`FileId`], so this map is what turns a span back
188/// into text. It is append-only: a file's identity is its position, and nothing
189/// reassigns one.
190#[derive(Clone, Debug, Default)]
191pub struct SourceMap {
192    files: IndexVec<FileId, SourceFile>,
193}
194
195impl SourceMap {
196    /// Returns an empty map.
197    pub fn new() -> Self {
198        Self::default()
199    }
200
201    /// Adds `text` under `name` and returns its identity.
202    ///
203    /// # Panics
204    ///
205    /// Panics when the source exceeds the `u32` offset range, which is the
206    /// range [`Span`] measures in.
207    pub fn add(&mut self, name: SourceName, text: String) -> FileId {
208        assert!(
209            u32::try_from(text.len()).is_ok(),
210            "source {name} is larger than the u32 offset range",
211        );
212        let id = self.files.next_index();
213        self.files.push(SourceFile::new(id, name, text));
214        id
215    }
216
217    /// Returns the file `id` names.
218    ///
219    /// # Panics
220    ///
221    /// Panics when `id` came from another map.
222    pub fn file(&self, id: FileId) -> &SourceFile {
223        self.files
224            .get(id)
225            .unwrap_or_else(|| panic!("{id:?} does not belong to this source map"))
226    }
227
228    /// Returns the file `id` names, or `None` when it came from another map.
229    pub fn get(&self, id: FileId) -> Option<&SourceFile> {
230        self.files.get(id)
231    }
232
233    /// Returns the text `span` covers.
234    ///
235    /// # Panics
236    ///
237    /// Panics when `span` names a file of another map.
238    pub fn snippet(&self, span: Span) -> &str {
239        self.file(span.file()).snippet(span)
240    }
241
242    /// Returns the one-based line and column `span` starts at.
243    ///
244    /// # Panics
245    ///
246    /// Panics when `span` names a file of another map.
247    pub fn line_col(&self, span: Span) -> LineCol {
248        self.file(span.file()).line_col(span.lo())
249    }
250
251    /// Returns how many files the map holds.
252    pub fn len(&self) -> usize {
253        self.files.len()
254    }
255
256    /// Returns whether the map holds no files.
257    pub fn is_empty(&self) -> bool {
258        self.files.is_empty()
259    }
260
261    /// Returns every file, in the order they were added.
262    pub fn iter(&self) -> impl Iterator<Item = &SourceFile> {
263        self.files.iter()
264    }
265}
266
267#[cfg(test)]
268#[cfg_attr(coverage, coverage(off))]
269mod tests {
270    use super::{SourceFile, SourceMap, SourceName};
271    use crate::Idx as _;
272    use crate::span::{FileId, LineCol, Span};
273    use camino::Utf8PathBuf;
274
275    fn map_with(text: &str) -> (SourceMap, FileId) {
276        let mut map = SourceMap::new();
277        let id = map.add(SourceName::Anon("fixture".to_owned()), text.to_owned());
278        (map, id)
279    }
280
281    #[test]
282    fn a_source_name_renders_for_a_reader() {
283        assert_eq!(
284            SourceName::Real(Utf8PathBuf::from("a/b.flow")).to_string(),
285            "a/b.flow"
286        );
287        assert_eq!(SourceName::Anon("stdin".to_owned()).to_string(), "<stdin>");
288    }
289
290    #[test]
291    fn an_offset_is_found_from_the_line_and_column_it_is_at() {
292        let (map, id) = map_with("a\u{e9}b\ncd");
293        let file = map.file(id);
294        for offset in [0, 1, 3, 4, 5, 6, 7] {
295            assert_eq!(file.offset(file.line_col(offset)), Some(offset));
296        }
297        let at = |line, column| LineCol { line, column };
298        assert_eq!(file.offset(at(1, 5)), None, "past the line break");
299        assert_eq!(file.offset(at(2, 4)), None, "past the file's end");
300        assert_eq!(file.offset(at(3, 1)), None);
301        assert_eq!(file.offset(at(0, 1)), None);
302        assert_eq!(file.offset(at(1, 0)), None);
303    }
304
305    #[test]
306    fn a_file_reports_the_text_it_was_added_with() {
307        let (map, id) = map_with("flow main() {}\n");
308        let file = map.file(id);
309
310        assert_eq!(file.id(), id);
311        assert_eq!(file.name(), &SourceName::Anon("fixture".to_owned()));
312        assert_eq!(file.text(), "flow main() {}\n");
313        assert_eq!(file.len(), 15);
314        assert!(!file.is_empty());
315    }
316
317    #[test]
318    fn an_empty_file_still_has_one_line() {
319        let (map, id) = map_with("");
320        let file = map.file(id);
321
322        assert!(file.is_empty());
323        assert_eq!(file.len(), 0);
324        assert_eq!(file.line_count(), 1);
325        assert_eq!(file.line_text(0), "");
326        assert_eq!(file.line_col(0), LineCol { line: 1, column: 1 });
327    }
328
329    #[test]
330    fn a_trailing_newline_opens_no_extra_line() {
331        let (map, id) = map_with("one\ntwo\n");
332        let file = map.file(id);
333
334        assert_eq!(file.line_count(), 2);
335        assert_eq!(file.line_text(0), "one");
336        assert_eq!(file.line_text(1), "two");
337    }
338
339    #[test]
340    fn a_missing_trailing_newline_leaves_the_last_line_whole() {
341        let (map, id) = map_with("one\ntwo");
342        let file = map.file(id);
343
344        assert_eq!(file.line_count(), 2);
345        assert_eq!(file.line_text(1), "two");
346    }
347
348    #[test]
349    fn a_carriage_return_is_not_part_of_the_line() {
350        let (map, id) = map_with("one\r\ntwo\r\n");
351        let file = map.file(id);
352
353        assert_eq!(file.line_count(), 2);
354        assert_eq!(file.line_text(0), "one");
355        assert_eq!(file.line_text(1), "two");
356    }
357
358    #[test]
359    fn a_blank_line_between_two_lines_is_its_own_line() {
360        let (map, id) = map_with("one\n\ntwo\n");
361        let file = map.file(id);
362
363        assert_eq!(file.line_count(), 3);
364        assert_eq!(file.line_text(1), "");
365    }
366
367    #[test]
368    fn a_position_maps_to_its_one_based_line_and_column() {
369        let (map, id) = map_with("one\ntwo\nthree");
370        let file = map.file(id);
371
372        assert_eq!(file.line_col(0), LineCol { line: 1, column: 1 });
373        assert_eq!(file.line_col(2), LineCol { line: 1, column: 3 });
374        assert_eq!(file.line_col(3), LineCol { line: 1, column: 4 });
375        assert_eq!(file.line_col(4), LineCol { line: 2, column: 1 });
376        assert_eq!(file.line_col(8), LineCol { line: 3, column: 1 });
377        assert_eq!(file.line_col(13), LineCol { line: 3, column: 6 });
378    }
379
380    #[test]
381    fn a_column_counts_characters_rather_than_bytes() {
382        let (map, id) = map_with("héllo");
383        let file = map.file(id);
384
385        assert_eq!(file.len(), 6);
386        assert_eq!(file.line_col(3), LineCol { line: 1, column: 3 });
387        assert_eq!(file.line_col(6), LineCol { line: 1, column: 6 });
388    }
389
390    #[test]
391    fn a_span_reads_back_as_the_text_it_covers() {
392        let (map, id) = map_with("flow main() {}\n");
393        let extent = Span::from_bounds(id, 5, 9);
394
395        assert_eq!(map.file(id).snippet(extent), "main");
396        assert_eq!(map.snippet(extent), "main");
397        assert_eq!(map.line_col(extent), LineCol { line: 1, column: 6 });
398    }
399
400    #[test]
401    fn a_map_holds_its_files_in_the_order_they_were_added() {
402        let mut map = SourceMap::default();
403        assert!(map.is_empty());
404        assert_eq!(map.len(), 0);
405
406        let first = map.add(SourceName::Anon("a".to_owned()), "one".to_owned());
407        let second = map.add(
408            SourceName::Real(Utf8PathBuf::from("b.flow")),
409            "two".to_owned(),
410        );
411
412        assert_eq!(map.len(), 2);
413        assert!(!map.is_empty());
414        assert_eq!(first, FileId::from_usize(0));
415        assert_eq!(second, FileId::from_usize(1));
416        assert_eq!(
417            map.iter().map(SourceFile::text).collect::<Vec<_>>(),
418            ["one", "two"]
419        );
420        assert_eq!(map.get(first).map(SourceFile::text), Some("one"));
421        assert!(map.get(FileId::from_usize(2)).is_none());
422    }
423
424    #[test]
425    #[should_panic(expected = "does not belong to this source map")]
426    fn reading_a_foreign_file_id_is_a_defect() {
427        let (map, _) = map_with("one");
428        let _ = map.file(FileId::from_usize(1));
429    }
430
431    #[test]
432    #[should_panic(expected = "lies past the end of")]
433    fn a_position_past_the_end_is_a_defect() {
434        let (map, id) = map_with("one");
435        let _ = map.file(id).line_col(4);
436    }
437
438    #[test]
439    #[should_panic(expected = "is not a character boundary")]
440    fn a_position_inside_a_character_is_a_defect() {
441        let (map, id) = map_with("é");
442        let _ = map.file(id).line_col(1);
443    }
444
445    #[test]
446    #[should_panic(expected = "span names another file")]
447    fn reading_a_span_of_another_file_is_a_defect() {
448        let (map, id) = map_with("one");
449        let _ = map
450            .file(id)
451            .snippet(Span::from_bounds(FileId::from_usize(9), 0, 1));
452    }
453
454    #[test]
455    #[should_panic(expected = "does not cover whole characters")]
456    fn a_span_cutting_a_character_is_a_defect() {
457        let (map, id) = map_with("é");
458        let _ = map.file(id).snippet(Span::from_bounds(id, 0, 1));
459    }
460}