]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/source_map.rs
Rollup merge of #95376 - WaffleLapkin:drain_keep_rest, r=dtolnay
[rust.git] / compiler / rustc_span / src / source_map.rs
1 //! Types for tracking pieces of source code within a crate.
2 //!
3 //! The [`SourceMap`] tracks all the source code used within a single crate, mapping
4 //! from integer byte positions to the original source code location. Each bit
5 //! of source parsed during crate parsing (typically files, in-memory strings,
6 //! or various bits of macro expansion) cover a continuous range of bytes in the
7 //! `SourceMap` and are represented by [`SourceFile`]s. Byte positions are stored in
8 //! [`Span`] and used pervasively in the compiler. They are absolute positions
9 //! within the `SourceMap`, which upon request can be converted to line and column
10 //! information, source code snippets, etc.
11
12 pub use crate::hygiene::{ExpnData, ExpnKind};
13 pub use crate::*;
14
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_data_structures::stable_hasher::StableHasher;
17 use rustc_data_structures::sync::{AtomicU32, Lrc, MappedReadGuard, ReadGuard, RwLock};
18 use std::hash::Hash;
19 use std::path::{Path, PathBuf};
20 use std::sync::atomic::Ordering;
21 use std::{clone::Clone, cmp};
22 use std::{convert::TryFrom, unreachable};
23
24 use std::fs;
25 use std::io;
26 use tracing::debug;
27
28 #[cfg(test)]
29 mod tests;
30
31 /// Returns the span itself if it doesn't come from a macro expansion,
32 /// otherwise return the call site span up to the `enclosing_sp` by
33 /// following the `expn_data` chain.
34 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
35     let expn_data1 = sp.ctxt().outer_expn_data();
36     let expn_data2 = enclosing_sp.ctxt().outer_expn_data();
37     if expn_data1.is_root() || !expn_data2.is_root() && expn_data1.call_site == expn_data2.call_site
38     {
39         sp
40     } else {
41         original_sp(expn_data1.call_site, enclosing_sp)
42     }
43 }
44
45 pub mod monotonic {
46     use std::ops::{Deref, DerefMut};
47
48     /// A `MonotonicVec` is a `Vec` which can only be grown.
49     /// Once inserted, an element can never be removed or swapped,
50     /// guaranteeing that any indices into a `MonotonicVec` are stable
51     // This is declared in its own module to ensure that the private
52     // field is inaccessible
53     pub struct MonotonicVec<T>(Vec<T>);
54     impl<T> MonotonicVec<T> {
55         pub fn new(val: Vec<T>) -> MonotonicVec<T> {
56             MonotonicVec(val)
57         }
58
59         pub fn push(&mut self, val: T) {
60             self.0.push(val);
61         }
62     }
63
64     impl<T> Default for MonotonicVec<T> {
65         fn default() -> Self {
66             MonotonicVec::new(vec![])
67         }
68     }
69
70     impl<T> Deref for MonotonicVec<T> {
71         type Target = Vec<T>;
72         fn deref(&self) -> &Self::Target {
73             &self.0
74         }
75     }
76
77     impl<T> !DerefMut for MonotonicVec<T> {}
78 }
79
80 #[derive(Clone, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
81 pub struct Spanned<T> {
82     pub node: T,
83     pub span: Span,
84 }
85
86 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
87     Spanned { node: t, span: sp }
88 }
89
90 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
91     respan(DUMMY_SP, t)
92 }
93
94 // _____________________________________________________________________________
95 // SourceFile, MultiByteChar, FileName, FileLines
96 //
97
98 /// An abstraction over the fs operations used by the Parser.
99 pub trait FileLoader {
100     /// Query the existence of a file.
101     fn file_exists(&self, path: &Path) -> bool;
102
103     /// Read the contents of a UTF-8 file into memory.
104     fn read_file(&self, path: &Path) -> io::Result<String>;
105 }
106
107 /// A FileLoader that uses std::fs to load real files.
108 pub struct RealFileLoader;
109
110 impl FileLoader for RealFileLoader {
111     fn file_exists(&self, path: &Path) -> bool {
112         path.exists()
113     }
114
115     fn read_file(&self, path: &Path) -> io::Result<String> {
116         fs::read_to_string(path)
117     }
118 }
119
120 /// This is a [SourceFile] identifier that is used to correlate source files between
121 /// subsequent compilation sessions (which is something we need to do during
122 /// incremental compilation).
123 ///
124 /// The [StableSourceFileId] also contains the CrateNum of the crate the source
125 /// file was originally parsed for. This way we get two separate entries in
126 /// the [SourceMap] if the same file is part of both the local and an upstream
127 /// crate. Trying to only have one entry for both cases is problematic because
128 /// at the point where we discover that there's a local use of the file in
129 /// addition to the upstream one, we might already have made decisions based on
130 /// the assumption that it's an upstream file. Treating the two files as
131 /// different has no real downsides.
132 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
133 pub struct StableSourceFileId {
134     // A hash of the source file's FileName. This is hash so that it's size
135     // is more predictable than if we included the actual FileName value.
136     pub file_name_hash: u64,
137
138     // The CrateNum of the crate this source file was originally parsed for.
139     // We cannot include this information in the hash because at the time
140     // of hashing we don't have the context to map from the CrateNum's numeric
141     // value to a StableCrateId.
142     pub cnum: CrateNum,
143 }
144
145 // FIXME: we need a more globally consistent approach to the problem solved by
146 // StableSourceFileId, perhaps built atop source_file.name_hash.
147 impl StableSourceFileId {
148     pub fn new(source_file: &SourceFile) -> StableSourceFileId {
149         StableSourceFileId::new_from_name(&source_file.name, source_file.cnum)
150     }
151
152     fn new_from_name(name: &FileName, cnum: CrateNum) -> StableSourceFileId {
153         let mut hasher = StableHasher::new();
154         name.hash(&mut hasher);
155         StableSourceFileId { file_name_hash: hasher.finish(), cnum }
156     }
157 }
158
159 // _____________________________________________________________________________
160 // SourceMap
161 //
162
163 #[derive(Default)]
164 pub(super) struct SourceMapFiles {
165     source_files: monotonic::MonotonicVec<Lrc<SourceFile>>,
166     stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>,
167 }
168
169 pub struct SourceMap {
170     /// The address space below this value is currently used by the files in the source map.
171     used_address_space: AtomicU32,
172
173     files: RwLock<SourceMapFiles>,
174     file_loader: Box<dyn FileLoader + Sync + Send>,
175     // This is used to apply the file path remapping as specified via
176     // `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`.
177     path_mapping: FilePathMapping,
178
179     /// The algorithm used for hashing the contents of each source file.
180     hash_kind: SourceFileHashAlgorithm,
181 }
182
183 impl SourceMap {
184     pub fn new(path_mapping: FilePathMapping) -> SourceMap {
185         Self::with_file_loader_and_hash_kind(
186             Box::new(RealFileLoader),
187             path_mapping,
188             SourceFileHashAlgorithm::Md5,
189         )
190     }
191
192     pub fn with_file_loader_and_hash_kind(
193         file_loader: Box<dyn FileLoader + Sync + Send>,
194         path_mapping: FilePathMapping,
195         hash_kind: SourceFileHashAlgorithm,
196     ) -> SourceMap {
197         SourceMap {
198             used_address_space: AtomicU32::new(0),
199             files: Default::default(),
200             file_loader,
201             path_mapping,
202             hash_kind,
203         }
204     }
205
206     pub fn path_mapping(&self) -> &FilePathMapping {
207         &self.path_mapping
208     }
209
210     pub fn file_exists(&self, path: &Path) -> bool {
211         self.file_loader.file_exists(path)
212     }
213
214     pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
215         let src = self.file_loader.read_file(path)?;
216         let filename = path.to_owned().into();
217         Ok(self.new_source_file(filename, src))
218     }
219
220     /// Loads source file as a binary blob.
221     ///
222     /// Unlike `load_file`, guarantees that no normalization like BOM-removal
223     /// takes place.
224     pub fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
225         // Ideally, this should use `self.file_loader`, but it can't
226         // deal with binary files yet.
227         let bytes = fs::read(path)?;
228
229         // We need to add file to the `SourceMap`, so that it is present
230         // in dep-info. There's also an edge case that file might be both
231         // loaded as a binary via `include_bytes!` and as proper `SourceFile`
232         // via `mod`, so we try to use real file contents and not just an
233         // empty string.
234         let text = std::str::from_utf8(&bytes).unwrap_or("").to_string();
235         self.new_source_file(path.to_owned().into(), text);
236         Ok(bytes)
237     }
238
239     // By returning a `MonotonicVec`, we ensure that consumers cannot invalidate
240     // any existing indices pointing into `files`.
241     pub fn files(&self) -> MappedReadGuard<'_, monotonic::MonotonicVec<Lrc<SourceFile>>> {
242         ReadGuard::map(self.files.borrow(), |files| &files.source_files)
243     }
244
245     pub fn source_file_by_stable_id(
246         &self,
247         stable_id: StableSourceFileId,
248     ) -> Option<Lrc<SourceFile>> {
249         self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned()
250     }
251
252     fn allocate_address_space(&self, size: usize) -> Result<usize, OffsetOverflowError> {
253         let size = u32::try_from(size).map_err(|_| OffsetOverflowError)?;
254
255         loop {
256             let current = self.used_address_space.load(Ordering::Relaxed);
257             let next = current
258                 .checked_add(size)
259                 // Add one so there is some space between files. This lets us distinguish
260                 // positions in the `SourceMap`, even in the presence of zero-length files.
261                 .and_then(|next| next.checked_add(1))
262                 .ok_or(OffsetOverflowError)?;
263
264             if self
265                 .used_address_space
266                 .compare_exchange(current, next, Ordering::Relaxed, Ordering::Relaxed)
267                 .is_ok()
268             {
269                 return Ok(usize::try_from(current).unwrap());
270             }
271         }
272     }
273
274     /// Creates a new `SourceFile`.
275     /// If a file already exists in the `SourceMap` with the same ID, that file is returned
276     /// unmodified.
277     pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
278         self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| {
279             eprintln!("fatal error: rustc does not support files larger than 4GB");
280             crate::fatal_error::FatalError.raise()
281         })
282     }
283
284     fn try_new_source_file(
285         &self,
286         filename: FileName,
287         src: String,
288     ) -> Result<Lrc<SourceFile>, OffsetOverflowError> {
289         // Note that filename may not be a valid path, eg it may be `<anon>` etc,
290         // but this is okay because the directory determined by `path.pop()` will
291         // be empty, so the working directory will be used.
292         let (filename, _) = self.path_mapping.map_filename_prefix(&filename);
293
294         let file_id = StableSourceFileId::new_from_name(&filename, LOCAL_CRATE);
295
296         let lrc_sf = match self.source_file_by_stable_id(file_id) {
297             Some(lrc_sf) => lrc_sf,
298             None => {
299                 let start_pos = self.allocate_address_space(src.len())?;
300
301                 let source_file = Lrc::new(SourceFile::new(
302                     filename,
303                     src,
304                     Pos::from_usize(start_pos),
305                     self.hash_kind,
306                 ));
307
308                 // Let's make sure the file_id we generated above actually matches
309                 // the ID we generate for the SourceFile we just created.
310                 debug_assert_eq!(StableSourceFileId::new(&source_file), file_id);
311
312                 let mut files = self.files.borrow_mut();
313
314                 files.source_files.push(source_file.clone());
315                 files.stable_id_to_source_file.insert(file_id, source_file.clone());
316
317                 source_file
318             }
319         };
320         Ok(lrc_sf)
321     }
322
323     /// Allocates a new `SourceFile` representing a source file from an external
324     /// crate. The source code of such an "imported `SourceFile`" is not available,
325     /// but we still know enough to generate accurate debuginfo location
326     /// information for things inlined from other crates.
327     pub fn new_imported_source_file(
328         &self,
329         filename: FileName,
330         src_hash: SourceFileHash,
331         name_hash: u128,
332         source_len: usize,
333         cnum: CrateNum,
334         file_local_lines: Lock<SourceFileLines>,
335         mut file_local_multibyte_chars: Vec<MultiByteChar>,
336         mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
337         mut file_local_normalized_pos: Vec<NormalizedPos>,
338         original_start_pos: BytePos,
339         metadata_index: u32,
340     ) -> Lrc<SourceFile> {
341         let start_pos = self
342             .allocate_address_space(source_len)
343             .expect("not enough address space for imported source file");
344
345         let end_pos = Pos::from_usize(start_pos + source_len);
346         let start_pos = Pos::from_usize(start_pos);
347
348         // Translate these positions into the new global frame of reference,
349         // now that the offset of the SourceFile is known.
350         //
351         // These are all unsigned values. `original_start_pos` may be larger or
352         // smaller than `start_pos`, but `pos` is always larger than both.
353         // Therefore, `(pos - original_start_pos) + start_pos` won't overflow
354         // but `start_pos - original_start_pos` might. So we use the former
355         // form rather than pre-computing the offset into a local variable. The
356         // compiler backend can optimize away the repeated computations in a
357         // way that won't trigger overflow checks.
358         match &mut *file_local_lines.borrow_mut() {
359             SourceFileLines::Lines(lines) => {
360                 for pos in lines {
361                     *pos = (*pos - original_start_pos) + start_pos;
362                 }
363             }
364             SourceFileLines::Diffs(SourceFileDiffs { line_start, .. }) => {
365                 *line_start = (*line_start - original_start_pos) + start_pos;
366             }
367         }
368         for mbc in &mut file_local_multibyte_chars {
369             mbc.pos = (mbc.pos - original_start_pos) + start_pos;
370         }
371         for swc in &mut file_local_non_narrow_chars {
372             *swc = (*swc - original_start_pos) + start_pos;
373         }
374         for nc in &mut file_local_normalized_pos {
375             nc.pos = (nc.pos - original_start_pos) + start_pos;
376         }
377
378         let source_file = Lrc::new(SourceFile {
379             name: filename,
380             src: None,
381             src_hash,
382             external_src: Lock::new(ExternalSource::Foreign {
383                 kind: ExternalSourceKind::AbsentOk,
384                 metadata_index,
385             }),
386             start_pos,
387             end_pos,
388             lines: file_local_lines,
389             multibyte_chars: file_local_multibyte_chars,
390             non_narrow_chars: file_local_non_narrow_chars,
391             normalized_pos: file_local_normalized_pos,
392             name_hash,
393             cnum,
394         });
395
396         let mut files = self.files.borrow_mut();
397
398         files.source_files.push(source_file.clone());
399         files
400             .stable_id_to_source_file
401             .insert(StableSourceFileId::new(&source_file), source_file.clone());
402
403         source_file
404     }
405
406     // If there is a doctest offset, applies it to the line.
407     pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
408         match file {
409             FileName::DocTest(_, offset) => {
410                 if *offset < 0 {
411                     orig - (-(*offset)) as usize
412                 } else {
413                     orig + *offset as usize
414                 }
415             }
416             _ => orig,
417         }
418     }
419
420     /// Return the SourceFile that contains the given `BytePos`
421     pub fn lookup_source_file(&self, pos: BytePos) -> Lrc<SourceFile> {
422         let idx = self.lookup_source_file_idx(pos);
423         (*self.files.borrow().source_files)[idx].clone()
424     }
425
426     /// Looks up source information about a `BytePos`.
427     pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
428         let sf = self.lookup_source_file(pos);
429         let (line, col, col_display) = sf.lookup_file_pos_with_col_display(pos);
430         Loc { file: sf, line, col, col_display }
431     }
432
433     // If the corresponding `SourceFile` is empty, does not return a line number.
434     pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
435         let f = self.lookup_source_file(pos);
436
437         match f.lookup_line(pos) {
438             Some(line) => Ok(SourceFileAndLine { sf: f, line }),
439             None => Err(f),
440         }
441     }
442
443     fn span_to_string(&self, sp: Span, filename_display_pref: FileNameDisplayPreference) -> String {
444         if self.files.borrow().source_files.is_empty() || sp.is_dummy() {
445             return "no-location".to_string();
446         }
447
448         let lo = self.lookup_char_pos(sp.lo());
449         let hi = self.lookup_char_pos(sp.hi());
450         format!(
451             "{}:{}:{}: {}:{}",
452             lo.file.name.display(filename_display_pref),
453             lo.line,
454             lo.col.to_usize() + 1,
455             hi.line,
456             hi.col.to_usize() + 1,
457         )
458     }
459
460     /// Format the span location suitable for embedding in build artifacts
461     pub fn span_to_embeddable_string(&self, sp: Span) -> String {
462         self.span_to_string(sp, FileNameDisplayPreference::Remapped)
463     }
464
465     /// Format the span location suitable for pretty printing anotations with relative line numbers
466     pub fn span_to_relative_line_string(&self, sp: Span, relative_to: Span) -> String {
467         if self.files.borrow().source_files.is_empty() || sp.is_dummy() || relative_to.is_dummy() {
468             return "no-location".to_string();
469         }
470
471         let lo = self.lookup_char_pos(sp.lo());
472         let hi = self.lookup_char_pos(sp.hi());
473         let offset = self.lookup_char_pos(relative_to.lo());
474
475         if lo.file.name != offset.file.name || !relative_to.contains(sp) {
476             return self.span_to_embeddable_string(sp);
477         }
478
479         let lo_line = lo.line.saturating_sub(offset.line);
480         let hi_line = hi.line.saturating_sub(offset.line);
481
482         format!(
483             "{}:+{}:{}: +{}:{}",
484             lo.file.name.display(FileNameDisplayPreference::Remapped),
485             lo_line,
486             lo.col.to_usize() + 1,
487             hi_line,
488             hi.col.to_usize() + 1,
489         )
490     }
491
492     /// Format the span location to be printed in diagnostics. Must not be emitted
493     /// to build artifacts as this may leak local file paths. Use span_to_embeddable_string
494     /// for string suitable for embedding.
495     pub fn span_to_diagnostic_string(&self, sp: Span) -> String {
496         self.span_to_string(sp, self.path_mapping.filename_display_for_diagnostics)
497     }
498
499     pub fn span_to_filename(&self, sp: Span) -> FileName {
500         self.lookup_char_pos(sp.lo()).file.name.clone()
501     }
502
503     pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> {
504         filename.display(self.path_mapping.filename_display_for_diagnostics)
505     }
506
507     pub fn is_multiline(&self, sp: Span) -> bool {
508         let lo = self.lookup_source_file_idx(sp.lo());
509         let hi = self.lookup_source_file_idx(sp.hi());
510         if lo != hi {
511             return true;
512         }
513         let f = (*self.files.borrow().source_files)[lo].clone();
514         f.lookup_line(sp.lo()) != f.lookup_line(sp.hi())
515     }
516
517     #[instrument(skip(self), level = "trace")]
518     pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> {
519         let lo = self.lookup_char_pos(sp.lo());
520         trace!(?lo);
521         let hi = self.lookup_char_pos(sp.hi());
522         trace!(?hi);
523         if lo.file.start_pos != hi.file.start_pos {
524             return Err(SpanLinesError::DistinctSources(DistinctSources {
525                 begin: (lo.file.name.clone(), lo.file.start_pos),
526                 end: (hi.file.name.clone(), hi.file.start_pos),
527             }));
528         }
529         Ok((lo, hi))
530     }
531
532     pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
533         match self.span_to_prev_source(sp) {
534             Ok(s) => s.rsplit_once('\n').unwrap_or(("", &s)).1.trim_start().is_empty(),
535             Err(_) => false,
536         }
537     }
538
539     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
540         debug!("span_to_lines(sp={:?})", sp);
541         let (lo, hi) = self.is_valid_span(sp)?;
542         assert!(hi.line >= lo.line);
543
544         if sp.is_dummy() {
545             return Ok(FileLines { file: lo.file, lines: Vec::new() });
546         }
547
548         let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
549
550         // The span starts partway through the first line,
551         // but after that it starts from offset 0.
552         let mut start_col = lo.col;
553
554         // For every line but the last, it extends from `start_col`
555         // and to the end of the line. Be careful because the line
556         // numbers in Loc are 1-based, so we subtract 1 to get 0-based
557         // lines.
558         //
559         // FIXME: now that we handle DUMMY_SP up above, we should consider
560         // asserting that the line numbers here are all indeed 1-based.
561         let hi_line = hi.line.saturating_sub(1);
562         for line_index in lo.line.saturating_sub(1)..hi_line {
563             let line_len = lo.file.get_line(line_index).map_or(0, |s| s.chars().count());
564             lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
565             start_col = CharPos::from_usize(0);
566         }
567
568         // For the last line, it extends from `start_col` to `hi.col`:
569         lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
570
571         Ok(FileLines { file: lo.file, lines })
572     }
573
574     /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
575     /// extract function takes three arguments: a string slice containing the source, an index in
576     /// the slice for the beginning of the span and an index in the slice for the end of the span.
577     fn span_to_source<F, T>(&self, sp: Span, extract_source: F) -> Result<T, SpanSnippetError>
578     where
579         F: Fn(&str, usize, usize) -> Result<T, SpanSnippetError>,
580     {
581         let local_begin = self.lookup_byte_offset(sp.lo());
582         let local_end = self.lookup_byte_offset(sp.hi());
583
584         if local_begin.sf.start_pos != local_end.sf.start_pos {
585             Err(SpanSnippetError::DistinctSources(DistinctSources {
586                 begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos),
587                 end: (local_end.sf.name.clone(), local_end.sf.start_pos),
588             }))
589         } else {
590             self.ensure_source_file_source_present(local_begin.sf.clone());
591
592             let start_index = local_begin.pos.to_usize();
593             let end_index = local_end.pos.to_usize();
594             let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
595
596             if start_index > end_index || end_index > source_len {
597                 return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
598                     name: local_begin.sf.name.clone(),
599                     source_len,
600                     begin_pos: local_begin.pos,
601                     end_pos: local_end.pos,
602                 }));
603             }
604
605             if let Some(ref src) = local_begin.sf.src {
606                 extract_source(src, start_index, end_index)
607             } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
608                 extract_source(src, start_index, end_index)
609             } else {
610                 Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() })
611             }
612         }
613     }
614
615     pub fn is_span_accessible(&self, sp: Span) -> bool {
616         self.span_to_source(sp, |src, start_index, end_index| {
617             Ok(src.get(start_index..end_index).is_some())
618         })
619         .map_or(false, |is_accessible| is_accessible)
620     }
621
622     /// Returns the source snippet as `String` corresponding to the given `Span`.
623     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
624         self.span_to_source(sp, |src, start_index, end_index| {
625             src.get(start_index..end_index)
626                 .map(|s| s.to_string())
627                 .ok_or(SpanSnippetError::IllFormedSpan(sp))
628         })
629     }
630
631     pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
632         Some(self.indentation_before(sp)?.len())
633     }
634
635     pub fn indentation_before(&self, sp: Span) -> Option<String> {
636         self.span_to_source(sp, |src, start_index, _| {
637             let before = &src[..start_index];
638             let last_line = before.rsplit_once('\n').map_or(before, |(_, last)| last);
639             Ok(last_line
640                 .split_once(|c: char| !c.is_whitespace())
641                 .map_or(last_line, |(indent, _)| indent)
642                 .to_string())
643         })
644         .ok()
645     }
646
647     /// Returns the source snippet as `String` before the given `Span`.
648     pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
649         self.span_to_source(sp, |src, start_index, _| {
650             src.get(..start_index).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
651         })
652     }
653
654     /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span
655     /// if no character could be found or if an error occurred while retrieving the code snippet.
656     pub fn span_extend_to_prev_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
657         if let Ok(prev_source) = self.span_to_prev_source(sp) {
658             let prev_source = prev_source.rsplit(c).next().unwrap_or("");
659             if !prev_source.is_empty() && (accept_newlines || !prev_source.contains('\n')) {
660                 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
661             }
662         }
663
664         sp
665     }
666
667     /// Extends the given `Span` to just after the previous occurrence of `pat` when surrounded by
668     /// whitespace. Returns None if the pattern could not be found or if an error occurred while
669     /// retrieving the code snippet.
670     pub fn span_extend_to_prev_str(
671         &self,
672         sp: Span,
673         pat: &str,
674         accept_newlines: bool,
675         include_whitespace: bool,
676     ) -> Option<Span> {
677         // assure that the pattern is delimited, to avoid the following
678         //     fn my_fn()
679         //           ^^^^ returned span without the check
680         //     ---------- correct span
681         let prev_source = self.span_to_prev_source(sp).ok()?;
682         for ws in &[" ", "\t", "\n"] {
683             let pat = pat.to_owned() + ws;
684             if let Some(pat_pos) = prev_source.rfind(&pat) {
685                 let just_after_pat_pos = pat_pos + pat.len() - 1;
686                 let just_after_pat_plus_ws = if include_whitespace {
687                     just_after_pat_pos
688                         + prev_source[just_after_pat_pos..]
689                             .find(|c: char| !c.is_whitespace())
690                             .unwrap_or(0)
691                 } else {
692                     just_after_pat_pos
693                 };
694                 let len = prev_source.len() - just_after_pat_plus_ws;
695                 let prev_source = &prev_source[just_after_pat_plus_ws..];
696                 if accept_newlines || !prev_source.trim_start().contains('\n') {
697                     return Some(sp.with_lo(BytePos(sp.lo().0 - len as u32)));
698                 }
699             }
700         }
701
702         None
703     }
704
705     /// Returns the source snippet as `String` after the given `Span`.
706     pub fn span_to_next_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
707         self.span_to_source(sp, |src, _, end_index| {
708             src.get(end_index..).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
709         })
710     }
711
712     /// Extends the given `Span` while the next character matches the predicate
713     pub fn span_extend_while(
714         &self,
715         span: Span,
716         f: impl Fn(char) -> bool,
717     ) -> Result<Span, SpanSnippetError> {
718         self.span_to_source(span, |s, _start, end| {
719             let n = s[end..].char_indices().find(|&(_, c)| !f(c)).map_or(s.len() - end, |(i, _)| i);
720             Ok(span.with_hi(span.hi() + BytePos(n as u32)))
721         })
722     }
723
724     /// Extends the given `Span` to just before the next occurrence of `c`.
725     pub fn span_extend_to_next_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
726         if let Ok(next_source) = self.span_to_next_source(sp) {
727             let next_source = next_source.split(c).next().unwrap_or("");
728             if !next_source.is_empty() && (accept_newlines || !next_source.contains('\n')) {
729                 return sp.with_hi(BytePos(sp.hi().0 + next_source.len() as u32));
730             }
731         }
732
733         sp
734     }
735
736     /// Extends the given `Span` to contain the entire line it is on.
737     pub fn span_extend_to_line(&self, sp: Span) -> Span {
738         self.span_extend_to_prev_char(self.span_extend_to_next_char(sp, '\n', true), '\n', true)
739     }
740
741     /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char`
742     /// `c`.
743     pub fn span_until_char(&self, sp: Span, c: char) -> Span {
744         match self.span_to_snippet(sp) {
745             Ok(snippet) => {
746                 let snippet = snippet.split(c).next().unwrap_or("").trim_end();
747                 if !snippet.is_empty() && !snippet.contains('\n') {
748                     sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
749                 } else {
750                     sp
751                 }
752             }
753             _ => sp,
754         }
755     }
756
757     /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char`
758     /// `c`.
759     pub fn span_through_char(&self, sp: Span, c: char) -> Span {
760         if let Ok(snippet) = self.span_to_snippet(sp) {
761             if let Some(offset) = snippet.find(c) {
762                 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
763             }
764         }
765         sp
766     }
767
768     /// Given a `Span`, gets a new `Span` covering the first token and all its trailing whitespace
769     /// or the original `Span`.
770     ///
771     /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
772     pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
773         let mut whitespace_found = false;
774
775         self.span_take_while(sp, |c| {
776             if !whitespace_found && c.is_whitespace() {
777                 whitespace_found = true;
778             }
779
780             !whitespace_found || c.is_whitespace()
781         })
782     }
783
784     /// Given a `Span`, gets a new `Span` covering the first token without its trailing whitespace
785     /// or the original `Span` in case of error.
786     ///
787     /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
788     pub fn span_until_whitespace(&self, sp: Span) -> Span {
789         self.span_take_while(sp, |c| !c.is_whitespace())
790     }
791
792     /// Given a `Span`, gets a shorter one until `predicate` yields `false`.
793     pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
794     where
795         P: for<'r> FnMut(&'r char) -> bool,
796     {
797         if let Ok(snippet) = self.span_to_snippet(sp) {
798             let offset = snippet.chars().take_while(predicate).map(|c| c.len_utf8()).sum::<usize>();
799
800             sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
801         } else {
802             sp
803         }
804     }
805
806     /// Given a `Span`, return a span ending in the closest `{`. This is useful when you have a
807     /// `Span` enclosing a whole item but we need to point at only the head (usually the first
808     /// line) of that item.
809     ///
810     /// *Only suitable for diagnostics.*
811     pub fn guess_head_span(&self, sp: Span) -> Span {
812         // FIXME: extend the AST items to have a head span, or replace callers with pointing at
813         // the item's ident when appropriate.
814         self.span_until_char(sp, '{')
815     }
816
817     /// Returns a new span representing just the first character of the given span.
818     pub fn start_point(&self, sp: Span) -> Span {
819         let width = {
820             let sp = sp.data();
821             let local_begin = self.lookup_byte_offset(sp.lo);
822             let start_index = local_begin.pos.to_usize();
823             let src = local_begin.sf.external_src.borrow();
824
825             let snippet = if let Some(ref src) = local_begin.sf.src {
826                 Some(&src[start_index..])
827             } else if let Some(src) = src.get_source() {
828                 Some(&src[start_index..])
829             } else {
830                 None
831             };
832
833             match snippet {
834                 None => 1,
835                 Some(snippet) => match snippet.chars().next() {
836                     None => 1,
837                     Some(c) => c.len_utf8(),
838                 },
839             }
840         };
841
842         sp.with_hi(BytePos(sp.lo().0 + width as u32))
843     }
844
845     /// Returns a new span representing just the last character of this span.
846     pub fn end_point(&self, sp: Span) -> Span {
847         let pos = sp.hi().0;
848
849         let width = self.find_width_of_character_at_span(sp, false);
850         let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
851
852         let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
853         sp.with_lo(end_point)
854     }
855
856     /// Returns a new span representing the next character after the end-point of this span.
857     pub fn next_point(&self, sp: Span) -> Span {
858         if sp.is_dummy() {
859             return sp;
860         }
861         let start_of_next_point = sp.hi().0;
862
863         let width = self.find_width_of_character_at_span(sp.shrink_to_hi(), true);
864         // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
865         // in the case of a multibyte character, where the width != 1, the next span should
866         // span multiple bytes to include the whole character.
867         let end_of_next_point =
868             start_of_next_point.checked_add(width - 1).unwrap_or(start_of_next_point);
869
870         let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
871         Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt(), None)
872     }
873
874     /// Finds the width of the character, either before or after the end of provided span,
875     /// depending on the `forwards` parameter.
876     fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
877         let sp = sp.data();
878         if sp.lo == sp.hi {
879             debug!("find_width_of_character_at_span: early return empty span");
880             return 1;
881         }
882
883         let local_begin = self.lookup_byte_offset(sp.lo);
884         let local_end = self.lookup_byte_offset(sp.hi);
885         debug!(
886             "find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
887             local_begin, local_end
888         );
889
890         if local_begin.sf.start_pos != local_end.sf.start_pos {
891             debug!("find_width_of_character_at_span: begin and end are in different files");
892             return 1;
893         }
894
895         let start_index = local_begin.pos.to_usize();
896         let end_index = local_end.pos.to_usize();
897         debug!(
898             "find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
899             start_index, end_index
900         );
901
902         // Disregard indexes that are at the start or end of their spans, they can't fit bigger
903         // characters.
904         if (!forwards && end_index == usize::MIN) || (forwards && start_index == usize::MAX) {
905             debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
906             return 1;
907         }
908
909         let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
910         debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
911         // Ensure indexes are also not malformed.
912         if start_index > end_index || end_index > source_len {
913             debug!("find_width_of_character_at_span: source indexes are malformed");
914             return 1;
915         }
916
917         let src = local_begin.sf.external_src.borrow();
918
919         // We need to extend the snippet to the end of the src rather than to end_index so when
920         // searching forwards for boundaries we've got somewhere to search.
921         let snippet = if let Some(ref src) = local_begin.sf.src {
922             &src[start_index..]
923         } else if let Some(src) = src.get_source() {
924             &src[start_index..]
925         } else {
926             return 1;
927         };
928         debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
929
930         let mut target = if forwards { end_index + 1 } else { end_index - 1 };
931         debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
932
933         while !snippet.is_char_boundary(target - start_index) && target < source_len {
934             target = if forwards {
935                 target + 1
936             } else {
937                 match target.checked_sub(1) {
938                     Some(target) => target,
939                     None => {
940                         break;
941                     }
942                 }
943             };
944             debug!("find_width_of_character_at_span: target=`{:?}`", target);
945         }
946         debug!("find_width_of_character_at_span: final target=`{:?}`", target);
947
948         if forwards { (target - end_index) as u32 } else { (end_index - target) as u32 }
949     }
950
951     pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
952         // Remap filename before lookup
953         let filename = self.path_mapping().map_filename_prefix(filename).0;
954         for sf in self.files.borrow().source_files.iter() {
955             if filename == sf.name {
956                 return Some(sf.clone());
957             }
958         }
959         None
960     }
961
962     /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
963     pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
964         let idx = self.lookup_source_file_idx(bpos);
965         let sf = (*self.files.borrow().source_files)[idx].clone();
966         let offset = bpos - sf.start_pos;
967         SourceFileAndBytePos { sf, pos: offset }
968     }
969
970     // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`.
971     // This index is guaranteed to be valid for the lifetime of this `SourceMap`,
972     // since `source_files` is a `MonotonicVec`
973     pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
974         self.files
975             .borrow()
976             .source_files
977             .binary_search_by_key(&pos, |key| key.start_pos)
978             .unwrap_or_else(|p| p - 1)
979     }
980
981     pub fn count_lines(&self) -> usize {
982         self.files().iter().fold(0, |a, f| a + f.count_lines())
983     }
984
985     pub fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
986         source_file.add_external_src(|| {
987             match source_file.name {
988                 FileName::Real(ref name) if let Some(local_path) = name.local_path() => {
989                     self.file_loader.read_file(local_path).ok()
990                 }
991                 _ => None,
992             }
993         })
994     }
995
996     pub fn is_imported(&self, sp: Span) -> bool {
997         let source_file_index = self.lookup_source_file_idx(sp.lo());
998         let source_file = &self.files()[source_file_index];
999         source_file.is_imported()
1000     }
1001
1002     /// Gets the span of a statement. If the statement is a macro expansion, the
1003     /// span in the context of the block span is found. The trailing semicolon is included
1004     /// on a best-effort basis.
1005     pub fn stmt_span(&self, stmt_span: Span, block_span: Span) -> Span {
1006         if !stmt_span.from_expansion() {
1007             return stmt_span;
1008         }
1009         let mac_call = original_sp(stmt_span, block_span);
1010         self.mac_call_stmt_semi_span(mac_call).map_or(mac_call, |s| mac_call.with_hi(s.hi()))
1011     }
1012
1013     /// Tries to find the span of the semicolon of a macro call statement.
1014     /// The input must be the *call site* span of a statement from macro expansion.
1015     /// ```ignore (illustrative)
1016     /// //       v output
1017     ///    mac!();
1018     /// // ^^^^^^ input
1019     /// ```
1020     pub fn mac_call_stmt_semi_span(&self, mac_call: Span) -> Option<Span> {
1021         let span = self.span_extend_while(mac_call, char::is_whitespace).ok()?;
1022         let span = span.shrink_to_hi().with_hi(BytePos(span.hi().0.checked_add(1)?));
1023         if self.span_to_snippet(span).as_deref() != Ok(";") {
1024             return None;
1025         }
1026         Some(span)
1027     }
1028 }
1029
1030 #[derive(Clone)]
1031 pub struct FilePathMapping {
1032     mapping: Vec<(PathBuf, PathBuf)>,
1033     filename_display_for_diagnostics: FileNameDisplayPreference,
1034 }
1035
1036 impl FilePathMapping {
1037     pub fn empty() -> FilePathMapping {
1038         FilePathMapping::new(Vec::new())
1039     }
1040
1041     pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1042         let filename_display_for_diagnostics = if mapping.is_empty() {
1043             FileNameDisplayPreference::Local
1044         } else {
1045             FileNameDisplayPreference::Remapped
1046         };
1047
1048         FilePathMapping { mapping, filename_display_for_diagnostics }
1049     }
1050
1051     /// Applies any path prefix substitution as defined by the mapping.
1052     /// The return value is the remapped path and a boolean indicating whether
1053     /// the path was affected by the mapping.
1054     pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1055         if path.as_os_str().is_empty() {
1056             // Exit early if the path is empty and therefore there's nothing to remap.
1057             // This is mostly to reduce spam for `RUSTC_LOG=[remap_path_prefix]`.
1058             return (path, false);
1059         }
1060
1061         return remap_path_prefix(&self.mapping, path);
1062
1063         #[instrument(level = "debug", skip(mapping))]
1064         fn remap_path_prefix(mapping: &[(PathBuf, PathBuf)], path: PathBuf) -> (PathBuf, bool) {
1065             // NOTE: We are iterating over the mapping entries from last to first
1066             //       because entries specified later on the command line should
1067             //       take precedence.
1068             for &(ref from, ref to) in mapping.iter().rev() {
1069                 debug!("Trying to apply {:?} => {:?}", from, to);
1070
1071                 if let Ok(rest) = path.strip_prefix(from) {
1072                     let remapped = if rest.as_os_str().is_empty() {
1073                         // This is subtle, joining an empty path onto e.g. `foo/bar` will
1074                         // result in `foo/bar/`, that is, there'll be an additional directory
1075                         // separator at the end. This can lead to duplicated directory separators
1076                         // in remapped paths down the line.
1077                         // So, if we have an exact match, we just return that without a call
1078                         // to `Path::join()`.
1079                         to.clone()
1080                     } else {
1081                         to.join(rest)
1082                     };
1083                     debug!("Match - remapped {:?} => {:?}", path, remapped);
1084
1085                     return (remapped, true);
1086                 } else {
1087                     debug!("No match - prefix {:?} does not match {:?}", from, path);
1088                 }
1089             }
1090
1091             debug!("Path {:?} was not remapped", path);
1092             (path, false)
1093         }
1094     }
1095
1096     fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) {
1097         match file {
1098             FileName::Real(realfile) if let RealFileName::LocalPath(local_path) = realfile => {
1099                 let (mapped_path, mapped) = self.map_prefix(local_path.to_path_buf());
1100                 let realfile = if mapped {
1101                     RealFileName::Remapped {
1102                         local_path: Some(local_path.clone()),
1103                         virtual_name: mapped_path,
1104                     }
1105                 } else {
1106                     realfile.clone()
1107                 };
1108                 (FileName::Real(realfile), mapped)
1109             }
1110             FileName::Real(_) => unreachable!("attempted to remap an already remapped filename"),
1111             other => (other.clone(), false),
1112         }
1113     }
1114
1115     /// Expand a relative path to an absolute path with remapping taken into account.
1116     /// Use this when absolute paths are required (e.g. debuginfo or crate metadata).
1117     ///
1118     /// The resulting `RealFileName` will have its `local_path` portion erased if
1119     /// possible (i.e. if there's also a remapped path).
1120     pub fn to_embeddable_absolute_path(
1121         &self,
1122         file_path: RealFileName,
1123         working_directory: &RealFileName,
1124     ) -> RealFileName {
1125         match file_path {
1126             // Anything that's already remapped we don't modify, except for erasing
1127             // the `local_path` portion.
1128             RealFileName::Remapped { local_path: _, virtual_name } => {
1129                 RealFileName::Remapped {
1130                     // We do not want any local path to be exported into metadata
1131                     local_path: None,
1132                     // We use the remapped name verbatim, even if it looks like a relative
1133                     // path. The assumption is that the user doesn't want us to further
1134                     // process paths that have gone through remapping.
1135                     virtual_name,
1136                 }
1137             }
1138
1139             RealFileName::LocalPath(unmapped_file_path) => {
1140                 // If no remapping has been applied yet, try to do so
1141                 let (new_path, was_remapped) = self.map_prefix(unmapped_file_path);
1142                 if was_remapped {
1143                     // It was remapped, so don't modify further
1144                     return RealFileName::Remapped { local_path: None, virtual_name: new_path };
1145                 }
1146
1147                 if new_path.is_absolute() {
1148                     // No remapping has applied to this path and it is absolute,
1149                     // so the working directory cannot influence it either, so
1150                     // we are done.
1151                     return RealFileName::LocalPath(new_path);
1152                 }
1153
1154                 debug_assert!(new_path.is_relative());
1155                 let unmapped_file_path_rel = new_path;
1156
1157                 match working_directory {
1158                     RealFileName::LocalPath(unmapped_working_dir_abs) => {
1159                         let file_path_abs = unmapped_working_dir_abs.join(unmapped_file_path_rel);
1160
1161                         // Although neither `working_directory` nor the file name were subject
1162                         // to path remapping, the concatenation between the two may be. Hence
1163                         // we need to do a remapping here.
1164                         let (file_path_abs, was_remapped) = self.map_prefix(file_path_abs);
1165                         if was_remapped {
1166                             RealFileName::Remapped {
1167                                 // Erase the actual path
1168                                 local_path: None,
1169                                 virtual_name: file_path_abs,
1170                             }
1171                         } else {
1172                             // No kind of remapping applied to this path, so
1173                             // we leave it as it is.
1174                             RealFileName::LocalPath(file_path_abs)
1175                         }
1176                     }
1177                     RealFileName::Remapped {
1178                         local_path: _,
1179                         virtual_name: remapped_working_dir_abs,
1180                     } => {
1181                         // If working_directory has been remapped, then we emit
1182                         // Remapped variant as the expanded path won't be valid
1183                         RealFileName::Remapped {
1184                             local_path: None,
1185                             virtual_name: Path::new(remapped_working_dir_abs)
1186                                 .join(unmapped_file_path_rel),
1187                         }
1188                     }
1189                 }
1190             }
1191         }
1192     }
1193 }