solar-interface 0.3.0

Source positions, diagnostics, and related helper functions
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! SourceMap related types and operations.

use crate::{BytePos, CharPos, Span};
use arc_swap::ArcSwapOption;
use once_map::OnceMap;
use solar_data_structures::{
    map::FxBuildHasher,
    sync::{MappedRwLockReadGuard, RwLock, RwLockReadGuard},
};
use std::{
    fmt,
    io::{self, Read},
    ops::Range,
    path::{Path, PathBuf},
    sync::{Arc, OnceLock},
};

mod analyze;

mod file;
pub use file::*;

mod file_resolver;
pub(crate) use file_resolver::absolute_path;
pub use file_resolver::{FileResolver, ResolveError, apply_import_remappings};

#[cfg(test)]
mod tests;

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanLinesError {
    DistinctSources(Box<DistinctSources>),
}

/// An error that can occur when converting a `Span` to a snippet.
///
/// In general these errors only occur on malformed spans created by the user.
/// The parser never creates a span that would cause these errors.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanSnippetError {
    IllFormedSpan(Span),
    DistinctSources(Box<DistinctSources>),
    MalformedForSourcemap(MalformedSourceMapPositions),
    SourceNotAvailable { filename: FileName },
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct DistinctSources {
    pub begin: (FileName, BytePos),
    pub end: (FileName, BytePos),
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct MalformedSourceMapPositions {
    pub name: FileName,
    pub source_len: usize,
    pub begin_pos: BytePos,
    pub end_pos: BytePos,
}

/// A value paired with a source file.
#[derive(Clone, Debug)]
pub struct WithSourceFile<T, F = Arc<SourceFile>> {
    pub file: F,
    pub data: T,
}

impl<T, F> std::ops::Deref for WithSourceFile<T, F> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl<T, F> std::ops::DerefMut for WithSourceFile<T, F> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}

impl<T: Clone> WithSourceFile<T, &Arc<SourceFile>> {
    /// Clones the data and shares ownership of the source file.
    pub fn to_owned(&self) -> WithSourceFile<T> {
        WithSourceFile { file: self.file.clone(), data: self.data.clone() }
    }
}

impl<T> WithSourceFile<T, &Arc<SourceFile>> {
    /// Shares ownership of the source file without cloning the data.
    pub fn into_owned(self) -> WithSourceFile<T> {
        WithSourceFile { file: self.file.clone(), data: self.data }
    }
}

/// A source code location used for error reporting.
#[derive(Clone, Debug)]
pub struct Loc {
    /// The (1-based) line number.
    pub line: usize,
    /// The (0-based) column offset.
    pub col: CharPos,
    /// The (0-based) column offset when displayed.
    pub col_display: usize,
}

impl Default for Loc {
    fn default() -> Self {
        Self { line: 0, col: CharPos(0), col_display: 0 }
    }
}

/// A source code location used for error reporting.
///
/// This is like [`Loc`], but it includes the line and column offsets of the start and end of the
/// span.
#[derive(Clone, Debug, Default)]
pub struct SpanLoc {
    /// The location of the start of the span.
    pub lo: Loc,
    /// The location of the end of the span.
    pub hi: Loc,
}

// Used to be structural records.
#[derive(Debug)]
pub struct SourceFileAndLine<F = Arc<SourceFile>> {
    pub sf: F,
    /// Index of line, starting from 0.
    pub line: usize,
}

#[derive(Debug)]
pub struct SourceFileAndBytePos<F = Arc<SourceFile>> {
    pub sf: F,
    pub pos: BytePos,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct LineInfo {
    /// Index of line, starting from 0.
    pub line_index: usize,

    /// Column in line where span begins, starting from 0.
    pub start_col: CharPos,

    /// Column in line where span ends, starting from 0, exclusive.
    pub end_col: CharPos,
}

pub type FileLines<F = Arc<SourceFile>> = WithSourceFile<Vec<LineInfo>, F>;

/// Abstraction over IO operations.
///
/// This is called by the file resolver and source map to access the file system.
///
/// The [default implementation][RealFileLoader] uses [`std::fs`].
pub trait FileLoader: Send + Sync + 'static {
    fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf>;
    fn load_stdin(&self) -> io::Result<String>;
    fn load_file(&self, path: &Path) -> io::Result<String>;
    fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>>;
}

