flow-span 0.1.0-rc.5

Source positions, source files, the identifier interner, and the places in a run.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Source files and the map that owns them.

use camino::Utf8PathBuf;

use crate::IndexVec;
use crate::span::{FileId, LineCol, Span};

/// Where a source file came from.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum SourceName {
    /// A file on disk.
    Real(Utf8PathBuf),
    /// A source with no path: a test fixture, a string a host supplied.
    Anon(String),
}

impl std::fmt::Display for SourceName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SourceName::Real(path) => write!(f, "{path}"),
            SourceName::Anon(label) => write!(f, "<{label}>"),
        }
    }
}

/// One source file, with the line index a caret needs.
///
/// Line starts are computed once at construction. Every later question about a
/// position is a binary search over that vector rather than a rescan, which
/// matters because a diagnostic-heavy run asks the question many times per file.
#[derive(Clone, Debug)]
pub struct SourceFile {
    id: FileId,
    name: SourceName,
    text: String,
    line_starts: Vec<u32>,
}

impl SourceFile {
    /// Returns this file's identity within its map.
    pub const fn id(&self) -> FileId {
        self.id
    }

    /// Returns where this file came from.
    pub const fn name(&self) -> &SourceName {
        &self.name
    }

    /// Returns the whole source text.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the source length in bytes.
    ///
    /// # Panics
    ///
    /// Never for a file a [`SourceMap`] holds: [`SourceMap::add`] refuses text
    /// whose length does not fit in a `u32` offset.
    pub fn len(&self) -> u32 {
        u32::try_from(self.text.len()).expect("source length fits in u32")
    }

    /// Returns whether the source is empty.
    pub fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    /// Returns how many lines the file has.
    ///
    /// A file always has at least one line, and a trailing newline does not
    /// open an extra one.
    pub fn line_count(&self) -> usize {
        self.line_starts.len()
    }

    /// Returns the one-based line and column of `offset`.
    ///
    /// # Panics
    ///
    /// Panics when `offset` lies past the end of the file, or inside a
    /// multi-byte character. Both are defects in whatever produced the offset:
    /// spans come from a lexer whose token extents partition the file.
    pub fn line_col(&self, offset: u32) -> LineCol {
        let position = crate::widen(offset);
        assert!(
            position <= self.text.len(),
            "offset {position} lies past the end of {} ({} bytes)",
            self.name,
            self.text.len(),
        );

        let line_index = self.line_index(offset);
        let line_start = crate::widen(self.line_starts[line_index]);
        let prefix = self
            .text
            .get(line_start..position)
            .unwrap_or_else(|| panic!("offset {position} is not a character boundary"));

        LineCol {
            line: u32::try_from(line_index + 1).expect("line number fits in u32"),
            column: u32::try_from(prefix.chars().count() + 1).expect("column fits in u32"),
        }
    }

    /// Returns the offset `at` names, the inverse of [`SourceFile::line_col`]:
    /// `None` when the file has no such line, or the line no such column. A
    /// line's columns end at its line break, or one past the file's last
    /// character on its last line.
    pub fn offset(&self, at: LineCol) -> Option<u32> {
        let index = crate::widen(at.line).checked_sub(1)?;
        let column = crate::widen(at.column).checked_sub(1)?;
        let start = crate::widen(*self.line_starts.get(index)?);
        let end = self
            .line_starts
            .get(index + 1)
            .map_or(self.text.len(), |next| crate::widen(*next));
        let line = &self.text[start..end];
        let within = line
            .char_indices()
            .map(|(at, _)| at)
            .chain((end == self.text.len()).then_some(line.len()))
            .nth(column)?;
        u32::try_from(start + within).ok()
    }

    /// Returns the zero-based index of the line containing `offset`.
    pub fn line_index(&self, offset: u32) -> usize {
        match self.line_starts.binary_search(&offset) {
            Ok(exact) => exact,
            Err(next) => next - 1,
        }
    }

    /// Returns the text of the zero-based line `index`, without its newline.
    ///
    /// # Panics
    ///
    /// Panics when `index` names no line.
    pub fn line_text(&self, index: usize) -> &str {
        let start = crate::widen(self.line_starts[index]);
        let end = self
            .line_starts
            .get(index + 1)
            .map_or(self.text.len(), |next| crate::widen(*next));

        let line = &self.text[start..end];
        let line = line.strip_suffix('\n').unwrap_or(line);
        line.strip_suffix('\r').unwrap_or(line)
    }

    /// Returns the text `span` covers.
    ///
    /// # Panics
    ///
    /// Panics when the span names another file, lies past the end, or does not
    /// land on character boundaries.
    pub fn snippet(&self, span: Span) -> &str {
        assert_eq!(span.file(), self.id, "span names another file");
        self.text.get(span.range()).unwrap_or_else(|| {
            panic!(
                "span {span:?} does not cover whole characters of {}",
                self.name
            )
        })
    }

