1 //! Types for tracking pieces of source code within a crate.
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.
12 pub use crate::hygiene::{ExpnData, ExpnKind};
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};
19 use std::path::{Path, PathBuf};
20 use std::sync::atomic::Ordering;
21 use std::{clone::Clone, cmp};
22 use std::{convert::TryFrom, unreachable};
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
41 original_sp(expn_data1.call_site, enclosing_sp)
46 use std::ops::{Deref, DerefMut};
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> {
59 pub fn push(&mut self, val: T) {
64 impl<T> Default for MonotonicVec<T> {
65 fn default() -> Self {
66 MonotonicVec::new(vec![])
70 impl<T> Deref for MonotonicVec<T> {
72 fn deref(&self) -> &Self::Target {
77 impl<T> !DerefMut for MonotonicVec<T> {}
80 #[derive(Clone, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
81 pub struct Spanned<T> {
86 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
87 Spanned { node: t, span: sp }
90 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
94 // _____________________________________________________________________________
95 // SourceFile, MultiByteChar, FileName, FileLines
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;
103 /// Read the contents of a UTF-8 file into memory.
104 fn read_file(&self, path: &Path) -> io::Result<String>;
107 /// A FileLoader that uses std::fs to load real files.
108 pub struct RealFileLoader;
110 impl FileLoader for RealFileLoader {
111 fn file_exists(&self, path: &Path) -> bool {
115 fn read_file(&self, path: &Path) -> io::Result<String> {
116 fs::read_to_string(path)
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).
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,
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.
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)
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 }
159 // _____________________________________________________________________________
164 pub(super) struct SourceMapFiles {
165 source_files: monotonic::MonotonicVec<Lrc<SourceFile>>,
166 stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>,
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,
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,
179 /// The algorithm used for hashing the contents of each source file.
180 hash_kind: SourceFileHashAlgorithm,
184 pub fn new(path_mapping: FilePathMapping) -> SourceMap {
185 Self::with_file_loader_and_hash_kind(
186 Box::new(RealFileLoader),
188 SourceFileHashAlgorithm::Md5,
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,
198 used_address_space: AtomicU32::new(0),
199 files: Default::default(),
206 pub fn path_mapping(&self) -> &FilePathMapping {
210 pub fn file_exists(&self, path: &Path) -> bool {
211 self.file_loader.file_exists(path)
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))
220 /// Loads source file as a binary blob.
222 /// Unlike `load_file`, guarantees that no normalization like BOM-removal
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)?;
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
234 let text = std::str::from_utf8(&bytes).unwrap_or("").to_string();
235 self.new_source_file(path.to_owned().into(), text);
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)
245 pub fn source_file_by_stable_id(
247 stable_id: StableSourceFileId,
248 ) -> Option<Lrc<SourceFile>> {
249 self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned()
252 fn allocate_address_space(&self, size: usize) -> Result<usize, OffsetOverflowError> {
253 let size = u32::try_from(size).map_err(|_| OffsetOverflowError)?;
256 let current = self.used_address_space.load(Ordering::Relaxed);
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)?;
266 .compare_exchange(current, next, Ordering::Relaxed, Ordering::Relaxed)
269 return Ok(usize::try_from(current).unwrap());
274 /// Creates a new `SourceFile`.
275 /// If a file already exists in the `SourceMap` with the same ID, that file is returned
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()
284 fn try_new_source_file(
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);
294 let file_id = StableSourceFileId::new_from_name(&filename, LOCAL_CRATE);
296 let lrc_sf = match self.source_file_by_stable_id(file_id) {
297 Some(lrc_sf) => lrc_sf,
299 let start_pos = self.allocate_address_space(src.len())?;
301 let source_file = Lrc::new(SourceFile::new(
304 Pos::from_usize(start_pos),
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);
312 let mut files = self.files.borrow_mut();
314 files.source_files.push(source_file.clone());
315 files.stable_id_to_source_file.insert(file_id, source_file.clone());
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(
330 src_hash: SourceFileHash,
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 original_end_pos: BytePos,
340 ) -> Lrc<SourceFile> {
342 .allocate_address_space(source_len)
343 .expect("not enough address space for imported source file");
345 let end_pos = Pos::from_usize(start_pos + source_len);
346 let start_pos = Pos::from_usize(start_pos);
348 // Translate these positions into the new global frame of reference,
349 // now that the offset of the SourceFile is known.
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) => {
361 *pos = (*pos - original_start_pos) + start_pos;
364 SourceFileLines::Diffs(SourceFileDiffs { line_start, .. }) => {
365 *line_start = (*line_start - original_start_pos) + start_pos;
368 for mbc in &mut file_local_multibyte_chars {
369 mbc.pos = (mbc.pos - original_start_pos) + start_pos;
371 for swc in &mut file_local_non_narrow_chars {
372 *swc = (*swc - original_start_pos) + start_pos;
374 for nc in &mut file_local_normalized_pos {
375 nc.pos = (nc.pos - original_start_pos) + start_pos;
378 let source_file = Lrc::new(SourceFile {
382 external_src: Lock::new(ExternalSource::Foreign {
383 kind: ExternalSourceKind::AbsentOk,
389 lines: file_local_lines,
390 multibyte_chars: file_local_multibyte_chars,
391 non_narrow_chars: file_local_non_narrow_chars,
392 normalized_pos: file_local_normalized_pos,
397 let mut files = self.files.borrow_mut();
399 files.source_files.push(source_file.clone());
401 .stable_id_to_source_file
402 .insert(StableSourceFileId::new(&source_file), source_file.clone());
407 // If there is a doctest offset, applies it to the line.
408 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
410 FileName::DocTest(_, offset) => {
412 orig - (-(*offset)) as usize
414 orig + *offset as usize
421 /// Return the SourceFile that contains the given `BytePos`
422 pub fn lookup_source_file(&self, pos: BytePos) -> Lrc<SourceFile> {
423 let idx = self.lookup_source_file_idx(pos);
424 (*self.files.borrow().source_files)[idx].clone()
427 /// Looks up source information about a `BytePos`.
428 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
429 let sf = self.lookup_source_file(pos);
430 let (line, col, col_display) = sf.lookup_file_pos_with_col_display(pos);
431 Loc { file: sf, line, col, col_display }
434 // If the corresponding `SourceFile` is empty, does not return a line number.
435 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
436 let f = self.lookup_source_file(pos);
438 match f.lookup_line(pos) {
439 Some(line) => Ok(SourceFileAndLine { sf: f, line }),
444 fn span_to_string(&self, sp: Span, filename_display_pref: FileNameDisplayPreference) -> String {
445 if self.files.borrow().source_files.is_empty() || sp.is_dummy() {
446 return "no-location".to_string();
449 let lo = self.lookup_char_pos(sp.lo());
450 let hi = self.lookup_char_pos(sp.hi());
453 lo.file.name.display(filename_display_pref),
455 lo.col.to_usize() + 1,
457 hi.col.to_usize() + 1,
461 /// Format the span location suitable for embedding in build artifacts
462 pub fn span_to_embeddable_string(&self, sp: Span) -> String {
463 self.span_to_string(sp, FileNameDisplayPreference::Remapped)
466 /// Format the span location to be printed in diagnostics. Must not be emitted
467 /// to build artifacts as this may leak local file paths. Use span_to_embeddable_string
468 /// for string suitable for embedding.
469 pub fn span_to_diagnostic_string(&self, sp: Span) -> String {
470 self.span_to_string(sp, self.path_mapping.filename_display_for_diagnostics)
473 pub fn span_to_filename(&self, sp: Span) -> FileName {
474 self.lookup_char_pos(sp.lo()).file.name.clone()
477 pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> {
478 filename.display(self.path_mapping.filename_display_for_diagnostics)
481 pub fn is_multiline(&self, sp: Span) -> bool {
482 let lo = self.lookup_source_file_idx(sp.lo());
483 let hi = self.lookup_source_file_idx(sp.hi());
487 let f = (*self.files.borrow().source_files)[lo].clone();
488 f.lookup_line(sp.lo()) != f.lookup_line(sp.hi())
491 #[instrument(skip(self), level = "trace")]
492 pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> {
493 let lo = self.lookup_char_pos(sp.lo());
495 let hi = self.lookup_char_pos(sp.hi());
497 if lo.file.start_pos != hi.file.start_pos {
498 return Err(SpanLinesError::DistinctSources(DistinctSources {
499 begin: (lo.file.name.clone(), lo.file.start_pos),
500 end: (hi.file.name.clone(), hi.file.start_pos),
506 pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
507 match self.span_to_prev_source(sp) {
508 Ok(s) => s.rsplit_once('\n').unwrap_or(("", &s)).1.trim_start().is_empty(),
513 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
514 debug!("span_to_lines(sp={:?})", sp);
515 let (lo, hi) = self.is_valid_span(sp)?;
516 assert!(hi.line >= lo.line);
519 return Ok(FileLines { file: lo.file, lines: Vec::new() });
522 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
524 // The span starts partway through the first line,
525 // but after that it starts from offset 0.
526 let mut start_col = lo.col;
528 // For every line but the last, it extends from `start_col`
529 // and to the end of the line. Be careful because the line
530 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
533 // FIXME: now that we handle DUMMY_SP up above, we should consider
534 // asserting that the line numbers here are all indeed 1-based.
535 let hi_line = hi.line.saturating_sub(1);
536 for line_index in lo.line.saturating_sub(1)..hi_line {
537 let line_len = lo.file.get_line(line_index).map_or(0, |s| s.chars().count());
538 lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
539 start_col = CharPos::from_usize(0);
542 // For the last line, it extends from `start_col` to `hi.col`:
543 lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
545 Ok(FileLines { file: lo.file, lines })
548 /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
549 /// extract function takes three arguments: a string slice containing the source, an index in
550 /// the slice for the beginning of the span and an index in the slice for the end of the span.
551 fn span_to_source<F, T>(&self, sp: Span, extract_source: F) -> Result<T, SpanSnippetError>
553 F: Fn(&str, usize, usize) -> Result<T, SpanSnippetError>,
555 let local_begin = self.lookup_byte_offset(sp.lo());
556 let local_end = self.lookup_byte_offset(sp.hi());
558 if local_begin.sf.start_pos != local_end.sf.start_pos {
559 Err(SpanSnippetError::DistinctSources(DistinctSources {
560 begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos),
561 end: (local_end.sf.name.clone(), local_end.sf.start_pos),
564 self.ensure_source_file_source_present(local_begin.sf.clone());
566 let start_index = local_begin.pos.to_usize();
567 let end_index = local_end.pos.to_usize();
568 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
570 if start_index > end_index || end_index > source_len {
571 return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
572 name: local_begin.sf.name.clone(),
574 begin_pos: local_begin.pos,
575 end_pos: local_end.pos,
579 if let Some(ref src) = local_begin.sf.src {
580 extract_source(src, start_index, end_index)
581 } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
582 extract_source(src, start_index, end_index)
584 Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() })
589 /// Returns whether or not this span points into a file
590 /// in the current crate. This may be `false` for spans
591 /// produced by a macro expansion, or for spans associated
592 /// with the definition of an item in a foreign crate
593 pub fn is_local_span(&self, sp: Span) -> bool {
594 let local_begin = self.lookup_byte_offset(sp.lo());
595 let local_end = self.lookup_byte_offset(sp.hi());
596 // This might be a weird span that covers multiple files
597 local_begin.sf.src.is_some() && local_end.sf.src.is_some()
600 /// Returns the source snippet as `String` corresponding to the given `Span`.
601 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
602 self.span_to_source(sp, |src, start_index, end_index| {
603 src.get(start_index..end_index)
604 .map(|s| s.to_string())
605 .ok_or(SpanSnippetError::IllFormedSpan(sp))
609 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
610 Some(self.indentation_before(sp)?.len())
613 pub fn indentation_before(&self, sp: Span) -> Option<String> {
614 self.span_to_source(sp, |src, start_index, _| {
615 let before = &src[..start_index];
616 let last_line = before.rsplit_once('\n').map_or(before, |(_, last)| last);
618 .split_once(|c: char| !c.is_whitespace())
619 .map_or(last_line, |(indent, _)| indent)
625 /// Returns the source snippet as `String` before the given `Span`.
626 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
627 self.span_to_source(sp, |src, start_index, _| {
628 src.get(..start_index).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
632 /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span
633 /// if no character could be found or if an error occurred while retrieving the code snippet.
634 pub fn span_extend_to_prev_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
635 if let Ok(prev_source) = self.span_to_prev_source(sp) {
636 let prev_source = prev_source.rsplit(c).next().unwrap_or("");
637 if !prev_source.is_empty() && (accept_newlines || !prev_source.contains('\n')) {
638 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
645 /// Extends the given `Span` to just after the previous occurrence of `pat` when surrounded by
646 /// whitespace. Returns None if the pattern could not be found or if an error occurred while
647 /// retrieving the code snippet.
648 pub fn span_extend_to_prev_str(
652 accept_newlines: bool,
653 include_whitespace: bool,
655 // assure that the pattern is delimited, to avoid the following
657 // ^^^^ returned span without the check
658 // ---------- correct span
659 let prev_source = self.span_to_prev_source(sp).ok()?;
660 for ws in &[" ", "\t", "\n"] {
661 let pat = pat.to_owned() + ws;
662 if let Some(pat_pos) = prev_source.rfind(&pat) {
663 let just_after_pat_pos = pat_pos + pat.len() - 1;
664 let just_after_pat_plus_ws = if include_whitespace {
666 + prev_source[just_after_pat_pos..]
667 .find(|c: char| !c.is_whitespace())
672 let len = prev_source.len() - just_after_pat_plus_ws;
673 let prev_source = &prev_source[just_after_pat_plus_ws..];
674 if accept_newlines || !prev_source.trim_start().contains('\n') {
675 return Some(sp.with_lo(BytePos(sp.lo().0 - len as u32)));
683 /// Returns the source snippet as `String` after the given `Span`.
684 pub fn span_to_next_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
685 self.span_to_source(sp, |src, _, end_index| {
686 src.get(end_index..).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
690 /// Extends the given `Span` while the next character matches the predicate
691 pub fn span_extend_while(
694 f: impl Fn(char) -> bool,
695 ) -> Result<Span, SpanSnippetError> {
696 self.span_to_source(span, |s, _start, end| {
697 let n = s[end..].char_indices().find(|&(_, c)| !f(c)).map_or(s.len() - end, |(i, _)| i);
698 Ok(span.with_hi(span.hi() + BytePos(n as u32)))
702 /// Extends the given `Span` to just after the next occurrence of `c`.
703 pub fn span_extend_to_next_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
704 if let Ok(next_source) = self.span_to_next_source(sp) {
705 let next_source = next_source.split(c).next().unwrap_or("");
706 if !next_source.is_empty() && (accept_newlines || !next_source.contains('\n')) {
707 return sp.with_hi(BytePos(sp.hi().0 + next_source.len() as u32));
714 /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char`
716 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
717 match self.span_to_snippet(sp) {
719 let snippet = snippet.split(c).next().unwrap_or("").trim_end();
720 if !snippet.is_empty() && !snippet.contains('\n') {
721 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
730 /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char`
732 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
733 if let Ok(snippet) = self.span_to_snippet(sp) {
734 if let Some(offset) = snippet.find(c) {
735 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
741 /// Given a `Span`, gets a new `Span` covering the first token and all its trailing whitespace
742 /// or the original `Span`.
744 /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
745 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
746 let mut whitespace_found = false;
748 self.span_take_while(sp, |c| {
749 if !whitespace_found && c.is_whitespace() {
750 whitespace_found = true;
753 !whitespace_found || c.is_whitespace()
757 /// Given a `Span`, gets a new `Span` covering the first token without its trailing whitespace
758 /// or the original `Span` in case of error.
760 /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
761 pub fn span_until_whitespace(&self, sp: Span) -> Span {
762 self.span_take_while(sp, |c| !c.is_whitespace())
765 /// Given a `Span`, gets a shorter one until `predicate` yields `false`.
766 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
768 P: for<'r> FnMut(&'r char) -> bool,
770 if let Ok(snippet) = self.span_to_snippet(sp) {
771 let offset = snippet.chars().take_while(predicate).map(|c| c.len_utf8()).sum::<usize>();
773 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
779 /// Given a `Span`, return a span ending in the closest `{`. This is useful when you have a
780 /// `Span` enclosing a whole item but we need to point at only the head (usually the first
781 /// line) of that item.
783 /// *Only suitable for diagnostics.*
784 pub fn guess_head_span(&self, sp: Span) -> Span {
785 // FIXME: extend the AST items to have a head span, or replace callers with pointing at
786 // the item's ident when appropriate.
787 self.span_until_char(sp, '{')
790 /// Returns a new span representing just the first character of the given span.
791 pub fn start_point(&self, sp: Span) -> Span {
794 let local_begin = self.lookup_byte_offset(sp.lo);
795 let start_index = local_begin.pos.to_usize();
796 let src = local_begin.sf.external_src.borrow();
798 let snippet = if let Some(ref src) = local_begin.sf.src {
799 Some(&src[start_index..])
800 } else if let Some(src) = src.get_source() {
801 Some(&src[start_index..])
808 Some(snippet) => match snippet.chars().next() {
810 Some(c) => c.len_utf8(),
815 sp.with_hi(BytePos(sp.lo().0 + width as u32))
818 /// Returns a new span representing just the last character of this span.
819 pub fn end_point(&self, sp: Span) -> Span {
822 let width = self.find_width_of_character_at_span(sp, false);
823 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
825 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
826 sp.with_lo(end_point)
829 /// Returns a new span representing the next character after the end-point of this span.
830 pub fn next_point(&self, sp: Span) -> Span {
834 let start_of_next_point = sp.hi().0;
836 let width = self.find_width_of_character_at_span(sp.shrink_to_hi(), true);
837 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
838 // in the case of a multibyte character, where the width != 1, the next span should
839 // span multiple bytes to include the whole character.
840 let end_of_next_point =
841 start_of_next_point.checked_add(width - 1).unwrap_or(start_of_next_point);
843 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
844 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt(), None)
847 /// Finds the width of the character, either before or after the end of provided span,
848 /// depending on the `forwards` parameter.
849 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
852 debug!("find_width_of_character_at_span: early return empty span");
856 let local_begin = self.lookup_byte_offset(sp.lo);
857 let local_end = self.lookup_byte_offset(sp.hi);
859 "find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
860 local_begin, local_end
863 if local_begin.sf.start_pos != local_end.sf.start_pos {
864 debug!("find_width_of_character_at_span: begin and end are in different files");
868 let start_index = local_begin.pos.to_usize();
869 let end_index = local_end.pos.to_usize();
871 "find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
872 start_index, end_index
875 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
877 if (!forwards && end_index == usize::MIN) || (forwards && start_index == usize::MAX) {
878 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
882 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
883 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
884 // Ensure indexes are also not malformed.
885 if start_index > end_index || end_index > source_len {
886 debug!("find_width_of_character_at_span: source indexes are malformed");
890 let src = local_begin.sf.external_src.borrow();
892 // We need to extend the snippet to the end of the src rather than to end_index so when
893 // searching forwards for boundaries we've got somewhere to search.
894 let snippet = if let Some(ref src) = local_begin.sf.src {
896 } else if let Some(src) = src.get_source() {
901 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
903 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
904 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
906 while !snippet.is_char_boundary(target - start_index) && target < source_len {
907 target = if forwards {
910 match target.checked_sub(1) {
911 Some(target) => target,
917 debug!("find_width_of_character_at_span: target=`{:?}`", target);
919 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
921 if forwards { (target - end_index) as u32 } else { (end_index - target) as u32 }
924 pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
925 // Remap filename before lookup
926 let filename = self.path_mapping().map_filename_prefix(filename).0;
927 for sf in self.files.borrow().source_files.iter() {
928 if filename == sf.name {
929 return Some(sf.clone());
935 /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
936 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
937 let idx = self.lookup_source_file_idx(bpos);
938 let sf = (*self.files.borrow().source_files)[idx].clone();
939 let offset = bpos - sf.start_pos;
940 SourceFileAndBytePos { sf, pos: offset }
943 // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`.
944 // This index is guaranteed to be valid for the lifetime of this `SourceMap`,
945 // since `source_files` is a `MonotonicVec`
946 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
950 .binary_search_by_key(&pos, |key| key.start_pos)
951 .unwrap_or_else(|p| p - 1)
954 pub fn count_lines(&self) -> usize {
955 self.files().iter().fold(0, |a, f| a + f.count_lines())
958 pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
959 let prev_span = self.span_extend_to_prev_str(span, "fn", true, true).unwrap_or(span);
960 if let Ok(snippet) = self.span_to_snippet(prev_span) {
962 "generate_fn_name_span: span={:?}, prev_span={:?}, snippet={:?}",
963 span, prev_span, snippet
966 if snippet.is_empty() {
971 .find(|c: char| !c.is_alphanumeric() && c != '_')
972 .expect("no label after fn");
973 Some(prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32)))
979 /// Takes the span of a type parameter in a function signature and try to generate a span for
980 /// the function name (with generics) and a new snippet for this span with the pointed type
981 /// parameter as a new local type parameter.
984 /// ```rust,ignore (pseudo-Rust)
986 /// fn my_function(param: T)
987 /// // ^ Original span
990 /// fn my_function(param: T)
991 /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
994 /// Attention: The method used is very fragile since it essentially duplicates the work of the
995 /// parser. If you need to use this function or something similar, please consider updating the
996 /// `SourceMap` functions and this function to something more robust.
997 pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
998 // Try to extend the span to the previous "fn" keyword to retrieve the function
1000 if let Some(sugg_span) = self.span_extend_to_prev_str(span, "fn", false, true) {
1001 if let Ok(snippet) = self.span_to_snippet(sugg_span) {
1002 // Consume the function name.
1003 let mut offset = snippet
1004 .find(|c: char| !c.is_alphanumeric() && c != '_')
1005 .expect("no label after fn");
1007 // Consume the generics part of the function signature.
1008 let mut bracket_counter = 0;
1009 let mut last_char = None;
1010 for c in snippet[offset..].chars() {
1012 '<' => bracket_counter += 1,
1013 '>' => bracket_counter -= 1,
1015 if bracket_counter == 0 {
1021 offset += c.len_utf8();
1022 last_char = Some(c);
1025 // Adjust the suggestion span to encompass the function name with its generics.
1026 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
1028 // Prepare the new suggested snippet to append the type parameter that triggered
1029 // the error in the generics of the function signature.
1030 let mut new_snippet = if last_char == Some('>') {
1031 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
1033 format!("{}<", &snippet[..offset])
1036 .push_str(&self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
1037 new_snippet.push('>');
1039 return Some((sugg_span, new_snippet));
1045 pub fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
1046 source_file.add_external_src(|| {
1047 match source_file.name {
1048 FileName::Real(ref name) if let Some(local_path) = name.local_path() => {
1049 self.file_loader.read_file(local_path).ok()
1056 pub fn is_imported(&self, sp: Span) -> bool {
1057 let source_file_index = self.lookup_source_file_idx(sp.lo());
1058 let source_file = &self.files()[source_file_index];
1059 source_file.is_imported()
1062 /// Gets the span of a statement. If the statement is a macro expansion, the
1063 /// span in the context of the block span is found. The trailing semicolon is included
1064 /// on a best-effort basis.
1065 pub fn stmt_span(&self, stmt_span: Span, block_span: Span) -> Span {
1066 if !stmt_span.from_expansion() {
1069 let mac_call = original_sp(stmt_span, block_span);
1070 self.mac_call_stmt_semi_span(mac_call).map_or(mac_call, |s| mac_call.with_hi(s.hi()))
1073 /// Tries to find the span of the semicolon of a macro call statement.
1074 /// The input must be the *call site* span of a statement from macro expansion.
1075 /// ```ignore (illustrative)
1080 pub fn mac_call_stmt_semi_span(&self, mac_call: Span) -> Option<Span> {
1081 let span = self.span_extend_while(mac_call, char::is_whitespace).ok()?;
1082 let span = span.shrink_to_hi().with_hi(BytePos(span.hi().0.checked_add(1)?));
1083 if self.span_to_snippet(span).as_deref() != Ok(";") {
1091 pub struct FilePathMapping {
1092 mapping: Vec<(PathBuf, PathBuf)>,
1093 filename_display_for_diagnostics: FileNameDisplayPreference,
1096 impl FilePathMapping {
1097 pub fn empty() -> FilePathMapping {
1098 FilePathMapping::new(Vec::new())
1101 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1102 let filename_display_for_diagnostics = if mapping.is_empty() {
1103 FileNameDisplayPreference::Local
1105 FileNameDisplayPreference::Remapped
1108 FilePathMapping { mapping, filename_display_for_diagnostics }
1111 /// Applies any path prefix substitution as defined by the mapping.
1112 /// The return value is the remapped path and a boolean indicating whether
1113 /// the path was affected by the mapping.
1114 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1115 if path.as_os_str().is_empty() {
1116 // Exit early if the path is empty and therefore there's nothing to remap.
1117 // This is mostly to reduce spam for `RUSTC_LOG=[remap_path_prefix]`.
1118 return (path, false);
1121 return remap_path_prefix(&self.mapping, path);
1123 #[instrument(level = "debug", skip(mapping))]
1124 fn remap_path_prefix(mapping: &[(PathBuf, PathBuf)], path: PathBuf) -> (PathBuf, bool) {
1125 // NOTE: We are iterating over the mapping entries from last to first
1126 // because entries specified later on the command line should
1128 for &(ref from, ref to) in mapping.iter().rev() {
1129 debug!("Trying to apply {:?} => {:?}", from, to);
1131 if let Ok(rest) = path.strip_prefix(from) {
1132 let remapped = if rest.as_os_str().is_empty() {
1133 // This is subtle, joining an empty path onto e.g. `foo/bar` will
1134 // result in `foo/bar/`, that is, there'll be an additional directory
1135 // separator at the end. This can lead to duplicated directory separators
1136 // in remapped paths down the line.
1137 // So, if we have an exact match, we just return that without a call
1138 // to `Path::join()`.
1143 debug!("Match - remapped {:?} => {:?}", path, remapped);
1145 return (remapped, true);
1147 debug!("No match - prefix {:?} does not match {:?}", from, path);
1151 debug!("Path {:?} was not remapped", path);
1156 fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) {
1158 FileName::Real(realfile) if let RealFileName::LocalPath(local_path) = realfile => {
1159 let (mapped_path, mapped) = self.map_prefix(local_path.to_path_buf());
1160 let realfile = if mapped {
1161 RealFileName::Remapped {
1162 local_path: Some(local_path.clone()),
1163 virtual_name: mapped_path,
1168 (FileName::Real(realfile), mapped)
1170 FileName::Real(_) => unreachable!("attempted to remap an already remapped filename"),
1171 other => (other.clone(), false),
1175 /// Expand a relative path to an absolute path with remapping taken into account.
1176 /// Use this when absolute paths are required (e.g. debuginfo or crate metadata).
1178 /// The resulting `RealFileName` will have its `local_path` portion erased if
1179 /// possible (i.e. if there's also a remapped path).
1180 pub fn to_embeddable_absolute_path(
1182 file_path: RealFileName,
1183 working_directory: &RealFileName,
1186 // Anything that's already remapped we don't modify, except for erasing
1187 // the `local_path` portion.
1188 RealFileName::Remapped { local_path: _, virtual_name } => {
1189 RealFileName::Remapped {
1190 // We do not want any local path to be exported into metadata
1192 // We use the remapped name verbatim, even if it looks like a relative
1193 // path. The assumption is that the user doesn't want us to further
1194 // process paths that have gone through remapping.
1199 RealFileName::LocalPath(unmapped_file_path) => {
1200 // If no remapping has been applied yet, try to do so
1201 let (new_path, was_remapped) = self.map_prefix(unmapped_file_path);
1203 // It was remapped, so don't modify further
1204 return RealFileName::Remapped { local_path: None, virtual_name: new_path };
1207 if new_path.is_absolute() {
1208 // No remapping has applied to this path and it is absolute,
1209 // so the working directory cannot influence it either, so
1211 return RealFileName::LocalPath(new_path);
1214 debug_assert!(new_path.is_relative());
1215 let unmapped_file_path_rel = new_path;
1217 match working_directory {
1218 RealFileName::LocalPath(unmapped_working_dir_abs) => {
1219 let file_path_abs = unmapped_working_dir_abs.join(unmapped_file_path_rel);
1221 // Although neither `working_directory` nor the file name were subject
1222 // to path remapping, the concatenation between the two may be. Hence
1223 // we need to do a remapping here.
1224 let (file_path_abs, was_remapped) = self.map_prefix(file_path_abs);
1226 RealFileName::Remapped {
1227 // Erase the actual path
1229 virtual_name: file_path_abs,
1232 // No kind of remapping applied to this path, so
1233 // we leave it as it is.
1234 RealFileName::LocalPath(file_path_abs)
1237 RealFileName::Remapped {
1239 virtual_name: remapped_working_dir_abs,
1241 // If working_directory has been remapped, then we emit
1242 // Remapped variant as the expanded path won't be valid
1243 RealFileName::Remapped {
1245 virtual_name: Path::new(remapped_working_dir_abs)
1246 .join(unmapped_file_path_rel),