1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The CodeMap tracks all the source code used within a single crate, mapping
12 //! from integer byte positions to the original source code location. Each bit
13 //! of source parsed during crate parsing (typically files, in-memory strings,
14 //! or various bits of macro expansion) cover a continuous range of bytes in the
15 //! CodeMap and are represented by FileMaps. Byte positions are stored in
16 //! `spans` and used pervasively in the compiler. They are absolute positions
17 //! within the CodeMap, which upon request can be converted to line and column
18 //! information, source code snippets, etc.
21 pub use syntax_pos::*;
22 pub use syntax_pos::hygiene::{ExpnFormat, ExpnInfo, NameAndSpan};
23 pub use self::ExpnFormat::*;
25 use rustc_data_structures::fx::FxHashMap;
26 use rustc_data_structures::stable_hasher::StableHasher;
27 use rustc_data_structures::sync::Lrc;
28 use std::cell::{RefCell, Ref};
31 use std::path::{Path, PathBuf};
35 use std::io::{self, Read};
36 use errors::CodeMapper;
38 /// Return the span itself if it doesn't come from a macro expansion,
39 /// otherwise return the call site span up to the `enclosing_sp` by
40 /// following the `expn_info` chain.
41 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
42 let call_site1 = sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
43 let call_site2 = enclosing_sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
44 match (call_site1, call_site2) {
46 (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
47 (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
51 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
52 pub struct Spanned<T> {
57 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
58 Spanned {node: t, span: sp}
61 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
65 // _____________________________________________________________________________
66 // FileMap, MultiByteChar, FileName, FileLines
69 /// An abstraction over the fs operations used by the Parser.
70 pub trait FileLoader {
71 /// Query the existence of a file.
72 fn file_exists(&self, path: &Path) -> bool;
74 /// Return an absolute path to a file, if possible.
75 fn abs_path(&self, path: &Path) -> Option<PathBuf>;
77 /// Read the contents of an UTF-8 file into memory.
78 fn read_file(&self, path: &Path) -> io::Result<String>;
81 /// A FileLoader that uses std::fs to load real files.
82 pub struct RealFileLoader;
84 impl FileLoader for RealFileLoader {
85 fn file_exists(&self, path: &Path) -> bool {
86 fs::metadata(path).is_ok()
89 fn abs_path(&self, path: &Path) -> Option<PathBuf> {
90 if path.is_absolute() {
91 Some(path.to_path_buf())
95 .map(|cwd| cwd.join(path))
99 fn read_file(&self, path: &Path) -> io::Result<String> {
100 let mut src = String::new();
101 fs::File::open(path)?.read_to_string(&mut src)?;
106 // This is a FileMap identifier that is used to correlate FileMaps between
107 // subsequent compilation sessions (which is something we need to do during
108 // incremental compilation).
109 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
110 pub struct StableFilemapId(u128);
112 impl StableFilemapId {
113 pub fn new(filemap: &FileMap) -> StableFilemapId {
114 let mut hasher = StableHasher::new();
116 filemap.name.hash(&mut hasher);
117 filemap.name_was_remapped.hash(&mut hasher);
118 filemap.unmapped_path.hash(&mut hasher);
120 StableFilemapId(hasher.finish())
124 // _____________________________________________________________________________
129 pub(super) files: RefCell<Vec<Lrc<FileMap>>>,
130 file_loader: Box<FileLoader>,
131 // This is used to apply the file path remapping as specified via
132 // --remap-path-prefix to all FileMaps allocated within this CodeMap.
133 path_mapping: FilePathMapping,
134 stable_id_to_filemap: RefCell<FxHashMap<StableFilemapId, Lrc<FileMap>>>,
135 /// In case we are in a doctest, replace all file names with the PathBuf,
136 /// and add the given offsets to the line info
137 doctest_offset: Option<(FileName, isize)>,
141 pub fn new(path_mapping: FilePathMapping) -> CodeMap {
143 files: RefCell::new(Vec::new()),
144 file_loader: Box::new(RealFileLoader),
146 stable_id_to_filemap: RefCell::new(FxHashMap()),
147 doctest_offset: None,
151 pub fn new_doctest(path_mapping: FilePathMapping,
152 file: FileName, line: isize) -> CodeMap {
154 doctest_offset: Some((file, line)),
155 ..CodeMap::new(path_mapping)
160 pub fn with_file_loader(file_loader: Box<FileLoader>,
161 path_mapping: FilePathMapping)
164 files: RefCell::new(Vec::new()),
167 stable_id_to_filemap: RefCell::new(FxHashMap()),
168 doctest_offset: None,
172 pub fn path_mapping(&self) -> &FilePathMapping {
176 pub fn file_exists(&self, path: &Path) -> bool {
177 self.file_loader.file_exists(path)
180 pub fn load_file(&self, path: &Path) -> io::Result<Lrc<FileMap>> {
181 let src = self.file_loader.read_file(path)?;
182 let filename = if let Some((ref name, _)) = self.doctest_offset {
185 path.to_owned().into()
187 Ok(self.new_filemap(filename, src))
190 pub fn files(&self) -> Ref<Vec<Lrc<FileMap>>> {
194 pub fn filemap_by_stable_id(&self, stable_id: StableFilemapId) -> Option<Lrc<FileMap>> {
195 self.stable_id_to_filemap.borrow().get(&stable_id).map(|fm| fm.clone())
198 fn next_start_pos(&self) -> usize {
199 let files = self.files.borrow();
202 // Add one so there is some space between files. This lets us distinguish
203 // positions in the codemap, even in the presence of zero-length files.
204 Some(last) => last.end_pos.to_usize() + 1,
208 /// Creates a new filemap without setting its line information. If you don't
209 /// intend to set the line information yourself, you should use new_filemap_and_lines.
210 pub fn new_filemap(&self, filename: FileName, src: String) -> Lrc<FileMap> {
211 let start_pos = self.next_start_pos();
212 let mut files = self.files.borrow_mut();
214 // The path is used to determine the directory for loading submodules and
215 // include files, so it must be before remapping.
216 // Note that filename may not be a valid path, eg it may be `<anon>` etc,
217 // but this is okay because the directory determined by `path.pop()` will
218 // be empty, so the working directory will be used.
219 let unmapped_path = filename.clone();
221 let (filename, was_remapped) = match filename {
222 FileName::Real(filename) => {
223 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
224 (FileName::Real(filename), was_remapped)
226 other => (other, false),
228 let filemap = Lrc::new(FileMap::new(
233 Pos::from_usize(start_pos),
236 files.push(filemap.clone());
238 self.stable_id_to_filemap
240 .insert(StableFilemapId::new(&filemap), filemap.clone());
245 /// Creates a new filemap and sets its line information.
246 pub fn new_filemap_and_lines(&self, filename: &Path, src: &str) -> Lrc<FileMap> {
247 let fm = self.new_filemap(filename.to_owned().into(), src.to_owned());
248 let mut byte_pos: u32 = fm.start_pos.0;
249 for line in src.lines() {
250 // register the start of this line
251 fm.next_line(BytePos(byte_pos));
253 // update byte_pos to include this line and the \n at the end
254 byte_pos += line.len() as u32 + 1;
260 /// Allocates a new FileMap representing a source file from an external
261 /// crate. The source code of such an "imported filemap" is not available,
262 /// but we still know enough to generate accurate debuginfo location
263 /// information for things inlined from other crates.
264 pub fn new_imported_filemap(&self,
266 name_was_remapped: bool,
267 crate_of_origin: u32,
271 mut file_local_lines: Vec<BytePos>,
272 mut file_local_multibyte_chars: Vec<MultiByteChar>,
273 mut file_local_non_narrow_chars: Vec<NonNarrowChar>)
275 let start_pos = self.next_start_pos();
276 let mut files = self.files.borrow_mut();
278 let end_pos = Pos::from_usize(start_pos + source_len);
279 let start_pos = Pos::from_usize(start_pos);
281 for pos in &mut file_local_lines {
282 *pos = *pos + start_pos;
285 for mbc in &mut file_local_multibyte_chars {
286 mbc.pos = mbc.pos + start_pos;
289 for swc in &mut file_local_non_narrow_chars {
290 *swc = *swc + start_pos;
293 let filemap = Lrc::new(FileMap {
300 external_src: RefCell::new(ExternalSource::AbsentOk),
303 lines: RefCell::new(file_local_lines),
304 multibyte_chars: RefCell::new(file_local_multibyte_chars),
305 non_narrow_chars: RefCell::new(file_local_non_narrow_chars),
309 files.push(filemap.clone());
311 self.stable_id_to_filemap
313 .insert(StableFilemapId::new(&filemap), filemap.clone());
318 pub fn mk_substr_filename(&self, sp: Span) -> String {
319 let pos = self.lookup_char_pos(sp.lo());
320 format!("<{}:{}:{}>",
323 pos.col.to_usize() + 1)
326 // If there is a doctest_offset, apply it to the line
327 pub fn doctest_offset_line(&self, mut orig: usize) -> usize {
328 if let Some((_, line)) = self.doctest_offset {
330 orig = orig + line as usize;
332 orig = orig - (-line) as usize;
338 /// Lookup source information about a BytePos
339 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
340 let chpos = self.bytepos_to_file_charpos(pos);
341 match self.lookup_line(pos) {
342 Ok(FileMapAndLine { fm: f, line: a }) => {
343 let line = a + 1; // Line numbers start at 1
344 let linebpos = (*f.lines.borrow())[a];
345 let linechpos = self.bytepos_to_file_charpos(linebpos);
346 let col = chpos - linechpos;
349 let non_narrow_chars = f.non_narrow_chars.borrow();
350 let start_width_idx = non_narrow_chars
351 .binary_search_by_key(&linebpos, |x| x.pos())
352 .unwrap_or_else(|x| x);
353 let end_width_idx = non_narrow_chars
354 .binary_search_by_key(&pos, |x| x.pos())
355 .unwrap_or_else(|x| x);
356 let special_chars = end_width_idx - start_width_idx;
357 let non_narrow: usize =
358 non_narrow_chars[start_width_idx..end_width_idx]
362 col.0 - special_chars + non_narrow
364 debug!("byte pos {:?} is on the line at byte pos {:?}",
366 debug!("char pos {:?} is on the line at char pos {:?}",
368 debug!("byte is on line: {}", line);
369 assert!(chpos >= linechpos);
379 let non_narrow_chars = f.non_narrow_chars.borrow();
380 let end_width_idx = non_narrow_chars
381 .binary_search_by_key(&pos, |x| x.pos())
382 .unwrap_or_else(|x| x);
383 let non_narrow: usize =
384 non_narrow_chars[0..end_width_idx]
388 chpos.0 - end_width_idx + non_narrow
400 // If the relevant filemap is empty, we don't return a line number.
401 pub fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Lrc<FileMap>> {
402 let idx = self.lookup_filemap_idx(pos);
404 let files = self.files.borrow();
405 let f = (*files)[idx].clone();
407 match f.lookup_line(pos) {
408 Some(line) => Ok(FileMapAndLine { fm: f, line: line }),
413 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
414 let loc = self.lookup_char_pos(pos);
416 filename: loc.file.name.clone(),
423 /// Returns `Some(span)`, a union of the lhs and rhs span. The lhs must precede the rhs. If
424 /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
425 /// For this to work, the spans have to be:
427 /// * the ctxt of both spans much match
428 /// * the lhs span needs to end on the same line the rhs span begins
429 /// * the lhs span must start at or before the rhs span
430 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
431 // make sure we're at the same expansion id
432 if sp_lhs.ctxt() != sp_rhs.ctxt() {
436 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
438 Err(_) => return None
440 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
442 Err(_) => return None
445 // if we must cross lines to merge, don't merge
446 if lhs_end.line != rhs_begin.line {
450 // ensure these follow the expected order and we don't overlap
451 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
452 Some(sp_lhs.to(sp_rhs))
458 pub fn span_to_string(&self, sp: Span) -> String {
459 if self.files.borrow().is_empty() && sp.source_equal(&DUMMY_SP) {
460 return "no-location".to_string();
463 let lo = self.lookup_char_pos_adj(sp.lo());
464 let hi = self.lookup_char_pos_adj(sp.hi());
465 format!("{}:{}:{}: {}:{}",
468 lo.col.to_usize() + 1,
470 hi.col.to_usize() + 1)
473 pub fn span_to_filename(&self, sp: Span) -> FileName {
474 self.lookup_char_pos(sp.lo()).file.name.clone()
477 pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
478 self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
479 .expect("CodeMap::span_to_unmapped_path called for imported FileMap?")
482 pub fn is_multiline(&self, sp: Span) -> bool {
483 let lo = self.lookup_char_pos(sp.lo());
484 let hi = self.lookup_char_pos(sp.hi());
488 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
489 debug!("span_to_lines(sp={:?})", sp);
491 if sp.lo() > sp.hi() {
492 return Err(SpanLinesError::IllFormedSpan(sp));
495 let lo = self.lookup_char_pos(sp.lo());
496 debug!("span_to_lines: lo={:?}", lo);
497 let hi = self.lookup_char_pos(sp.hi());
498 debug!("span_to_lines: hi={:?}", hi);
500 if lo.file.start_pos != hi.file.start_pos {
501 return Err(SpanLinesError::DistinctSources(DistinctSources {
502 begin: (lo.file.name.clone(), lo.file.start_pos),
503 end: (hi.file.name.clone(), hi.file.start_pos),
506 assert!(hi.line >= lo.line);
508 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
510 // The span starts partway through the first line,
511 // but after that it starts from offset 0.
512 let mut start_col = lo.col;
514 // For every line but the last, it extends from `start_col`
515 // and to the end of the line. Be careful because the line
516 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
518 for line_index in lo.line-1 .. hi.line-1 {
519 let line_len = lo.file.get_line(line_index)
520 .map(|s| s.chars().count())
522 lines.push(LineInfo { line_index,
524 end_col: CharPos::from_usize(line_len) });
525 start_col = CharPos::from_usize(0);
528 // For the last line, it extends from `start_col` to `hi.col`:
529 lines.push(LineInfo { line_index: hi.line - 1,
533 Ok(FileLines {file: lo.file, lines: lines})
536 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
537 if sp.lo() > sp.hi() {
538 return Err(SpanSnippetError::IllFormedSpan(sp));
541 let local_begin = self.lookup_byte_offset(sp.lo());
542 let local_end = self.lookup_byte_offset(sp.hi());
544 if local_begin.fm.start_pos != local_end.fm.start_pos {
545 return Err(SpanSnippetError::DistinctSources(DistinctSources {
546 begin: (local_begin.fm.name.clone(),
547 local_begin.fm.start_pos),
548 end: (local_end.fm.name.clone(),
549 local_end.fm.start_pos)
552 self.ensure_filemap_source_present(local_begin.fm.clone());
554 let start_index = local_begin.pos.to_usize();
555 let end_index = local_end.pos.to_usize();
556 let source_len = (local_begin.fm.end_pos -
557 local_begin.fm.start_pos).to_usize();
559 if start_index > end_index || end_index > source_len {
560 return Err(SpanSnippetError::MalformedForCodemap(
561 MalformedCodemapPositions {
562 name: local_begin.fm.name.clone(),
564 begin_pos: local_begin.pos,
565 end_pos: local_end.pos,
569 if let Some(ref src) = local_begin.fm.src {
570 return Ok((&src[start_index..end_index]).to_string());
571 } else if let Some(src) = local_begin.fm.external_src.borrow().get_source() {
572 return Ok((&src[start_index..end_index]).to_string());
574 return Err(SpanSnippetError::SourceNotAvailable {
575 filename: local_begin.fm.name.clone()
581 /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
582 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
583 match self.span_to_snippet(sp) {
585 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right();
586 if !snippet.is_empty() && !snippet.contains('\n') {
587 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
596 /// Given a `Span`, get a new `Span` covering the first token and all its trailing whitespace or
597 /// the original `Span`.
599 /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
600 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
601 if let Ok(snippet) = self.span_to_snippet(sp) {
603 // get the bytes width of all the non-whitespace characters
604 for c in snippet.chars().take_while(|c| !c.is_whitespace()) {
605 offset += c.len_utf8();
607 // get the bytes width of all the whitespace characters after that
608 for c in snippet[offset..].chars().take_while(|c| c.is_whitespace()) {
609 offset += c.len_utf8();
612 return sp.with_hi(BytePos(sp.lo().0 + offset as u32));
618 /// Given a `Span`, try to get a shorter span ending just after the first occurrence of `char`
620 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
621 if let Ok(snippet) = self.span_to_snippet(sp) {
622 if let Some(offset) = snippet.find(c) {
623 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
629 pub fn def_span(&self, sp: Span) -> Span {
630 self.span_until_char(sp, '{')
633 /// Returns a new span representing just the end-point of this span
634 pub fn end_point(&self, sp: Span) -> Span {
637 let width = self.find_width_of_character_at_span(sp, false);
638 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
640 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
641 sp.with_lo(end_point)
644 /// Returns a new span representing the next character after the end-point of this span
645 pub fn next_point(&self, sp: Span) -> Span {
646 let start_of_next_point = sp.hi().0;
648 let width = self.find_width_of_character_at_span(sp, true);
649 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
650 // in the case of a multibyte character, where the width != 1, the next span should
651 // span multiple bytes to include the whole character.
652 let end_of_next_point = start_of_next_point.checked_add(
653 width - 1).unwrap_or(start_of_next_point);
655 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
656 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
659 /// Finds the width of a character, either before or after the provided span.
660 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
661 // Disregard malformed spans and assume a one-byte wide character.
662 if sp.lo() >= sp.hi() {
663 debug!("find_width_of_character_at_span: early return malformed span");
667 let local_begin = self.lookup_byte_offset(sp.lo());
668 let local_end = self.lookup_byte_offset(sp.hi());
669 debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
670 local_begin, local_end);
672 let start_index = local_begin.pos.to_usize();
673 let end_index = local_end.pos.to_usize();
674 debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
675 start_index, end_index);
677 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
679 if (!forwards && end_index == usize::min_value()) ||
680 (forwards && start_index == usize::max_value()) {
681 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
685 let source_len = (local_begin.fm.end_pos - local_begin.fm.start_pos).to_usize();
686 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
687 // Ensure indexes are also not malformed.
688 if start_index > end_index || end_index > source_len {
689 debug!("find_width_of_character_at_span: source indexes are malformed");
693 let src = local_begin.fm.external_src.borrow();
695 // We need to extend the snippet to the end of the src rather than to end_index so when
696 // searching forwards for boundaries we've got somewhere to search.
697 let snippet = if let Some(ref src) = local_begin.fm.src {
699 (&src[start_index..len])
700 } else if let Some(src) = src.get_source() {
702 (&src[start_index..len])
706 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
708 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
709 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
711 while !snippet.is_char_boundary(target - start_index) && target < source_len {
712 target = if forwards {
715 match target.checked_sub(1) {
716 Some(target) => target,
722 debug!("find_width_of_character_at_span: target=`{:?}`", target);
724 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
727 (target - end_index) as u32
729 (end_index - target) as u32
733 pub fn get_filemap(&self, filename: &FileName) -> Option<Lrc<FileMap>> {
734 for fm in self.files.borrow().iter() {
735 if *filename == fm.name {
736 return Some(fm.clone());
742 /// For a global BytePos compute the local offset within the containing FileMap
743 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
744 let idx = self.lookup_filemap_idx(bpos);
745 let fm = (*self.files.borrow())[idx].clone();
746 let offset = bpos - fm.start_pos;
747 FileMapAndBytePos {fm: fm, pos: offset}
750 /// Converts an absolute BytePos to a CharPos relative to the filemap.
751 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
752 let idx = self.lookup_filemap_idx(bpos);
753 let files = self.files.borrow();
754 let map = &(*files)[idx];
756 // The number of extra bytes due to multibyte chars in the FileMap
757 let mut total_extra_bytes = 0;
759 for mbc in map.multibyte_chars.borrow().iter() {
760 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
762 // every character is at least one byte, so we only
763 // count the actual extra bytes.
764 total_extra_bytes += mbc.bytes - 1;
765 // We should never see a byte position in the middle of a
767 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
773 assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
774 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
777 // Return the index of the filemap (in self.files) which contains pos.
778 pub fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
779 let files = self.files.borrow();
781 let count = files.len();
783 // Binary search for the filemap.
788 if files[m].start_pos > pos {
795 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
800 pub fn count_lines(&self) -> usize {
801 self.files().iter().fold(0, |a, f| a + f.count_lines())
805 impl CodeMapper for CodeMap {
806 fn lookup_char_pos(&self, pos: BytePos) -> Loc {
807 self.lookup_char_pos(pos)
809 fn span_to_lines(&self, sp: Span) -> FileLinesResult {
810 self.span_to_lines(sp)
812 fn span_to_string(&self, sp: Span) -> String {
813 self.span_to_string(sp)
815 fn span_to_filename(&self, sp: Span) -> FileName {
816 self.span_to_filename(sp)
818 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
819 self.merge_spans(sp_lhs, sp_rhs)
821 fn call_span_if_macro(&self, sp: Span) -> Span {
822 if self.span_to_filename(sp.clone()).is_macros() {
823 let v = sp.macro_backtrace();
824 if let Some(use_site) = v.last() {
825 return use_site.call_site;
830 fn ensure_filemap_source_present(&self, file_map: Lrc<FileMap>) -> bool {
831 file_map.add_external_src(
832 || match file_map.name {
833 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
838 fn doctest_offset_line(&self, line: usize) -> usize {
839 self.doctest_offset_line(line)
844 pub struct FilePathMapping {
845 mapping: Vec<(PathBuf, PathBuf)>,
848 impl FilePathMapping {
849 pub fn empty() -> FilePathMapping {
855 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
861 /// Applies any path prefix substitution as defined by the mapping.
862 /// The return value is the remapped path and a boolean indicating whether
863 /// the path was affected by the mapping.
864 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
865 // NOTE: We are iterating over the mapping entries from last to first
866 // because entries specified later on the command line should
868 for &(ref from, ref to) in self.mapping.iter().rev() {
869 if let Ok(rest) = path.strip_prefix(from) {
870 return (to.join(rest), true);
878 // _____________________________________________________________________________
885 use std::borrow::Cow;
886 use rustc_data_structures::sync::Lrc;
890 let cm = CodeMap::new(FilePathMapping::empty());
891 let fm = cm.new_filemap(PathBuf::from("blork.rs").into(),
892 "first line.\nsecond line".to_string());
893 fm.next_line(BytePos(0));
894 // Test we can get lines with partial line info.
895 assert_eq!(fm.get_line(0), Some(Cow::from("first line.")));
896 // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
897 fm.next_line(BytePos(10));
898 assert_eq!(fm.get_line(1), Some(Cow::from(".")));
899 fm.next_line(BytePos(12));
900 assert_eq!(fm.get_line(2), Some(Cow::from("second line")));
906 let cm = CodeMap::new(FilePathMapping::empty());
907 let fm = cm.new_filemap(PathBuf::from("blork.rs").into(),
908 "first line.\nsecond line".to_string());
909 // TESTING *REALLY* BROKEN BEHAVIOR:
910 fm.next_line(BytePos(0));
911 fm.next_line(BytePos(10));
912 fm.next_line(BytePos(2));
915 fn init_code_map() -> CodeMap {
916 let cm = CodeMap::new(FilePathMapping::empty());
917 let fm1 = cm.new_filemap(PathBuf::from("blork.rs").into(),
918 "first line.\nsecond line".to_string());
919 let fm2 = cm.new_filemap(PathBuf::from("empty.rs").into(),
921 let fm3 = cm.new_filemap(PathBuf::from("blork2.rs").into(),
922 "first line.\nsecond line".to_string());
924 fm1.next_line(BytePos(0));
925 fm1.next_line(BytePos(12));
926 fm2.next_line(fm2.start_pos);
927 fm3.next_line(fm3.start_pos);
928 fm3.next_line(fm3.start_pos + BytePos(12));
935 // Test lookup_byte_offset
936 let cm = init_code_map();
938 let fmabp1 = cm.lookup_byte_offset(BytePos(23));
939 assert_eq!(fmabp1.fm.name, PathBuf::from("blork.rs").into());
940 assert_eq!(fmabp1.pos, BytePos(23));
942 let fmabp1 = cm.lookup_byte_offset(BytePos(24));
943 assert_eq!(fmabp1.fm.name, PathBuf::from("empty.rs").into());
944 assert_eq!(fmabp1.pos, BytePos(0));
946 let fmabp2 = cm.lookup_byte_offset(BytePos(25));
947 assert_eq!(fmabp2.fm.name, PathBuf::from("blork2.rs").into());
948 assert_eq!(fmabp2.pos, BytePos(0));
953 // Test bytepos_to_file_charpos
954 let cm = init_code_map();
956 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
957 assert_eq!(cp1, CharPos(22));
959 let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
960 assert_eq!(cp2, CharPos(0));
965 // Test zero-length filemaps.
966 let cm = init_code_map();
968 let loc1 = cm.lookup_char_pos(BytePos(22));
969 assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
970 assert_eq!(loc1.line, 2);
971 assert_eq!(loc1.col, CharPos(10));
973 let loc2 = cm.lookup_char_pos(BytePos(25));
974 assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
975 assert_eq!(loc2.line, 1);
976 assert_eq!(loc2.col, CharPos(0));
979 fn init_code_map_mbc() -> CodeMap {
980 let cm = CodeMap::new(FilePathMapping::empty());
981 // € is a three byte utf8 char.
983 cm.new_filemap(PathBuf::from("blork.rs").into(),
984 "fir€st €€€€ line.\nsecond line".to_string());
985 let fm2 = cm.new_filemap(PathBuf::from("blork2.rs").into(),
986 "first line€€.\n€ second line".to_string());
988 fm1.next_line(BytePos(0));
989 fm1.next_line(BytePos(28));
990 fm2.next_line(fm2.start_pos);
991 fm2.next_line(fm2.start_pos + BytePos(20));
993 fm1.record_multibyte_char(BytePos(3), 3);
994 fm1.record_multibyte_char(BytePos(9), 3);
995 fm1.record_multibyte_char(BytePos(12), 3);
996 fm1.record_multibyte_char(BytePos(15), 3);
997 fm1.record_multibyte_char(BytePos(18), 3);
998 fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
999 fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
1000 fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
1007 // Test bytepos_to_file_charpos in the presence of multi-byte chars
1008 let cm = init_code_map_mbc();
1010 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
1011 assert_eq!(cp1, CharPos(3));
1013 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
1014 assert_eq!(cp2, CharPos(4));
1016 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
1017 assert_eq!(cp3, CharPos(12));
1019 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
1020 assert_eq!(cp4, CharPos(15));
1025 // Test span_to_lines for a span ending at the end of filemap
1026 let cm = init_code_map();
1027 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1028 let file_lines = cm.span_to_lines(span).unwrap();
1030 assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
1031 assert_eq!(file_lines.lines.len(), 1);
1032 assert_eq!(file_lines.lines[0].line_index, 1);
1035 /// Given a string like " ~~~~~~~~~~~~ ", produces a span
1036 /// converting that range. The idea is that the string has the same
1037 /// length as the input, and we uncover the byte positions. Note
1038 /// that this can span lines and so on.
1039 fn span_from_selection(input: &str, selection: &str) -> Span {
1040 assert_eq!(input.len(), selection.len());
1041 let left_index = selection.find('~').unwrap() as u32;
1042 let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
1043 Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
1046 /// Test span_to_snippet and span_to_lines for a span converting 3
1047 /// lines in the middle of a file.
1049 fn span_to_snippet_and_lines_spanning_multiple_lines() {
1050 let cm = CodeMap::new(FilePathMapping::empty());
1051 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1052 let selection = " \n ~~\n~~~\n~~~~~ \n \n";
1053 cm.new_filemap_and_lines(Path::new("blork.rs"), inputtext);
1054 let span = span_from_selection(inputtext, selection);
1056 // check that we are extracting the text we thought we were extracting
1057 assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1059 // check that span_to_lines gives us the complete result with the lines/cols we expected
1060 let lines = cm.span_to_lines(span).unwrap();
1061 let expected = vec![
1062 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1063 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1064 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1066 assert_eq!(lines.lines, expected);
1071 // Test span_to_snippet for a span ending at the end of filemap
1072 let cm = init_code_map();
1073 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1074 let snippet = cm.span_to_snippet(span);
1076 assert_eq!(snippet, Ok("second line".to_string()));
1081 // Test span_to_str for a span ending at the end of filemap
1082 let cm = init_code_map();
1083 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1084 let sstr = cm.span_to_string(span);
1086 assert_eq!(sstr, "blork.rs:2:1: 2:12");
1089 /// Test failing to merge two spans on different lines
1091 fn span_merging_fail() {
1092 let cm = CodeMap::new(FilePathMapping::empty());
1093 let inputtext = "bbbb BB\ncc CCC\n";
1094 let selection1 = " ~~\n \n";
1095 let selection2 = " \n ~~~\n";
1096 cm.new_filemap_and_lines(Path::new("blork.rs"), inputtext);
1097 let span1 = span_from_selection(inputtext, selection1);
1098 let span2 = span_from_selection(inputtext, selection2);
1100 assert!(cm.merge_spans(span1, span2).is_none());
1103 /// Returns the span corresponding to the `n`th occurrence of
1104 /// `substring` in `source_text`.
1105 trait CodeMapExtension {
1106 fn span_substr(&self,
1107 file: &Lrc<FileMap>,
1114 impl CodeMapExtension for CodeMap {
1115 fn span_substr(&self,
1116 file: &Lrc<FileMap>,
1122 println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
1123 file.name, file.start_pos, substring, n);
1127 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
1128 panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
1129 source_text, n, substring, i);
1131 let lo = hi + offset;
1132 hi = lo + substring.len();
1134 let span = Span::new(
1135 BytePos(lo as u32 + file.start_pos.0),
1136 BytePos(hi as u32 + file.start_pos.0),
1139 assert_eq!(&self.span_to_snippet(span).unwrap()[..],