1 //! The `SourceMap` tracks all the source code used within a single crate, mapping
2 //! from integer byte positions to the original source code location. Each bit
3 //! of source parsed during crate parsing (typically files, in-memory strings,
4 //! or various bits of macro expansion) cover a continuous range of bytes in the
5 //! `SourceMap` and are represented by `SourceFile`s. Byte positions are stored in
6 //! `Span` and used pervasively in the compiler. They are absolute positions
7 //! within the `SourceMap`, which upon request can be converted to line and column
8 //! information, source code snippets, etc.
10 pub use crate::hygiene::{ExpnData, ExpnKind};
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::stable_hasher::StableHasher;
15 use rustc_data_structures::sync::{AtomicU32, Lock, LockGuard, Lrc, MappedLockGuard};
17 use std::convert::TryFrom;
19 use std::path::{Path, PathBuf};
20 use std::sync::atomic::Ordering;
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
39 original_sp(expn_data1.call_site, enclosing_sp)
44 use std::ops::{Deref, DerefMut};
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> {
57 pub fn push(&mut self, val: T) {
62 impl<T> Default for MonotonicVec<T> {
63 fn default() -> Self {
64 MonotonicVec::new(vec![])
68 impl<T> Deref for MonotonicVec<T> {
70 fn deref(&self) -> &Self::Target {
75 impl<T> !DerefMut for MonotonicVec<T> {}
78 #[derive(Clone, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
79 pub struct Spanned<T> {
84 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
85 Spanned { node: t, span: sp }
88 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
92 // _____________________________________________________________________________
93 // SourceFile, MultiByteChar, FileName, FileLines
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;
101 /// Read the contents of an UTF-8 file into memory.
102 fn read_file(&self, path: &Path) -> io::Result<String>;
105 /// A FileLoader that uses std::fs to load real files.
106 pub struct RealFileLoader;
108 impl FileLoader for RealFileLoader {
109 fn file_exists(&self, path: &Path) -> bool {
110 fs::metadata(path).is_ok()
113 fn read_file(&self, path: &Path) -> io::Result<String> {
114 fs::read_to_string(path)
118 // This is a `SourceFile` identifier that is used to correlate `SourceFile`s between
119 // subsequent compilation sessions (which is something we need to do during
120 // incremental compilation).
121 #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
122 pub struct StableSourceFileId(u128);
124 // FIXME: we need a more globally consistent approach to the problem solved by
125 // StableSourceFileId, perhaps built atop source_file.name_hash.
126 impl StableSourceFileId {
127 pub fn new(source_file: &SourceFile) -> StableSourceFileId {
128 StableSourceFileId::new_from_pieces(
130 source_file.name_was_remapped,
131 source_file.unmapped_path.as_ref(),
137 name_was_remapped: bool,
138 unmapped_path: Option<&FileName>,
139 ) -> StableSourceFileId {
140 let mut hasher = StableHasher::new();
142 if let FileName::Real(real_name) = name {
143 // rust-lang/rust#70924: Use the stable (virtualized) name when
144 // available. (We do not want artifacts from transient file system
145 // paths for libstd to leak into our build artifacts.)
146 real_name.stable_name().hash(&mut hasher)
148 name.hash(&mut hasher);
150 name_was_remapped.hash(&mut hasher);
151 unmapped_path.hash(&mut hasher);
153 StableSourceFileId(hasher.finish())
157 // _____________________________________________________________________________
162 pub(super) struct SourceMapFiles {
163 source_files: monotonic::MonotonicVec<Lrc<SourceFile>>,
164 stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>,
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,
171 files: Lock<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,
177 /// The algorithm used for hashing the contents of each source file.
178 hash_kind: SourceFileHashAlgorithm,
182 pub fn new(path_mapping: FilePathMapping) -> SourceMap {
183 Self::with_file_loader_and_hash_kind(
184 Box::new(RealFileLoader),
186 SourceFileHashAlgorithm::Md5,
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,
196 used_address_space: AtomicU32::new(0),
197 files: Default::default(),
204 pub fn path_mapping(&self) -> &FilePathMapping {
208 pub fn file_exists(&self, path: &Path) -> bool {
209 self.file_loader.file_exists(path)
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))
218 /// Loads source file as a binary blob.
220 /// Unlike `load_file`, guarantees that no normalization like BOM-removal
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)?;
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
232 let text = std::str::from_utf8(&bytes).unwrap_or("").to_string();
233 self.new_source_file(path.to_owned().into(), text);
237 // By returning a `MonotonicVec`, we ensure that consumers cannot invalidate
238 // any existing indices pointing into `files`.
239 pub fn files(&self) -> MappedLockGuard<'_, monotonic::MonotonicVec<Lrc<SourceFile>>> {
240 LockGuard::map(self.files.borrow(), |files| &mut files.source_files)
243 pub fn source_file_by_stable_id(
245 stable_id: StableSourceFileId,
246 ) -> Option<Lrc<SourceFile>> {
247 self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned()
250 fn allocate_address_space(&self, size: usize) -> Result<usize, OffsetOverflowError> {
251 let size = u32::try_from(size).map_err(|_| OffsetOverflowError)?;
254 let current = self.used_address_space.load(Ordering::Relaxed);
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)?;
264 .compare_exchange(current, next, Ordering::Relaxed, Ordering::Relaxed)
267 return Ok(usize::try_from(current).unwrap());
272 /// Creates a new `SourceFile`.
273 /// If a file already exists in the `SourceMap` with the same ID, that file is returned
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()
282 fn try_new_source_file(
284 mut filename: FileName,
286 ) -> Result<Lrc<SourceFile>, OffsetOverflowError> {
287 // The path is used to determine the directory for loading submodules and
288 // include files, so it must be before remapping.
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 unmapped_path = filename.clone();
295 if let FileName::Real(real_filename) = &mut filename {
296 match real_filename {
297 RealFileName::Named(path_to_be_remapped)
298 | RealFileName::Devirtualized {
299 local_path: path_to_be_remapped,
302 let mapped = self.path_mapping.map_prefix(path_to_be_remapped.clone());
303 was_remapped = mapped.1;
304 *path_to_be_remapped = mapped.0;
308 was_remapped = false;
312 StableSourceFileId::new_from_pieces(&filename, was_remapped, Some(&unmapped_path));
314 let lrc_sf = match self.source_file_by_stable_id(file_id) {
315 Some(lrc_sf) => lrc_sf,
317 let start_pos = self.allocate_address_space(src.len())?;
319 let source_file = Lrc::new(SourceFile::new(
324 Pos::from_usize(start_pos),
328 let mut files = self.files.borrow_mut();
330 files.source_files.push(source_file.clone());
331 files.stable_id_to_source_file.insert(file_id, source_file.clone());
339 /// Allocates a new `SourceFile` representing a source file from an external
340 /// crate. The source code of such an "imported `SourceFile`" is not available,
341 /// but we still know enough to generate accurate debuginfo location
342 /// information for things inlined from other crates.
343 pub fn new_imported_source_file(
346 name_was_remapped: bool,
347 src_hash: SourceFileHash,
351 mut file_local_lines: Vec<BytePos>,
352 mut file_local_multibyte_chars: Vec<MultiByteChar>,
353 mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
354 mut file_local_normalized_pos: Vec<NormalizedPos>,
355 original_start_pos: BytePos,
356 original_end_pos: BytePos,
357 ) -> Lrc<SourceFile> {
359 .allocate_address_space(source_len)
360 .expect("not enough address space for imported source file");
362 let end_pos = Pos::from_usize(start_pos + source_len);
363 let start_pos = Pos::from_usize(start_pos);
365 for pos in &mut file_local_lines {
366 *pos = *pos + start_pos;
369 for mbc in &mut file_local_multibyte_chars {
370 mbc.pos = mbc.pos + start_pos;
373 for swc in &mut file_local_non_narrow_chars {
374 *swc = *swc + start_pos;
377 for nc in &mut file_local_normalized_pos {
378 nc.pos = nc.pos + start_pos;
381 let source_file = Lrc::new(SourceFile {
387 external_src: Lock::new(ExternalSource::Foreign {
388 kind: ExternalSourceKind::AbsentOk,
394 lines: file_local_lines,
395 multibyte_chars: file_local_multibyte_chars,
396 non_narrow_chars: file_local_non_narrow_chars,
397 normalized_pos: file_local_normalized_pos,
402 let mut files = self.files.borrow_mut();
404 files.source_files.push(source_file.clone());
406 .stable_id_to_source_file
407 .insert(StableSourceFileId::new(&source_file), source_file.clone());
412 pub fn mk_substr_filename(&self, sp: Span) -> String {
413 let pos = self.lookup_char_pos(sp.lo());
414 format!("<{}:{}:{}>", pos.file.name, pos.line, pos.col.to_usize() + 1)
417 // If there is a doctest offset, applies it to the line.
418 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
420 FileName::DocTest(_, offset) => {
422 orig - (-(*offset)) as usize
424 orig + *offset as usize
431 /// Looks up source information about a `BytePos`.
432 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
433 let chpos = self.bytepos_to_file_charpos(pos);
434 match self.lookup_line(pos) {
435 Ok(SourceFileAndLine { sf: f, line: a }) => {
436 let line = a + 1; // Line numbers start at 1
437 let linebpos = f.lines[a];
438 let linechpos = self.bytepos_to_file_charpos(linebpos);
439 let col = chpos - linechpos;
442 let start_width_idx = f
444 .binary_search_by_key(&linebpos, |x| x.pos())
445 .unwrap_or_else(|x| x);
446 let end_width_idx = f
448 .binary_search_by_key(&pos, |x| x.pos())
449 .unwrap_or_else(|x| x);
450 let special_chars = end_width_idx - start_width_idx;
451 let non_narrow: usize = f.non_narrow_chars[start_width_idx..end_width_idx]
455 col.0 - special_chars + non_narrow
457 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
458 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
459 debug!("byte is on line: {}", line);
460 assert!(chpos >= linechpos);
461 Loc { file: f, line, col, col_display }
465 let end_width_idx = f
467 .binary_search_by_key(&pos, |x| x.pos())
468 .unwrap_or_else(|x| x);
469 let non_narrow: usize =
470 f.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
471 chpos.0 - end_width_idx + non_narrow
473 Loc { file: f, line: 0, col: chpos, col_display }
478 // If the corresponding `SourceFile` is empty, does not return a line number.
479 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
480 let idx = self.lookup_source_file_idx(pos);
482 let f = (*self.files.borrow().source_files)[idx].clone();
484 match f.lookup_line(pos) {
485 Some(line) => Ok(SourceFileAndLine { sf: f, line }),
490 /// Returns `Some(span)`, a union of the LHS and RHS span. The LHS must precede the RHS. If
491 /// there are gaps between LHS and RHS, the resulting union will cross these gaps.
492 /// For this to work,
494 /// * the syntax contexts of both spans much match,
495 /// * the LHS span needs to end on the same line the RHS span begins,
496 /// * the LHS span must start at or before the RHS span.
497 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
498 // Ensure we're at the same expansion ID.
499 if sp_lhs.ctxt() != sp_rhs.ctxt() {
503 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
505 Err(_) => return None,
507 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
509 Err(_) => return None,
512 // If we must cross lines to merge, don't merge.
513 if lhs_end.line != rhs_begin.line {
517 // Ensure these follow the expected order and that we don't overlap.
518 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
519 Some(sp_lhs.to(sp_rhs))
525 pub fn span_to_string(&self, sp: Span) -> String {
526 if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
527 return "no-location".to_string();
530 let lo = self.lookup_char_pos(sp.lo());
531 let hi = self.lookup_char_pos(sp.hi());
536 lo.col.to_usize() + 1,
538 hi.col.to_usize() + 1,
542 pub fn span_to_filename(&self, sp: Span) -> FileName {
543 self.lookup_char_pos(sp.lo()).file.name.clone()
546 pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
547 self.lookup_char_pos(sp.lo())
551 .expect("`SourceMap::span_to_unmapped_path` called for imported `SourceFile`?")
554 pub fn is_multiline(&self, sp: Span) -> bool {
555 let lo = self.lookup_char_pos(sp.lo());
556 let hi = self.lookup_char_pos(sp.hi());
560 pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> {
561 let lo = self.lookup_char_pos(sp.lo());
562 debug!("span_to_lines: lo={:?}", lo);
563 let hi = self.lookup_char_pos(sp.hi());
564 debug!("span_to_lines: hi={:?}", hi);
565 if lo.file.start_pos != hi.file.start_pos {
566 return Err(SpanLinesError::DistinctSources(DistinctSources {
567 begin: (lo.file.name.clone(), lo.file.start_pos),
568 end: (hi.file.name.clone(), hi.file.start_pos),
574 pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
575 match self.span_to_prev_source(sp) {
576 Ok(s) => s.split('\n').last().map(|l| l.trim_start().is_empty()).unwrap_or(false),
581 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
582 debug!("span_to_lines(sp={:?})", sp);
583 let (lo, hi) = self.is_valid_span(sp)?;
584 assert!(hi.line >= lo.line);
587 return Ok(FileLines { file: lo.file, lines: Vec::new() });
590 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
592 // The span starts partway through the first line,
593 // but after that it starts from offset 0.
594 let mut start_col = lo.col;
596 // For every line but the last, it extends from `start_col`
597 // and to the end of the line. Be careful because the line
598 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
601 // FIXME: now that we handle DUMMY_SP up above, we should consider
602 // asserting that the line numbers here are all indeed 1-based.
603 let hi_line = hi.line.saturating_sub(1);
604 for line_index in lo.line.saturating_sub(1)..hi_line {
605 let line_len = lo.file.get_line(line_index).map(|s| s.chars().count()).unwrap_or(0);
606 lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
607 start_col = CharPos::from_usize(0);
610 // For the last line, it extends from `start_col` to `hi.col`:
611 lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
613 Ok(FileLines { file: lo.file, lines })
616 /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
617 /// extract function takes three arguments: a string slice containing the source, an index in
618 /// the slice for the beginning of the span and an index in the slice for the end of the span.
619 fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
621 F: Fn(&str, usize, usize) -> Result<String, SpanSnippetError>,
623 let local_begin = self.lookup_byte_offset(sp.lo());
624 let local_end = self.lookup_byte_offset(sp.hi());
626 if local_begin.sf.start_pos != local_end.sf.start_pos {
627 Err(SpanSnippetError::DistinctSources(DistinctSources {
628 begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos),
629 end: (local_end.sf.name.clone(), local_end.sf.start_pos),
632 self.ensure_source_file_source_present(local_begin.sf.clone());
634 let start_index = local_begin.pos.to_usize();
635 let end_index = local_end.pos.to_usize();
636 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
638 if start_index > end_index || end_index > source_len {
639 return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
640 name: local_begin.sf.name.clone(),
642 begin_pos: local_begin.pos,
643 end_pos: local_end.pos,
647 if let Some(ref src) = local_begin.sf.src {
648 extract_source(src, start_index, end_index)
649 } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
650 extract_source(src, start_index, end_index)
652 Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() })
657 /// Returns the source snippet as `String` corresponding to the given `Span`.
658 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
659 self.span_to_source(sp, |src, start_index, end_index| {
660 src.get(start_index..end_index)
661 .map(|s| s.to_string())
662 .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))
666 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
667 match self.span_to_prev_source(sp) {
672 .map(|last_line| last_line.len() - last_line.trim_start().len()),
676 /// Returns the source snippet as `String` before the given `Span`.
677 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
678 self.span_to_source(sp, |src, start_index, _| {
679 src.get(..start_index)
680 .map(|s| s.to_string())
681 .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))
685 /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span
686 /// if no character could be found or if an error occurred while retrieving the code snippet.
687 pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span {
688 if let Ok(prev_source) = self.span_to_prev_source(sp) {
689 let prev_source = prev_source.rsplit(c).next().unwrap_or("").trim_start();
690 if !prev_source.is_empty() && !prev_source.contains('\n') {
691 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
698 /// Extends the given `Span` to just after the previous occurrence of `pat` when surrounded by
699 /// whitespace. Returns the same span if no character could be found or if an error occurred
700 /// while retrieving the code snippet.
701 pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
702 // assure that the pattern is delimited, to avoid the following
704 // ^^^^ returned span without the check
705 // ---------- correct span
706 for ws in &[" ", "\t", "\n"] {
707 let pat = pat.to_owned() + ws;
708 if let Ok(prev_source) = self.span_to_prev_source(sp) {
709 let prev_source = prev_source.rsplit(&pat).next().unwrap_or("").trim_start();
710 if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) {
711 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
719 /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char`
721 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
722 match self.span_to_snippet(sp) {
724 let snippet = snippet.split(c).next().unwrap_or("").trim_end();
725 if !snippet.is_empty() && !snippet.contains('\n') {
726 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
735 /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char`
737 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
738 if let Ok(snippet) = self.span_to_snippet(sp) {
739 if let Some(offset) = snippet.find(c) {
740 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
746 /// Given a `Span`, gets a new `Span` covering the first token and all its trailing whitespace
747 /// or the original `Span`.
749 /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
750 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
751 let mut whitespace_found = false;
753 self.span_take_while(sp, |c| {
754 if !whitespace_found && c.is_whitespace() {
755 whitespace_found = true;
758 !whitespace_found || c.is_whitespace()
762 /// Given a `Span`, gets a new `Span` covering the first token without its trailing whitespace
763 /// or the original `Span` in case of error.
765 /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
766 pub fn span_until_whitespace(&self, sp: Span) -> Span {
767 self.span_take_while(sp, |c| !c.is_whitespace())
770 /// Given a `Span`, gets a shorter one until `predicate` yields `false`.
771 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
773 P: for<'r> FnMut(&'r char) -> bool,
775 if let Ok(snippet) = self.span_to_snippet(sp) {
776 let offset = snippet.chars().take_while(predicate).map(|c| c.len_utf8()).sum::<usize>();
778 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
784 /// Given a `Span`, return a span ending in the closest `{`. This is useful when you have a
785 /// `Span` enclosing a whole item but we need to point at only the head (usually the first
786 /// line) of that item.
788 /// *Only suitable for diagnostics.*
789 pub fn guess_head_span(&self, sp: Span) -> Span {
790 // FIXME: extend the AST items to have a head span, or replace callers with pointing at
791 // the item's ident when appropriate.
792 self.span_until_char(sp, '{')
795 /// Returns a new span representing just the start point of this span.
796 pub fn start_point(&self, sp: Span) -> Span {
798 let width = self.find_width_of_character_at_span(sp, false);
799 let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
800 let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
801 sp.with_hi(end_point)
804 /// Returns a new span representing just the end point of this span.
805 pub fn end_point(&self, sp: Span) -> Span {
808 let width = self.find_width_of_character_at_span(sp, false);
809 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
811 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
812 sp.with_lo(end_point)
815 /// Returns a new span representing the next character after the end-point of this span.
816 pub fn next_point(&self, sp: Span) -> Span {
817 let start_of_next_point = sp.hi().0;
819 let width = self.find_width_of_character_at_span(sp.shrink_to_hi(), true);
820 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
821 // in the case of a multibyte character, where the width != 1, the next span should
822 // span multiple bytes to include the whole character.
823 let end_of_next_point =
824 start_of_next_point.checked_add(width - 1).unwrap_or(start_of_next_point);
826 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
827 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
830 /// Finds the width of a character, either before or after the provided span.
831 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
834 debug!("find_width_of_character_at_span: early return empty span");
838 let local_begin = self.lookup_byte_offset(sp.lo);
839 let local_end = self.lookup_byte_offset(sp.hi);
841 "find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
842 local_begin, local_end
845 if local_begin.sf.start_pos != local_end.sf.start_pos {
846 debug!("find_width_of_character_at_span: begin and end are in different files");
850 let start_index = local_begin.pos.to_usize();
851 let end_index = local_end.pos.to_usize();
853 "find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
854 start_index, end_index
857 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
859 if (!forwards && end_index == usize::MIN) || (forwards && start_index == usize::MAX) {
860 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
864 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
865 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
866 // Ensure indexes are also not malformed.
867 if start_index > end_index || end_index > source_len {
868 debug!("find_width_of_character_at_span: source indexes are malformed");
872 let src = local_begin.sf.external_src.borrow();
874 // We need to extend the snippet to the end of the src rather than to end_index so when
875 // searching forwards for boundaries we've got somewhere to search.
876 let snippet = if let Some(ref src) = local_begin.sf.src {
878 &src[start_index..len]
879 } else if let Some(src) = src.get_source() {
881 &src[start_index..len]
885 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
887 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
888 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
890 while !snippet.is_char_boundary(target - start_index) && target < source_len {
891 target = if forwards {
894 match target.checked_sub(1) {
895 Some(target) => target,
901 debug!("find_width_of_character_at_span: target=`{:?}`", target);
903 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
905 if forwards { (target - end_index) as u32 } else { (end_index - target) as u32 }
908 pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
909 for sf in self.files.borrow().source_files.iter() {
910 if *filename == sf.name {
911 return Some(sf.clone());
917 /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
918 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
919 let idx = self.lookup_source_file_idx(bpos);
920 let sf = (*self.files.borrow().source_files)[idx].clone();
921 let offset = bpos - sf.start_pos;
922 SourceFileAndBytePos { sf, pos: offset }
925 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
926 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
927 let idx = self.lookup_source_file_idx(bpos);
928 let map = &(*self.files.borrow().source_files)[idx];
930 // The number of extra bytes due to multibyte chars in the `SourceFile`.
931 let mut total_extra_bytes = 0;
933 for mbc in map.multibyte_chars.iter() {
934 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
936 // Every character is at least one byte, so we only
937 // count the actual extra bytes.
938 total_extra_bytes += mbc.bytes as u32 - 1;
939 // We should never see a byte position in the middle of a
941 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
947 assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
948 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
951 // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`.
952 // This index is guaranteed to be valid for the lifetime of this `SourceMap`,
953 // since `source_files` is a `MonotonicVec`
954 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
958 .binary_search_by_key(&pos, |key| key.start_pos)
959 .unwrap_or_else(|p| p - 1)
962 pub fn count_lines(&self) -> usize {
963 self.files().iter().fold(0, |a, f| a + f.count_lines())
966 pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
967 let prev_span = self.span_extend_to_prev_str(span, "fn", true);
968 if let Ok(snippet) = self.span_to_snippet(prev_span) {
970 "generate_fn_name_span: span={:?}, prev_span={:?}, snippet={:?}",
971 span, prev_span, snippet
974 if snippet.is_empty() {
979 .find(|c: char| !c.is_alphanumeric() && c != '_')
980 .expect("no label after fn");
981 Some(prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32)))
987 /// Takes the span of a type parameter in a function signature and try to generate a span for
988 /// the function name (with generics) and a new snippet for this span with the pointed type
989 /// parameter as a new local type parameter.
992 /// ```rust,ignore (pseudo-Rust)
994 /// fn my_function(param: T)
995 /// // ^ Original span
998 /// fn my_function(param: T)
999 /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
1002 /// Attention: The method used is very fragile since it essentially duplicates the work of the
1003 /// parser. If you need to use this function or something similar, please consider updating the
1004 /// `SourceMap` functions and this function to something more robust.
1005 pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
1006 // Try to extend the span to the previous "fn" keyword to retrieve the function
1008 let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
1009 if sugg_span != span {
1010 if let Ok(snippet) = self.span_to_snippet(sugg_span) {
1011 // Consume the function name.
1012 let mut offset = snippet
1013 .find(|c: char| !c.is_alphanumeric() && c != '_')
1014 .expect("no label after fn");
1016 // Consume the generics part of the function signature.
1017 let mut bracket_counter = 0;
1018 let mut last_char = None;
1019 for c in snippet[offset..].chars() {
1021 '<' => bracket_counter += 1,
1022 '>' => bracket_counter -= 1,
1024 if bracket_counter == 0 {
1030 offset += c.len_utf8();
1031 last_char = Some(c);
1034 // Adjust the suggestion span to encompass the function name with its generics.
1035 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
1037 // Prepare the new suggested snippet to append the type parameter that triggered
1038 // the error in the generics of the function signature.
1039 let mut new_snippet = if last_char == Some('>') {
1040 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
1042 format!("{}<", &snippet[..offset])
1045 .push_str(&self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
1046 new_snippet.push('>');
1048 return Some((sugg_span, new_snippet));
1054 pub fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
1055 source_file.add_external_src(|| match source_file.name {
1056 FileName::Real(ref name) => self.file_loader.read_file(name.local_path()).ok(),
1061 pub fn is_imported(&self, sp: Span) -> bool {
1062 let source_file_index = self.lookup_source_file_idx(sp.lo());
1063 let source_file = &self.files()[source_file_index];
1064 source_file.is_imported()
1069 pub struct FilePathMapping {
1070 mapping: Vec<(PathBuf, PathBuf)>,
1073 impl FilePathMapping {
1074 pub fn empty() -> FilePathMapping {
1075 FilePathMapping { mapping: vec![] }
1078 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1079 FilePathMapping { mapping }
1082 /// Applies any path prefix substitution as defined by the mapping.
1083 /// The return value is the remapped path and a boolean indicating whether
1084 /// the path was affected by the mapping.
1085 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1086 // NOTE: We are iterating over the mapping entries from last to first
1087 // because entries specified later on the command line should
1089 for &(ref from, ref to) in self.mapping.iter().rev() {
1090 if let Ok(rest) = path.strip_prefix(from) {
1091 return (to.join(rest), true);