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.
11 pub use syntax_pos::*;
12 pub use syntax_pos::hygiene::{ExpnFormat, ExpnInfo};
13 pub use self::ExpnFormat::*;
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_data_structures::stable_hasher::StableHasher;
17 use rustc_data_structures::sync::{Lrc, Lock, LockGuard, MappedLockGuard};
20 use std::path::{Path, PathBuf};
25 use errors::SourceMapper;
27 /// Return 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 /// Return 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(),
151 file_loader: file_loader,
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 let start_pos = self.next_start_pos();
194 // The path is used to determine the directory for loading submodules and
195 // include files, so it must be before remapping.
196 // Note that filename may not be a valid path, eg it may be `<anon>` etc,
197 // but this is okay because the directory determined by `path.pop()` will
198 // be empty, so the working directory will be used.
199 let unmapped_path = filename.clone();
201 let (filename, was_remapped) = match filename {
202 FileName::Real(filename) => {
203 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
204 (FileName::Real(filename), was_remapped)
206 other => (other, false),
209 let file_id = StableSourceFileId::new_from_pieces(&filename,
211 Some(&unmapped_path));
213 return match self.source_file_by_stable_id(file_id) {
214 Some(lrc_sf) => lrc_sf,
216 let source_file = Lrc::new(SourceFile::new(
221 Pos::from_usize(start_pos),
224 let mut files = self.files.borrow_mut();
226 files.source_files.push(source_file.clone());
227 files.stable_id_to_source_file.insert(file_id, source_file.clone());
234 /// Allocates a new SourceFile representing a source file from an external
235 /// crate. The source code of such an "imported source_file" is not available,
236 /// but we still know enough to generate accurate debuginfo location
237 /// information for things inlined from other crates.
238 pub fn new_imported_source_file(
241 name_was_remapped: bool,
242 crate_of_origin: u32,
246 mut file_local_lines: Vec<BytePos>,
247 mut file_local_multibyte_chars: Vec<MultiByteChar>,
248 mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
249 ) -> Lrc<SourceFile> {
250 let start_pos = self.next_start_pos();
252 let end_pos = Pos::from_usize(start_pos + source_len);
253 let start_pos = Pos::from_usize(start_pos);
255 for pos in &mut file_local_lines {
256 *pos = *pos + start_pos;
259 for mbc in &mut file_local_multibyte_chars {
260 mbc.pos = mbc.pos + start_pos;
263 for swc in &mut file_local_non_narrow_chars {
264 *swc = *swc + start_pos;
267 let source_file = Lrc::new(SourceFile {
274 external_src: Lock::new(ExternalSource::AbsentOk),
277 lines: file_local_lines,
278 multibyte_chars: file_local_multibyte_chars,
279 non_narrow_chars: file_local_non_narrow_chars,
283 let mut files = self.files.borrow_mut();
285 files.source_files.push(source_file.clone());
286 files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file),
287 source_file.clone());
292 pub fn mk_substr_filename(&self, sp: Span) -> String {
293 let pos = self.lookup_char_pos(sp.lo());
294 format!("<{}:{}:{}>",
297 pos.col.to_usize() + 1)
300 // If there is a doctest_offset, apply it to the line
301 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
303 FileName::DocTest(_, offset) => {
304 return if *offset >= 0 {
305 orig + *offset as usize
307 orig - (-(*offset)) as usize
314 /// Lookup source information about a BytePos
315 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
316 let chpos = self.bytepos_to_file_charpos(pos);
317 match self.lookup_line(pos) {
318 Ok(SourceFileAndLine { sf: f, line: a }) => {
319 let line = a + 1; // Line numbers start at 1
320 let linebpos = f.lines[a];
321 let linechpos = self.bytepos_to_file_charpos(linebpos);
322 let col = chpos - linechpos;
325 let start_width_idx = f
327 .binary_search_by_key(&linebpos, |x| x.pos())
328 .unwrap_or_else(|x| x);
329 let end_width_idx = f
331 .binary_search_by_key(&pos, |x| x.pos())
332 .unwrap_or_else(|x| x);
333 let special_chars = end_width_idx - start_width_idx;
334 let non_narrow: usize = f
335 .non_narrow_chars[start_width_idx..end_width_idx]
339 col.0 - special_chars + non_narrow
341 debug!("byte pos {:?} is on the line at byte pos {:?}",
343 debug!("char pos {:?} is on the line at char pos {:?}",
345 debug!("byte is on line: {}", line);
346 assert!(chpos >= linechpos);
356 let end_width_idx = f
358 .binary_search_by_key(&pos, |x| x.pos())
359 .unwrap_or_else(|x| x);
360 let non_narrow: usize = f
361 .non_narrow_chars[0..end_width_idx]
365 chpos.0 - end_width_idx + non_narrow
377 // If the relevant source_file is empty, we don't return a line number.
378 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
379 let idx = self.lookup_source_file_idx(pos);
381 let f = (*self.files.borrow().source_files)[idx].clone();
383 match f.lookup_line(pos) {
384 Some(line) => Ok(SourceFileAndLine { sf: f, line: line }),
389 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
390 let loc = self.lookup_char_pos(pos);
392 filename: loc.file.name.clone(),
399 /// Returns `Some(span)`, a union of the lhs and rhs span. The lhs must precede the rhs. If
400 /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
401 /// For this to work, the spans have to be:
403 /// * the ctxt of both spans much match
404 /// * the lhs span needs to end on the same line the rhs span begins
405 /// * the lhs span must start at or before the rhs span
406 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
407 // make sure we're at the same expansion id
408 if sp_lhs.ctxt() != sp_rhs.ctxt() {
412 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
414 Err(_) => return None
416 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
418 Err(_) => return None
421 // if we must cross lines to merge, don't merge
422 if lhs_end.line != rhs_begin.line {
426 // ensure these follow the expected order and we don't overlap
427 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
428 Some(sp_lhs.to(sp_rhs))
434 pub fn span_to_string(&self, sp: Span) -> String {
435 if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
436 return "no-location".to_string();
439 let lo = self.lookup_char_pos_adj(sp.lo());
440 let hi = self.lookup_char_pos_adj(sp.hi());
441 format!("{}:{}:{}: {}:{}",
444 lo.col.to_usize() + 1,
446 hi.col.to_usize() + 1)
449 pub fn span_to_filename(&self, sp: Span) -> FileName {
450 self.lookup_char_pos(sp.lo()).file.name.clone()
453 pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
454 self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
455 .expect("SourceMap::span_to_unmapped_path called for imported SourceFile?")
458 pub fn is_multiline(&self, sp: Span) -> bool {
459 let lo = self.lookup_char_pos(sp.lo());
460 let hi = self.lookup_char_pos(sp.hi());
464 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
465 debug!("span_to_lines(sp={:?})", sp);
467 if sp.lo() > sp.hi() {
468 return Err(SpanLinesError::IllFormedSpan(sp));
471 let lo = self.lookup_char_pos(sp.lo());
472 debug!("span_to_lines: lo={:?}", lo);
473 let hi = self.lookup_char_pos(sp.hi());
474 debug!("span_to_lines: hi={:?}", hi);
476 if lo.file.start_pos != hi.file.start_pos {
477 return Err(SpanLinesError::DistinctSources(DistinctSources {
478 begin: (lo.file.name.clone(), lo.file.start_pos),
479 end: (hi.file.name.clone(), hi.file.start_pos),
482 assert!(hi.line >= lo.line);
484 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
486 // The span starts partway through the first line,
487 // but after that it starts from offset 0.
488 let mut start_col = lo.col;
490 // For every line but the last, it extends from `start_col`
491 // and to the end of the line. Be careful because the line
492 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
494 for line_index in lo.line-1 .. hi.line-1 {
495 let line_len = lo.file.get_line(line_index)
496 .map(|s| s.chars().count())
498 lines.push(LineInfo { line_index,
500 end_col: CharPos::from_usize(line_len) });
501 start_col = CharPos::from_usize(0);
504 // For the last line, it extends from `start_col` to `hi.col`:
505 lines.push(LineInfo { line_index: hi.line - 1,
509 Ok(FileLines {file: lo.file, lines: lines})
512 /// Extract the source surrounding the given `Span` using the `extract_source` function. The
513 /// extract function takes three arguments: a string slice containing the source, an index in
514 /// the slice for the beginning of the span and an index in the slice for the end of the span.
515 fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
516 where F: Fn(&str, usize, usize) -> String
518 if sp.lo() > sp.hi() {
519 return Err(SpanSnippetError::IllFormedSpan(sp));
522 let local_begin = self.lookup_byte_offset(sp.lo());
523 let local_end = self.lookup_byte_offset(sp.hi());
525 if local_begin.sf.start_pos != local_end.sf.start_pos {
526 return Err(SpanSnippetError::DistinctSources(DistinctSources {
527 begin: (local_begin.sf.name.clone(),
528 local_begin.sf.start_pos),
529 end: (local_end.sf.name.clone(),
530 local_end.sf.start_pos)
533 self.ensure_source_file_source_present(local_begin.sf.clone());
535 let start_index = local_begin.pos.to_usize();
536 let end_index = local_end.pos.to_usize();
537 let source_len = (local_begin.sf.end_pos -
538 local_begin.sf.start_pos).to_usize();
540 if start_index > end_index || end_index > source_len {
541 return Err(SpanSnippetError::MalformedForSourcemap(
542 MalformedSourceMapPositions {
543 name: local_begin.sf.name.clone(),
545 begin_pos: local_begin.pos,
546 end_pos: local_end.pos,
550 if let Some(ref src) = local_begin.sf.src {
551 return Ok(extract_source(src, start_index, end_index));
552 } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
553 return Ok(extract_source(src, start_index, end_index));
555 return Err(SpanSnippetError::SourceNotAvailable {
556 filename: local_begin.sf.name.clone()
562 /// Return the source snippet as `String` corresponding to the given `Span`
563 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
564 self.span_to_source(sp, |src, start_index, end_index| src[start_index..end_index]
568 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
569 match self.span_to_prev_source(sp) {
571 Ok(source) => source.split('\n').last().map(|last_line| {
572 last_line.len() - last_line.trim_start().len()
577 /// Return the source snippet as `String` before the given `Span`
578 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
579 self.span_to_source(sp, |src, start_index, _| src[..start_index].to_string())
582 /// Extend the given `Span` to just after the previous occurrence of `c`. Return the same span
583 /// if no character could be found or if an error occurred while retrieving the code snippet.
584 pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span {
585 if let Ok(prev_source) = self.span_to_prev_source(sp) {
586 let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_start();
587 if !prev_source.is_empty() && !prev_source.contains('\n') {
588 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
595 /// Extend the given `Span` to just after the previous occurrence of `pat` when surrounded by
596 /// whitespace. Return the same span if no character could be found or if an error occurred
597 /// while retrieving the code snippet.
598 pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
599 // assure that the pattern is delimited, to avoid the following
601 // ^^^^ returned span without the check
602 // ---------- correct span
603 for ws in &[" ", "\t", "\n"] {
604 let pat = pat.to_owned() + ws;
605 if let Ok(prev_source) = self.span_to_prev_source(sp) {
606 let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_start();
607 if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) {
608 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
616 /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
617 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
618 match self.span_to_snippet(sp) {
620 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end();
621 if !snippet.is_empty() && !snippet.contains('\n') {
622 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
631 /// Given a `Span`, try to get a shorter span ending just after the first occurrence of `char`
633 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
634 if let Ok(snippet) = self.span_to_snippet(sp) {
635 if let Some(offset) = snippet.find(c) {
636 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
642 /// Given a `Span`, get a new `Span` covering the first token and all its trailing whitespace or
643 /// the original `Span`.
645 /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
646 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
647 let mut whitespace_found = false;
649 self.span_take_while(sp, |c| {
650 if !whitespace_found && c.is_whitespace() {
651 whitespace_found = true;
654 if whitespace_found && !c.is_whitespace() {
662 /// Given a `Span`, get a new `Span` covering the first token without its trailing whitespace or
663 /// the original `Span` in case of error.
665 /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
666 pub fn span_until_whitespace(&self, sp: Span) -> Span {
667 self.span_take_while(sp, |c| !c.is_whitespace())
670 /// Given a `Span`, get a shorter one until `predicate` yields false.
671 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
672 where P: for <'r> FnMut(&'r char) -> bool
674 if let Ok(snippet) = self.span_to_snippet(sp) {
675 let offset = snippet.chars()
676 .take_while(predicate)
677 .map(|c| c.len_utf8())
680 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
686 pub fn def_span(&self, sp: Span) -> Span {
687 self.span_until_char(sp, '{')
690 /// Returns a new span representing just the start-point of this span
691 pub fn start_point(&self, sp: Span) -> Span {
693 let width = self.find_width_of_character_at_span(sp, false);
694 let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
695 let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
696 sp.with_hi(end_point)
699 /// Returns a new span representing just the end-point of this span
700 pub fn end_point(&self, sp: Span) -> Span {
703 let width = self.find_width_of_character_at_span(sp, false);
704 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
706 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
707 sp.with_lo(end_point)
710 /// Returns a new span representing the next character after the end-point of this span
711 pub fn next_point(&self, sp: Span) -> Span {
712 let start_of_next_point = sp.hi().0;
714 let width = self.find_width_of_character_at_span(sp, true);
715 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
716 // in the case of a multibyte character, where the width != 1, the next span should
717 // span multiple bytes to include the whole character.
718 let end_of_next_point = start_of_next_point.checked_add(
719 width - 1).unwrap_or(start_of_next_point);
721 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
722 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
725 /// Finds the width of a character, either before or after the provided span.
726 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
727 // Disregard malformed spans and assume a one-byte wide character.
728 if sp.lo() >= sp.hi() {
729 debug!("find_width_of_character_at_span: early return malformed span");
733 let local_begin = self.lookup_byte_offset(sp.lo());
734 let local_end = self.lookup_byte_offset(sp.hi());
735 debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
736 local_begin, local_end);
738 let start_index = local_begin.pos.to_usize();
739 let end_index = local_end.pos.to_usize();
740 debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
741 start_index, end_index);
743 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
745 if (!forwards && end_index == usize::min_value()) ||
746 (forwards && start_index == usize::max_value()) {
747 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
751 let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
752 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
753 // Ensure indexes are also not malformed.
754 if start_index > end_index || end_index > source_len {
755 debug!("find_width_of_character_at_span: source indexes are malformed");
759 let src = local_begin.sf.external_src.borrow();
761 // We need to extend the snippet to the end of the src rather than to end_index so when
762 // searching forwards for boundaries we've got somewhere to search.
763 let snippet = if let Some(ref src) = local_begin.sf.src {
765 (&src[start_index..len])
766 } else if let Some(src) = src.get_source() {
768 (&src[start_index..len])
772 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
774 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
775 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
777 while !snippet.is_char_boundary(target - start_index) && target < source_len {
778 target = if forwards {
781 match target.checked_sub(1) {
782 Some(target) => target,
788 debug!("find_width_of_character_at_span: target=`{:?}`", target);
790 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
793 (target - end_index) as u32
795 (end_index - target) as u32
799 pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
800 for sf in self.files.borrow().source_files.iter() {
801 if *filename == sf.name {
802 return Some(sf.clone());
808 /// For a global BytePos compute the local offset within the containing SourceFile
809 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
810 let idx = self.lookup_source_file_idx(bpos);
811 let sf = (*self.files.borrow().source_files)[idx].clone();
812 let offset = bpos - sf.start_pos;
813 SourceFileAndBytePos {sf: sf, pos: offset}
816 /// Converts an absolute BytePos to a CharPos relative to the source_file.
817 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
818 let idx = self.lookup_source_file_idx(bpos);
819 let map = &(*self.files.borrow().source_files)[idx];
821 // The number of extra bytes due to multibyte chars in the SourceFile
822 let mut total_extra_bytes = 0;
824 for mbc in map.multibyte_chars.iter() {
825 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
827 // every character is at least one byte, so we only
828 // count the actual extra bytes.
829 total_extra_bytes += mbc.bytes as u32 - 1;
830 // We should never see a byte position in the middle of a
832 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
838 assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
839 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
842 // Return the index of the source_file (in self.files) which contains pos.
843 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
844 let files = self.files.borrow();
845 let files = &files.source_files;
846 let count = files.len();
848 // Binary search for the source_file.
853 if files[m].start_pos > pos {
860 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
865 pub fn count_lines(&self) -> usize {
866 self.files().iter().fold(0, |a, f| a + f.count_lines())
870 pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
871 let prev_span = self.span_extend_to_prev_str(span, "fn", true);
872 self.span_to_snippet(prev_span).map(|snippet| {
873 let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
874 .expect("no label after fn");
875 prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
879 /// Take the span of a type parameter in a function signature and try to generate a span for the
880 /// function name (with generics) and a new snippet for this span with the pointed type
881 /// parameter as a new local type parameter.
884 /// ```rust,ignore (pseudo-Rust)
886 /// fn my_function(param: T)
887 /// // ^ Original span
890 /// fn my_function(param: T)
891 /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
894 /// Attention: The method used is very fragile since it essentially duplicates the work of the
895 /// parser. If you need to use this function or something similar, please consider updating the
896 /// source_map functions and this function to something more robust.
897 pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
898 // Try to extend the span to the previous "fn" keyword to retrieve the function
900 let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
901 if sugg_span != span {
902 if let Ok(snippet) = self.span_to_snippet(sugg_span) {
903 // Consume the function name
904 let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
905 .expect("no label after fn");
907 // Consume the generics part of the function signature
908 let mut bracket_counter = 0;
909 let mut last_char = None;
910 for c in snippet[offset..].chars() {
912 '<' => bracket_counter += 1,
913 '>' => bracket_counter -= 1,
914 '(' => if bracket_counter == 0 { break; }
917 offset += c.len_utf8();
921 // Adjust the suggestion span to encompass the function name with its generics
922 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
924 // Prepare the new suggested snippet to append the type parameter that triggered
925 // the error in the generics of the function signature
926 let mut new_snippet = if last_char == Some('>') {
927 format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
929 format!("{}<", &snippet[..offset])
931 new_snippet.push_str(
932 &self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
933 new_snippet.push('>');
935 return Some((sugg_span, new_snippet));
943 impl SourceMapper for SourceMap {
944 fn lookup_char_pos(&self, pos: BytePos) -> Loc {
945 self.lookup_char_pos(pos)
947 fn span_to_lines(&self, sp: Span) -> FileLinesResult {
948 self.span_to_lines(sp)
950 fn span_to_string(&self, sp: Span) -> String {
951 self.span_to_string(sp)
953 fn span_to_filename(&self, sp: Span) -> FileName {
954 self.span_to_filename(sp)
956 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
957 self.merge_spans(sp_lhs, sp_rhs)
959 fn call_span_if_macro(&self, sp: Span) -> Span {
960 if self.span_to_filename(sp.clone()).is_macros() {
961 let v = sp.macro_backtrace();
962 if let Some(use_site) = v.last() {
963 return use_site.call_site;
968 fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
969 source_file.add_external_src(
970 || match source_file.name {
971 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
976 fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize {
977 self.doctest_offset_line(file, line)
982 pub struct FilePathMapping {
983 mapping: Vec<(PathBuf, PathBuf)>,
986 impl FilePathMapping {
987 pub fn empty() -> FilePathMapping {
993 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
999 /// Applies any path prefix substitution as defined by the mapping.
1000 /// The return value is the remapped path and a boolean indicating whether
1001 /// the path was affected by the mapping.
1002 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1003 // NOTE: We are iterating over the mapping entries from last to first
1004 // because entries specified later on the command line should
1006 for &(ref from, ref to) in self.mapping.iter().rev() {
1007 if let Ok(rest) = path.strip_prefix(from) {
1008 return (to.join(rest), true);
1016 // _____________________________________________________________________________
1023 use rustc_data_structures::sync::Lrc;
1025 fn init_source_map() -> SourceMap {
1026 let sm = SourceMap::new(FilePathMapping::empty());
1027 sm.new_source_file(PathBuf::from("blork.rs").into(),
1028 "first line.\nsecond line".to_string());
1029 sm.new_source_file(PathBuf::from("empty.rs").into(),
1031 sm.new_source_file(PathBuf::from("blork2.rs").into(),
1032 "first line.\nsecond line".to_string());
1038 // Test lookup_byte_offset
1039 let sm = init_source_map();
1041 let srcfbp1 = sm.lookup_byte_offset(BytePos(23));
1042 assert_eq!(srcfbp1.sf.name, PathBuf::from("blork.rs").into());
1043 assert_eq!(srcfbp1.pos, BytePos(23));
1045 let srcfbp1 = sm.lookup_byte_offset(BytePos(24));
1046 assert_eq!(srcfbp1.sf.name, PathBuf::from("empty.rs").into());
1047 assert_eq!(srcfbp1.pos, BytePos(0));
1049 let srcfbp2 = sm.lookup_byte_offset(BytePos(25));
1050 assert_eq!(srcfbp2.sf.name, PathBuf::from("blork2.rs").into());
1051 assert_eq!(srcfbp2.pos, BytePos(0));
1056 // Test bytepos_to_file_charpos
1057 let sm = init_source_map();
1059 let cp1 = sm.bytepos_to_file_charpos(BytePos(22));
1060 assert_eq!(cp1, CharPos(22));
1062 let cp2 = sm.bytepos_to_file_charpos(BytePos(25));
1063 assert_eq!(cp2, CharPos(0));
1068 // Test zero-length source_files.
1069 let sm = init_source_map();
1071 let loc1 = sm.lookup_char_pos(BytePos(22));
1072 assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
1073 assert_eq!(loc1.line, 2);
1074 assert_eq!(loc1.col, CharPos(10));
1076 let loc2 = sm.lookup_char_pos(BytePos(25));
1077 assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
1078 assert_eq!(loc2.line, 1);
1079 assert_eq!(loc2.col, CharPos(0));
1082 fn init_source_map_mbc() -> SourceMap {
1083 let sm = SourceMap::new(FilePathMapping::empty());
1084 // € is a three byte utf8 char.
1085 sm.new_source_file(PathBuf::from("blork.rs").into(),
1086 "fir€st €€€€ line.\nsecond line".to_string());
1087 sm.new_source_file(PathBuf::from("blork2.rs").into(),
1088 "first line€€.\n€ second line".to_string());
1094 // Test bytepos_to_file_charpos in the presence of multi-byte chars
1095 let sm = init_source_map_mbc();
1097 let cp1 = sm.bytepos_to_file_charpos(BytePos(3));
1098 assert_eq!(cp1, CharPos(3));
1100 let cp2 = sm.bytepos_to_file_charpos(BytePos(6));
1101 assert_eq!(cp2, CharPos(4));
1103 let cp3 = sm.bytepos_to_file_charpos(BytePos(56));
1104 assert_eq!(cp3, CharPos(12));
1106 let cp4 = sm.bytepos_to_file_charpos(BytePos(61));
1107 assert_eq!(cp4, CharPos(15));
1112 // Test span_to_lines for a span ending at the end of source_file
1113 let sm = init_source_map();
1114 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1115 let file_lines = sm.span_to_lines(span).unwrap();
1117 assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
1118 assert_eq!(file_lines.lines.len(), 1);
1119 assert_eq!(file_lines.lines[0].line_index, 1);
1122 /// Given a string like " ~~~~~~~~~~~~ ", produces a span
1123 /// converting that range. The idea is that the string has the same
1124 /// length as the input, and we uncover the byte positions. Note
1125 /// that this can span lines and so on.
1126 fn span_from_selection(input: &str, selection: &str) -> Span {
1127 assert_eq!(input.len(), selection.len());
1128 let left_index = selection.find('~').unwrap() as u32;
1129 let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
1130 Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
1133 /// Test span_to_snippet and span_to_lines for a span converting 3
1134 /// lines in the middle of a file.
1136 fn span_to_snippet_and_lines_spanning_multiple_lines() {
1137 let sm = SourceMap::new(FilePathMapping::empty());
1138 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1139 let selection = " \n ~~\n~~~\n~~~~~ \n \n";
1140 sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_string());
1141 let span = span_from_selection(inputtext, selection);
1143 // check that we are extracting the text we thought we were extracting
1144 assert_eq!(&sm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1146 // check that span_to_lines gives us the complete result with the lines/cols we expected
1147 let lines = sm.span_to_lines(span).unwrap();
1148 let expected = vec![
1149 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1150 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1151 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1153 assert_eq!(lines.lines, expected);
1158 // Test span_to_snippet for a span ending at the end of source_file
1159 let sm = init_source_map();
1160 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1161 let snippet = sm.span_to_snippet(span);
1163 assert_eq!(snippet, Ok("second line".to_string()));
1168 // Test span_to_str for a span ending at the end of source_file
1169 let sm = init_source_map();
1170 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1171 let sstr = sm.span_to_string(span);
1173 assert_eq!(sstr, "blork.rs:2:1: 2:12");
1176 /// Test failing to merge two spans on different lines
1178 fn span_merging_fail() {
1179 let sm = SourceMap::new(FilePathMapping::empty());
1180 let inputtext = "bbbb BB\ncc CCC\n";
1181 let selection1 = " ~~\n \n";
1182 let selection2 = " \n ~~~\n";
1183 sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_owned());
1184 let span1 = span_from_selection(inputtext, selection1);
1185 let span2 = span_from_selection(inputtext, selection2);
1187 assert!(sm.merge_spans(span1, span2).is_none());
1190 /// Returns the span corresponding to the `n`th occurrence of
1191 /// `substring` in `source_text`.
1192 trait SourceMapExtension {
1193 fn span_substr(&self,
1194 file: &Lrc<SourceFile>,
1201 impl SourceMapExtension for SourceMap {
1202 fn span_substr(&self,
1203 file: &Lrc<SourceFile>,
1209 println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
1210 file.name, file.start_pos, substring, n);
1214 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
1215 panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
1216 source_text, n, substring, i);
1218 let lo = hi + offset;
1219 hi = lo + substring.len();
1221 let span = Span::new(
1222 BytePos(lo as u32 + file.start_pos.0),
1223 BytePos(hi as u32 + file.start_pos.0),
1226 assert_eq!(&self.span_to_snippet(span).unwrap()[..],