/// Default file loader that uses [`std::fs`].
pub struct RealFileLoader;

#[allow(clippy::disallowed_methods)] // Only place that's allowed.
impl FileLoader for RealFileLoader {
    fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf> {
        crate::canonicalize(path)
    }

    fn load_stdin(&self) -> io::Result<String> {
        let mut src = String::new();
        io::stdin().read_to_string(&mut src)?;
        Ok(src)
    }

    fn load_file(&self, path: &Path) -> io::Result<String> {
        std::fs::read_to_string(path)
    }

    fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
        std::fs::read(path)
    }
}

/// The directories that source file names are displayed relative to, and the current directory,
/// whose drive they are displayed without.
#[derive(Debug)]
pub(crate) struct SourceRoots {
    pub(crate) base_path: Option<PathBuf>,
    pub(crate) include_paths: Vec<PathBuf>,
    current_dir: Option<PathBuf>,
}

impl SourceRoots {
    /// Returns the source unit name of `path`, like solc does for command-line paths.
    pub(crate) fn source_unit_name<'a>(&self, path: &'a Path) -> &'a Path {
        let roots = self.base_path.iter().chain(&self.include_paths);
        file_resolver::source_unit_name(path, roots, self.current_dir.as_deref())
    }
}

/// Stores all the sources of the current compilation session.
#[derive(derive_more::Debug)]
pub struct SourceMap {
    // INVARIANT: `source_files` is monotonic.
    source_files: RwLock<Vec<Arc<SourceFile>>>,
    #[debug(skip)]
    id_to_file: OnceMap<SourceFileId, Arc<SourceFile>, FxBuildHasher>,

    roots: ArcSwapOption<SourceRoots>,
    #[debug(skip)]
    file_loader: OnceLock<Box<dyn FileLoader>>,
}

impl Default for SourceMap {
    fn default() -> Self {
        Self::empty()
    }
}

impl SourceMap {
    /// Creates a new empty source map.
    pub fn empty() -> Self {
        Self {
            source_files: Default::default(),
            id_to_file: Default::default(),
            roots: Default::default(),
            file_loader: Default::default(),
        }
    }

    /// Clears the source map.
    pub fn clear(&mut self) {
        let _ = self.take();
    }

    /// Clears the source map, returning all the contained `SourceFile`s.
    #[must_use]
    pub fn take(&mut self) -> Vec<Arc<SourceFile>> {
        self.id_to_file.clear();
        std::mem::take(self.source_files.get_mut())
    }

    /// Sets the file loader for the source map.
    /// This may only be called once. Further calls will do nothing.
    ///
    /// See [its documentation][FileLoader] for more details.
    pub fn set_file_loader(&self, file_loader: impl FileLoader) {
        if let Err(_prev) = self.file_loader.set(Box::new(file_loader)) {
            warn!("file loader already set");
        }
    }

    /// Returns the file loader for the source map.
    ///
    /// See [its documentation][FileLoader] for more details.
    pub fn file_loader(&self) -> &dyn FileLoader {
        self.file_loader.get().map(std::ops::Deref::deref).unwrap_or(&RealFileLoader)
    }

    /// Sets the base path, include paths and current directory for the source map.
    ///
    /// Source file names are displayed relative to the base path or include paths, without the
    /// current directory's drive, and new file resolvers use the base path as their default.
    pub(crate) fn set_roots(
        &self,
        base_path: Option<PathBuf>,
        include_paths: Vec<PathBuf>,
        current_dir: Option<PathBuf>,
    ) {
        self.roots.store(Some(Arc::new(SourceRoots { base_path, include_paths, current_dir })));
    }

    pub(crate) fn roots(&self) -> arc_swap::Guard<Option<Arc<SourceRoots>>> {
        self.roots.load()
    }

