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)
43 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
44 pub struct Spanned<T> {
49 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
50 Spanned { node: t, span: sp }
53 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
57 // _____________________________________________________________________________
58 // SourceFile, MultiByteChar, FileName, FileLines
61 /// An abstraction over the fs operations used by the Parser.
62 pub trait FileLoader {
63 /// Query the existence of a file.
64 fn file_exists(&self, path: &Path) -> bool;
66 /// Read the contents of an UTF-8 file into memory.
67 fn read_file(&self, path: &Path) -> io::Result<String>;
70 /// A FileLoader that uses std::fs to load real files.
71 pub struct RealFileLoader;
73 impl FileLoader for RealFileLoader {
74 fn file_exists(&self, path: &Path) -> bool {
75 fs::metadata(path).is_ok()
78 fn read_file(&self, path: &Path) -> io::Result<String> {
79 fs::read_to_string(path)
83 // This is a `SourceFile` identifier that is used to correlate `SourceFile`s between
84 // subsequent compilation sessions (which is something we need to do during
85 // incremental compilation).
86 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
87 pub struct StableSourceFileId(u128);
89 impl StableSourceFileId {
90 pub fn new(source_file: &SourceFile) -> StableSourceFileId {
91 StableSourceFileId::new_from_pieces(
93 source_file.name_was_remapped,
94 source_file.unmapped_path.as_ref(),
98 pub fn new_from_pieces(
100 name_was_remapped: bool,
101 unmapped_path: Option<&FileName>,
102 ) -> StableSourceFileId {
103 let mut hasher = StableHasher::new();
105 name.hash(&mut hasher);
106 name_was_remapped.hash(&mut hasher);
107 unmapped_path.hash(&mut hasher);
109 StableSourceFileId(hasher.finish())
113 // _____________________________________________________________________________
118 pub(super) struct SourceMapFiles {
119 source_files: Vec<Lrc<SourceFile>>,
120 stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>,
123 pub struct SourceMap {
124 /// The address space below this value is currently used by the files in the source map.
125 used_address_space: AtomicU32,
127 files: Lock<SourceMapFiles>,
128 file_loader: Box<dyn FileLoader + Sync + Send>,
129 // This is used to apply the file path remapping as specified via
130 // `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`.
131 path_mapping: FilePathMapping,
133 /// The algorithm used for hashing the contents of each source file.
134 hash_kind: SourceFileHashAlgorithm,
138 pub fn new(path_mapping: FilePathMapping) -> SourceMap {
139 Self::with_file_loader_and_hash_kind(
140 Box::new(RealFileLoader),
142 SourceFileHashAlgorithm::Md5,
146 pub fn with_file_loader_and_hash_kind(
147 file_loader: Box<dyn FileLoader + Sync + Send>,
148 path_mapping: FilePathMapping,
149 hash_kind: SourceFileHashAlgorithm,
152 used_address_space: AtomicU32::new(0),
153 files: Default::default(),
160 pub fn path_mapping(&self) -> &FilePathMapping {
164 pub fn file_exists(&self, path: &Path) -> bool {
165 self.file_loader.file_exists(path)
168 pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
169 let src = self.file_loader.read_file(path)?;
170 let filename = path.to_owned().into();
171 Ok(self.new_source_file(filename, src))
174 /// Loads source file as a binary blob.
176 /// Unlike `load_file`, guarantees that no normalization like BOM-removal
178 pub fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
179 // Ideally, this should use `self.file_loader`, but it can't
180 // deal with binary files yet.
181 let bytes = fs::read(path)?;
183 // We need to add file to the `SourceMap`, so that it is present
184 // in dep-info. There's also an edge case that file might be both
185 // loaded as a binary via `include_bytes!` and as proper `SourceFile`
186 // via `mod`, so we try to use real file contents and not just an
188 let text = std::str::from_utf8(&bytes).unwrap_or("").to_string();
189 self.new_source_file(path.to_owned().into(), text);
193 pub fn files(&self) -> MappedLockGuard<'_, Vec<Lrc<SourceFile>>> {
194 LockGuard::map(self.files.borrow(), |files| &mut files.source_files)
197 pub fn source_file_by_stable_id(
199 stable_id: StableSourceFileId,
200 ) -> Option<Lrc<SourceFile>> {
201 self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned()
204 fn allocate_address_space(&self, size: usize) -> Result<usize, OffsetOverflowError> {
205 let size = u32::try_from(size).map_err(|_| OffsetOverflowError)?;
208 let current = self.used_address_space.load(Ordering::Relaxed);
211 // Add one so there is some space between files. This lets us distinguish
212 // positions in the `SourceMap`, even in the presence of zero-length files.
213 .and_then(|next| next.checked_add(1))
214 .ok_or(OffsetOverflowError)?;
218 .compare_exchange(current, next, Ordering::Relaxed, Ordering::Relaxed)
221 return Ok(usize::try_from(current).unwrap());
226 /// Creates a new `SourceFile`.
227 /// If a file already exists in the `SourceMap` with the same ID, that file is returned
229 pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
230 self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| {
231 eprintln!("fatal error: rustc does not support files larger than 4GB");
232 crate::fatal_error::FatalError.raise()
236 fn try_new_source_file(
240 ) -> Result<Lrc<SourceFile>, OffsetOverflowError> {
241 // The path is used to determine the directory for loading submodules and
242 // include files, so it must be before remapping.
243 // Note that filename may not be a valid path, eg it may be `<anon>` etc,
244 // but this is okay because the directory determined by `path.pop()` will
245 // be empty, so the working directory will be used.
246 let unmapped_path = filename.clone();
248 let (filename, was_remapped) = match filename {
249 FileName::Real(filename) => {
250 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
251 (FileName::Real(filename), was_remapped)
253 other => (other, false),
257 StableSourceFileId::new_from_pieces(&filename, was_remapped, Some(&unmapped_path));
259 let lrc_sf = match self.source_file_by_stable_id(file_id) {
260 Some(lrc_sf) => lrc_sf,
262 let start_pos = self.allocate_address_space(src.len())?;
264 let source_file = Lrc::new(SourceFile::new(
269 Pos::from_usize(start_pos),
273 let mut files = self.files.borrow_mut();
275 files.source_files.push(source_file.clone());
276 files.stable_id_to_source_file.insert(file_id, source_file.clone());
284 /// Allocates a new `SourceFile` representing a source file from an external
285 /// crate. The source code of such an "imported `SourceFile`" is not available,
286 /// but we still know enough to generate accurate debuginfo location
287 /// information for things inlined from other crates.
288 pub fn new_imported_source_file(
291 name_was_remapped: bool,
292 src_hash: SourceFileHash,
296 mut file_local_lines: Vec<BytePos>,
297 mut file_local_multibyte_chars: Vec<MultiByteChar>,
298 mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
299 mut file_local_normalized_pos: Vec<NormalizedPos>,
300 original_start_pos: BytePos,
301 original_end_pos: BytePos,
302 ) -> Lrc<SourceFile> {
304 .allocate_address_space(source_len)
305 .expect("not enough address space for imported source file");
307 let end_pos = Pos::from_usize(start_pos + source_len);
308 let start_pos = Pos::from_usize(start_pos);
310 for pos in &mut file_local_lines {
311 *pos = *pos + start_pos;
314 for mbc in &mut file_local_multibyte_chars {
315 mbc.pos = mbc.pos + start_pos;
318 for swc in &mut file_local_non_narrow_chars {
319 *swc = *swc + start_pos;
322 for nc in &mut file_local_normalized_pos {
323 nc.pos = nc.pos + start_pos;
326 let source_file = Lrc::new(SourceFile {
332 external_src: Lock::new(ExternalSource::Foreign {
333 kind: ExternalSourceKind::AbsentOk,
339 lines: file_local_lines,
340 multibyte_chars: file_local_multibyte_chars,
341 non_narrow_chars: file_local_non_narrow_chars,
342 normalized_pos: file_local_normalized_pos,
347 let mut files = self.files.borrow_mut();
349 files.source_files.push(source_file.clone());
351 .stable_id_to_source_file
352 .insert(StableSourceFileId::new(&source_file), source_file.clone());
357 pub fn mk_substr_filename(&self, sp: Span) -> String {
358 let pos = self.lookup_char_pos(sp.lo());
359 format!("<{}:{}:{}>", pos.file.name, pos.line, pos.col.to_usize() + 1)
362 // If there is a doctest offset, applies it to the line.
363 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
365 FileName::DocTest(_, offset) => {
367 orig - (-(*offset)) as usize
369 orig + *offset as usize
376 /// Looks up source information about a `BytePos`.
377 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
378 let chpos = self.bytepos_to_file_charpos(pos);
379 match self.lookup_line(pos) {
380 Ok(SourceFileAndLine { sf: f, line: a }) => {
381 let line = a + 1; // Line numbers start at 1
382 let linebpos = f.lines[a];
383 let linechpos = self.bytepos_to_file_charpos(linebpos);
384 let col = chpos - linechpos;
387 let start_width_idx = f
389 .binary_search_by_key(&linebpos, |x| x.pos())
390 .unwrap_or_else(|x| x);
391 let end_width_idx = f
393 .binary_search_by_key(&pos, |x| x.pos())
394 .unwrap_or_else(|x| x);
395 let special_chars = end_width_idx - start_width_idx;
396 let non_narrow: usize = f.non_narrow_chars[start_width_idx..end_width_idx]
400 col.0 - special_chars + non_narrow
402 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
403 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
404 debug!("byte is on line: {}", line);
405 assert!(chpos >= linechpos);
406 Loc { file: f, line, col, col_display }
410 let end_width_idx = f
412 .binary_search_by_key(&pos, |x| x.pos())
413 .unwrap_or_else(|x| x);
414 let non_narrow: usize =
415 f.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
416 chpos.0 - end_width_idx + non_narrow
418 Loc { file: f, line: 0, col: chpos, col_display }
423 // If the corresponding `SourceFile` is empty, does not return a line number.
424 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
425 let idx = self.lookup_source_file_idx(pos);
427 let f = (*self.files.borrow().source_files)[idx].clone();
429 match f.lookup_line(pos) {
430 Some(line) => Ok(SourceFileAndLine { sf: f, line }),
435 /// Returns `Some(span)`, a union of the LHS and RHS span. The LHS must precede the RHS. If
436 /// there are gaps between LHS and RHS, the resulting union will cross these gaps.
437 /// For this to work,
439 /// * the syntax contexts of both spans much match,
440 /// * the LHS span needs to end on the same line the RHS span begins,
441 /// * the LHS span must start at or before the RHS span.
442 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
443 // Ensure we're at the same expansion ID.
444 if sp_lhs.ctxt() != sp_rhs.ctxt() {
448 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
450 Err(_) => return None,
452 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
454 Err(_) => return None,
457 // If we must cross lines to merge, don't merge.
458 if lhs_end.line != rhs_begin.line {
462 // Ensure these follow the expected order and that we don't overlap.
463 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
464 Some(sp_lhs.to(sp_rhs))
470 pub fn span_to_string(&self, sp: Span) -> String {
471 if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
472 return "no-location".to_string();
475 let lo = self.lookup_char_pos(sp.lo());
476 let hi = self.lookup_char_pos(sp.hi());
481 lo.col.to_usize() + 1,
483 hi.col.to_usize() + 1,
487 pub fn span_to_filename(&self, sp: Span) -> FileName {
488 self.lookup_char_pos(sp.lo()).file.name.clone()
491 pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
492 self.lookup_char_pos(sp.lo())
496 .expect("`SourceMap::span_to_unmapped_path` called for imported `SourceFile`?")
499 pub fn is_multiline(&self, sp: Span) -> bool {
500 let lo = self.lookup_char_pos(sp.lo());
501 let hi = self.lookup_char_pos(sp.hi());
505 pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> {
506 let lo = self.lookup_char_pos(sp.lo());
507 debug!("span_to_lines: lo={:?}", lo);
508 let hi = self.lookup_char_pos(sp.hi());
509 debug!("span_to_lines: hi={:?}", hi);
510 if lo.file.start_pos != hi.file.start_pos {
511 return Err(SpanLinesError::DistinctSources(DistinctSources {
512 begin: (lo.file.name.clone(), lo.file.start_pos),
513 end: (hi.file.name.clone(), hi.file.start_pos),
519 pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
520 match self.span_to_prev_source(sp) {
521 Ok(s) => s.split('\n').last().map(|l| l.trim_start().is_empty()).unwrap_or(false),
526 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
527 debug!("span_to_lines(sp={:?})", sp);
528 let (lo, hi) = self.is_valid_span(sp)?;
529 assert!(hi.line >= lo.line);
532 return Ok(FileLines { file: lo.file, lines: Vec::new() });
535 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
537 // The span starts partway through the first line,
538 // but after that it starts from offset 0.
539 let mut start_col = lo.col;
541 // For every line but the last, it extends from `start_col`
542 // and to the end of the line. Be careful because the line
543 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
546 // FIXME: now that we handle DUMMY_SP up above, we should consider
547 // asserting that the line numbers here are all indeed 1-based.
548 let hi_line = hi.line.saturating_sub(1);
549 for line_index in lo.line.saturating_sub(1)..hi_line {
550 let line_len = lo.file.get_line(line_index).map(|s| s.chars().count()).unwrap_or(0);
551 lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
552 start_col = CharPos::from_usize(0);
555 // For the last line, it extends from `start_col` to `hi.col`:
556 lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
558 Ok(FileLines { file: lo.file, lines })
561 /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
562 /// extract function takes three arguments: a string slice containing the source, an index in
563 /// the slice for the beginning of the span and an index in the slice for the end of the span.
564 fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
566 F: Fn(&str, usize, usize) -> Result<String, SpanSnippetError>,
568 let local_begin = self.lookup_byte_offset(sp.lo());
569 let local_end = self.lookup_byte_offset(sp.hi());
571 if local_begin.sf.start_pos != local_end.sf.start_pos {
572 Err(SpanSnippetError::DistinctSources(DistinctSources {
573 begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos),
574 end: (local_end.sf.name.clone(), local_end.sf.start_pos),
577 self.ensure_source_file_source_present(local_begin.sf.clone());
579 let start_index = local_begin.pos.to_usize();
580 let end_index = local_end.pos.to_usize();
581 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
583 if start_index > end_index || end_index > source_len {
584 return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
585 name: local_begin.sf.name.clone(),
587 begin_pos: local_begin.pos,
588 end_pos: local_end.pos,
592 if let Some(ref src) = local_begin.sf.src {
593 extract_source(src, start_index, end_index)
594 } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
595 extract_source(src, start_index, end_index)
597 Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() })
602 /// Returns the source snippet as `String` corresponding to the given `Span`.
603 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
604 self.span_to_source(sp, |src, start_index, end_index| {
605 src.get(start_index..end_index)
606 .map(|s| s.to_string())
607 .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))
611 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
612 match self.span_to_prev_source(sp) {
617 .map(|last_line| last_line.len() - last_line.trim_start().len()),
621 /// Returns the source snippet as `String` before the given `Span`.
622 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
623 self.span_to_source(sp, |src, start_index, _| {
624 src.get(..start_index)
625 .map(|s| s.to_string())
626 .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))
630 /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span
631 /// if no character could be found or if an error occurred while retrieving the code snippet.
632 pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span {
633 if let Ok(prev_source) = self.span_to_prev_source(sp) {
634 let prev_source = prev_source.rsplit(c).next().unwrap_or("").trim_start();
635 if !prev_source.is_empty() && !prev_source.contains('\n') {
636 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
643 /// Extends the given `Span` to just after the previous occurrence of `pat` when surrounded by
644 /// whitespace. Returns the same span if no character could be found or if an error occurred
645 /// while retrieving the code snippet.
646 pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
647 // assure that the pattern is delimited, to avoid the following
649 // ^^^^ returned span without the check
650 // ---------- correct span
651 for ws in &[" ", "\t", "\n"] {
652 let pat = pat.to_owned() + ws;
653 if let Ok(prev_source) = self.span_to_prev_source(sp) {
654 let prev_source = prev_source.rsplit(&pat).next().unwrap_or("").trim_start();
655 if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) {
656 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
664 /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char`
666 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
667 match self.span_to_snippet(sp) {
669 let snippet = snippet.split(c).next().unwrap_or("").trim_end();
670 if !snippet.is_empty() && !snippet.contains('\n') {
671 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
680 /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char`
682 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
683 if let Ok(snippet) = self.span_to_snippet(sp) {
684 if let Some(offset) = snippet.find(c) {
685 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
691 /// Given a `Span`, gets a new `Span` covering the first token and all its trailing whitespace
692 /// or the original `Span`.
694 /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
695 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
696 let mut whitespace_found = false;
698 self.span_take_while(sp, |c| {
699 if !whitespace_found && c.is_whitespace() {
700 whitespace_found = true;
703 !whitespace_found || c.is_whitespace()
707 /// Given a `Span`, gets a new `Span` covering the first token without its trailing whitespace
708 /// or the original `Span` in case of error.
710 /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
711 pub fn span_until_whitespace(&self, sp: Span) -> Span {
712 self.span_take_while(sp, |c| !c.is_whitespace())
715 /// Given a `Span`, gets a shorter one until `predicate` yields `false`.
716 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
718 P: for<'r> FnMut(&'r char) -> bool,
720 if let Ok(snippet) = self.span_to_snippet(sp) {
721 let offset = snippet.chars().take_while(predicate).map(|c| c.len_utf8()).sum::<usize>();
723 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
729 /// Given a `Span`, return a span ending in the closest `{`. This is useful when you have a
730 /// `Span` enclosing a whole item but we need to point at only the head (usually the first
731 /// line) of that item.
733 /// *Only suitable for diagnostics.*
734 pub fn guess_head_span(&self, sp: Span) -> Span {
735 // FIXME: extend the AST items to have a head span, or replace callers with pointing at
736 // the item's ident when appropriate.
737 self.span_until_char(sp, '{')
740 /// Returns a new span representing just the start point of this span.
741 pub fn start_point(&self, sp: Span) -> Span {
743 let width = self.find_width_of_character_at_span(sp, false);
744 let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
745 let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
746 sp.with_hi(end_point)
749 /// Returns a new span representing just the end point of this span.
750 pub fn end_point(&self, sp: Span) -> Span {
753 let width = self.find_width_of_character_at_span(sp, false);
754 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
756 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
757 sp.with_lo(end_point)
760 /// Returns a new span representing the next character after the end-point of this span.
761 pub fn next_point(&self, sp: Span) -> Span {
762 let start_of_next_point = sp.hi().0;
764 let width = self.find_width_of_character_at_span(sp.shrink_to_hi(), true);
765 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
766 // in the case of a multibyte character, where the width != 1, the next span should
767 // span multiple bytes to include the whole character.
768 let end_of_next_point =
769 start_of_next_point.checked_add(width - 1).unwrap_or(start_of_next_point);
771 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
772 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
775 /// Finds the width of a character, either before or after the provided span.
776 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
779 debug!("find_width_of_character_at_span: early return empty span");
783 let local_begin = self.lookup_byte_offset(sp.lo);
784 let local_end = self.lookup_byte_offset(sp.hi);
786 "find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
787 local_begin, local_end
790 if local_begin.sf.start_pos != local_end.sf.start_pos {
791 debug!("find_width_of_character_at_span: begin and end are in different files");
795 let start_index = local_begin.pos.to_usize();
796 let end_index = local_end.pos.to_usize();
798 "find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
799 start_index, end_index
802 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
804 if (!forwards && end_index == usize::min_value())
805 || (forwards && start_index == usize::max_value())
807 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
811 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
812 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
813 // Ensure indexes are also not malformed.
814 if start_index > end_index || end_index > source_len {
815 debug!("find_width_of_character_at_span: source indexes are malformed");
819 let src = local_begin.sf.external_src.borrow();
821 // We need to extend the snippet to the end of the src rather than to end_index so when
822 // searching forwards for boundaries we've got somewhere to search.
823 let snippet = if let Some(ref src) = local_begin.sf.src {
825 &src[start_index..len]
826 } else if let Some(src) = src.get_source() {
828 &src[start_index..len]
832 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
834 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
835 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
837 while !snippet.is_char_boundary(target - start_index) && target < source_len {
838 target = if forwards {
841 match target.checked_sub(1) {
842 Some(target) => target,
848 debug!("find_width_of_character_at_span: target=`{:?}`", target);
850 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
852 if forwards { (target - end_index) as u32 } else { (end_index - target) as u32 }
855 pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
856 for sf in self.files.borrow().source_files.iter() {
857 if *filename == sf.name {
858 return Some(sf.clone());
864 /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
865 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
866 let idx = self.lookup_source_file_idx(bpos);
867 let sf = (*self.files.borrow().source_files)[idx].clone();
868 let offset = bpos - sf.start_pos;
869 SourceFileAndBytePos { sf, pos: offset }
872 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
873 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
874 let idx = self.lookup_source_file_idx(bpos);
875 let map = &(*self.files.borrow().source_files)[idx];
877 // The number of extra bytes due to multibyte chars in the `SourceFile`.
878 let mut total_extra_bytes = 0;
880 for mbc in map.multibyte_chars.iter() {
881 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
883 // Every character is at least one byte, so we only
884 // count the actual extra bytes.
885 total_extra_bytes += mbc.bytes as u32 - 1;
886 // We should never see a byte position in the middle of a
888 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
894 assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
895 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
898 // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`.
899 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
903 .binary_search_by_key(&pos, |key| key.start_pos)
904 .unwrap_or_else(|p| p - 1)
907 pub fn count_lines(&self) -> usize {
908 self.files().iter().fold(0, |a, f| a + f.count_lines())
911 pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
912 let prev_span = self.span_extend_to_prev_str(span, "fn", true);
913 self.span_to_snippet(prev_span)
916 .find(|c: char| !c.is_alphanumeric() && c != '_')
917 .expect("no label after fn");
918 prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
923 /// Takes the span of a type parameter in a function signature and try to generate a span for
924 /// the function name (with generics) and a new snippet for this span with the pointed type
925 /// parameter as a new local type parameter.
928 /// ```rust,ignore (pseudo-Rust)
930 /// fn my_function(param: T)
931 /// // ^ Original span
934 /// fn my_function(param: T)
935 /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
938 /// Attention: The method used is very fragile since it essentially duplicates the work of the
939 /// parser. If you need to use this function or something similar, please consider updating the
940 /// `SourceMap` functions and this function to something more robust.
941 pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
942 // Try to extend the span to the previous "fn" keyword to retrieve the function
944 let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
945 if sugg_span != span {
946 if let Ok(snippet) = self.span_to_snippet(sugg_span) {
947 // Consume the function name.
948 let mut offset = snippet
949 .find(|c: char| !c.is_alphanumeric() && c != '_')
950 .expect("no label after fn");
952 // Consume the generics part of the function signature.
953 let mut bracket_counter = 0;
954 let mut last_char = None;
955 for c in snippet[offset..].chars() {
957 '<' => bracket_counter += 1,
958 '>' => bracket_counter -= 1,
960 if bracket_counter == 0 {
966 offset += c.len_utf8();
970 // Adjust the suggestion span to encompass the function name with its generics.
971 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
973 // Prepare the new suggested snippet to append the type parameter that triggered
974 // the error in the generics of the function signature.
975 let mut new_snippet = if last_char == Some('>') {
976 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
978 format!("{}<", &snippet[..offset])
981 .push_str(&self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
982 new_snippet.push('>');
984 return Some((sugg_span, new_snippet));
990 pub fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
991 source_file.add_external_src(|| match source_file.name {
992 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
997 pub fn is_imported(&self, sp: Span) -> bool {
998 let source_file_index = self.lookup_source_file_idx(sp.lo());
999 let source_file = &self.files()[source_file_index];
1000 source_file.is_imported()
1005 pub struct FilePathMapping {
1006 mapping: Vec<(PathBuf, PathBuf)>,
1009 impl FilePathMapping {
1010 pub fn empty() -> FilePathMapping {
1011 FilePathMapping { mapping: vec![] }
1014 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1015 FilePathMapping { mapping }
1018 /// Applies any path prefix substitution as defined by the mapping.
1019 /// The return value is the remapped path and a boolean indicating whether
1020 /// the path was affected by the mapping.
1021 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1022 // NOTE: We are iterating over the mapping entries from last to first
1023 // because entries specified later on the command line should
1025 for &(ref from, ref to) in self.mapping.iter().rev() {
1026 if let Ok(rest) = path.strip_prefix(from) {
1027 return (to.join(rest), true);