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 SourceFiles. Byte positions are stored in
6 //! `spans` 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 syntax_pos::*;
11 pub use syntax_pos::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};
25 use errors::SourceMapper;
30 /// Returns the span itself if it doesn't come from a macro expansion,
31 /// otherwise return the call site span up to the `enclosing_sp` by
32 /// following the `expn_data` chain.
33 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
34 let expn_data1 = sp.ctxt().outer_expn_data();
35 let expn_data2 = enclosing_sp.ctxt().outer_expn_data();
36 if expn_data1.is_root() ||
37 !expn_data2.is_root() && expn_data1.call_site == expn_data2.call_site {
40 original_sp(expn_data1.call_site, enclosing_sp)
44 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
45 pub struct Spanned<T> {
50 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
51 Spanned {node: t, span: sp}
54 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
58 // _____________________________________________________________________________
59 // SourceFile, MultiByteChar, FileName, FileLines
62 /// An abstraction over the fs operations used by the Parser.
63 pub trait FileLoader {
64 /// Query the existence of a file.
65 fn file_exists(&self, path: &Path) -> bool;
67 /// Returns an absolute path to a file, if possible.
68 fn abs_path(&self, path: &Path) -> Option<PathBuf>;
70 /// Read the contents of an UTF-8 file into memory.
71 fn read_file(&self, path: &Path) -> io::Result<String>;
74 /// A FileLoader that uses std::fs to load real files.
75 pub struct RealFileLoader;
77 impl FileLoader for RealFileLoader {
78 fn file_exists(&self, path: &Path) -> bool {
79 fs::metadata(path).is_ok()
82 fn abs_path(&self, path: &Path) -> Option<PathBuf> {
83 if path.is_absolute() {
84 Some(path.to_path_buf())
88 .map(|cwd| cwd.join(path))
92 fn read_file(&self, path: &Path) -> io::Result<String> {
93 fs::read_to_string(path)
97 // This is a SourceFile identifier that is used to correlate SourceFiles between
98 // subsequent compilation sessions (which is something we need to do during
99 // incremental compilation).
100 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
101 pub struct StableSourceFileId(u128);
103 impl StableSourceFileId {
104 pub fn new(source_file: &SourceFile) -> StableSourceFileId {
105 StableSourceFileId::new_from_pieces(&source_file.name,
106 source_file.name_was_remapped,
107 source_file.unmapped_path.as_ref())
110 pub fn new_from_pieces(name: &FileName,
111 name_was_remapped: bool,
112 unmapped_path: Option<&FileName>) -> StableSourceFileId {
113 let mut hasher = StableHasher::new();
115 name.hash(&mut hasher);
116 name_was_remapped.hash(&mut hasher);
117 unmapped_path.hash(&mut hasher);
119 StableSourceFileId(hasher.finish())
123 // _____________________________________________________________________________
128 pub(super) struct SourceMapFiles {
129 source_files: Vec<Lrc<SourceFile>>,
130 stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>
133 pub struct SourceMap {
134 files: Lock<SourceMapFiles>,
135 file_loader: Box<dyn FileLoader + Sync + Send>,
136 // This is used to apply the file path remapping as specified via
137 // --remap-path-prefix to all SourceFiles allocated within this SourceMap.
138 path_mapping: FilePathMapping,
142 pub fn new(path_mapping: FilePathMapping) -> SourceMap {
144 files: Default::default(),
145 file_loader: Box::new(RealFileLoader),
150 pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
151 path_mapping: FilePathMapping)
154 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("")
190 self.new_source_file(path.to_owned().into(), text);
194 pub fn files(&self) -> MappedLockGuard<'_, Vec<Lrc<SourceFile>>> {
195 LockGuard::map(self.files.borrow(), |files| &mut files.source_files)
198 pub fn source_file_by_stable_id(&self, stable_id: StableSourceFileId) ->
199 Option<Lrc<SourceFile>> {
200 self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|sf| sf.clone())
203 fn next_start_pos(&self) -> usize {
204 match self.files.borrow().source_files.last() {
206 // Add one so there is some space between files. This lets us distinguish
207 // positions in the source_map, even in the presence of zero-length files.
208 Some(last) => last.end_pos.to_usize() + 1,
212 /// Creates a new source_file.
213 /// If a file already exists in the source_map with the same id, that file is returned
215 pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
216 self.try_new_source_file(filename, src)
217 .unwrap_or_else(|OffsetOverflowError| {
218 eprintln!("fatal error: rustc does not support files larger than 4GB");
219 errors::FatalError.raise()
223 fn try_new_source_file(
227 ) -> Result<Lrc<SourceFile>, OffsetOverflowError> {
228 let start_pos = self.next_start_pos();
230 // The path is used to determine the directory for loading submodules and
231 // include files, so it must be before remapping.
232 // Note that filename may not be a valid path, eg it may be `<anon>` etc,
233 // but this is okay because the directory determined by `path.pop()` will
234 // be empty, so the working directory will be used.
235 let unmapped_path = filename.clone();
237 let (filename, was_remapped) = match filename {
238 FileName::Real(filename) => {
239 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
240 (FileName::Real(filename), was_remapped)
242 other => (other, false),
245 let file_id = StableSourceFileId::new_from_pieces(&filename,
247 Some(&unmapped_path));
249 let lrc_sf = match self.source_file_by_stable_id(file_id) {
250 Some(lrc_sf) => lrc_sf,
252 let source_file = Lrc::new(SourceFile::new(
257 Pos::from_usize(start_pos),
260 let mut files = self.files.borrow_mut();
262 files.source_files.push(source_file.clone());
263 files.stable_id_to_source_file.insert(file_id, source_file.clone());
271 /// Allocates a new SourceFile representing a source file from an external
272 /// crate. The source code of such an "imported source_file" is not available,
273 /// but we still know enough to generate accurate debuginfo location
274 /// information for things inlined from other crates.
275 pub fn new_imported_source_file(
278 name_was_remapped: bool,
279 crate_of_origin: u32,
283 mut file_local_lines: Vec<BytePos>,
284 mut file_local_multibyte_chars: Vec<MultiByteChar>,
285 mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
286 ) -> Lrc<SourceFile> {
287 let start_pos = self.next_start_pos();
289 let end_pos = Pos::from_usize(start_pos + source_len);
290 let start_pos = Pos::from_usize(start_pos);
292 for pos in &mut file_local_lines {
293 *pos = *pos + start_pos;
296 for mbc in &mut file_local_multibyte_chars {
297 mbc.pos = mbc.pos + start_pos;
300 for swc in &mut file_local_non_narrow_chars {
301 *swc = *swc + start_pos;
304 let source_file = Lrc::new(SourceFile {
311 external_src: Lock::new(ExternalSource::AbsentOk),
314 lines: file_local_lines,
315 multibyte_chars: file_local_multibyte_chars,
316 non_narrow_chars: file_local_non_narrow_chars,
320 let mut files = self.files.borrow_mut();
322 files.source_files.push(source_file.clone());
323 files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file),
324 source_file.clone());
329 pub fn mk_substr_filename(&self, sp: Span) -> String {
330 let pos = self.lookup_char_pos(sp.lo());
331 format!("<{}:{}:{}>",
334 pos.col.to_usize() + 1)
337 // If there is a doctest_offset, apply it to the line
338 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
340 FileName::DocTest(_, offset) => {
341 return if *offset >= 0 {
342 orig + *offset as usize
344 orig - (-(*offset)) as usize
351 /// Lookup source information about a BytePos
352 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
353 let chpos = self.bytepos_to_file_charpos(pos);
354 match self.lookup_line(pos) {
355 Ok(SourceFileAndLine { sf: f, line: a }) => {
356 let line = a + 1; // Line numbers start at 1
357 let linebpos = f.lines[a];
358 let linechpos = self.bytepos_to_file_charpos(linebpos);
359 let col = chpos - linechpos;
362 let start_width_idx = f
364 .binary_search_by_key(&linebpos, |x| x.pos())
365 .unwrap_or_else(|x| x);
366 let end_width_idx = f
368 .binary_search_by_key(&pos, |x| x.pos())
369 .unwrap_or_else(|x| x);
370 let special_chars = end_width_idx - start_width_idx;
371 let non_narrow: usize = f
372 .non_narrow_chars[start_width_idx..end_width_idx]
376 col.0 - special_chars + non_narrow
378 debug!("byte pos {:?} is on the line at byte pos {:?}",
380 debug!("char pos {:?} is on the line at char pos {:?}",
382 debug!("byte is on line: {}", line);
383 assert!(chpos >= linechpos);
393 let end_width_idx = f
395 .binary_search_by_key(&pos, |x| x.pos())
396 .unwrap_or_else(|x| x);
397 let non_narrow: usize = f
398 .non_narrow_chars[0..end_width_idx]
402 chpos.0 - end_width_idx + non_narrow
414 // If the relevant source_file is empty, we don't return a line number.
415 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
416 let idx = self.lookup_source_file_idx(pos);
418 let f = (*self.files.borrow().source_files)[idx].clone();
420 match f.lookup_line(pos) {
421 Some(line) => Ok(SourceFileAndLine { sf: f, line }),
426 /// Returns `Some(span)`, a union of the lhs and rhs span. The lhs must precede the rhs. If
427 /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
428 /// For this to work, the spans have to be:
430 /// * the ctxt of both spans much match
431 /// * the lhs span needs to end on the same line the rhs span begins
432 /// * the lhs span must start at or before the rhs span
433 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
434 // make sure we're at the same expansion id
435 if sp_lhs.ctxt() != sp_rhs.ctxt() {
439 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
441 Err(_) => return None
443 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
445 Err(_) => return None
448 // if we must cross lines to merge, don't merge
449 if lhs_end.line != rhs_begin.line {
453 // ensure these follow the expected order and we don't overlap
454 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
455 Some(sp_lhs.to(sp_rhs))
461 pub fn span_to_string(&self, sp: Span) -> String {
462 if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
463 return "no-location".to_string();
466 let lo = self.lookup_char_pos(sp.lo());
467 let hi = self.lookup_char_pos(sp.hi());
468 format!("{}:{}:{}: {}:{}",
471 lo.col.to_usize() + 1,
473 hi.col.to_usize() + 1)
476 pub fn span_to_filename(&self, sp: Span) -> FileName {
477 self.lookup_char_pos(sp.lo()).file.name.clone()
480 pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
481 self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
482 .expect("SourceMap::span_to_unmapped_path called for imported SourceFile?")
485 pub fn is_multiline(&self, sp: Span) -> bool {
486 let lo = self.lookup_char_pos(sp.lo());
487 let hi = self.lookup_char_pos(sp.hi());
491 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
492 debug!("span_to_lines(sp={:?})", sp);
494 if sp.lo() > sp.hi() {
495 return Err(SpanLinesError::IllFormedSpan(sp));
498 let lo = self.lookup_char_pos(sp.lo());
499 debug!("span_to_lines: lo={:?}", lo);
500 let hi = self.lookup_char_pos(sp.hi());
501 debug!("span_to_lines: hi={:?}", hi);
503 if lo.file.start_pos != hi.file.start_pos {
504 return Err(SpanLinesError::DistinctSources(DistinctSources {
505 begin: (lo.file.name.clone(), lo.file.start_pos),
506 end: (hi.file.name.clone(), hi.file.start_pos),
509 assert!(hi.line >= lo.line);
511 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
513 // The span starts partway through the first line,
514 // but after that it starts from offset 0.
515 let mut start_col = lo.col;
517 // For every line but the last, it extends from `start_col`
518 // and to the end of the line. Be careful because the line
519 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
521 for line_index in lo.line-1 .. hi.line-1 {
522 let line_len = lo.file.get_line(line_index)
523 .map(|s| s.chars().count())
525 lines.push(LineInfo { line_index,
527 end_col: CharPos::from_usize(line_len) });
528 start_col = CharPos::from_usize(0);
531 // For the last line, it extends from `start_col` to `hi.col`:
532 lines.push(LineInfo { line_index: hi.line - 1,
536 Ok(FileLines {file: lo.file, lines})
539 /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
540 /// extract function takes three arguments: a string slice containing the source, an index in
541 /// the slice for the beginning of the span and an index in the slice for the end of the span.
542 fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
543 where F: Fn(&str, usize, usize) -> Result<String, SpanSnippetError>
545 if sp.lo() > sp.hi() {
546 return Err(SpanSnippetError::IllFormedSpan(sp));
549 let local_begin = self.lookup_byte_offset(sp.lo());
550 let local_end = self.lookup_byte_offset(sp.hi());
552 if local_begin.sf.start_pos != local_end.sf.start_pos {
553 return Err(SpanSnippetError::DistinctSources(DistinctSources {
554 begin: (local_begin.sf.name.clone(),
555 local_begin.sf.start_pos),
556 end: (local_end.sf.name.clone(),
557 local_end.sf.start_pos)
560 self.ensure_source_file_source_present(local_begin.sf.clone());
562 let start_index = local_begin.pos.to_usize();
563 let end_index = local_end.pos.to_usize();
564 let source_len = (local_begin.sf.end_pos -
565 local_begin.sf.start_pos).to_usize();
567 if start_index > end_index || end_index > source_len {
568 return Err(SpanSnippetError::MalformedForSourcemap(
569 MalformedSourceMapPositions {
570 name: local_begin.sf.name.clone(),
572 begin_pos: local_begin.pos,
573 end_pos: local_end.pos,
577 if let Some(ref src) = local_begin.sf.src {
578 return extract_source(src, start_index, end_index);
579 } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
580 return extract_source(src, start_index, end_index);
582 return Err(SpanSnippetError::SourceNotAvailable {
583 filename: local_begin.sf.name.clone()
589 /// Returns the source snippet as `String` corresponding to the given `Span`
590 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
591 self.span_to_source(sp, |src, start_index, end_index| src.get(start_index..end_index)
592 .map(|s| s.to_string())
593 .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)))
596 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
597 match self.span_to_prev_source(sp) {
599 Ok(source) => source.split('\n').last().map(|last_line| {
600 last_line.len() - last_line.trim_start().len()
605 /// Returns the source snippet as `String` before the given `Span`
606 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
607 self.span_to_source(sp, |src, start_index, _| src.get(..start_index)
608 .map(|s| s.to_string())
609 .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)))
612 /// Extend the given `Span` to just after the previous occurrence of `c`. Return the same span
613 /// if no character could be found or if an error occurred while retrieving the code snippet.
614 pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span {
615 if let Ok(prev_source) = self.span_to_prev_source(sp) {
616 let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_start();
617 if !prev_source.is_empty() && !prev_source.contains('\n') {
618 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
625 /// Extend the given `Span` to just after the previous occurrence of `pat` when surrounded by
626 /// whitespace. Return the same span if no character could be found or if an error occurred
627 /// while retrieving the code snippet.
628 pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
629 // assure that the pattern is delimited, to avoid the following
631 // ^^^^ returned span without the check
632 // ---------- correct span
633 for ws in &[" ", "\t", "\n"] {
634 let pat = pat.to_owned() + ws;
635 if let Ok(prev_source) = self.span_to_prev_source(sp) {
636 let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_start();
637 if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) {
638 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
646 /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
647 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
648 match self.span_to_snippet(sp) {
650 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end();
651 if !snippet.is_empty() && !snippet.contains('\n') {
652 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
661 /// Given a `Span`, try to get a shorter span ending just after the first occurrence of `char`
663 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
664 if let Ok(snippet) = self.span_to_snippet(sp) {
665 if let Some(offset) = snippet.find(c) {
666 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
672 /// Given a `Span`, get a new `Span` covering the first token and all its trailing whitespace or
673 /// the original `Span`.
675 /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
676 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
677 let mut whitespace_found = false;
679 self.span_take_while(sp, |c| {
680 if !whitespace_found && c.is_whitespace() {
681 whitespace_found = true;
684 if whitespace_found && !c.is_whitespace() {
692 /// Given a `Span`, get a new `Span` covering the first token without its trailing whitespace or
693 /// the original `Span` in case of error.
695 /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
696 pub fn span_until_whitespace(&self, sp: Span) -> Span {
697 self.span_take_while(sp, |c| !c.is_whitespace())
700 /// Given a `Span`, get a shorter one until `predicate` yields false.
701 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
702 where P: for <'r> FnMut(&'r char) -> bool
704 if let Ok(snippet) = self.span_to_snippet(sp) {
705 let offset = snippet.chars()
706 .take_while(predicate)
707 .map(|c| c.len_utf8())
710 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
716 pub fn def_span(&self, sp: Span) -> Span {
717 self.span_until_char(sp, '{')
720 /// Returns a new span representing just the start-point of this span
721 pub fn start_point(&self, sp: Span) -> Span {
723 let width = self.find_width_of_character_at_span(sp, false);
724 let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
725 let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
726 sp.with_hi(end_point)
729 /// Returns a new span representing just the end-point of this span
730 pub fn end_point(&self, sp: Span) -> Span {
733 let width = self.find_width_of_character_at_span(sp, false);
734 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
736 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
737 sp.with_lo(end_point)
740 /// Returns a new span representing the next character after the end-point of this span
741 pub fn next_point(&self, sp: Span) -> Span {
742 let start_of_next_point = sp.hi().0;
744 let width = self.find_width_of_character_at_span(sp, true);
745 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
746 // in the case of a multibyte character, where the width != 1, the next span should
747 // span multiple bytes to include the whole character.
748 let end_of_next_point = start_of_next_point.checked_add(
749 width - 1).unwrap_or(start_of_next_point);
751 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
752 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
755 /// Finds the width of a character, either before or after the provided span.
756 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
757 // Disregard malformed spans and assume a one-byte wide character.
758 if sp.lo() >= sp.hi() {
759 debug!("find_width_of_character_at_span: early return malformed span");
763 let local_begin = self.lookup_byte_offset(sp.lo());
764 let local_end = self.lookup_byte_offset(sp.hi());
765 debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
766 local_begin, local_end);
768 if local_begin.sf.start_pos != local_end.sf.start_pos {
769 debug!("find_width_of_character_at_span: begin and end are in different files");
773 let start_index = local_begin.pos.to_usize();
774 let end_index = local_end.pos.to_usize();
775 debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
776 start_index, end_index);
778 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
780 if (!forwards && end_index == usize::min_value()) ||
781 (forwards && start_index == usize::max_value()) {
782 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
786 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
787 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
788 // Ensure indexes are also not malformed.
789 if start_index > end_index || end_index > source_len {
790 debug!("find_width_of_character_at_span: source indexes are malformed");
794 let src = local_begin.sf.external_src.borrow();
796 // We need to extend the snippet to the end of the src rather than to end_index so when
797 // searching forwards for boundaries we've got somewhere to search.
798 let snippet = if let Some(ref src) = local_begin.sf.src {
800 (&src[start_index..len])
801 } else if let Some(src) = src.get_source() {
803 (&src[start_index..len])
807 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
809 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
810 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
812 while !snippet.is_char_boundary(target - start_index) && target < source_len {
813 target = if forwards {
816 match target.checked_sub(1) {
817 Some(target) => target,
823 debug!("find_width_of_character_at_span: target=`{:?}`", target);
825 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
828 (target - end_index) as u32
830 (end_index - target) as u32
834 pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
835 for sf in self.files.borrow().source_files.iter() {
836 if *filename == sf.name {
837 return Some(sf.clone());
843 /// For a global BytePos compute the local offset within the containing SourceFile
844 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
845 let idx = self.lookup_source_file_idx(bpos);
846 let sf = (*self.files.borrow().source_files)[idx].clone();
847 let offset = bpos - sf.start_pos;
848 SourceFileAndBytePos {sf, pos: offset}
851 /// Converts an absolute BytePos to a CharPos relative to the source_file.
852 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
853 let idx = self.lookup_source_file_idx(bpos);
854 let map = &(*self.files.borrow().source_files)[idx];
856 // The number of extra bytes due to multibyte chars in the SourceFile
857 let mut total_extra_bytes = 0;
859 for mbc in map.multibyte_chars.iter() {
860 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
862 // every character is at least one byte, so we only
863 // count the actual extra bytes.
864 total_extra_bytes += mbc.bytes as u32 - 1;
865 // We should never see a byte position in the middle of a
867 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
873 assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
874 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
877 // Return the index of the source_file (in self.files) which contains pos.
878 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
879 let files = self.files.borrow();
880 let files = &files.source_files;
881 let count = files.len();
883 // Binary search for the source_file.
888 if files[m].start_pos > pos {
895 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
900 pub fn count_lines(&self) -> usize {
901 self.files().iter().fold(0, |a, f| a + f.count_lines())
905 pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
906 let prev_span = self.span_extend_to_prev_str(span, "fn", true);
907 self.span_to_snippet(prev_span).map(|snippet| {
908 let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
909 .expect("no label after fn");
910 prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
914 /// Take the span of a type parameter in a function signature and try to generate a span for the
915 /// function name (with generics) and a new snippet for this span with the pointed type
916 /// parameter as a new local type parameter.
919 /// ```rust,ignore (pseudo-Rust)
921 /// fn my_function(param: T)
922 /// // ^ Original span
925 /// fn my_function(param: T)
926 /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
929 /// Attention: The method used is very fragile since it essentially duplicates the work of the
930 /// parser. If you need to use this function or something similar, please consider updating the
931 /// source_map functions and this function to something more robust.
932 pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
933 // Try to extend the span to the previous "fn" keyword to retrieve the function
935 let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
936 if sugg_span != span {
937 if let Ok(snippet) = self.span_to_snippet(sugg_span) {
938 // Consume the function name
939 let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
940 .expect("no label after fn");
942 // Consume the generics part of the function signature
943 let mut bracket_counter = 0;
944 let mut last_char = None;
945 for c in snippet[offset..].chars() {
947 '<' => bracket_counter += 1,
948 '>' => bracket_counter -= 1,
949 '(' => if bracket_counter == 0 { break; }
952 offset += c.len_utf8();
956 // Adjust the suggestion span to encompass the function name with its generics
957 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
959 // Prepare the new suggested snippet to append the type parameter that triggered
960 // the error in the generics of the function signature
961 let mut new_snippet = if last_char == Some('>') {
962 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
964 format!("{}<", &snippet[..offset])
966 new_snippet.push_str(
967 &self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
968 new_snippet.push('>');
970 return Some((sugg_span, new_snippet));
978 impl SourceMapper for SourceMap {
979 fn lookup_char_pos(&self, pos: BytePos) -> Loc {
980 self.lookup_char_pos(pos)
982 fn span_to_lines(&self, sp: Span) -> FileLinesResult {
983 self.span_to_lines(sp)
985 fn span_to_string(&self, sp: Span) -> String {
986 self.span_to_string(sp)
988 fn span_to_filename(&self, sp: Span) -> FileName {
989 self.span_to_filename(sp)
991 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
992 self.merge_spans(sp_lhs, sp_rhs)
994 fn call_span_if_macro(&self, sp: Span) -> Span {
995 if self.span_to_filename(sp.clone()).is_macros() {
996 let v = sp.macro_backtrace();
997 if let Some(use_site) = v.last() {
998 return use_site.call_site;
1003 fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
1004 source_file.add_external_src(
1005 || match source_file.name {
1006 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
1011 fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize {
1012 self.doctest_offset_line(file, line)
1017 pub struct FilePathMapping {
1018 mapping: Vec<(PathBuf, PathBuf)>,
1021 impl FilePathMapping {
1022 pub fn empty() -> FilePathMapping {
1028 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1034 /// Applies any path prefix substitution as defined by the mapping.
1035 /// The return value is the remapped path and a boolean indicating whether
1036 /// the path was affected by the mapping.
1037 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1038 // NOTE: We are iterating over the mapping entries from last to first
1039 // because entries specified later on the command line should
1041 for &(ref from, ref to) in self.mapping.iter().rev() {
1042 if let Ok(rest) = path.strip_prefix(from) {
1043 return (to.join(rest), true);