    /// Returns `true` if the source map is empty.
    pub fn is_empty(&self) -> bool {
        self.files().is_empty()
    }

    /// Parses a file name from a string.
    pub fn parse_file_name(&self, s: &str) -> FileName {
        match s {
            "stdin" | "<stdin>" => FileName::Stdin,
            s if s.starts_with('<') && s.ends_with('>') => {
                FileName::Custom(s[1..s.len() - 1].to_string())
            }
            s => {
                if let Some(file) = FileResolver::new(self).get_file(s.as_ref()).or_else(|| {
                    let files = self.files();
                    files
                        .iter()
                        .find(|file| self.filename_for_diagnostics(&file.name).to_string() == s)
                        .cloned()
                }) {
                    file.name.clone()
                } else {
                    FileName::Custom(s.to_string())
                }
            }
        }
    }

    /// Returns the source file with the given path, if it exists.
    /// Does not attempt to load the file.
    pub fn get_file(&self, path: impl Into<FileName>) -> Option<Arc<SourceFile>> {
        self.get_file_ref(&path.into())
    }

    /// Returns the source file with the given path, if it exists.
    /// Does not attempt to load the file.
    pub fn get_file_ref(&self, filename: &FileName) -> Option<Arc<SourceFile>> {
        self.id_to_file.get_cloned(&SourceFileId::new(filename))
    }

    /// Loads a file from the given path.
    pub fn load_file(&self, path: &Path) -> io::Result<Arc<SourceFile>> {
        self.load_file_with_name(path.into(), path)
    }

    /// Loads a file with the given name from the given path.
    pub fn load_file_with_name(&self, name: FileName, path: &Path) -> io::Result<Arc<SourceFile>> {
        self.new_source_file_with(name, || self.file_loader().load_file(path))
    }

    /// Loads `stdin`.
    pub fn load_stdin(&self) -> io::Result<Arc<SourceFile>> {
        self.new_source_file_with(FileName::Stdin, || self.file_loader().load_stdin())
    }

    /// Creates a new `SourceFile` with the given name and source string.
    ///
    /// See [`new_source_file_with`](Self::new_source_file_with) for more details.
    pub fn new_source_file(
        &self,
        name: impl Into<FileName>,
        src: impl Into<String>,
    ) -> io::Result<Arc<SourceFile>> {
        self.new_source_file_with(name.into(), || Ok(src.into()))
    }

    /// Creates a new `SourceFile` that retains the given shared source string.
    pub fn new_source_file_shared(
        &self,
        name: impl Into<FileName>,
        src: Arc<String>,
    ) -> io::Result<Arc<SourceFile>> {
        let filename = name.into();
        let id = SourceFileId::new(&filename);
        self.id_to_file.try_insert_cloned(id, |&id| {
            let file = SourceFile::new(filename, id, src)?;
            self.append_source_file(file)
        })
    }

    /// Creates a new `SourceFile` with the given name and source string closure.
    ///
    /// If a file already exists in the `SourceMap` with the same ID, that file is returned
    /// unmodified, and `get_src` is not called.
    ///
    /// Returns an error if the file is larger than 4GiB or other errors occur while creating the
    /// `SourceFile`.
    ///
    /// Note that the `FileLoader` is not used when calling this function.
    #[instrument(level = "debug", skip_all, fields(filename = %filename.display()))]
    pub fn new_source_file_with(
        &self,
        filename: FileName,
        get_src: impl FnOnce() -> io::Result<String>,
    ) -> io::Result<Arc<SourceFile>> {
        let id = SourceFileId::new(&filename);
        self.id_to_file.try_insert_cloned(id, |&id| {
            let file = SourceFile::new(filename, id, Arc::new(get_src()?))?;
            self.append_source_file(file)
        })
    }

    fn append_source_file(&self, mut file: SourceFile) -> io::Result<Arc<SourceFile>> {
        trace!(name=%file.name.display(), len=file.src.len(), loc=file.count_lines(), "adding to source map");

        let source_files = &mut *self.source_files.write();
        file.start_pos = BytePos(if let Some(last_file) = source_files.last() {
            // Add one so there is some space between files. This lets us distinguish
            // positions in the `SourceMap`, even in the presence of zero-length files.
            last_file.end_position().0.checked_add(1).ok_or(OffsetOverflowError(()))?
        } else {
            0
        });

        let file = Arc::new(file);
        source_files.push(file.clone());

        Ok(file)
    }

