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 an 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 `SourceFile`s between
121 // subsequent compilation sessions (which is something we need to do during
122 // incremental compilation).
123 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
124 pub struct StableSourceFileId(u128);
126 // FIXME: we need a more globally consistent approach to the problem solved by
127 // StableSourceFileId, perhaps built atop source_file.name_hash.
128 impl StableSourceFileId {
129 pub fn new(source_file: &SourceFile) -> StableSourceFileId {
130 StableSourceFileId::new_from_name(&source_file.name)
133 fn new_from_name(name: &FileName) -> StableSourceFileId {
134 let mut hasher = StableHasher::new();
136 name.hash(&mut hasher);
138 StableSourceFileId(hasher.finish())
142 // _____________________________________________________________________________
147 pub(super) struct SourceMapFiles {
148 source_files: monotonic::MonotonicVec<Lrc<SourceFile>>,
149 stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>,
152 pub struct SourceMap {
153 /// The address space below this value is currently used by the files in the source map.
154 used_address_space: AtomicU32,
156 files: RwLock<SourceMapFiles>,
157 file_loader: Box<dyn FileLoader + Sync + Send>,
158 // This is used to apply the file path remapping as specified via
159 // `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`.
160 path_mapping: FilePathMapping,
162 /// The algorithm used for hashing the contents of each source file.
163 hash_kind: SourceFileHashAlgorithm,
167 pub fn new(path_mapping: FilePathMapping) -> SourceMap {
168 Self::with_file_loader_and_hash_kind(
169 Box::new(RealFileLoader),
171 SourceFileHashAlgorithm::Md5,
175 pub fn with_file_loader_and_hash_kind(
176 file_loader: Box<dyn FileLoader + Sync + Send>,
177 path_mapping: FilePathMapping,
178 hash_kind: SourceFileHashAlgorithm,
181 used_address_space: AtomicU32::new(0),
182 files: Default::default(),
189 pub fn path_mapping(&self) -> &FilePathMapping {
193 pub fn file_exists(&self, path: &Path) -> bool {
194 self.file_loader.file_exists(path)
197 pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
198 let src = self.file_loader.read_file(path)?;
199 let filename = path.to_owned().into();
200 Ok(self.new_source_file(filename, src))
203 /// Loads source file as a binary blob.
205 /// Unlike `load_file`, guarantees that no normalization like BOM-removal
207 pub fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
208 // Ideally, this should use `self.file_loader`, but it can't
209 // deal with binary files yet.
210 let bytes = fs::read(path)?;
212 // We need to add file to the `SourceMap`, so that it is present
213 // in dep-info. There's also an edge case that file might be both
214 // loaded as a binary via `include_bytes!` and as proper `SourceFile`
215 // via `mod`, so we try to use real file contents and not just an
217 let text = std::str::from_utf8(&bytes).unwrap_or("").to_string();
218 self.new_source_file(path.to_owned().into(), text);
222 // By returning a `MonotonicVec`, we ensure that consumers cannot invalidate
223 // any existing indices pointing into `files`.
224 pub fn files(&self) -> MappedReadGuard<'_, monotonic::MonotonicVec<Lrc<SourceFile>>> {
225 ReadGuard::map(self.files.borrow(), |files| &files.source_files)
228 pub fn source_file_by_stable_id(
230 stable_id: StableSourceFileId,
231 ) -> Option<Lrc<SourceFile>> {
232 self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned()
235 fn allocate_address_space(&self, size: usize) -> Result<usize, OffsetOverflowError> {
236 let size = u32::try_from(size).map_err(|_| OffsetOverflowError)?;
239 let current = self.used_address_space.load(Ordering::Relaxed);
242 // Add one so there is some space between files. This lets us distinguish
243 // positions in the `SourceMap`, even in the presence of zero-length files.
244 .and_then(|next| next.checked_add(1))
245 .ok_or(OffsetOverflowError)?;
249 .compare_exchange(current, next, Ordering::Relaxed, Ordering::Relaxed)
252 return Ok(usize::try_from(current).unwrap());
257 /// Creates a new `SourceFile`.
258 /// If a file already exists in the `SourceMap` with the same ID, that file is returned
260 pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
261 self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| {
262 eprintln!("fatal error: rustc does not support files larger than 4GB");
263 crate::fatal_error::FatalError.raise()
267 fn try_new_source_file(
271 ) -> Result<Lrc<SourceFile>, OffsetOverflowError> {
272 // Note that filename may not be a valid path, eg it may be `<anon>` etc,
273 // but this is okay because the directory determined by `path.pop()` will
274 // be empty, so the working directory will be used.
275 let (filename, _) = self.path_mapping.map_filename_prefix(&filename);
277 let file_id = StableSourceFileId::new_from_name(&filename);
279 let lrc_sf = match self.source_file_by_stable_id(file_id) {
280 Some(lrc_sf) => lrc_sf,
282 let start_pos = self.allocate_address_space(src.len())?;
284 let source_file = Lrc::new(SourceFile::new(
287 Pos::from_usize(start_pos),
291 let mut files = self.files.borrow_mut();
293 files.source_files.push(source_file.clone());
294 files.stable_id_to_source_file.insert(file_id, source_file.clone());
302 /// Allocates a new `SourceFile` representing a source file from an external
303 /// crate. The source code of such an "imported `SourceFile`" is not available,
304 /// but we still know enough to generate accurate debuginfo location
305 /// information for things inlined from other crates.
306 pub fn new_imported_source_file(
309 src_hash: SourceFileHash,
313 mut file_local_lines: Vec<BytePos>,
314 mut file_local_multibyte_chars: Vec<MultiByteChar>,
315 mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
316 mut file_local_normalized_pos: Vec<NormalizedPos>,
317 original_start_pos: BytePos,
318 original_end_pos: BytePos,
319 ) -> Lrc<SourceFile> {
321 .allocate_address_space(source_len)
322 .expect("not enough address space for imported source file");
324 let end_pos = Pos::from_usize(start_pos + source_len);
325 let start_pos = Pos::from_usize(start_pos);
327 for pos in &mut file_local_lines {
328 *pos = *pos + start_pos;
331 for mbc in &mut file_local_multibyte_chars {
332 mbc.pos = mbc.pos + start_pos;
335 for swc in &mut file_local_non_narrow_chars {
336 *swc = *swc + start_pos;
339 for nc in &mut file_local_normalized_pos {
340 nc.pos = nc.pos + start_pos;
343 let source_file = Lrc::new(SourceFile {
347 external_src: Lock::new(ExternalSource::Foreign {
348 kind: ExternalSourceKind::AbsentOk,
354 lines: file_local_lines,
355 multibyte_chars: file_local_multibyte_chars,
356 non_narrow_chars: file_local_non_narrow_chars,
357 normalized_pos: file_local_normalized_pos,
362 let mut files = self.files.borrow_mut();
364 files.source_files.push(source_file.clone());
366 .stable_id_to_source_file
367 .insert(StableSourceFileId::new(&source_file), source_file.clone());
372 // If there is a doctest offset, applies it to the line.
373 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
375 FileName::DocTest(_, offset) => {
377 orig - (-(*offset)) as usize
379 orig + *offset as usize
386 /// Return the SourceFile that contains the given `BytePos`
387 pub fn lookup_source_file(&self, pos: BytePos) -> Lrc<SourceFile> {
388 let idx = self.lookup_source_file_idx(pos);
389 (*self.files.borrow().source_files)[idx].clone()
392 /// Looks up source information about a `BytePos`.
393 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
394 let sf = self.lookup_source_file(pos);
395 let (line, col, col_display) = sf.lookup_file_pos_with_col_display(pos);
396 Loc { file: sf, line, col, col_display }
399 // If the corresponding `SourceFile` is empty, does not return a line number.
400 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
401 let f = self.lookup_source_file(pos);
403 match f.lookup_line(pos) {
404 Some(line) => Ok(SourceFileAndLine { sf: f, line }),
409 fn span_to_string(&self, sp: Span, prefer_local: bool) -> String {
410 if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
411 return "no-location".to_string();
414 let lo = self.lookup_char_pos(sp.lo());
415 let hi = self.lookup_char_pos(sp.hi());
418 if prefer_local { lo.file.name.prefer_local() } else { lo.file.name.prefer_remapped() },
420 lo.col.to_usize() + 1,
422 hi.col.to_usize() + 1,
426 /// Format the span location suitable for embedding in build artifacts
427 pub fn span_to_embeddable_string(&self, sp: Span) -> String {
428 self.span_to_string(sp, false)
431 /// Format the span location to be printed in diagnostics. Must not be emitted
432 /// to build artifacts as this may leak local file paths. Use span_to_embeddable_string
433 /// for string suitable for embedding.
434 pub fn span_to_diagnostic_string(&self, sp: Span) -> String {
435 self.span_to_string(sp, true)
438 pub fn span_to_filename(&self, sp: Span) -> FileName {
439 self.lookup_char_pos(sp.lo()).file.name.clone()
442 pub fn is_multiline(&self, sp: Span) -> bool {
443 let lo = self.lookup_char_pos(sp.lo());
444 let hi = self.lookup_char_pos(sp.hi());
448 pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> {
449 let lo = self.lookup_char_pos(sp.lo());
450 debug!("span_to_lines: lo={:?}", lo);
451 let hi = self.lookup_char_pos(sp.hi());
452 debug!("span_to_lines: hi={:?}", hi);
453 if lo.file.start_pos != hi.file.start_pos {
454 return Err(SpanLinesError::DistinctSources(DistinctSources {
455 begin: (lo.file.name.clone(), lo.file.start_pos),
456 end: (hi.file.name.clone(), hi.file.start_pos),
462 pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
463 match self.span_to_prev_source(sp) {
464 Ok(s) => s.rsplit_once('\n').unwrap_or(("", &s)).1.trim_start().is_empty(),
469 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
470 debug!("span_to_lines(sp={:?})", sp);
471 let (lo, hi) = self.is_valid_span(sp)?;
472 assert!(hi.line >= lo.line);
475 return Ok(FileLines { file: lo.file, lines: Vec::new() });
478 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
480 // The span starts partway through the first line,
481 // but after that it starts from offset 0.
482 let mut start_col = lo.col;
484 // For every line but the last, it extends from `start_col`
485 // and to the end of the line. Be careful because the line
486 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
489 // FIXME: now that we handle DUMMY_SP up above, we should consider
490 // asserting that the line numbers here are all indeed 1-based.
491 let hi_line = hi.line.saturating_sub(1);
492 for line_index in lo.line.saturating_sub(1)..hi_line {
493 let line_len = lo.file.get_line(line_index).map_or(0, |s| s.chars().count());
494 lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
495 start_col = CharPos::from_usize(0);
498 // For the last line, it extends from `start_col` to `hi.col`:
499 lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
501 Ok(FileLines { file: lo.file, lines })
504 /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
505 /// extract function takes three arguments: a string slice containing the source, an index in
506 /// the slice for the beginning of the span and an index in the slice for the end of the span.
507 fn span_to_source<F, T>(&self, sp: Span, extract_source: F) -> Result<T, SpanSnippetError>
509 F: Fn(&str, usize, usize) -> Result<T, SpanSnippetError>,
511 let local_begin = self.lookup_byte_offset(sp.lo());
512 let local_end = self.lookup_byte_offset(sp.hi());
514 if local_begin.sf.start_pos != local_end.sf.start_pos {
515 Err(SpanSnippetError::DistinctSources(DistinctSources {
516 begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos),
517 end: (local_end.sf.name.clone(), local_end.sf.start_pos),
520 self.ensure_source_file_source_present(local_begin.sf.clone());
522 let start_index = local_begin.pos.to_usize();
523 let end_index = local_end.pos.to_usize();
524 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
526 if start_index > end_index || end_index > source_len {
527 return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
528 name: local_begin.sf.name.clone(),
530 begin_pos: local_begin.pos,
531 end_pos: local_end.pos,
535 if let Some(ref src) = local_begin.sf.src {
536 extract_source(src, start_index, end_index)
537 } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
538 extract_source(src, start_index, end_index)
540 Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() })
545 /// Returns the source snippet as `String` corresponding to the given `Span`.
546 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
547 self.span_to_source(sp, |src, start_index, end_index| {
548 src.get(start_index..end_index)
549 .map(|s| s.to_string())
550 .ok_or(SpanSnippetError::IllFormedSpan(sp))
554 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
555 match self.span_to_prev_source(sp) {
558 let last_line = source.rsplit_once('\n').unwrap_or(("", &source)).1;
560 Some(last_line.len() - last_line.trim_start().len())
565 /// Returns the source snippet as `String` before the given `Span`.
566 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
567 self.span_to_source(sp, |src, start_index, _| {
568 src.get(..start_index).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
572 /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span
573 /// if no character could be found or if an error occurred while retrieving the code snippet.
574 pub fn span_extend_to_prev_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
575 if let Ok(prev_source) = self.span_to_prev_source(sp) {
576 let prev_source = prev_source.rsplit(c).next().unwrap_or("");
577 if !prev_source.is_empty() && (accept_newlines || !prev_source.contains('\n')) {
578 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
585 /// Extends the given `Span` to just after the previous occurrence of `pat` when surrounded by
586 /// whitespace. Returns the same span if no character could be found or if an error occurred
587 /// while retrieving the code snippet.
588 pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
589 // assure that the pattern is delimited, to avoid the following
591 // ^^^^ returned span without the check
592 // ---------- correct span
593 for ws in &[" ", "\t", "\n"] {
594 let pat = pat.to_owned() + ws;
595 if let Ok(prev_source) = self.span_to_prev_source(sp) {
596 let prev_source = prev_source.rsplit(&pat).next().unwrap_or("").trim_start();
597 if prev_source.is_empty() && sp.lo().0 != 0 {
598 return sp.with_lo(BytePos(sp.lo().0 - 1));
599 } else if accept_newlines || !prev_source.contains('\n') {
600 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
608 /// Returns the source snippet as `String` after the given `Span`.
609 pub fn span_to_next_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
610 self.span_to_source(sp, |src, _, end_index| {
611 src.get(end_index..).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
615 /// Extends the given `Span` to just after the next occurrence of `c`.
616 pub fn span_extend_to_next_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
617 if let Ok(next_source) = self.span_to_next_source(sp) {
618 let next_source = next_source.split(c).next().unwrap_or("");
619 if !next_source.is_empty() && (accept_newlines || !next_source.contains('\n')) {
620 return sp.with_hi(BytePos(sp.hi().0 + next_source.len() as u32));
627 /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char`
629 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
630 match self.span_to_snippet(sp) {
632 let snippet = snippet.split(c).next().unwrap_or("").trim_end();
633 if !snippet.is_empty() && !snippet.contains('\n') {
634 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
643 /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char`
645 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
646 if let Ok(snippet) = self.span_to_snippet(sp) {
647 if let Some(offset) = snippet.find(c) {
648 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
654 /// Given a `Span`, gets a new `Span` covering the first token and all its trailing whitespace
655 /// or the original `Span`.
657 /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
658 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
659 let mut whitespace_found = false;
661 self.span_take_while(sp, |c| {
662 if !whitespace_found && c.is_whitespace() {
663 whitespace_found = true;
666 !whitespace_found || c.is_whitespace()
670 /// Given a `Span`, gets a new `Span` covering the first token without its trailing whitespace
671 /// or the original `Span` in case of error.
673 /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
674 pub fn span_until_whitespace(&self, sp: Span) -> Span {
675 self.span_take_while(sp, |c| !c.is_whitespace())
678 /// Given a `Span`, gets a shorter one until `predicate` yields `false`.
679 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
681 P: for<'r> FnMut(&'r char) -> bool,
683 if let Ok(snippet) = self.span_to_snippet(sp) {
684 let offset = snippet.chars().take_while(predicate).map(|c| c.len_utf8()).sum::<usize>();
686 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
692 /// Given a `Span`, return a span ending in the closest `{`. This is useful when you have a
693 /// `Span` enclosing a whole item but we need to point at only the head (usually the first
694 /// line) of that item.
696 /// *Only suitable for diagnostics.*
697 pub fn guess_head_span(&self, sp: Span) -> Span {
698 // FIXME: extend the AST items to have a head span, or replace callers with pointing at
699 // the item's ident when appropriate.
700 self.span_until_char(sp, '{')
703 /// Returns a new span representing just the first character of the given span.
704 pub fn start_point(&self, sp: Span) -> Span {
707 let local_begin = self.lookup_byte_offset(sp.lo);
708 let start_index = local_begin.pos.to_usize();
709 let src = local_begin.sf.external_src.borrow();
711 let snippet = if let Some(ref src) = local_begin.sf.src {
712 Some(&src[start_index..])
713 } else if let Some(src) = src.get_source() {
714 Some(&src[start_index..])
721 Some(snippet) => match snippet.chars().next() {
723 Some(c) => c.len_utf8(),
728 sp.with_hi(BytePos(sp.lo().0 + width as u32))
731 /// Returns a new span representing just the last character of this span.
732 pub fn end_point(&self, sp: Span) -> Span {
735 let width = self.find_width_of_character_at_span(sp, false);
736 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
738 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
739 sp.with_lo(end_point)
742 /// Returns a new span representing the next character after the end-point of this span.
743 pub fn next_point(&self, sp: Span) -> Span {
747 let start_of_next_point = sp.hi().0;
749 let width = self.find_width_of_character_at_span(sp.shrink_to_hi(), true);
750 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
751 // in the case of a multibyte character, where the width != 1, the next span should
752 // span multiple bytes to include the whole character.
753 let end_of_next_point =
754 start_of_next_point.checked_add(width - 1).unwrap_or(start_of_next_point);
756 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
757 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
760 /// Finds the width of the character, either before or after the end of provided span,
761 /// depending on the `forwards` parameter.
762 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
765 debug!("find_width_of_character_at_span: early return empty span");
769 let local_begin = self.lookup_byte_offset(sp.lo);
770 let local_end = self.lookup_byte_offset(sp.hi);
772 "find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
773 local_begin, local_end
776 if local_begin.sf.start_pos != local_end.sf.start_pos {
777 debug!("find_width_of_character_at_span: begin and end are in different files");
781 let start_index = local_begin.pos.to_usize();
782 let end_index = local_end.pos.to_usize();
784 "find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
785 start_index, end_index
788 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
790 if (!forwards && end_index == usize::MIN) || (forwards && start_index == usize::MAX) {
791 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
795 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
796 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
797 // Ensure indexes are also not malformed.
798 if start_index > end_index || end_index > source_len {
799 debug!("find_width_of_character_at_span: source indexes are malformed");
803 let src = local_begin.sf.external_src.borrow();
805 // We need to extend the snippet to the end of the src rather than to end_index so when
806 // searching forwards for boundaries we've got somewhere to search.
807 let snippet = if let Some(ref src) = local_begin.sf.src {
809 } else if let Some(src) = src.get_source() {
814 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
816 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
817 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
819 while !snippet.is_char_boundary(target - start_index) && target < source_len {
820 target = if forwards {
823 match target.checked_sub(1) {
824 Some(target) => target,
830 debug!("find_width_of_character_at_span: target=`{:?}`", target);
832 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
834 if forwards { (target - end_index) as u32 } else { (end_index - target) as u32 }
837 pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
838 // Remap filename before lookup
839 let filename = self.path_mapping().map_filename_prefix(filename).0;
840 for sf in self.files.borrow().source_files.iter() {
841 if filename == sf.name {
842 return Some(sf.clone());
848 /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
849 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
850 let idx = self.lookup_source_file_idx(bpos);
851 let sf = (*self.files.borrow().source_files)[idx].clone();
852 let offset = bpos - sf.start_pos;
853 SourceFileAndBytePos { sf, pos: offset }
856 // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`.
857 // This index is guaranteed to be valid for the lifetime of this `SourceMap`,
858 // since `source_files` is a `MonotonicVec`
859 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
863 .binary_search_by_key(&pos, |key| key.start_pos)
864 .unwrap_or_else(|p| p - 1)
867 pub fn count_lines(&self) -> usize {
868 self.files().iter().fold(0, |a, f| a + f.count_lines())
871 pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
872 let prev_span = self.span_extend_to_prev_str(span, "fn", true);
873 if let Ok(snippet) = self.span_to_snippet(prev_span) {
875 "generate_fn_name_span: span={:?}, prev_span={:?}, snippet={:?}",
876 span, prev_span, snippet
879 if snippet.is_empty() {
884 .find(|c: char| !c.is_alphanumeric() && c != '_')
885 .expect("no label after fn");
886 Some(prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32)))
892 /// Takes the span of a type parameter in a function signature and try to generate a span for
893 /// the function name (with generics) and a new snippet for this span with the pointed type
894 /// parameter as a new local type parameter.
897 /// ```rust,ignore (pseudo-Rust)
899 /// fn my_function(param: T)
900 /// // ^ Original span
903 /// fn my_function(param: T)
904 /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
907 /// Attention: The method used is very fragile since it essentially duplicates the work of the
908 /// parser. If you need to use this function or something similar, please consider updating the
909 /// `SourceMap` functions and this function to something more robust.
910 pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
911 // Try to extend the span to the previous "fn" keyword to retrieve the function
913 let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
914 if sugg_span != span {
915 if let Ok(snippet) = self.span_to_snippet(sugg_span) {
916 // Consume the function name.
917 let mut offset = snippet
918 .find(|c: char| !c.is_alphanumeric() && c != '_')
919 .expect("no label after fn");
921 // Consume the generics part of the function signature.
922 let mut bracket_counter = 0;
923 let mut last_char = None;
924 for c in snippet[offset..].chars() {
926 '<' => bracket_counter += 1,
927 '>' => bracket_counter -= 1,
929 if bracket_counter == 0 {
935 offset += c.len_utf8();
939 // Adjust the suggestion span to encompass the function name with its generics.
940 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
942 // Prepare the new suggested snippet to append the type parameter that triggered
943 // the error in the generics of the function signature.
944 let mut new_snippet = if last_char == Some('>') {
945 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
947 format!("{}<", &snippet[..offset])
950 .push_str(&self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
951 new_snippet.push('>');
953 return Some((sugg_span, new_snippet));
959 pub fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
960 source_file.add_external_src(|| match source_file.name {
961 FileName::Real(ref name) => {
962 if let Some(local_path) = name.local_path() {
963 self.file_loader.read_file(local_path).ok()
972 pub fn is_imported(&self, sp: Span) -> bool {
973 let source_file_index = self.lookup_source_file_idx(sp.lo());
974 let source_file = &self.files()[source_file_index];
975 source_file.is_imported()
980 pub struct FilePathMapping {
981 mapping: Vec<(PathBuf, PathBuf)>,
984 impl FilePathMapping {
985 pub fn empty() -> FilePathMapping {
986 FilePathMapping { mapping: vec![] }
989 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
990 FilePathMapping { mapping }
993 /// Applies any path prefix substitution as defined by the mapping.
994 /// The return value is the remapped path and a boolean indicating whether
995 /// the path was affected by the mapping.
996 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
997 // NOTE: We are iterating over the mapping entries from last to first
998 // because entries specified later on the command line should
1000 for &(ref from, ref to) in self.mapping.iter().rev() {
1001 if let Ok(rest) = path.strip_prefix(from) {
1002 return (to.join(rest), true);
1009 fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) {
1011 FileName::Real(realfile) => {
1012 if let RealFileName::LocalPath(local_path) = realfile {
1013 let (mapped_path, mapped) = self.map_prefix(local_path.to_path_buf());
1014 let realfile = if mapped {
1015 RealFileName::Remapped {
1016 local_path: Some(local_path.clone()),
1017 virtual_name: mapped_path,
1022 (FileName::Real(realfile), mapped)
1024 unreachable!("attempted to remap an already remapped filename");
1027 other => (other.clone(), false),