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 std::cell::{RefCell, Ref};
30 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<Rc<FileMap>>>,
130 file_loader: Box<FileLoader>,
131 // This is used to apply the file path remapping as specified via
132 // -Zremap-path-prefix to all FileMaps allocated within this CodeMap.
133 path_mapping: FilePathMapping,
134 stable_id_to_filemap: RefCell<FxHashMap<StableFilemapId, Rc<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<Rc<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<Rc<FileMap>>> {
194 pub fn filemap_by_stable_id(&self, stable_id: StableFilemapId) -> Option<Rc<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) -> Rc<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 = Rc::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) -> Rc<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 = Rc::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)).to_string()
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, Rc<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 return (format!("{}:{}:{}: {}:{}",
468 lo.col.to_usize() + 1,
470 hi.col.to_usize() + 1)).to_string()
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`, try to get a shorter span ending just after the first
597 /// occurrence of `char` `c`.
598 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
599 if let Ok(snippet) = self.span_to_snippet(sp) {
600 if let Some(offset) = snippet.find(c) {
601 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
607 pub fn def_span(&self, sp: Span) -> Span {
608 self.span_until_char(sp, '{')
611 /// Returns a new span representing just the end-point of this span
612 pub fn end_point(&self, sp: Span) -> Span {
615 let width = self.find_width_of_character_at_span(sp, false);
616 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
618 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
619 sp.with_lo(end_point)
622 /// Returns a new span representing the next character after the end-point of this span
623 pub fn next_point(&self, sp: Span) -> Span {
624 let start_of_next_point = sp.hi().0;
626 let width = self.find_width_of_character_at_span(sp, true);
627 // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
628 // in the case of a multibyte character, where the width != 1, the next span should
629 // span multiple bytes to include the whole character.
630 let end_of_next_point = start_of_next_point.checked_add(
631 width - 1).unwrap_or(start_of_next_point);
633 let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
634 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
637 /// Finds the width of a character, either before or after the provided span.
638 fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
639 // Disregard malformed spans and assume a one-byte wide character.
640 if sp.lo() >= sp.hi() {
641 debug!("find_width_of_character_at_span: early return malformed span");
645 let local_begin = self.lookup_byte_offset(sp.lo());
646 let local_end = self.lookup_byte_offset(sp.hi());
647 debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
648 local_begin, local_end);
650 let start_index = local_begin.pos.to_usize();
651 let end_index = local_end.pos.to_usize();
652 debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
653 start_index, end_index);
655 // Disregard indexes that are at the start or end of their spans, they can't fit bigger
657 if (!forwards && end_index == usize::min_value()) ||
658 (forwards && start_index == usize::max_value()) {
659 debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
663 let source_len = (local_begin.fm.end_pos - local_begin.fm.start_pos).to_usize();
664 debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
665 // Ensure indexes are also not malformed.
666 if start_index > end_index || end_index > source_len {
667 debug!("find_width_of_character_at_span: source indexes are malformed");
671 // We need to extend the snippet to the end of the src rather than to end_index so when
672 // searching forwards for boundaries we've got somewhere to search.
673 let snippet = if let Some(ref src) = local_begin.fm.src {
675 (&src[start_index..len]).to_string()
676 } else if let Some(src) = local_begin.fm.external_src.borrow().get_source() {
678 (&src[start_index..len]).to_string()
682 debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
684 let file_start_pos = local_begin.fm.start_pos.to_usize();
685 let file_end_pos = local_begin.fm.end_pos.to_usize();
686 debug!("find_width_of_character_at_span: file_start_pos=`{:?}` file_end_pos=`{:?}`",
687 file_start_pos, file_end_pos);
689 let mut target = if forwards { end_index + 1 } else { end_index - 1 };
690 debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
692 while !snippet.is_char_boundary(target - start_index)
693 && target >= file_start_pos && target <= file_end_pos {
694 target = if forwards { target + 1 } else { target - 1 };
695 debug!("find_width_of_character_at_span: target=`{:?}`", target);
697 debug!("find_width_of_character_at_span: final target=`{:?}`", target);
700 (target - end_index) as u32
702 (end_index - target) as u32
706 pub fn get_filemap(&self, filename: &FileName) -> Option<Rc<FileMap>> {
707 for fm in self.files.borrow().iter() {
708 if *filename == fm.name {
709 return Some(fm.clone());
715 /// For a global BytePos compute the local offset within the containing FileMap
716 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
717 let idx = self.lookup_filemap_idx(bpos);
718 let fm = (*self.files.borrow())[idx].clone();
719 let offset = bpos - fm.start_pos;
720 FileMapAndBytePos {fm: fm, pos: offset}
723 /// Converts an absolute BytePos to a CharPos relative to the filemap.
724 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
725 let idx = self.lookup_filemap_idx(bpos);
726 let files = self.files.borrow();
727 let map = &(*files)[idx];
729 // The number of extra bytes due to multibyte chars in the FileMap
730 let mut total_extra_bytes = 0;
732 for mbc in map.multibyte_chars.borrow().iter() {
733 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
735 // every character is at least one byte, so we only
736 // count the actual extra bytes.
737 total_extra_bytes += mbc.bytes - 1;
738 // We should never see a byte position in the middle of a
740 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
746 assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
747 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
750 // Return the index of the filemap (in self.files) which contains pos.
751 pub fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
752 let files = self.files.borrow();
754 let count = files.len();
756 // Binary search for the filemap.
761 if files[m].start_pos > pos {
768 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
773 pub fn count_lines(&self) -> usize {
774 self.files().iter().fold(0, |a, f| a + f.count_lines())
778 impl CodeMapper for CodeMap {
779 fn lookup_char_pos(&self, pos: BytePos) -> Loc {
780 self.lookup_char_pos(pos)
782 fn span_to_lines(&self, sp: Span) -> FileLinesResult {
783 self.span_to_lines(sp)
785 fn span_to_string(&self, sp: Span) -> String {
786 self.span_to_string(sp)
788 fn span_to_filename(&self, sp: Span) -> FileName {
789 self.span_to_filename(sp)
791 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
792 self.merge_spans(sp_lhs, sp_rhs)
794 fn call_span_if_macro(&self, sp: Span) -> Span {
795 if self.span_to_filename(sp.clone()).is_macros() {
796 let v = sp.macro_backtrace();
797 if let Some(use_site) = v.last() {
798 return use_site.call_site;
803 fn ensure_filemap_source_present(&self, file_map: Rc<FileMap>) -> bool {
804 file_map.add_external_src(
805 || match file_map.name {
806 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
811 fn doctest_offset_line(&self, line: usize) -> usize {
812 self.doctest_offset_line(line)
817 pub struct FilePathMapping {
818 mapping: Vec<(PathBuf, PathBuf)>,
821 impl FilePathMapping {
822 pub fn empty() -> FilePathMapping {
828 pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
834 /// Applies any path prefix substitution as defined by the mapping.
835 /// The return value is the remapped path and a boolean indicating whether
836 /// the path was affected by the mapping.
837 pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
838 // NOTE: We are iterating over the mapping entries from last to first
839 // because entries specified later on the command line should
841 for &(ref from, ref to) in self.mapping.iter().rev() {
842 if let Ok(rest) = path.strip_prefix(from) {
843 return (to.join(rest), true);
851 // _____________________________________________________________________________
858 use std::borrow::Cow;
863 let cm = CodeMap::new(FilePathMapping::empty());
864 let fm = cm.new_filemap(PathBuf::from("blork.rs").into(),
865 "first line.\nsecond line".to_string());
866 fm.next_line(BytePos(0));
867 // Test we can get lines with partial line info.
868 assert_eq!(fm.get_line(0), Some(Cow::from("first line.")));
869 // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
870 fm.next_line(BytePos(10));
871 assert_eq!(fm.get_line(1), Some(Cow::from(".")));
872 fm.next_line(BytePos(12));
873 assert_eq!(fm.get_line(2), Some(Cow::from("second line")));
879 let cm = CodeMap::new(FilePathMapping::empty());
880 let fm = cm.new_filemap(PathBuf::from("blork.rs").into(),
881 "first line.\nsecond line".to_string());
882 // TESTING *REALLY* BROKEN BEHAVIOR:
883 fm.next_line(BytePos(0));
884 fm.next_line(BytePos(10));
885 fm.next_line(BytePos(2));
888 fn init_code_map() -> CodeMap {
889 let cm = CodeMap::new(FilePathMapping::empty());
890 let fm1 = cm.new_filemap(PathBuf::from("blork.rs").into(),
891 "first line.\nsecond line".to_string());
892 let fm2 = cm.new_filemap(PathBuf::from("empty.rs").into(),
894 let fm3 = cm.new_filemap(PathBuf::from("blork2.rs").into(),
895 "first line.\nsecond line".to_string());
897 fm1.next_line(BytePos(0));
898 fm1.next_line(BytePos(12));
899 fm2.next_line(fm2.start_pos);
900 fm3.next_line(fm3.start_pos);
901 fm3.next_line(fm3.start_pos + BytePos(12));
908 // Test lookup_byte_offset
909 let cm = init_code_map();
911 let fmabp1 = cm.lookup_byte_offset(BytePos(23));
912 assert_eq!(fmabp1.fm.name, PathBuf::from("blork.rs").into());
913 assert_eq!(fmabp1.pos, BytePos(23));
915 let fmabp1 = cm.lookup_byte_offset(BytePos(24));
916 assert_eq!(fmabp1.fm.name, PathBuf::from("empty.rs").into());
917 assert_eq!(fmabp1.pos, BytePos(0));
919 let fmabp2 = cm.lookup_byte_offset(BytePos(25));
920 assert_eq!(fmabp2.fm.name, PathBuf::from("blork2.rs").into());
921 assert_eq!(fmabp2.pos, BytePos(0));
926 // Test bytepos_to_file_charpos
927 let cm = init_code_map();
929 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
930 assert_eq!(cp1, CharPos(22));
932 let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
933 assert_eq!(cp2, CharPos(0));
938 // Test zero-length filemaps.
939 let cm = init_code_map();
941 let loc1 = cm.lookup_char_pos(BytePos(22));
942 assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
943 assert_eq!(loc1.line, 2);
944 assert_eq!(loc1.col, CharPos(10));
946 let loc2 = cm.lookup_char_pos(BytePos(25));
947 assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
948 assert_eq!(loc2.line, 1);
949 assert_eq!(loc2.col, CharPos(0));
952 fn init_code_map_mbc() -> CodeMap {
953 let cm = CodeMap::new(FilePathMapping::empty());
954 // € is a three byte utf8 char.
956 cm.new_filemap(PathBuf::from("blork.rs").into(),
957 "fir€st €€€€ line.\nsecond line".to_string());
958 let fm2 = cm.new_filemap(PathBuf::from("blork2.rs").into(),
959 "first line€€.\n€ second line".to_string());
961 fm1.next_line(BytePos(0));
962 fm1.next_line(BytePos(28));
963 fm2.next_line(fm2.start_pos);
964 fm2.next_line(fm2.start_pos + BytePos(20));
966 fm1.record_multibyte_char(BytePos(3), 3);
967 fm1.record_multibyte_char(BytePos(9), 3);
968 fm1.record_multibyte_char(BytePos(12), 3);
969 fm1.record_multibyte_char(BytePos(15), 3);
970 fm1.record_multibyte_char(BytePos(18), 3);
971 fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
972 fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
973 fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
980 // Test bytepos_to_file_charpos in the presence of multi-byte chars
981 let cm = init_code_map_mbc();
983 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
984 assert_eq!(cp1, CharPos(3));
986 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
987 assert_eq!(cp2, CharPos(4));
989 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
990 assert_eq!(cp3, CharPos(12));
992 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
993 assert_eq!(cp4, CharPos(15));
998 // Test span_to_lines for a span ending at the end of filemap
999 let cm = init_code_map();
1000 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1001 let file_lines = cm.span_to_lines(span).unwrap();
1003 assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
1004 assert_eq!(file_lines.lines.len(), 1);
1005 assert_eq!(file_lines.lines[0].line_index, 1);
1008 /// Given a string like " ~~~~~~~~~~~~ ", produces a span
1009 /// converting that range. The idea is that the string has the same
1010 /// length as the input, and we uncover the byte positions. Note
1011 /// that this can span lines and so on.
1012 fn span_from_selection(input: &str, selection: &str) -> Span {
1013 assert_eq!(input.len(), selection.len());
1014 let left_index = selection.find('~').unwrap() as u32;
1015 let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
1016 Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
1019 /// Test span_to_snippet and span_to_lines for a span converting 3
1020 /// lines in the middle of a file.
1022 fn span_to_snippet_and_lines_spanning_multiple_lines() {
1023 let cm = CodeMap::new(FilePathMapping::empty());
1024 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1025 let selection = " \n ~~\n~~~\n~~~~~ \n \n";
1026 cm.new_filemap_and_lines(Path::new("blork.rs"), inputtext);
1027 let span = span_from_selection(inputtext, selection);
1029 // check that we are extracting the text we thought we were extracting
1030 assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1032 // check that span_to_lines gives us the complete result with the lines/cols we expected
1033 let lines = cm.span_to_lines(span).unwrap();
1034 let expected = vec![
1035 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1036 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1037 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1039 assert_eq!(lines.lines, expected);
1044 // Test span_to_snippet for a span ending at the end of filemap
1045 let cm = init_code_map();
1046 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1047 let snippet = cm.span_to_snippet(span);
1049 assert_eq!(snippet, Ok("second line".to_string()));
1054 // Test span_to_str for a span ending at the end of filemap
1055 let cm = init_code_map();
1056 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1057 let sstr = cm.span_to_string(span);
1059 assert_eq!(sstr, "blork.rs:2:1: 2:12");
1062 /// Test failing to merge two spans on different lines
1064 fn span_merging_fail() {
1065 let cm = CodeMap::new(FilePathMapping::empty());
1066 let inputtext = "bbbb BB\ncc CCC\n";
1067 let selection1 = " ~~\n \n";
1068 let selection2 = " \n ~~~\n";
1069 cm.new_filemap_and_lines(Path::new("blork.rs"), inputtext);
1070 let span1 = span_from_selection(inputtext, selection1);
1071 let span2 = span_from_selection(inputtext, selection2);
1073 assert!(cm.merge_spans(span1, span2).is_none());
1076 /// Returns the span corresponding to the `n`th occurrence of
1077 /// `substring` in `source_text`.
1078 trait CodeMapExtension {
1079 fn span_substr(&self,
1087 impl CodeMapExtension for CodeMap {
1088 fn span_substr(&self,
1095 println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
1096 file.name, file.start_pos, substring, n);
1100 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
1101 panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
1102 source_text, n, substring, i);
1104 let lo = hi + offset;
1105 hi = lo + substring.len();
1107 let span = Span::new(
1108 BytePos(lo as u32 + file.start_pos.0),
1109 BytePos(hi as u32 + file.start_pos.0),
1112 assert_eq!(&self.span_to_snippet(span).unwrap()[..],