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