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, ExpnInfo};
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;
27 /// Returns the span itself if it doesn't come from a macro expansion,
28 /// otherwise return the call site span up to the `enclosing_sp` by
29 /// following the `expn_info` chain.
30 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
31 let call_site1 = sp.ctxt().outer_expn_info().map(|ei| ei.call_site);
32 let call_site2 = enclosing_sp.ctxt().outer_expn_info().map(|ei| ei.call_site);
33 match (call_site1, call_site2) {
35 (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
36 (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
40 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
41 pub struct Spanned<T> {
46 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
47 Spanned {node: t, span: sp}
50 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
54 // _____________________________________________________________________________
55 // SourceFile, MultiByteChar, FileName, FileLines
58 /// An abstraction over the fs operations used by the Parser.
59 pub trait FileLoader {
60 /// Query the existence of a file.
61 fn file_exists(&self, path: &Path) -> bool;
63 /// Returns an absolute path to a file, if possible.
64 fn abs_path(&self, path: &Path) -> Option<PathBuf>;
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 abs_path(&self, path: &Path) -> Option<PathBuf> {
79 if path.is_absolute() {
80 Some(path.to_path_buf())
84 .map(|cwd| cwd.join(path))
88 fn read_file(&self, path: &Path) -> io::Result<String> {
89 fs::read_to_string(path)
93 // This is a SourceFile identifier that is used to correlate SourceFiles between
94 // subsequent compilation sessions (which is something we need to do during
95 // incremental compilation).
96 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
97 pub struct StableSourceFileId(u128);
99 impl StableSourceFileId {
100 pub fn new(source_file: &SourceFile) -> StableSourceFileId {
101 StableSourceFileId::new_from_pieces(&source_file.name,
102 source_file.name_was_remapped,
103 source_file.unmapped_path.as_ref())
106 pub fn new_from_pieces(name: &FileName,
107 name_was_remapped: bool,
108 unmapped_path: Option<&FileName>) -> StableSourceFileId {
109 let mut hasher = StableHasher::new();
111 name.hash(&mut hasher);
112 name_was_remapped.hash(&mut hasher);
113 unmapped_path.hash(&mut hasher);
115 StableSourceFileId(hasher.finish())
119 // _____________________________________________________________________________
124 pub(super) struct SourceMapFiles {
125 pub(super) source_files: Vec<Lrc<SourceFile>>,
126 stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>
129 pub struct SourceMap {
130 pub(super) files: Lock<SourceMapFiles>,
131 file_loader: Box<dyn FileLoader + Sync + Send>,
132 // This is used to apply the file path remapping as specified via
133 // --remap-path-prefix to all SourceFiles allocated within this SourceMap.
134 path_mapping: FilePathMapping,
138 pub fn new(path_mapping: FilePathMapping) -> SourceMap {
140 files: Default::default(),
141 file_loader: Box::new(RealFileLoader),
146 pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
147 path_mapping: FilePathMapping)
150 files: Default::default(),
156 pub fn path_mapping(&self) -> &FilePathMapping {
160 pub fn file_exists(&self, path: &Path) -> bool {
161 self.file_loader.file_exists(path)
164 pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
165 let src = self.file_loader.read_file(path)?;
166 let filename = path.to_owned().into();
167 Ok(self.new_source_file(filename, src))
170 pub fn files(&self) -> MappedLockGuard<'_, Vec<Lrc<SourceFile>>> {
171 LockGuard::map(self.files.borrow(), |files| &mut files.source_files)
174 pub fn source_file_by_stable_id(&self, stable_id: StableSourceFileId) ->
175 Option<Lrc<SourceFile>> {
176 self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|sf| sf.clone())
179 fn next_start_pos(&self) -> usize {
180 match self.files.borrow().source_files.last() {
182 // Add one so there is some space between files. This lets us distinguish
183 // positions in the source_map, even in the presence of zero-length files.
184 Some(last) => last.end_pos.to_usize() + 1,
188 /// Creates a new source_file.
189 /// If a file already exists in the source_map with the same id, that file is returned
191 pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
192 self.try_new_source_file(filename, src)
193 .unwrap_or_else(|OffsetOverflowError| {
194 eprintln!("fatal error: rustc does not support files larger than 4GB");
195 errors::FatalError.raise()
199 fn try_new_source_file(
203 ) -> Result<Lrc<SourceFile>, OffsetOverflowError> {
204 let start_pos = self.next_start_pos();
206 // The path is used to determine the directory for loading submodules and
207 // include files, so it must be before remapping.
208 // Note that filename may not be a valid path, eg it may be `<anon>` etc,
209 // but this is okay because the directory determined by `path.pop()` will
210 // be empty, so the working directory will be used.
211 let unmapped_path = filename.clone();
213 let (filename, was_remapped) = match filename {
214 FileName::Real(filename) => {
215 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
216 (FileName::Real(filename), was_remapped)
218 other => (other, false),
221 let file_id = StableSourceFileId::new_from_pieces(&filename,
223 Some(&unmapped_path));
225 let lrc_sf = match self.source_file_by_stable_id(file_id) {
226 Some(lrc_sf) => lrc_sf,
228 let source_file = Lrc::new(SourceFile::new(
233 Pos::from_usize(start_pos),
236 let mut files = self.files.borrow_mut();
238 files.source_files.push(source_file.clone());
239 files.stable_id_to_source_file.insert(file_id, source_file.clone());
247 /// Allocates a new SourceFile representing a source file from an external
248 /// crate. The source code of such an "imported source_file" is not available,
249 /// but we still know enough to generate accurate debuginfo location
250 /// information for things inlined from other crates.
251 pub fn new_imported_source_file(
254 name_was_remapped: bool,
255 crate_of_origin: u32,
259 mut file_local_lines: Vec<BytePos>,
260 mut file_local_multibyte_chars: Vec<MultiByteChar>,
261 mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
262 ) -> Lrc<SourceFile> {
263 let start_pos = self.next_start_pos();
265 let end_pos = Pos::from_usize(start_pos + source_len);
266 let start_pos = Pos::from_usize(start_pos);
268 for pos in &mut file_local_lines {
269 *pos = *pos + start_pos;
272 for mbc in &mut file_local_multibyte_chars {
273 mbc.pos = mbc.pos + start_pos;
276 for swc in &mut file_local_non_narrow_chars {
277 *swc = *swc + start_pos;
280 let source_file = Lrc::new(SourceFile {
287 external_src: Lock::new(ExternalSource::AbsentOk),
290 lines: file_local_lines,
291 multibyte_chars: file_local_multibyte_chars,
292 non_narrow_chars: file_local_non_narrow_chars,
296 let mut files = self.files.borrow_mut();
298 files.source_files.push(source_file.clone());
299 files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file),
300 source_file.clone());
305 pub fn mk_substr_filename(&self, sp: Span) -> String {
306 let pos = self.lookup_char_pos(sp.lo());
307 format!("<{}:{}:{}>",
310 pos.col.to_usize() + 1)
313 // If there is a doctest_offset, apply it to the line
314 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
316 FileName::DocTest(_, offset) => {
317 return if *offset >= 0 {
318 orig + *offset as usize
320 orig - (-(*offset)) as usize
327 /// Lookup source information about a BytePos
328 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
329 let chpos = self.bytepos_to_file_charpos(pos);
330 match self.lookup_line(pos) {
331 Ok(SourceFileAndLine { sf: f, line: a }) => {
332 let line = a + 1; // Line numbers start at 1
333 let linebpos = f.lines[a];
334 let linechpos = self.bytepos_to_file_charpos(linebpos);
335 let col = chpos - linechpos;
338 let start_width_idx = f
340 .binary_search_by_key(&linebpos, |x| x.pos())
341 .unwrap_or_else(|x| x);
342 let end_width_idx = f
344 .binary_search_by_key(&pos, |x| x.pos())
345 .unwrap_or_else(|x| x);
346 let special_chars = end_width_idx - start_width_idx;
347 let non_narrow: usize = f
348 .non_narrow_chars[start_width_idx..end_width_idx]
352 col.0 - special_chars + non_narrow
354 debug!("byte pos {:?} is on the line at byte pos {:?}",
356 debug!("char pos {:?} is on the line at char pos {:?}",
358 debug!("byte is on line: {}", line);
359 assert!(chpos >= linechpos);
369 let end_width_idx = f
371 .binary_search_by_key(&pos, |x| x.pos())
372 .unwrap_or_else(|x| x);
373 let non_narrow: usize = f
374 .non_narrow_chars[0..end_width_idx]
378 chpos.0 - end_width_idx + non_narrow
390 // If the relevant source_file is empty, we don't return a line number.
391 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
392 let idx = self.lookup_source_file_idx(pos);
394 let f = (*self.files.borrow().source_files)[idx].clone();
396 match f.lookup_line(pos) {
397 Some(line) => Ok(SourceFileAndLine { sf: f, line }),
402 /// Returns `Some(span)`, a union of the lhs and rhs span. The lhs must precede the rhs. If
403 /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
404 /// For this to work, the spans have to be:
406 /// * the ctxt of both spans much match
407 /// * the lhs span needs to end on the same line the rhs span begins
408 /// * the lhs span must start at or before the rhs span
409 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
410 // make sure we're at the same expansion id
411 if sp_lhs.ctxt() != sp_rhs.ctxt() {
415 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
417 Err(_) => return None
419 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
421 Err(_) => return None
424 // if we must cross lines to merge, don't merge
425 if lhs_end.line != rhs_begin.line {
429 // ensure these follow the expected order and we don't overlap
430 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
431 Some(sp_lhs.to(sp_rhs))
437 pub fn span_to_string(&self, sp: Span) -> String {
438 if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
439 return "no-location".to_string();
442 let lo = self.lookup_char_pos(sp.lo());
443 let hi = self.lookup_char_pos(sp.hi());
444 format!("{}:{}:{}: {}:{}",
447 lo.col.to_usize() + 1,
449 hi.col.to_usize() + 1)
452 pub fn span_to_filename(&self, sp: Span) -> FileName {
453 self.lookup_char_pos(sp.lo()).file.name.clone()
456 pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
457 self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
458 .expect("SourceMap::span_to_unmapped_path called for imported SourceFile?")
461 pub fn is_multiline(&self, sp: Span) -> bool {
462 let lo = self.lookup_char_pos(sp.lo());
463 let hi = self.lookup_char_pos(sp.hi());
467 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
468 debug!("span_to_lines(sp={:?})", sp);
470 if sp.lo() > sp.hi() {
471 return Err(SpanLinesError::IllFormedSpan(sp));
474 let lo = self.lookup_char_pos(sp.lo());
475 debug!("span_to_lines: lo={:?}", lo);
476 let hi = self.lookup_char_pos(sp.hi());
477 debug!("span_to_lines: hi={:?}", hi);
479 if lo.file.start_pos != hi.file.start_pos {
480 return Err(SpanLinesError::DistinctSources(DistinctSources {
481 begin: (lo.file.name.clone(), lo.file.start_pos),
482 end: (hi.file.name.clone(), hi.file.start_pos),
485 assert!(hi.line >= lo.line);
487 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
489 // The span starts partway through the first line,
490 // but after that it starts from offset 0.
491 let mut start_col = lo.col;
493 // For every line but the last, it extends from `start_col`
494 // and to the end of the line. Be careful because the line
495 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
497 for line_index in lo.line-1 .. hi.line-1 {
498 let line_len = lo.file.get_line(line_index)
499 .map(|s| s.chars().count())
501 lines.push(LineInfo { line_index,
503 end_col: CharPos::from_usize(line_len) });
504 start_col = CharPos::from_usize(0);
507 // For the last line, it extends from `start_col` to `hi.col`:
508 lines.push(LineInfo { line_index: hi.line - 1,
512 Ok(FileLines {file: lo.file, lines})
515 /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
516 /// extract function takes three arguments: a string slice containing the source, an index in
517 /// the slice for the beginning of the span and an index in the slice for the end of the span.
518 fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
519 where F: Fn(&str, usize, usize) -> String
521 if sp.lo() > sp.hi() {
522 return Err(SpanSnippetError::IllFormedSpan(sp));
525 let local_begin = self.lookup_byte_offset(sp.lo());
526 let local_end = self.lookup_byte_offset(sp.hi());
528 if local_begin.sf.start_pos != local_end.sf.start_pos {
529 return Err(SpanSnippetError::DistinctSources(DistinctSources {
530 begin: (local_begin.sf.name.clone(),
531 local_begin.sf.start_pos),
532 end: (local_end.sf.name.clone(),
533 local_end.sf.start_pos)
536 self.ensure_source_file_source_present(local_begin.sf.clone());
538 let start_index = local_begin.pos.to_usize();
539 let end_index = local_end.pos.to_usize();
540 let source_len = (local_begin.sf.end_pos -
541 local_begin.sf.start_pos).to_usize();
543 if start_index > end_index || end_index > source_len {
544 return Err(SpanSnippetError::MalformedForSourcemap(
545 MalformedSourceMapPositions {
546 name: local_begin.sf.name.clone(),
548 begin_pos: local_begin.pos,
549 end_pos: local_end.pos,
553 if let Some(ref src) = local_begin.sf.src {
554 return Ok(extract_source(src, start_index, end_index));
555 } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
556 return Ok(extract_source(src, start_index, end_index));
558 return Err(SpanSnippetError::SourceNotAvailable {
559 filename: local_begin.sf.name.clone()
565 /// Returns the source snippet as `String` corresponding to the given `Span`
566 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
567 self.span_to_source(sp, |src, start_index, end_index| src[start_index..end_index]
571 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
572 match self.span_to_prev_source(sp) {
574 Ok(source) => source.split('\n').last().map(|last_line| {
575 last_line.len() - last_line.trim_start().len()
580 /// Returns the source snippet as `String` before the given `Span`
581 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
582 self.span_to_source(sp, |src, start_index, _| src[..start_index].to_string())
585 /// Extend the given `Span` to just after the previous occurrence of `c`. Return the same span
586 /// if no character could be found or if an error occurred while retrieving the code snippet.
587 pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span {
588 if let Ok(prev_source) = self.span_to_prev_source(sp) {
589 let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_start();
590 if !prev_source.is_empty() && !prev_source.contains('\n') {
591 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
598 /// Extend the given `Span` to just after the previous occurrence of `pat` when surrounded by
599 /// whitespace. Return the same span if no character could be found or if an error occurred
600 /// while retrieving the code snippet.
601 pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
602 // assure that the pattern is delimited, to avoid the following
604 // ^^^^ returned span without the check
605 // ---------- correct span
606 for ws in &[" ", "\t", "\n"] {
607 let pat = pat.to_owned() + ws;
608 if let Ok(prev_source) = self.span_to_prev_source(sp) {
609 let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_start();
610 if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) {
611 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
619 /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
620 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
621 match self.span_to_snippet(sp) {
623 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end();
624 if !snippet.is_empty() && !snippet.contains('\n') {
625 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
634 /// Given a `Span`, try to get a shorter span ending just after the first occurrence of `char`
636 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
637 if let Ok(snippet) = self.span_to_snippet(sp) {
638 if let Some(offset) = snippet.find(c) {
639 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
645 /// Given a `Span`, get a new `Span` covering the first token and all its trailing whitespace or
646 /// the original `Span`.
648 /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
649 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
650 let mut whitespace_found = false;
652 self.span_take_while(sp, |c| {
653 if !whitespace_found && c.is_whitespace() {
654 whitespace_found = true;
657 if whitespace_found && !c.is_whitespace() {
665 /// Given a `Span`, get a new `Span` covering the first token without its trailing whitespace or
666 /// the original `Span` in case of error.
668 /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
669 pub fn span_until_whitespace(&self, sp: Span) -> Span {
670 self.span_take_while(sp, |c| !c.is_whitespace())
673 /// Given a `Span`, get a shorter one until `predicate` yields false.
674 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
675 where P: for <'r> FnMut(&'r char) -> bool
677 if let Ok(snippet) = self.span_to_snippet(sp) {
678 let offset = snippet.chars()
679 .take_while(predicate)
680 .map(|c| c.len_utf8())
683 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
689 pub fn def_span(&self, sp: Span) -> Span {
690 self.span_until_char(sp, '{')
693 /// Returns a new span representing just the start-point of this span
694 pub fn start_point(&self, sp: Span) -> Span {
696 let width = self.find_width_of_character_at_span(sp, false);
697 let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
698 let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
699 sp.with_hi(end_point)
702 /// Returns a new span representing just the end-point of this span
703 pub fn end_point(&self, sp: Span) -> Span {
706 let width = self.find_width_of_character_at_span(sp, false);
707 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
709 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
710 sp.with_lo(end_point)
713 /// Returns a new span representing the next character after the end-point of this span
714 pub fn next_point(&self, sp: Span) -> Span {
715 let start_of_next_point = sp.hi().0;
717 let width = self.find_width_of_character_at_span(sp, true);
718 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
719 // in the case of a multibyte character, where the width != 1, the next span should
720 // span multiple bytes to include the whole character.
721 let end_of_next_point = start_of_next_point.checked_add(
722 width - 1).unwrap_or(start_of_next_point);
724 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
725 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
728 /// Finds the width of a character, either before or after the provided span.
729 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
730 // Disregard malformed spans and assume a one-byte wide character.
731 if sp.lo() >= sp.hi() {
732 debug!("find_width_of_character_at_span: early return malformed span");
736 let local_begin = self.lookup_byte_offset(sp.lo());
737 let local_end = self.lookup_byte_offset(sp.hi());
738 debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
739 local_begin, local_end);
741 if local_begin.sf.start_pos != local_end.sf.start_pos {
742 debug!("find_width_of_character_at_span: begin and end are in different files");
746 let start_index = local_begin.pos.to_usize();
747 let end_index = local_end.pos.to_usize();
748 debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
749 start_index, end_index);
751 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
753 if (!forwards && end_index == usize::min_value()) ||
754 (forwards && start_index == usize::max_value()) {
755 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
759 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
760 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
761 // Ensure indexes are also not malformed.
762 if start_index > end_index || end_index > source_len {
763 debug!("find_width_of_character_at_span: source indexes are malformed");
767 let src = local_begin.sf.external_src.borrow();
769 // We need to extend the snippet to the end of the src rather than to end_index so when
770 // searching forwards for boundaries we've got somewhere to search.
771 let snippet = if let Some(ref src) = local_begin.sf.src {
773 (&src[start_index..len])
774 } else if let Some(src) = src.get_source() {
776 (&src[start_index..len])
780 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
782 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
783 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
785 while !snippet.is_char_boundary(target - start_index) && target < source_len {
786 target = if forwards {
789 match target.checked_sub(1) {
790 Some(target) => target,
796 debug!("find_width_of_character_at_span: target=`{:?}`", target);
798 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
801 (target - end_index) as u32
803 (end_index - target) as u32
807 pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
808 for sf in self.files.borrow().source_files.iter() {
809 if *filename == sf.name {
810 return Some(sf.clone());
816 /// For a global BytePos compute the local offset within the containing SourceFile
817 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
818 let idx = self.lookup_source_file_idx(bpos);
819 let sf = (*self.files.borrow().source_files)[idx].clone();
820 let offset = bpos - sf.start_pos;
821 SourceFileAndBytePos {sf, pos: offset}
824 /// Converts an absolute BytePos to a CharPos relative to the source_file.
825 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
826 let idx = self.lookup_source_file_idx(bpos);
827 let map = &(*self.files.borrow().source_files)[idx];
829 // The number of extra bytes due to multibyte chars in the SourceFile
830 let mut total_extra_bytes = 0;
832 for mbc in map.multibyte_chars.iter() {
833 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
835 // every character is at least one byte, so we only
836 // count the actual extra bytes.
837 total_extra_bytes += mbc.bytes as u32 - 1;
838 // We should never see a byte position in the middle of a
840 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
846 assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
847 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
850 // Return the index of the source_file (in self.files) which contains pos.
851 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
852 let files = self.files.borrow();
853 let files = &files.source_files;
854 let count = files.len();
856 // Binary search for the source_file.
861 if files[m].start_pos > pos {
868 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
873 pub fn count_lines(&self) -> usize {
874 self.files().iter().fold(0, |a, f| a + f.count_lines())
878 pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
879 let prev_span = self.span_extend_to_prev_str(span, "fn", true);
880 self.span_to_snippet(prev_span).map(|snippet| {
881 let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
882 .expect("no label after fn");
883 prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
887 /// Take the span of a type parameter in a function signature and try to generate a span for the
888 /// function name (with generics) and a new snippet for this span with the pointed type
889 /// parameter as a new local type parameter.
892 /// ```rust,ignore (pseudo-Rust)
894 /// fn my_function(param: T)
895 /// // ^ Original span
898 /// fn my_function(param: T)
899 /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
902 /// Attention: The method used is very fragile since it essentially duplicates the work of the
903 /// parser. If you need to use this function or something similar, please consider updating the
904 /// source_map functions and this function to something more robust.
905 pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
906 // Try to extend the span to the previous "fn" keyword to retrieve the function
908 let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
909 if sugg_span != span {
910 if let Ok(snippet) = self.span_to_snippet(sugg_span) {
911 // Consume the function name
912 let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
913 .expect("no label after fn");
915 // Consume the generics part of the function signature
916 let mut bracket_counter = 0;
917 let mut last_char = None;
918 for c in snippet[offset..].chars() {
920 '<' => bracket_counter += 1,
921 '>' => bracket_counter -= 1,
922 '(' => if bracket_counter == 0 { break; }
925 offset += c.len_utf8();
929 // Adjust the suggestion span to encompass the function name with its generics
930 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
932 // Prepare the new suggested snippet to append the type parameter that triggered
933 // the error in the generics of the function signature
934 let mut new_snippet = if last_char == Some('>') {
935 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
937 format!("{}<", &snippet[..offset])
939 new_snippet.push_str(
940 &self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
941 new_snippet.push('>');
943 return Some((sugg_span, new_snippet));
951 impl SourceMapper for SourceMap {
952 fn lookup_char_pos(&self, pos: BytePos) -> Loc {
953 self.lookup_char_pos(pos)
955 fn span_to_lines(&self, sp: Span) -> FileLinesResult {
956 self.span_to_lines(sp)
958 fn span_to_string(&self, sp: Span) -> String {
959 self.span_to_string(sp)
961 fn span_to_filename(&self, sp: Span) -> FileName {
962 self.span_to_filename(sp)
964 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
965 self.merge_spans(sp_lhs, sp_rhs)
967 fn call_span_if_macro(&self, sp: Span) -> Span {
968 if self.span_to_filename(sp.clone()).is_macros() {
969 let v = sp.macro_backtrace();
970 if let Some(use_site) = v.last() {
971 return use_site.call_site;
976 fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
977 source_file.add_external_src(
978 || match source_file.name {
979 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
984 fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize {
985 self.doctest_offset_line(file, line)
990 pub struct FilePathMapping {
991 mapping: Vec<(PathBuf, PathBuf)>,
994 impl FilePathMapping {
995 pub fn empty() -> FilePathMapping {
1001 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1007 /// Applies any path prefix substitution as defined by the mapping.
1008 /// The return value is the remapped path and a boolean indicating whether
1009 /// the path was affected by the mapping.
1010 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1011 // NOTE: We are iterating over the mapping entries from last to first
1012 // because entries specified later on the command line should
1014 for &(ref from, ref to) in self.mapping.iter().rev() {
1015 if let Ok(rest) = path.strip_prefix(from) {
1016 return (to.join(rest), true);
1024 // _____________________________________________________________________________
1031 use rustc_data_structures::sync::Lrc;
1033 fn init_source_map() -> SourceMap {
1034 let sm = SourceMap::new(FilePathMapping::empty());
1035 sm.new_source_file(PathBuf::from("blork.rs").into(),
1036 "first line.\nsecond line".to_string());
1037 sm.new_source_file(PathBuf::from("empty.rs").into(),
1039 sm.new_source_file(PathBuf::from("blork2.rs").into(),
1040 "first line.\nsecond line".to_string());
1046 // Test lookup_byte_offset
1047 let sm = init_source_map();
1049 let srcfbp1 = sm.lookup_byte_offset(BytePos(23));
1050 assert_eq!(srcfbp1.sf.name, PathBuf::from("blork.rs").into());
1051 assert_eq!(srcfbp1.pos, BytePos(23));
1053 let srcfbp1 = sm.lookup_byte_offset(BytePos(24));
1054 assert_eq!(srcfbp1.sf.name, PathBuf::from("empty.rs").into());
1055 assert_eq!(srcfbp1.pos, BytePos(0));
1057 let srcfbp2 = sm.lookup_byte_offset(BytePos(25));
1058 assert_eq!(srcfbp2.sf.name, PathBuf::from("blork2.rs").into());
1059 assert_eq!(srcfbp2.pos, BytePos(0));
1064 // Test bytepos_to_file_charpos
1065 let sm = init_source_map();
1067 let cp1 = sm.bytepos_to_file_charpos(BytePos(22));
1068 assert_eq!(cp1, CharPos(22));
1070 let cp2 = sm.bytepos_to_file_charpos(BytePos(25));
1071 assert_eq!(cp2, CharPos(0));
1076 // Test zero-length source_files.
1077 let sm = init_source_map();
1079 let loc1 = sm.lookup_char_pos(BytePos(22));
1080 assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
1081 assert_eq!(loc1.line, 2);
1082 assert_eq!(loc1.col, CharPos(10));
1084 let loc2 = sm.lookup_char_pos(BytePos(25));
1085 assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
1086 assert_eq!(loc2.line, 1);
1087 assert_eq!(loc2.col, CharPos(0));
1090 fn init_source_map_mbc() -> SourceMap {
1091 let sm = SourceMap::new(FilePathMapping::empty());
1092 // € is a three byte utf8 char.
1093 sm.new_source_file(PathBuf::from("blork.rs").into(),
1094 "fir€st €€€€ line.\nsecond line".to_string());
1095 sm.new_source_file(PathBuf::from("blork2.rs").into(),
1096 "first line€€.\n€ second line".to_string());
1102 // Test bytepos_to_file_charpos in the presence of multi-byte chars
1103 let sm = init_source_map_mbc();
1105 let cp1 = sm.bytepos_to_file_charpos(BytePos(3));
1106 assert_eq!(cp1, CharPos(3));
1108 let cp2 = sm.bytepos_to_file_charpos(BytePos(6));
1109 assert_eq!(cp2, CharPos(4));
1111 let cp3 = sm.bytepos_to_file_charpos(BytePos(56));
1112 assert_eq!(cp3, CharPos(12));
1114 let cp4 = sm.bytepos_to_file_charpos(BytePos(61));
1115 assert_eq!(cp4, CharPos(15));
1120 // Test span_to_lines for a span ending at the end of source_file
1121 let sm = init_source_map();
1122 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1123 let file_lines = sm.span_to_lines(span).unwrap();
1125 assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
1126 assert_eq!(file_lines.lines.len(), 1);
1127 assert_eq!(file_lines.lines[0].line_index, 1);
1130 /// Given a string like " ~~~~~~~~~~~~ ", produces a span
1131 /// converting that range. The idea is that the string has the same
1132 /// length as the input, and we uncover the byte positions. Note
1133 /// that this can span lines and so on.
1134 fn span_from_selection(input: &str, selection: &str) -> Span {
1135 assert_eq!(input.len(), selection.len());
1136 let left_index = selection.find('~').unwrap() as u32;
1137 let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
1138 Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
1141 /// Tests span_to_snippet and span_to_lines for a span converting 3
1142 /// lines in the middle of a file.
1144 fn span_to_snippet_and_lines_spanning_multiple_lines() {
1145 let sm = SourceMap::new(FilePathMapping::empty());
1146 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1147 let selection = " \n ~~\n~~~\n~~~~~ \n \n";
1148 sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_string());
1149 let span = span_from_selection(inputtext, selection);
1151 // check that we are extracting the text we thought we were extracting
1152 assert_eq!(&sm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1154 // check that span_to_lines gives us the complete result with the lines/cols we expected
1155 let lines = sm.span_to_lines(span).unwrap();
1156 let expected = vec![
1157 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1158 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1159 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1161 assert_eq!(lines.lines, expected);
1166 // Test span_to_snippet for a span ending at the end of source_file
1167 let sm = init_source_map();
1168 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1169 let snippet = sm.span_to_snippet(span);
1171 assert_eq!(snippet, Ok("second line".to_string()));
1176 // Test span_to_str for a span ending at the end of source_file
1177 let sm = init_source_map();
1178 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1179 let sstr = sm.span_to_string(span);
1181 assert_eq!(sstr, "blork.rs:2:1: 2:12");
1184 /// Tests failing to merge two spans on different lines
1186 fn span_merging_fail() {
1187 let sm = SourceMap::new(FilePathMapping::empty());
1188 let inputtext = "bbbb BB\ncc CCC\n";
1189 let selection1 = " ~~\n \n";
1190 let selection2 = " \n ~~~\n";
1191 sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_owned());
1192 let span1 = span_from_selection(inputtext, selection1);
1193 let span2 = span_from_selection(inputtext, selection2);
1195 assert!(sm.merge_spans(span1, span2).is_none());
1198 /// Returns the span corresponding to the `n`th occurrence of
1199 /// `substring` in `source_text`.
1200 trait SourceMapExtension {
1201 fn span_substr(&self,
1202 file: &Lrc<SourceFile>,
1209 impl SourceMapExtension for SourceMap {
1210 fn span_substr(&self,
1211 file: &Lrc<SourceFile>,
1217 println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
1218 file.name, file.start_pos, substring, n);
1222 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
1223 panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
1224 source_text, n, substring, i);
1226 let lo = hi + offset;
1227 hi = lo + substring.len();
1229 let span = Span::new(
1230 BytePos(lo as u32 + file.start_pos.0),
1231 BytePos(hi as u32 + file.start_pos.0),
1234 assert_eq!(&self.span_to_snippet(span).unwrap()[..],