    /// Returns a read guard to the source files in the source map.
    pub fn files(&self) -> SourceMapFiles<'_> {
        SourceMapFiles(RwLockReadGuard::map(self.source_files.read(), std::ops::Deref::deref))
    }

    /// Display the filename for diagnostics.
    pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> {
        FileNameDisplay { inner: filename, roots: self.roots() }
    }

    /// Returns `true` if the given span is multi-line.
    pub fn is_multiline(&self, span: Span) -> bool {
        self.files().is_multiline(span)
    }

    /// Returns the source snippet as `String` corresponding to the given `Span`.
    pub fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
        self.files().span_to_snippet(span).map(str::to_owned)
    }

    /// Returns the source snippet as `String` before the given `Span`.
    pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
        self.files().span_to_prev_source(sp).map(str::to_owned)
    }

    /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
    pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
        let files = self.files();
        let SourceFileAndBytePos { sf, pos } = files.lookup_byte_offset(bpos);
        SourceFileAndBytePos { sf: sf.clone(), pos }
    }

    /// Returns the index of the [`SourceFile`] (in `self.files`) that contains `pos`.
    ///
    /// This index is guaranteed to be valid for the lifetime of this `SourceMap`.
    pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
        self.files().lookup_source_file_idx(pos)
    }

    /// Return the SourceFile that contains the given `BytePos`.
    pub fn lookup_source_file(&self, pos: BytePos) -> Arc<SourceFile> {
        self.files().lookup_source_file(pos).clone()
    }

    /// Looks up source information about a `BytePos`.
    pub fn lookup_char_pos(&self, pos: BytePos) -> WithSourceFile<Loc> {
        self.files().lookup_char_pos(pos).into_owned()
    }

    /// If the corresponding `SourceFile` is empty, does not return a line number.
    pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Arc<SourceFile>> {
        self.files()
            .lookup_line(pos)
            .map(|SourceFileAndLine { sf, line }| SourceFileAndLine { sf: sf.clone(), line })
            .map_err(Arc::clone)
    }

    pub fn is_valid_span(&self, sp: Span) -> Result<WithSourceFile<SpanLoc>, SpanLinesError> {
        self.files().is_valid_span(sp).map(|source| source.into_owned())
    }

    pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
        self.files().is_line_before_span_empty(sp)
    }

    /// Computes the [`FileLines`] for the given span.
    pub fn span_to_lines(&self, sp: Span) -> Result<FileLines, SpanLinesError> {
        self.files().span_to_lines(sp).map(|source| source.into_owned())
    }

    /// Returns the source file and the range of text corresponding to the given span.
    ///
    /// See [`span_to_source`](Self::span_to_source).
    pub fn span_to_range(&self, sp: Span) -> Result<Range<usize>, SpanSnippetError> {
        self.files().span_to_range(sp)
    }

    /// Returns the source file and the range of text corresponding to the given span.
    pub fn span_to_source(
        &self,
        sp: Span,
    ) -> Result<WithSourceFile<Range<usize>>, SpanSnippetError> {
        self.files().span_to_source(sp).map(|source| source.into_owned())
    }

    /// Format the span location to be printed in diagnostics.
    ///
    /// Must not be emitted to build artifacts as this may leak local file paths.
    pub fn span_to_diagnostic_string(&self, sp: Span) -> impl fmt::Display {
        let (source_file, loc) = self.span_to_location_info(sp);
        fmt::from_fn(move |f| {
            let file_name = match &source_file {
                Some(sf) => self.filename_for_diagnostics(&sf.name),
                None => return f.write_str("no-location"),
            };
            let lo_line = loc.lo.line;
            let lo_col = loc.lo.col.0 + 1;
            let hi_line = loc.hi.line;
            let hi_col = loc.hi.col.0 + 1;
            write!(f, "{file_name}:{lo_line}:{lo_col}: {hi_line}:{hi_col}")
        })
    }

    /// Returns the source file, line, and column information for the given span.
    ///
    /// This is similar to [`is_valid_span`](Self::is_valid_span).
    pub fn span_to_location_info(&self, sp: Span) -> (Option<Arc<SourceFile>>, SpanLoc) {
        let files = self.files();
        let (file, loc) = files.span_to_location_info(sp);
        (file.cloned(), loc)
    }
}

