Skip to main content

solar_interface/source_map/
mod.rs

1//! SourceMap related types and operations.
2
3use crate::{BytePos, CharPos, Span};
4use arc_swap::ArcSwapOption;
5use once_map::OnceMap;
6use solar_data_structures::{
7    map::FxBuildHasher,
8    sync::{MappedRwLockReadGuard, RwLock, RwLockReadGuard},
9};
10use std::{
11    fmt,
12    io::{self, Read},
13    ops::Range,
14    path::{Path, PathBuf},
15    sync::{Arc, OnceLock},
16};
17
18mod analyze;
19
20mod file;
21pub use file::*;
22
23mod file_resolver;
24pub(crate) use file_resolver::absolute_path;
25pub use file_resolver::{FileResolver, ResolveError, apply_import_remappings};
26
27#[cfg(test)]
28mod tests;
29
30#[derive(Clone, PartialEq, Eq, Debug)]
31pub enum SpanLinesError {
32    DistinctSources(Box<DistinctSources>),
33}
34
35/// An error that can occur when converting a `Span` to a snippet.
36///
37/// In general these errors only occur on malformed spans created by the user.
38/// The parser never creates a span that would cause these errors.
39#[derive(Clone, PartialEq, Eq, Debug)]
40pub enum SpanSnippetError {
41    IllFormedSpan(Span),
42    DistinctSources(Box<DistinctSources>),
43    MalformedForSourcemap(MalformedSourceMapPositions),
44    SourceNotAvailable { filename: FileName },
45}
46
47#[derive(Clone, PartialEq, Eq, Debug)]
48pub struct DistinctSources {
49    pub begin: (FileName, BytePos),
50    pub end: (FileName, BytePos),
51}
52
53#[derive(Clone, PartialEq, Eq, Debug)]
54pub struct MalformedSourceMapPositions {
55    pub name: FileName,
56    pub source_len: usize,
57    pub begin_pos: BytePos,
58    pub end_pos: BytePos,
59}
60
61/// A value paired with a source file.
62#[derive(Clone, Debug)]
63pub struct WithSourceFile<T, F = Arc<SourceFile>> {
64    pub file: F,
65    pub data: T,
66}
67
68impl<T, F> std::ops::Deref for WithSourceFile<T, F> {
69    type Target = T;
70
71    #[inline]
72    fn deref(&self) -> &Self::Target {
73        &self.data
74    }
75}
76
77impl<T, F> std::ops::DerefMut for WithSourceFile<T, F> {
78    #[inline]
79    fn deref_mut(&mut self) -> &mut Self::Target {
80        &mut self.data
81    }
82}
83
84impl<T: Clone> WithSourceFile<T, &Arc<SourceFile>> {
85    /// Clones the data and shares ownership of the source file.
86    pub fn to_owned(&self) -> WithSourceFile<T> {
87        WithSourceFile { file: self.file.clone(), data: self.data.clone() }
88    }
89}
90
91impl<T> WithSourceFile<T, &Arc<SourceFile>> {
92    /// Shares ownership of the source file without cloning the data.
93    pub fn into_owned(self) -> WithSourceFile<T> {
94        WithSourceFile { file: self.file.clone(), data: self.data }
95    }
96}
97
98/// A source code location used for error reporting.
99#[derive(Clone, Debug)]
100pub struct Loc {
101    /// The (1-based) line number.
102    pub line: usize,
103    /// The (0-based) column offset.
104    pub col: CharPos,
105    /// The (0-based) column offset when displayed.
106    pub col_display: usize,
107}
108
109impl Default for Loc {
110    fn default() -> Self {
111        Self { line: 0, col: CharPos(0), col_display: 0 }
112    }
113}
114
115/// A source code location used for error reporting.
116///
117/// This is like [`Loc`], but it includes the line and column offsets of the start and end of the
118/// span.
119#[derive(Clone, Debug, Default)]
120pub struct SpanLoc {
121    /// The location of the start of the span.
122    pub lo: Loc,
123    /// The location of the end of the span.
124    pub hi: Loc,
125}
126
127// Used to be structural records.
128#[derive(Debug)]
129pub struct SourceFileAndLine<F = Arc<SourceFile>> {
130    pub sf: F,
131    /// Index of line, starting from 0.
132    pub line: usize,
133}
134
135#[derive(Debug)]
136pub struct SourceFileAndBytePos<F = Arc<SourceFile>> {
137    pub sf: F,
138    pub pos: BytePos,
139}
140
141#[derive(Copy, Clone, Debug, PartialEq, Eq)]
142pub struct LineInfo {
143    /// Index of line, starting from 0.
144    pub line_index: usize,
145
146    /// Column in line where span begins, starting from 0.
147    pub start_col: CharPos,
148
149    /// Column in line where span ends, starting from 0, exclusive.
150    pub end_col: CharPos,
151}
152
153pub type FileLines<F = Arc<SourceFile>> = WithSourceFile<Vec<LineInfo>, F>;
154
155/// Abstraction over IO operations.
156///
157/// This is called by the file resolver and source map to access the file system.
158///
159/// The [default implementation][RealFileLoader] uses [`std::fs`].
160pub trait FileLoader: Send + Sync + 'static {
161    fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf>;
162    fn load_stdin(&self) -> io::Result<String>;
163    fn load_file(&self, path: &Path) -> io::Result<String>;
164    fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>>;
165}
166
167/// Default file loader that uses [`std::fs`].
168pub struct RealFileLoader;
169
170#[allow(clippy::disallowed_methods)] // Only place that's allowed.
171impl FileLoader for RealFileLoader {
172    fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf> {
173        crate::canonicalize(path)
174    }
175
176    fn load_stdin(&self) -> io::Result<String> {
177        let mut src = String::new();
178        io::stdin().read_to_string(&mut src)?;
179        Ok(src)
180    }
181
182    fn load_file(&self, path: &Path) -> io::Result<String> {
183        std::fs::read_to_string(path)
184    }
185
186    fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
187        std::fs::read(path)
188    }
189}
190
191/// The directories that source file names are displayed relative to, and the current directory,
192/// whose drive they are displayed without.
193#[derive(Debug)]
194pub(crate) struct SourceRoots {
195    pub(crate) base_path: Option<PathBuf>,
196    pub(crate) include_paths: Vec<PathBuf>,
197    current_dir: Option<PathBuf>,
198}
199
200impl SourceRoots {
201    /// Returns the source unit name of `path`, like solc does for command-line paths.
202    pub(crate) fn source_unit_name<'a>(&self, path: &'a Path) -> &'a Path {
203        let roots = self.base_path.iter().chain(&self.include_paths);
204        file_resolver::source_unit_name(path, roots, self.current_dir.as_deref())
205    }
206}
207
208/// Stores all the sources of the current compilation session.
209#[derive(derive_more::Debug)]
210pub struct SourceMap {
211    // INVARIANT: `source_files` is monotonic.
212    source_files: RwLock<Vec<Arc<SourceFile>>>,
213    #[debug(skip)]
214    id_to_file: OnceMap<SourceFileId, Arc<SourceFile>, FxBuildHasher>,
215
216    roots: ArcSwapOption<SourceRoots>,
217    #[debug(skip)]
218    file_loader: OnceLock<Box<dyn FileLoader>>,
219}
220
221impl Default for SourceMap {
222    fn default() -> Self {
223        Self::empty()
224    }
225}
226
227impl SourceMap {
228    /// Creates a new empty source map.
229    pub fn empty() -> Self {
230        Self {
231            source_files: Default::default(),
232            id_to_file: Default::default(),
233            roots: Default::default(),
234            file_loader: Default::default(),
235        }
236    }
237
238    /// Clears the source map.
239    pub fn clear(&mut self) {
240        let _ = self.take();
241    }
242
243    /// Clears the source map, returning all the contained `SourceFile`s.
244    #[must_use]
245    pub fn take(&mut self) -> Vec<Arc<SourceFile>> {
246        self.id_to_file.clear();
247        std::mem::take(self.source_files.get_mut())
248    }
249
250    /// Sets the file loader for the source map.
251    /// This may only be called once. Further calls will do nothing.
252    ///
253    /// See [its documentation][FileLoader] for more details.
254    pub fn set_file_loader(&self, file_loader: impl FileLoader) {
255        if let Err(_prev) = self.file_loader.set(Box::new(file_loader)) {
256            warn!("file loader already set");
257        }
258    }
259
260    /// Returns the file loader for the source map.
261    ///
262    /// See [its documentation][FileLoader] for more details.
263    pub fn file_loader(&self) -> &dyn FileLoader {
264        self.file_loader.get().map(std::ops::Deref::deref).unwrap_or(&RealFileLoader)
265    }
266
267    /// Sets the base path, include paths and current directory for the source map.
268    ///
269    /// Source file names are displayed relative to the base path or include paths, without the
270    /// current directory's drive, and new file resolvers use the base path as their default.
271    pub(crate) fn set_roots(
272        &self,
273        base_path: Option<PathBuf>,
274        include_paths: Vec<PathBuf>,
275        current_dir: Option<PathBuf>,
276    ) {
277        self.roots.store(Some(Arc::new(SourceRoots { base_path, include_paths, current_dir })));
278    }
279
280    pub(crate) fn roots(&self) -> arc_swap::Guard<Option<Arc<SourceRoots>>> {
281        self.roots.load()
282    }
283
284    /// Returns `true` if the source map is empty.
285    pub fn is_empty(&self) -> bool {
286        self.files().is_empty()
287    }
288
289    /// Parses a file name from a string.
290    pub fn parse_file_name(&self, s: &str) -> FileName {
291        match s {
292            "stdin" | "<stdin>" => FileName::Stdin,
293            s if s.starts_with('<') && s.ends_with('>') => {
294                FileName::Custom(s[1..s.len() - 1].to_string())
295            }
296            s => {
297                if let Some(file) = FileResolver::new(self).get_file(s.as_ref()).or_else(|| {
298                    let files = self.files();
299                    files
300                        .iter()
301                        .find(|file| self.filename_for_diagnostics(&file.name).to_string() == s)
302                        .cloned()
303                }) {
304                    file.name.clone()
305                } else {
306                    FileName::Custom(s.to_string())
307                }
308            }
309        }
310    }
311
312    /// Returns the source file with the given path, if it exists.
313    /// Does not attempt to load the file.
314    pub fn get_file(&self, path: impl Into<FileName>) -> Option<Arc<SourceFile>> {
315        self.get_file_ref(&path.into())
316    }
317
318    /// Returns the source file with the given path, if it exists.
319    /// Does not attempt to load the file.
320    pub fn get_file_ref(&self, filename: &FileName) -> Option<Arc<SourceFile>> {
321        self.id_to_file.get_cloned(&SourceFileId::new(filename))
322    }
323
324    /// Loads a file from the given path.
325    pub fn load_file(&self, path: &Path) -> io::Result<Arc<SourceFile>> {
326        self.load_file_with_name(path.into(), path)
327    }
328
329    /// Loads a file with the given name from the given path.
330    pub fn load_file_with_name(&self, name: FileName, path: &Path) -> io::Result<Arc<SourceFile>> {
331        self.new_source_file_with(name, || self.file_loader().load_file(path))
332    }
333
334    /// Loads `stdin`.
335    pub fn load_stdin(&self) -> io::Result<Arc<SourceFile>> {
336        self.new_source_file_with(FileName::Stdin, || self.file_loader().load_stdin())
337    }
338
339    /// Creates a new `SourceFile` with the given name and source string.
340    ///
341    /// See [`new_source_file_with`](Self::new_source_file_with) for more details.
342    pub fn new_source_file(
343        &self,
344        name: impl Into<FileName>,
345        src: impl Into<String>,
346    ) -> io::Result<Arc<SourceFile>> {
347        self.new_source_file_with(name.into(), || Ok(src.into()))
348    }
349
350    /// Creates a new `SourceFile` that retains the given shared source string.
351    pub fn new_source_file_shared(
352        &self,
353        name: impl Into<FileName>,
354        src: Arc<String>,
355    ) -> io::Result<Arc<SourceFile>> {
356        let filename = name.into();
357        let id = SourceFileId::new(&filename);
358        self.id_to_file.try_insert_cloned(id, |&id| {
359            let file = SourceFile::new(filename, id, src)?;
360            self.append_source_file(file)
361        })
362    }
363
364    /// Creates a new `SourceFile` with the given name and source string closure.
365    ///
366    /// If a file already exists in the `SourceMap` with the same ID, that file is returned
367    /// unmodified, and `get_src` is not called.
368    ///
369    /// Returns an error if the file is larger than 4GiB or other errors occur while creating the
370    /// `SourceFile`.
371    ///
372    /// Note that the `FileLoader` is not used when calling this function.
373    #[instrument(level = "debug", skip_all, fields(filename = %filename.display()))]
374    pub fn new_source_file_with(
375        &self,
376        filename: FileName,
377        get_src: impl FnOnce() -> io::Result<String>,
378    ) -> io::Result<Arc<SourceFile>> {
379        let id = SourceFileId::new(&filename);
380        self.id_to_file.try_insert_cloned(id, |&id| {
381            let file = SourceFile::new(filename, id, Arc::new(get_src()?))?;
382            self.append_source_file(file)
383        })
384    }
385
386    fn append_source_file(&self, mut file: SourceFile) -> io::Result<Arc<SourceFile>> {
387        trace!(name=%file.name.display(), len=file.src.len(), loc=file.count_lines(), "adding to source map");
388
389        let source_files = &mut *self.source_files.write();
390        file.start_pos = BytePos(if let Some(last_file) = source_files.last() {
391            // Add one so there is some space between files. This lets us distinguish
392            // positions in the `SourceMap`, even in the presence of zero-length files.
393            last_file.end_position().0.checked_add(1).ok_or(OffsetOverflowError(()))?
394        } else {
395            0
396        });
397
398        let file = Arc::new(file);
399        source_files.push(file.clone());
400
401        Ok(file)
402    }
403
404    /// Returns a read guard to the source files in the source map.
405    pub fn files(&self) -> SourceMapFiles<'_> {
406        SourceMapFiles(RwLockReadGuard::map(self.source_files.read(), std::ops::Deref::deref))
407    }
408
409    /// Display the filename for diagnostics.
410    pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> {
411        FileNameDisplay { inner: filename, roots: self.roots() }
412    }
413
414    /// Returns `true` if the given span is multi-line.
415    pub fn is_multiline(&self, span: Span) -> bool {
416        self.files().is_multiline(span)
417    }
418
419    /// Returns the source snippet as `String` corresponding to the given `Span`.
420    pub fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
421        self.files().span_to_snippet(span).map(str::to_owned)
422    }
423
424    /// Returns the source snippet as `String` before the given `Span`.
425    pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
426        self.files().span_to_prev_source(sp).map(str::to_owned)
427    }
428
429    /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
430    pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
431        let files = self.files();
432        let SourceFileAndBytePos { sf, pos } = files.lookup_byte_offset(bpos);
433        SourceFileAndBytePos { sf: sf.clone(), pos }
434    }
435
436    /// Returns the index of the [`SourceFile`] (in `self.files`) that contains `pos`.
437    ///
438    /// This index is guaranteed to be valid for the lifetime of this `SourceMap`.
439    pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
440        self.files().lookup_source_file_idx(pos)
441    }
442
443    /// Return the SourceFile that contains the given `BytePos`.
444    pub fn lookup_source_file(&self, pos: BytePos) -> Arc<SourceFile> {
445        self.files().lookup_source_file(pos).clone()
446    }
447
448    /// Looks up source information about a `BytePos`.
449    pub fn lookup_char_pos(&self, pos: BytePos) -> WithSourceFile<Loc> {
450        self.files().lookup_char_pos(pos).into_owned()
451    }
452
453    /// If the corresponding `SourceFile` is empty, does not return a line number.
454    pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Arc<SourceFile>> {
455        self.files()
456            .lookup_line(pos)
457            .map(|SourceFileAndLine { sf, line }| SourceFileAndLine { sf: sf.clone(), line })
458            .map_err(Arc::clone)
459    }
460
461    pub fn is_valid_span(&self, sp: Span) -> Result<WithSourceFile<SpanLoc>, SpanLinesError> {
462        self.files().is_valid_span(sp).map(|source| source.into_owned())
463    }
464
465    pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
466        self.files().is_line_before_span_empty(sp)
467    }
468
469    /// Computes the [`FileLines`] for the given span.
470    pub fn span_to_lines(&self, sp: Span) -> Result<FileLines, SpanLinesError> {
471        self.files().span_to_lines(sp).map(|source| source.into_owned())
472    }
473
474    /// Returns the source file and the range of text corresponding to the given span.
475    ///
476    /// See [`span_to_source`](Self::span_to_source).
477    pub fn span_to_range(&self, sp: Span) -> Result<Range<usize>, SpanSnippetError> {
478        self.files().span_to_range(sp)
479    }
480
481    /// Returns the source file and the range of text corresponding to the given span.
482    pub fn span_to_source(
483        &self,
484        sp: Span,
485    ) -> Result<WithSourceFile<Range<usize>>, SpanSnippetError> {
486        self.files().span_to_source(sp).map(|source| source.into_owned())
487    }
488
489    /// Format the span location to be printed in diagnostics.
490    ///
491    /// Must not be emitted to build artifacts as this may leak local file paths.
492    pub fn span_to_diagnostic_string(&self, sp: Span) -> impl fmt::Display {
493        let (source_file, loc) = self.span_to_location_info(sp);
494        fmt::from_fn(move |f| {
495            let file_name = match &source_file {
496                Some(sf) => self.filename_for_diagnostics(&sf.name),
497                None => return f.write_str("no-location"),
498            };
499            let lo_line = loc.lo.line;
500            let lo_col = loc.lo.col.0 + 1;
501            let hi_line = loc.hi.line;
502            let hi_col = loc.hi.col.0 + 1;
503            write!(f, "{file_name}:{lo_line}:{lo_col}: {hi_line}:{hi_col}")
504        })
505    }
506
507    /// Returns the source file, line, and column information for the given span.
508    ///
509    /// This is similar to [`is_valid_span`](Self::is_valid_span).
510    pub fn span_to_location_info(&self, sp: Span) -> (Option<Arc<SourceFile>>, SpanLoc) {
511        let files = self.files();
512        let (file, loc) = files.span_to_location_info(sp);
513        (file.cloned(), loc)
514    }
515}
516
517/// A read guard that supports source lookups without cloning file handles.
518///
519/// Use this guard for repeated lookups; use [`SourceMap`] methods for individual lookups.
520/// While holding the guard, query it directly instead of calling methods that acquire another
521/// source-file lock. Drop the guard before loading files into the source map.
522pub struct SourceMapFiles<'a>(MappedRwLockReadGuard<'a, [Arc<SourceFile>]>);
523
524impl std::ops::Deref for SourceMapFiles<'_> {
525    type Target = [Arc<SourceFile>];
526
527    fn deref(&self) -> &Self::Target {
528        &self.0
529    }
530}
531
532impl SourceMapFiles<'_> {
533    /// Returns the index of the file containing a byte position.
534    pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
535        assert!(!self.is_empty(), "attempted to lookup source file in empty `SourceMap`");
536        self.partition_point(|file| file.start_pos <= pos) - 1
537    }
538
539    /// Returns the file containing a byte position.
540    pub fn lookup_source_file(&self, pos: BytePos) -> &Arc<SourceFile> {
541        &self[self.lookup_source_file_idx(pos)]
542    }
543
544    /// Returns the file and relative byte position.
545    pub fn lookup_byte_offset(&self, pos: BytePos) -> SourceFileAndBytePos<&Arc<SourceFile>> {
546        let sf = self.lookup_source_file(pos);
547        SourceFileAndBytePos { sf, pos: pos - sf.start_pos }
548    }
549
550    /// Returns the source location for a byte position.
551    pub fn lookup_char_pos(&self, pos: BytePos) -> WithSourceFile<Loc, &Arc<SourceFile>> {
552        let file = self.lookup_source_file(pos);
553        let (line, col, col_display) = file.lookup_file_pos_with_col_display(pos);
554        WithSourceFile { file, data: Loc { line, col, col_display } }
555    }
556
557    /// Returns the file and line, or the file alone if it is empty.
558    pub fn lookup_line(
559        &self,
560        pos: BytePos,
561    ) -> Result<SourceFileAndLine<&Arc<SourceFile>>, &Arc<SourceFile>> {
562        let sf = self.lookup_source_file(pos);
563        sf.lookup_line(sf.relative_position(pos))
564            .map(|line| SourceFileAndLine { sf, line })
565            .ok_or(sf)
566    }
567
568    /// Returns whether a span crosses lines or files.
569    pub fn is_multiline(&self, span: Span) -> bool {
570        let (f, end) = self.lookup_span_files(span);
571        if f.start_pos != end.start_pos {
572            return true;
573        }
574        let lo = f.relative_position(span.lo());
575        let hi = f.relative_position(span.hi());
576        f.lookup_line(lo) != f.lookup_line(hi)
577    }
578
579    /// Returns the source file and locations at both ends of a span.
580    pub fn is_valid_span(
581        &self,
582        sp: Span,
583    ) -> Result<WithSourceFile<SpanLoc, &Arc<SourceFile>>, SpanLinesError> {
584        let (begin, end) = self.lookup_span_files(sp);
585        if begin.start_pos != end.start_pos {
586            return Err(SpanLinesError::DistinctSources(Box::new(DistinctSources {
587                begin: (begin.name.clone(), begin.start_pos),
588                end: (end.name.clone(), end.start_pos),
589            })));
590        }
591        let (line, col, col_display) = begin.lookup_file_pos_with_col_display(sp.lo());
592        let lo = Loc { line, col, col_display };
593        let (line, col, col_display) = begin.lookup_file_pos_with_col_display(sp.hi());
594        let hi = Loc { line, col, col_display };
595        Ok(WithSourceFile { file: begin, data: SpanLoc { lo, hi } })
596    }
597
598    /// Computes the lines covered by a span.
599    pub fn span_to_lines(&self, sp: Span) -> Result<FileLines<&Arc<SourceFile>>, SpanLinesError> {
600        let WithSourceFile { file, data: SpanLoc { lo, hi } } = self.is_valid_span(sp)?;
601        assert!(hi.line >= lo.line);
602
603        if sp.is_dummy() {
604            return Ok(FileLines { file, data: Vec::new() });
605        }
606
607        let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
608
609        // The span starts partway through the first line,
610        // but after that it starts from offset 0.
611        let mut start_col = lo.col;
612
613        // For every line but the last, it extends from `start_col`
614        // and to the end of the line. Be careful because the line
615        // numbers in Loc are 1-based, so we subtract 1 to get 0-based
616        // lines.
617        //
618        // FIXME: now that we handle DUMMY_SP up above, we should consider
619        // asserting that the line numbers here are all indeed 1-based.
620        let hi_line = hi.line.saturating_sub(1);
621        for line_index in lo.line.saturating_sub(1)..hi_line {
622            let line_len = file.get_line(line_index).map_or(0, |s| s.chars().count());
623            lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
624            start_col = CharPos::from_usize(0);
625        }
626
627        // For the last line, it extends from `start_col` to `hi.col`:
628        lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
629
630        Ok(FileLines { file, data: lines })
631    }
632
633    /// Returns the source file and byte range for a span.
634    pub fn span_to_source(
635        &self,
636        sp: Span,
637    ) -> Result<WithSourceFile<Range<usize>, &Arc<SourceFile>>, SpanSnippetError> {
638        let (begin, end) = self.lookup_span_files(sp);
639        if begin.start_pos != end.start_pos {
640            return Err(SpanSnippetError::DistinctSources(Box::new(DistinctSources {
641                begin: (begin.name.clone(), begin.start_pos),
642                end: (end.name.clone(), end.start_pos),
643            })));
644        }
645
646        let begin_pos = sp.lo() - begin.start_pos;
647        let end_pos = sp.hi() - begin.start_pos;
648        let start_index = begin_pos.to_usize();
649        let end_index = end_pos.to_usize();
650        let source_len = begin.source_len.to_usize();
651
652        if start_index > end_index || end_index > source_len {
653            return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
654                name: begin.name.clone(),
655                source_len,
656                begin_pos,
657                end_pos,
658            }));
659        }
660
661        Ok(WithSourceFile { file: begin, data: start_index..end_index })
662    }
663
664    /// Returns the source text for a span.
665    pub fn span_to_snippet(&self, span: Span) -> Result<&str, SpanSnippetError> {
666        let WithSourceFile { file, data: range } = self.span_to_source(span)?;
667        file.src.get(range).ok_or(SpanSnippetError::IllFormedSpan(span))
668    }
669
670    /// Returns the source text preceding a span.
671    pub fn span_to_prev_source(&self, sp: Span) -> Result<&str, SpanSnippetError> {
672        let WithSourceFile { file, data: range } = self.span_to_source(sp)?;
673        file.src.get(..range.start).ok_or(SpanSnippetError::IllFormedSpan(sp))
674    }
675
676    /// Returns whether only whitespace precedes the span on its line.
677    pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
678        self.span_to_prev_source(sp)
679            .is_ok_and(|s| s.rsplit_once('\n').unwrap_or(("", s)).1.trim_start().is_empty())
680    }
681
682    /// Returns the byte range for a span.
683    pub fn span_to_range(&self, sp: Span) -> Result<Range<usize>, SpanSnippetError> {
684        self.span_to_source(sp).map(|source| source.data)
685    }
686
687    /// Returns source locations, or no location for dummy or invalid spans.
688    pub fn span_to_location_info(&self, sp: Span) -> (Option<&Arc<SourceFile>>, SpanLoc) {
689        if sp.is_dummy() || self.is_empty() {
690            return Default::default();
691        }
692        let Ok(WithSourceFile { file, data }) = self.is_valid_span(sp) else {
693            return Default::default();
694        };
695        (Some(file), data)
696    }
697
698    fn lookup_span_files(&self, sp: Span) -> (&Arc<SourceFile>, &Arc<SourceFile>) {
699        let begin = self.lookup_source_file(sp.lo());
700        let end = if (begin.start_pos..=begin.end_position()).contains(&sp.hi()) {
701            begin
702        } else {
703            self.lookup_source_file(sp.hi())
704        };
705        (begin, end)
706    }
707}