    fn new(id: FileId, name: SourceName, text: String) -> Self {
        let mut line_starts = vec![0_u32];
        for (offset, byte) in text.bytes().enumerate() {
            if byte == b'\n' && offset + 1 < text.len() {
                line_starts.push(u32::try_from(offset + 1).expect("line start offset fits in u32"));
            }
        }
        Self {
            id,
            name,
            text,
            line_starts,
        }
    }
}

/// Every source file one compilation reads.
///
/// A [`Span`] carries only a [`FileId`], so this map is what turns a span back
/// into text. It is append-only: a file's identity is its position, and nothing
/// reassigns one.
#[derive(Clone, Debug, Default)]
pub struct SourceMap {
    files: IndexVec<FileId, SourceFile>,
}

impl SourceMap {
    /// Returns an empty map.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds `text` under `name` and returns its identity.
    ///
    /// # Panics
    ///
    /// Panics when the source exceeds the `u32` offset range, which is the
    /// range [`Span`] measures in.
    pub fn add(&mut self, name: SourceName, text: String) -> FileId {
        assert!(
            u32::try_from(text.len()).is_ok(),
            "source {name} is larger than the u32 offset range",
        );
        let id = self.files.next_index();
        self.files.push(SourceFile::new(id, name, text));
        id
    }

    /// Returns the file `id` names.
    ///
    /// # Panics
    ///
    /// Panics when `id` came from another map.
    pub fn file(&self, id: FileId) -> &SourceFile {
        self.files
            .get(id)
            .unwrap_or_else(|| panic!("{id:?} does not belong to this source map"))
    }

    /// Returns the file `id` names, or `None` when it came from another map.
    pub fn get(&self, id: FileId) -> Option<&SourceFile> {
        self.files.get(id)
    }

    /// Returns the text `span` covers.
    ///
    /// # Panics
    ///
    /// Panics when `span` names a file of another map.
    pub fn snippet(&self, span: Span) -> &str {
        self.file(span.file()).snippet(span)
    }

    /// Returns the one-based line and column `span` starts at.
    ///
    /// # Panics
    ///
    /// Panics when `span` names a file of another map.
    pub fn line_col(&self, span: Span) -> LineCol {
        self.file(span.file()).line_col(span.lo())
    }

    /// Returns how many files the map holds.
    pub fn len(&self) -> usize {
        self.files.len()
    }

