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.
11 pub use crate::hygiene::{ExpnKind, ExpnData};
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::stable_hasher::StableHasher;
15 use rustc_data_structures::sync::{Lrc, Lock, LockGuard, MappedLockGuard};
18 use std::path::{Path, PathBuf};
28 /// Returns the span itself if it doesn't come from a macro expansion,
29 /// otherwise return the call site span up to the `enclosing_sp` by
30 /// following the `expn_data` chain.
31 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
32 let expn_data1 = sp.ctxt().outer_expn_data();
33 let expn_data2 = enclosing_sp.ctxt().outer_expn_data();
34 if expn_data1.is_root() ||
35 !expn_data2.is_root() && expn_data1.call_site == expn_data2.call_site {
38 original_sp(expn_data1.call_site, enclosing_sp)
42 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, HashStable_Generic)]
43 pub struct Spanned<T> {
48 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
49 Spanned {node: t, span: sp}
52 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
56 // _____________________________________________________________________________
57 // SourceFile, MultiByteChar, FileName, FileLines
60 /// An abstraction over the fs operations used by the Parser.
61 pub trait FileLoader {
62 /// Query the existence of a file.
63 fn file_exists(&self, path: &Path) -> bool;
65 /// Returns an absolute path to a file, if possible.
66 fn abs_path(&self, path: &Path) -> Option<PathBuf>;
68 /// Read the contents of an UTF-8 file into memory.
69 fn read_file(&self, path: &Path) -> io::Result<String>;
72 /// A FileLoader that uses std::fs to load real files.
73 pub struct RealFileLoader;
75 impl FileLoader for RealFileLoader {
76 fn file_exists(&self, path: &Path) -> bool {
77 fs::metadata(path).is_ok()
80 fn abs_path(&self, path: &Path) -> Option<PathBuf> {
81 if path.is_absolute() {
82 Some(path.to_path_buf())
86 .map(|cwd| cwd.join(path))
90 fn read_file(&self, path: &Path) -> io::Result<String> {
91 fs::read_to_string(path)
95 // This is a `SourceFile` identifier that is used to correlate `SourceFile`s between
96 // subsequent compilation sessions (which is something we need to do during
97 // incremental compilation).
98 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
99 pub struct StableSourceFileId(u128);
101 impl StableSourceFileId {
102 pub fn new(source_file: &SourceFile) -> StableSourceFileId {
103 StableSourceFileId::new_from_pieces(&source_file.name,
104 source_file.name_was_remapped,
105 source_file.unmapped_path.as_ref())
108 pub fn new_from_pieces(name: &FileName,
109 name_was_remapped: bool,
110 unmapped_path: Option<&FileName>) -> StableSourceFileId {
111 let mut hasher = StableHasher::new();
113 name.hash(&mut hasher);
114 name_was_remapped.hash(&mut hasher);
115 unmapped_path.hash(&mut hasher);
117 StableSourceFileId(hasher.finish())
121 // _____________________________________________________________________________
126 pub(super) struct SourceMapFiles {
127 source_files: Vec<Lrc<SourceFile>>,
128 stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>
131 pub struct SourceMap {
132 files: Lock<SourceMapFiles>,
133 file_loader: Box<dyn FileLoader + Sync + Send>,
134 // This is used to apply the file path remapping as specified via
135 // `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`.
136 path_mapping: FilePathMapping,
140 pub fn new(path_mapping: FilePathMapping) -> SourceMap {
142 files: Default::default(),
143 file_loader: Box::new(RealFileLoader),
148 pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
149 path_mapping: FilePathMapping)
152 files: Default::default(),
158 pub fn path_mapping(&self) -> &FilePathMapping {
162 pub fn file_exists(&self, path: &Path) -> bool {
163 self.file_loader.file_exists(path)
166 pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
167 let src = self.file_loader.read_file(path)?;
168 let filename = path.to_owned().into();
169 Ok(self.new_source_file(filename, src))
172 /// Loads source file as a binary blob.
174 /// Unlike `load_file`, guarantees that no normalization like BOM-removal
176 pub fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
177 // Ideally, this should use `self.file_loader`, but it can't
178 // deal with binary files yet.
179 let bytes = fs::read(path)?;
181 // We need to add file to the `SourceMap`, so that it is present
182 // in dep-info. There's also an edge case that file might be both
183 // loaded as a binary via `include_bytes!` and as proper `SourceFile`
184 // via `mod`, so we try to use real file contents and not just an
186 let text = std::str::from_utf8(&bytes).unwrap_or("")
188 self.new_source_file(path.to_owned().into(), text);
192 pub fn files(&self) -> MappedLockGuard<'_, Vec<Lrc<SourceFile>>> {
193 LockGuard::map(self.files.borrow(), |files| &mut files.source_files)
196 pub fn source_file_by_stable_id(&self, stable_id: StableSourceFileId) ->
197 Option<Lrc<SourceFile>> {
198 self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|sf| sf.clone())
201 fn next_start_pos(&self) -> usize {
202 match self.files.borrow().source_files.last() {
204 // Add one so there is some space between files. This lets us distinguish
205 // positions in the `SourceMap`, even in the presence of zero-length files.
206 Some(last) => last.end_pos.to_usize() + 1,
210 /// Creates a new `SourceFile`.
211 /// If a file already exists in the `SourceMap` with the same ID, that file is returned
213 pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
214 self.try_new_source_file(filename, src)
215 .unwrap_or_else(|OffsetOverflowError| {
216 eprintln!("fatal error: rustc does not support files larger than 4GB");
217 crate::fatal_error::FatalError.raise()
221 fn try_new_source_file(
225 ) -> Result<Lrc<SourceFile>, OffsetOverflowError> {
226 let start_pos = self.next_start_pos();
228 // The path is used to determine the directory for loading submodules and
229 // include files, so it must be before remapping.
230 // Note that filename may not be a valid path, eg it may be `<anon>` etc,
231 // but this is okay because the directory determined by `path.pop()` will
232 // be empty, so the working directory will be used.
233 let unmapped_path = filename.clone();
235 let (filename, was_remapped) = match filename {
236 FileName::Real(filename) => {
237 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
238 (FileName::Real(filename), was_remapped)
240 other => (other, false),
243 let file_id = StableSourceFileId::new_from_pieces(&filename,
245 Some(&unmapped_path));
247 let lrc_sf = match self.source_file_by_stable_id(file_id) {
248 Some(lrc_sf) => lrc_sf,
250 let source_file = Lrc::new(SourceFile::new(
255 Pos::from_usize(start_pos),
258 let mut files = self.files.borrow_mut();
260 files.source_files.push(source_file.clone());
261 files.stable_id_to_source_file.insert(file_id, source_file.clone());
269 /// Allocates a new `SourceFile` representing a source file from an external
270 /// crate. The source code of such an "imported `SourceFile`" is not available,
271 /// but we still know enough to generate accurate debuginfo location
272 /// information for things inlined from other crates.
273 pub fn new_imported_source_file(
276 name_was_remapped: bool,
277 crate_of_origin: u32,
281 mut file_local_lines: Vec<BytePos>,
282 mut file_local_multibyte_chars: Vec<MultiByteChar>,
283 mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
284 mut file_local_normalized_pos: Vec<NormalizedPos>,
285 ) -> Lrc<SourceFile> {
286 let start_pos = self.next_start_pos();
288 let end_pos = Pos::from_usize(start_pos + source_len);
289 let start_pos = Pos::from_usize(start_pos);
291 for pos in &mut file_local_lines {
292 *pos = *pos + start_pos;
295 for mbc in &mut file_local_multibyte_chars {
296 mbc.pos = mbc.pos + start_pos;
299 for swc in &mut file_local_non_narrow_chars {
300 *swc = *swc + start_pos;
303 for nc in &mut file_local_normalized_pos {
304 nc.pos = nc.pos + start_pos;
307 let source_file = Lrc::new(SourceFile {
314 external_src: Lock::new(ExternalSource::AbsentOk),
317 lines: file_local_lines,
318 multibyte_chars: file_local_multibyte_chars,
319 non_narrow_chars: file_local_non_narrow_chars,
320 normalized_pos: file_local_normalized_pos,
324 let mut files = self.files.borrow_mut();
326 files.source_files.push(source_file.clone());
327 files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file),
328 source_file.clone());
333 pub fn mk_substr_filename(&self, sp: Span) -> String {
334 let pos = self.lookup_char_pos(sp.lo());
335 format!("<{}:{}:{}>",
338 pos.col.to_usize() + 1)
341 // If there is a doctest offset, applies it to the line.
342 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
344 FileName::DocTest(_, offset) => {
345 return if *offset >= 0 {
346 orig + *offset as usize
348 orig - (-(*offset)) as usize
355 /// Looks up source information about a `BytePos`.
356 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
357 let chpos = self.bytepos_to_file_charpos(pos);
358 match self.lookup_line(pos) {
359 Ok(SourceFileAndLine { sf: f, line: a }) => {
360 let line = a + 1; // Line numbers start at 1
361 let linebpos = f.lines[a];
362 let linechpos = self.bytepos_to_file_charpos(linebpos);
363 let col = chpos - linechpos;
366 let start_width_idx = f
368 .binary_search_by_key(&linebpos, |x| x.pos())
369 .unwrap_or_else(|x| x);
370 let end_width_idx = f
372 .binary_search_by_key(&pos, |x| x.pos())
373 .unwrap_or_else(|x| x);
374 let special_chars = end_width_idx - start_width_idx;
375 let non_narrow: usize = f
376 .non_narrow_chars[start_width_idx..end_width_idx]
380 col.0 - special_chars + non_narrow
382 debug!("byte pos {:?} is on the line at byte pos {:?}",
384 debug!("char pos {:?} is on the line at char pos {:?}",
386 debug!("byte is on line: {}", line);
387 assert!(chpos >= linechpos);
397 let end_width_idx = f
399 .binary_search_by_key(&pos, |x| x.pos())
400 .unwrap_or_else(|x| x);
401 let non_narrow: usize = f
402 .non_narrow_chars[0..end_width_idx]
406 chpos.0 - end_width_idx + non_narrow
418 // If the corresponding `SourceFile` is empty, does not return a line number.
419 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
420 let idx = self.lookup_source_file_idx(pos);
422 let f = (*self.files.borrow().source_files)[idx].clone();
424 match f.lookup_line(pos) {
425 Some(line) => Ok(SourceFileAndLine { sf: f, line }),
430 /// Returns `Some(span)`, a union of the LHS and RHS span. The LHS must precede the RHS. If
431 /// there are gaps between LHS and RHS, the resulting union will cross these gaps.
432 /// For this to work,
434 /// * the syntax contexts of both spans much match,
435 /// * the LHS span needs to end on the same line the RHS span begins,
436 /// * the LHS span must start at or before the RHS span.
437 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
438 // Ensure we're at the same expansion ID.
439 if sp_lhs.ctxt() != sp_rhs.ctxt() {
443 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
445 Err(_) => return None
447 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
449 Err(_) => return None
452 // If we must cross lines to merge, don't merge.
453 if lhs_end.line != rhs_begin.line {
457 // Ensure these follow the expected order and that we don't overlap.
458 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
459 Some(sp_lhs.to(sp_rhs))
465 pub fn span_to_string(&self, sp: Span) -> String {
466 if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
467 return "no-location".to_string();
470 let lo = self.lookup_char_pos(sp.lo());
471 let hi = self.lookup_char_pos(sp.hi());
472 format!("{}:{}:{}: {}:{}",
475 lo.col.to_usize() + 1,
477 hi.col.to_usize() + 1,
481 pub fn span_to_filename(&self, sp: Span) -> FileName {
482 self.lookup_char_pos(sp.lo()).file.name.clone()
485 pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
486 self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
487 .expect("`SourceMap::span_to_unmapped_path` called for imported `SourceFile`?")
490 pub fn is_multiline(&self, sp: Span) -> bool {
491 let lo = self.lookup_char_pos(sp.lo());
492 let hi = self.lookup_char_pos(sp.hi());
496 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
497 debug!("span_to_lines(sp={:?})", sp);
499 let lo = self.lookup_char_pos(sp.lo());
500 debug!("span_to_lines: lo={:?}", lo);
501 let hi = self.lookup_char_pos(sp.hi());
502 debug!("span_to_lines: hi={:?}", hi);
504 if lo.file.start_pos != hi.file.start_pos {
505 return Err(SpanLinesError::DistinctSources(DistinctSources {
506 begin: (lo.file.name.clone(), lo.file.start_pos),
507 end: (hi.file.name.clone(), hi.file.start_pos),
510 assert!(hi.line >= lo.line);
512 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
514 // The span starts partway through the first line,
515 // but after that it starts from offset 0.
516 let mut start_col = lo.col;
518 // For every line but the last, it extends from `start_col`
519 // and to the end of the line. Be careful because the line
520 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
522 for line_index in lo.line-1 .. hi.line-1 {
523 let line_len = lo.file.get_line(line_index)
524 .map(|s| s.chars().count())
526 lines.push(LineInfo { line_index,
528 end_col: CharPos::from_usize(line_len) });
529 start_col = CharPos::from_usize(0);
532 // For the last line, it extends from `start_col` to `hi.col`:
533 lines.push(LineInfo { line_index: hi.line - 1,
537 Ok(FileLines {file: lo.file, lines})
540 /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
541 /// extract function takes three arguments: a string slice containing the source, an index in
542 /// the slice for the beginning of the span and an index in the slice for the end of the span.
543 fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
544 where F: Fn(&str, usize, usize) -> Result<String, SpanSnippetError>
546 let local_begin = self.lookup_byte_offset(sp.lo());
547 let local_end = self.lookup_byte_offset(sp.hi());
549 if local_begin.sf.start_pos != local_end.sf.start_pos {
550 return Err(SpanSnippetError::DistinctSources(DistinctSources {
551 begin: (local_begin.sf.name.clone(),
552 local_begin.sf.start_pos),
553 end: (local_end.sf.name.clone(),
554 local_end.sf.start_pos)
557 self.ensure_source_file_source_present(local_begin.sf.clone());
559 let start_index = local_begin.pos.to_usize();
560 let end_index = local_end.pos.to_usize();
561 let source_len = (local_begin.sf.end_pos -
562 local_begin.sf.start_pos).to_usize();
564 if start_index > end_index || end_index > source_len {
565 return Err(SpanSnippetError::MalformedForSourcemap(
566 MalformedSourceMapPositions {
567 name: local_begin.sf.name.clone(),
569 begin_pos: local_begin.pos,
570 end_pos: local_end.pos,
574 if let Some(ref src) = local_begin.sf.src {
575 return extract_source(src, start_index, end_index);
576 } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
577 return extract_source(src, start_index, end_index);
579 return Err(SpanSnippetError::SourceNotAvailable {
580 filename: local_begin.sf.name.clone()
586 /// Returns the source snippet as `String` corresponding to the given `Span`.
587 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
588 self.span_to_source(sp, |src, start_index, end_index| src.get(start_index..end_index)
589 .map(|s| s.to_string())
590 .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)))
593 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
594 match self.span_to_prev_source(sp) {
596 Ok(source) => source.split('\n').last().map(|last_line| {
597 last_line.len() - last_line.trim_start().len()
602 /// Returns the source snippet as `String` before the given `Span`.
603 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
604 self.span_to_source(sp, |src, start_index, _| src.get(..start_index)
605 .map(|s| s.to_string())
606 .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)))
609 /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span
610 /// if no character could be found or if an error occurred while retrieving the code snippet.
611 pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span {
612 if let Ok(prev_source) = self.span_to_prev_source(sp) {
613 let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_start();
614 if !prev_source.is_empty() && !prev_source.contains('\n') {
615 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
622 /// Extends the given `Span` to just after the previous occurrence of `pat` when surrounded by
623 /// whitespace. Returns the same span if no character could be found or if an error occurred
624 /// while retrieving the code snippet.
625 pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
626 // assure that the pattern is delimited, to avoid the following
628 // ^^^^ returned span without the check
629 // ---------- correct span
630 for ws in &[" ", "\t", "\n"] {
631 let pat = pat.to_owned() + ws;
632 if let Ok(prev_source) = self.span_to_prev_source(sp) {
633 let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_start();
634 if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) {
635 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
643 /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char`
645 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
646 match self.span_to_snippet(sp) {
648 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end();
649 if !snippet.is_empty() && !snippet.contains('\n') {
650 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
659 /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char`
661 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
662 if let Ok(snippet) = self.span_to_snippet(sp) {
663 if let Some(offset) = snippet.find(c) {
664 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
670 /// Given a `Span`, gets a new `Span` covering the first token and all its trailing whitespace
671 /// or the original `Span`.
673 /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
674 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
675 let mut whitespace_found = false;
677 self.span_take_while(sp, |c| {
678 if !whitespace_found && c.is_whitespace() {
679 whitespace_found = true;
682 if whitespace_found && !c.is_whitespace() {
690 /// Given a `Span`, gets a new `Span` covering the first token without its trailing whitespace
691 /// or the original `Span` in case of error.
693 /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
694 pub fn span_until_whitespace(&self, sp: Span) -> Span {
695 self.span_take_while(sp, |c| !c.is_whitespace())
698 /// Given a `Span`, gets a shorter one until `predicate` yields `false`.
699 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
700 where P: for <'r> FnMut(&'r char) -> bool
702 if let Ok(snippet) = self.span_to_snippet(sp) {
703 let offset = snippet.chars()
704 .take_while(predicate)
705 .map(|c| c.len_utf8())
708 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
714 pub fn def_span(&self, sp: Span) -> Span {
715 self.span_until_char(sp, '{')
718 /// Returns a new span representing just the start point of this span.
719 pub fn start_point(&self, sp: Span) -> Span {
721 let width = self.find_width_of_character_at_span(sp, false);
722 let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
723 let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
724 sp.with_hi(end_point)
727 /// Returns a new span representing just the end point of this span.
728 pub fn end_point(&self, sp: Span) -> Span {
731 let width = self.find_width_of_character_at_span(sp, false);
732 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
734 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
735 sp.with_lo(end_point)
738 /// Returns a new span representing the next character after the end-point of this span.
739 pub fn next_point(&self, sp: Span) -> Span {
740 let start_of_next_point = sp.hi().0;
742 let width = self.find_width_of_character_at_span(sp, true);
743 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
744 // in the case of a multibyte character, where the width != 1, the next span should
745 // span multiple bytes to include the whole character.
746 let end_of_next_point = start_of_next_point.checked_add(
747 width - 1).unwrap_or(start_of_next_point);
749 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
750 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
753 /// Finds the width of a character, either before or after the provided span.
754 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
757 debug!("find_width_of_character_at_span: early return empty span");
761 let local_begin = self.lookup_byte_offset(sp.lo);
762 let local_end = self.lookup_byte_offset(sp.hi);
763 debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
764 local_begin, local_end);
766 if local_begin.sf.start_pos != local_end.sf.start_pos {
767 debug!("find_width_of_character_at_span: begin and end are in different files");
771 let start_index = local_begin.pos.to_usize();
772 let end_index = local_end.pos.to_usize();
773 debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
774 start_index, end_index);
776 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
778 if (!forwards && end_index == usize::min_value()) ||
779 (forwards && start_index == usize::max_value()) {
780 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
784 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
785 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
786 // Ensure indexes are also not malformed.
787 if start_index > end_index || end_index > source_len {
788 debug!("find_width_of_character_at_span: source indexes are malformed");
792 let src = local_begin.sf.external_src.borrow();
794 // We need to extend the snippet to the end of the src rather than to end_index so when
795 // searching forwards for boundaries we've got somewhere to search.
796 let snippet = if let Some(ref src) = local_begin.sf.src {
798 (&src[start_index..len])
799 } else if let Some(src) = src.get_source() {
801 (&src[start_index..len])
805 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
807 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
808 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
810 while !snippet.is_char_boundary(target - start_index) && target < source_len {
811 target = if forwards {
814 match target.checked_sub(1) {
815 Some(target) => target,
821 debug!("find_width_of_character_at_span: target=`{:?}`", target);
823 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
826 (target - end_index) as u32
828 (end_index - target) as u32
832 pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
833 for sf in self.files.borrow().source_files.iter() {
834 if *filename == sf.name {
835 return Some(sf.clone());
841 /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
842 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
843 let idx = self.lookup_source_file_idx(bpos);
844 let sf = (*self.files.borrow().source_files)[idx].clone();
845 let offset = bpos - sf.start_pos;
846 SourceFileAndBytePos {sf, pos: offset}
849 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
850 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
851 let idx = self.lookup_source_file_idx(bpos);
852 let map = &(*self.files.borrow().source_files)[idx];
854 // The number of extra bytes due to multibyte chars in the `SourceFile`.
855 let mut total_extra_bytes = 0;
857 for mbc in map.multibyte_chars.iter() {
858 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
860 // Every character is at least one byte, so we only
861 // count the actual extra bytes.
862 total_extra_bytes += mbc.bytes as u32 - 1;
863 // We should never see a byte position in the middle of a
865 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
871 assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
872 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
875 // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`.
876 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
877 self.files.borrow().source_files.binary_search_by_key(&pos, |key| key.start_pos)
878 .unwrap_or_else(|p| p - 1)
881 pub fn count_lines(&self) -> usize {
882 self.files().iter().fold(0, |a, f| a + f.count_lines())
886 pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
887 let prev_span = self.span_extend_to_prev_str(span, "fn", true);
888 self.span_to_snippet(prev_span).map(|snippet| {
889 let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
890 .expect("no label after fn");
891 prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
895 /// Takes the span of a type parameter in a function signature and try to generate a span for
896 /// the function name (with generics) and a new snippet for this span with the pointed type
897 /// parameter as a new local type parameter.
900 /// ```rust,ignore (pseudo-Rust)
902 /// fn my_function(param: T)
903 /// // ^ Original span
906 /// fn my_function(param: T)
907 /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
910 /// Attention: The method used is very fragile since it essentially duplicates the work of the
911 /// parser. If you need to use this function or something similar, please consider updating the
912 /// `SourceMap` functions and this function to something more robust.
913 pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
914 // Try to extend the span to the previous "fn" keyword to retrieve the function
916 let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
917 if sugg_span != span {
918 if let Ok(snippet) = self.span_to_snippet(sugg_span) {
919 // Consume the function name.
920 let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
921 .expect("no label after fn");
923 // Consume the generics part of the function signature.
924 let mut bracket_counter = 0;
925 let mut last_char = None;
926 for c in snippet[offset..].chars() {
928 '<' => bracket_counter += 1,
929 '>' => bracket_counter -= 1,
930 '(' => if bracket_counter == 0 { break; }
933 offset += c.len_utf8();
937 // Adjust the suggestion span to encompass the function name with its generics.
938 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
940 // Prepare the new suggested snippet to append the type parameter that triggered
941 // the error in the generics of the function signature.
942 let mut new_snippet = if last_char == Some('>') {
943 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
945 format!("{}<", &snippet[..offset])
947 new_snippet.push_str(
948 &self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
949 new_snippet.push('>');
951 return Some((sugg_span, new_snippet));
957 pub fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
958 source_file.add_external_src(
959 || match source_file.name {
960 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
965 pub fn call_span_if_macro(&self, sp: Span) -> Span {
966 if self.span_to_filename(sp.clone()).is_macros() {
967 let v = sp.macro_backtrace();
968 if let Some(use_site) = v.last() {
969 return use_site.call_site;
977 pub struct FilePathMapping {
978 mapping: Vec<(PathBuf, PathBuf)>,
981 impl FilePathMapping {
982 pub fn empty() -> FilePathMapping {
988 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
994 /// Applies any path prefix substitution as defined by the mapping.
995 /// The return value is the remapped path and a boolean indicating whether
996 /// the path was affected by the mapping.
997 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
998 // NOTE: We are iterating over the mapping entries from last to first
999 // because entries specified later on the command line should
1001 for &(ref from, ref to) in self.mapping.iter().rev() {
1002 if let Ok(rest) = path.strip_prefix(from) {
1003 return (to.join(rest), true);