/// A read guard that supports source lookups without cloning file handles.
///
/// Use this guard for repeated lookups; use [`SourceMap`] methods for individual lookups.
/// While holding the guard, query it directly instead of calling methods that acquire another
/// source-file lock. Drop the guard before loading files into the source map.
pub struct SourceMapFiles<'a>(MappedRwLockReadGuard<'a, [Arc<SourceFile>]>);

impl std::ops::Deref for SourceMapFiles<'_> {
    type Target = [Arc<SourceFile>];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl SourceMapFiles<'_> {
    /// Returns the index of the file containing a byte position.
    pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
        assert!(!self.is_empty(), "attempted to lookup source file in empty `SourceMap`");
        self.partition_point(|file| file.start_pos <= pos) - 1
    }

    /// Returns the file containing a byte position.
    pub fn lookup_source_file(&self, pos: BytePos) -> &Arc<SourceFile> {
        &self[self.lookup_source_file_idx(pos)]
    }

    /// Returns the file and relative byte position.
    pub fn lookup_byte_offset(&self, pos: BytePos) -> SourceFileAndBytePos<&Arc<SourceFile>> {
        let sf = self.lookup_source_file(pos);
        SourceFileAndBytePos { sf, pos: pos - sf.start_pos }
    }

    /// Returns the source location for a byte position.
    pub fn lookup_char_pos(&self, pos: BytePos) -> WithSourceFile<Loc, &Arc<SourceFile>> {
        let file = self.lookup_source_file(pos);
        let (line, col, col_display) = file.lookup_file_pos_with_col_display(pos);
        WithSourceFile { file, data: Loc { line, col, col_display } }
    }

    /// Returns the file and line, or the file alone if it is empty.
    pub fn lookup_line(
        &self,
        pos: BytePos,
    ) -> Result<SourceFileAndLine<&Arc<SourceFile>>, &Arc<SourceFile>> {
        let sf = self.lookup_source_file(pos);
        sf.lookup_line(sf.relative_position(pos))
            .map(|line| SourceFileAndLine { sf, line })
            .ok_or(sf)
    }

    /// Returns whether a span crosses lines or files.
    pub fn is_multiline(&self, span: Span) -> bool {
        let (f, end) = self.lookup_span_files(span);
        if f.start_pos != end.start_pos {
            return true;
        }
        let lo = f.relative_position(span.lo());
        let hi = f.relative_position(span.hi());
        f.lookup_line(lo) != f.lookup_line(hi)
    }

    /// Returns the source file and locations at both ends of a span.
    pub fn is_valid_span(
        &self,
        sp: Span,
    ) -> Result<WithSourceFile<SpanLoc, &Arc<SourceFile>>, SpanLinesError> {
        let (begin, end) = self.lookup_span_files(sp);
        if begin.start_pos != end.start_pos {
            return Err(SpanLinesError::DistinctSources(Box::new(DistinctSources {
                begin: (begin.name.clone(), begin.start_pos),
                end: (end.name.clone(), end.start_pos),
            })));
        }
        let (line, col, col_display) = begin.lookup_file_pos_with_col_display(sp.lo());
        let lo = Loc { line, col, col_display };
        let (line, col, col_display) = begin.lookup_file_pos_with_col_display(sp.hi());
        let hi = Loc { line, col, col_display };
        Ok(WithSourceFile { file: begin, data: SpanLoc { lo, hi } })
    }

    /// Computes the lines covered by a span.
    pub fn span_to_lines(&self, sp: Span) -> Result<FileLines<&Arc<SourceFile>>, SpanLinesError> {
        let WithSourceFile { file, data: SpanLoc { lo, hi } } = self.is_valid_span(sp)?;
        assert!(hi.line >= lo.line);

        if sp.is_dummy() {
            return Ok(FileLines { file, data: Vec::new() });
        }

        let mut lines = Vec::with_capacity(hi.line - lo.line + 1);

        // The span starts partway through the first line,
        // but after that it starts from offset 0.
        let mut start_col = lo.col;

        // For every line but the last, it extends from `start_col`
        // and to the end of the line. Be careful because the line
        // numbers in Loc are 1-based, so we subtract 1 to get 0-based
        // lines.
        //
        // FIXME: now that we handle DUMMY_SP up above, we should consider
        // asserting that the line numbers here are all indeed 1-based.
        let hi_line = hi.line.saturating_sub(1);
        for line_index in lo.line.saturating_sub(1)..hi_line {
            let line_len = file.get_line(line_index).map_or(0, |s| s.chars().count());
            lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
            start_col = CharPos::from_usize(0);
        }

        // For the last line, it extends from `start_col` to `hi.col`:
        lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });

        Ok(FileLines { file, data: lines })
    }

    /// Returns the source file and byte range for a span.
    pub fn span_to_source(
        &self,
        sp: Span,
    ) -> Result<WithSourceFile<Range<usize>, &Arc<SourceFile>>, SpanSnippetError> {
        let (begin, end) = self.lookup_span_files(sp);
        if begin.start_pos != end.start_pos {
            return Err(SpanSnippetError::DistinctSources(Box::new(DistinctSources {
                begin: (begin.name.clone(), begin.start_pos),
                end: (end.name.clone(), end.start_pos),
            })));
        }

        let begin_pos = sp.lo() - begin.start_pos;
        let end_pos = sp.hi() - begin.start_pos;
        let start_index = begin_pos.to_usize();
        let end_index = end_pos.to_usize();
        let source_len = begin.source_len.to_usize();

        if start_index > end_index || end_index > source_len {
            return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
                name: begin.name.clone(),
                source_len,
                begin_pos,
                end_pos,
            }));
        }

        Ok(WithSourceFile { file: begin, data: start_index..end_index })
    }

    /// Returns the source text for a span.
    pub fn span_to_snippet(&self, span: Span) -> Result<&str, SpanSnippetError> {
        let WithSourceFile { file, data: range } = self.span_to_source(span)?;
        file.src.get(range).ok_or(SpanSnippetError::IllFormedSpan(span))
    }

    /// Returns the source text preceding a span.
    pub fn span_to_prev_source(&self, sp: Span) -> Result<&str, SpanSnippetError> {
        let WithSourceFile { file, data: range } = self.span_to_source(sp)?;
        file.src.get(..range.start).ok_or(SpanSnippetError::IllFormedSpan(sp))
    }

    /// Returns whether only whitespace precedes the span on its line.
    pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
        self.span_to_prev_source(sp)
            .is_ok_and(|s| s.rsplit_once('\n').unwrap_or(("", s)).1.trim_start().is_empty())
    }

    /// Returns the byte range for a span.
    pub fn span_to_range(&self, sp: Span) -> Result<Range<usize>, SpanSnippetError> {
        self.span_to_source(sp).map(|source| source.data)
    }

    /// Returns source locations, or no location for dummy or invalid spans.
    pub fn span_to_location_info(&self, sp: Span) -> (Option<&Arc<SourceFile>>, SpanLoc) {
        if sp.is_dummy() || self.is_empty() {
            return Default::default();
        }
        let Ok(WithSourceFile { file, data }) = self.is_valid_span(sp) else {
            return Default::default();
        };
        (Some(file), data)
    }

    fn lookup_span_files(&self, sp: Span) -> (&Arc<SourceFile>, &Arc<SourceFile>) {
        let begin = self.lookup_source_file(sp.lo());
        let end = if (begin.start_pos..=begin.end_position()).contains(&sp.hi()) {
            begin
        } else {
            self.lookup_source_file(sp.hi())
        };
        (begin, end)
    }
}