    /// Returns whether the map holds no files.
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    /// Returns every file, in the order they were added.
    pub fn iter(&self) -> impl Iterator<Item = &SourceFile> {
        self.files.iter()
    }
}

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

    fn map_with(text: &str) -> (SourceMap, FileId) {
        let mut map = SourceMap::new();
        let id = map.add(SourceName::Anon("fixture".to_owned()), text.to_owned());
        (map, id)
    }

    #[test]
    fn a_source_name_renders_for_a_reader() {
        assert_eq!(
            SourceName::Real(Utf8PathBuf::from("a/b.flow")).to_string(),
            "a/b.flow"
        );
        assert_eq!(SourceName::Anon("stdin".to_owned()).to_string(), "<stdin>");
    }

    #[test]
    fn an_offset_is_found_from_the_line_and_column_it_is_at() {
        let (map, id) = map_with("a\u{e9}b\ncd");
        let file = map.file(id);
        for offset in [0, 1, 3, 4, 5, 6, 7] {
            assert_eq!(file.offset(file.line_col(offset)), Some(offset));
        }
        let at = |line, column| LineCol { line, column };
        assert_eq!(file.offset(at(1, 5)), None, "past the line break");
        assert_eq!(file.offset(at(2, 4)), None, "past the file's end");
        assert_eq!(file.offset(at(3, 1)), None);
        assert_eq!(file.offset(at(0, 1)), None);
        assert_eq!(file.offset(at(1, 0)), None);
    }

    #[test]
    fn a_file_reports_the_text_it_was_added_with() {
        let (map, id) = map_with("flow main() {}\n");
        let file = map.file(id);

        assert_eq!(file.id(), id);
        assert_eq!(file.name(), &SourceName::Anon("fixture".to_owned()));
        assert_eq!(file.text(), "flow main() {}\n");
        assert_eq!(file.len(), 15);
        assert!(!file.is_empty());
    }

    #[test]
    fn an_empty_file_still_has_one_line() {
        let (map, id) = map_with("");
        let file = map.file(id);

        assert!(file.is_empty());
        assert_eq!(file.len(), 0);
        assert_eq!(file.line_count(), 1);
        assert_eq!(file.line_text(0), "");
        assert_eq!(file.line_col(0), LineCol { line: 1, column: 1 });
    }

    #[test]
    fn a_trailing_newline_opens_no_extra_line() {
        let (map, id) = map_with("one\ntwo\n");
        let file = map.file(id);

        assert_eq!(file.line_count(), 2);
        assert_eq!(file.line_text(0), "one");
        assert_eq!(file.line_text(1), "two");
    }

    #[test]
    fn a_missing_trailing_newline_leaves_the_last_line_whole() {
        let (map, id) = map_with("one\ntwo");
        let file = map.file(id);

        assert_eq!(file.line_count(), 2);
        assert_eq!(file.line_text(1), "two");
    }

    #[test]
    fn a_carriage_return_is_not_part_of_the_line() {
        let (map, id) = map_with("one\r\ntwo\r\n");
        let file = map.file(id);

        assert_eq!(file.line_count(), 2);
        assert_eq!(file.line_text(0), "one");
        assert_eq!(file.line_text(1), "two");
    }

    #[test]
    fn a_blank_line_between_two_lines_is_its_own_line() {
        let (map, id) = map_with("one\n\ntwo\n");
        let file = map.file(id);

        assert_eq!(file.line_count(), 3);
        assert_eq!(file.line_text(1), "");
    }

    #[test]
    fn a_position_maps_to_its_one_based_line_and_column() {
        let (map, id) = map_with("one\ntwo\nthree");
        let file = map.file(id);

        assert_eq!(file.line_col(0), LineCol { line: 1, column: 1 });
        assert_eq!(file.line_col(2), LineCol { line: 1, column: 3 });
        assert_eq!(file.line_col(3), LineCol { line: 1, column: 4 });
        assert_eq!(file.line_col(4), LineCol { line: 2, column: 1 });
        assert_eq!(file.line_col(8), LineCol { line: 3, column: 1 });
        assert_eq!(file.line_col(13), LineCol { line: 3, column: 6 });
    }

    #[test]
    fn a_column_counts_characters_rather_than_bytes() {
        let (map, id) = map_with("héllo");
        let file = map.file(id);

        assert_eq!(file.len(), 6);
        assert_eq!(file.line_col(3), LineCol { line: 1, column: 3 });
        assert_eq!(file.line_col(6), LineCol { line: 1, column: 6 });
    }

    #[test]
    fn a_span_reads_back_as_the_text_it_covers() {
        let (map, id) = map_with("flow main() {}\n");
        let extent = Span::from_bounds(id, 5, 9);

        assert_eq!(map.file(id).snippet(extent), "main");
        assert_eq!(map.snippet(extent), "main");
        assert_eq!(map.line_col(extent), LineCol { line: 1, column: 6 });
    }

    #[test]
    fn a_map_holds_its_files_in_the_order_they_were_added() {
        let mut map = SourceMap::default();
        assert!(map.is_empty());
        assert_eq!(map.len(), 0);

        let first = map.add(SourceName::Anon("a".to_owned()), "one".to_owned());
        let second = map.add(
            SourceName::Real(Utf8PathBuf::from("b.flow")),
            "two".to_owned(),
        );

        assert_eq!(map.len(), 2);
        assert!(!map.is_empty());
        assert_eq!(first, FileId::from_usize(0));
        assert_eq!(second, FileId::from_usize(1));
        assert_eq!(
            map.iter().map(SourceFile::text).collect::<Vec<_>>(),
            ["one", "two"]
        );
        assert_eq!(map.get(first).map(SourceFile::text), Some("one"));
        assert!(map.get(FileId::from_usize(2)).is_none());
    }

    #[test]
    #[should_panic(expected = "does not belong to this source map")]
    fn reading_a_foreign_file_id_is_a_defect() {
        let (map, _) = map_with("one");
        let _ = map.file(FileId::from_usize(1));
    }

    #[test]
    #[should_panic(expected = "lies past the end of")]
    fn a_position_past_the_end_is_a_defect() {
        let (map, id) = map_with("one");
        let _ = map.file(id).line_col(4);
    }

    #[test]
    #[should_panic(expected = "is not a character boundary")]
    fn a_position_inside_a_character_is_a_defect() {
        let (map, id) = map_with("é");
        let _ = map.file(id).line_col(1);
    }

    #[test]
    #[should_panic(expected = "span names another file")]
    fn reading_a_span_of_another_file_is_a_defect() {
        let (map, id) = map_with("one");
        let _ = map
            .file(id)
            .snippet(Span::from_bounds(FileId::from_usize(9), 0, 1));
    }

    #[test]
    #[should_panic(expected = "does not cover whole characters")]
    fn a_span_cutting_a_character_is_a_defect() {
        let (map, id) = map_with("é");
        let _ = map.file(id).snippet(Span::from_bounds(id, 0, 1));
    }
}