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.
20 pub use syntax_pos::*;
21 pub use syntax_pos::hygiene::{ExpnFormat, ExpnInfo, NameAndSpan};
22 pub use self::ExpnFormat::*;
24 use std::cell::{RefCell, Ref};
25 use std::path::{Path, PathBuf};
30 use std::io::{self, Read};
31 use errors::CodeMapper;
33 /// Return the span itself if it doesn't come from a macro expansion,
34 /// otherwise return the call site span up to the `enclosing_sp` by
35 /// following the `expn_info` chain.
36 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
37 let call_site1 = sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
38 let call_site2 = enclosing_sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
39 match (call_site1, call_site2) {
41 (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
42 (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
46 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
47 pub struct Spanned<T> {
52 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
53 Spanned {node: t, span: sp}
56 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
60 // _____________________________________________________________________________
61 // FileMap, MultiByteChar, FileName, FileLines
64 /// An abstraction over the fs operations used by the Parser.
65 pub trait FileLoader {
66 /// Query the existence of a file.
67 fn file_exists(&self, path: &Path) -> bool;
69 /// Return an absolute path to a file, if possible.
70 fn abs_path(&self, path: &Path) -> Option<PathBuf>;
72 /// Read the contents of an UTF-8 file into memory.
73 fn read_file(&self, path: &Path) -> io::Result<String>;
76 /// A FileLoader that uses std::fs to load real files.
77 pub struct RealFileLoader;
79 impl FileLoader for RealFileLoader {
80 fn file_exists(&self, path: &Path) -> bool {
81 fs::metadata(path).is_ok()
84 fn abs_path(&self, path: &Path) -> Option<PathBuf> {
85 if path.is_absolute() {
86 Some(path.to_path_buf())
90 .map(|cwd| cwd.join(path))
94 fn read_file(&self, path: &Path) -> io::Result<String> {
95 let mut src = String::new();
96 fs::File::open(path)?.read_to_string(&mut src)?;
101 // _____________________________________________________________________________
106 pub(super) files: RefCell<Vec<Rc<FileMap>>>,
107 file_loader: Box<FileLoader>,
108 // This is used to apply the file path remapping as specified via
109 // -Zremap-path-prefix to all FileMaps allocated within this CodeMap.
110 path_mapping: FilePathMapping,
114 pub fn new(path_mapping: FilePathMapping) -> CodeMap {
116 files: RefCell::new(Vec::new()),
117 file_loader: Box::new(RealFileLoader),
122 pub fn with_file_loader(file_loader: Box<FileLoader>,
123 path_mapping: FilePathMapping)
126 files: RefCell::new(Vec::new()),
132 pub fn path_mapping(&self) -> &FilePathMapping {
136 pub fn file_exists(&self, path: &Path) -> bool {
137 self.file_loader.file_exists(path)
140 pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> {
141 let src = self.file_loader.read_file(path)?;
142 Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
145 pub fn files(&self) -> Ref<Vec<Rc<FileMap>>> {
149 fn next_start_pos(&self) -> usize {
150 let files = self.files.borrow();
153 // Add one so there is some space between files. This lets us distinguish
154 // positions in the codemap, even in the presence of zero-length files.
155 Some(last) => last.end_pos.to_usize() + 1,
159 /// Creates a new filemap without setting its line information. If you don't
160 /// intend to set the line information yourself, you should use new_filemap_and_lines.
161 pub fn new_filemap(&self, filename: FileName, src: String) -> Rc<FileMap> {
162 let start_pos = self.next_start_pos();
163 let mut files = self.files.borrow_mut();
165 // The path is used to determine the directory for loading submodules and
166 // include files, so it must be before remapping.
167 // Note that filename may not be a valid path, eg it may be `<anon>` etc,
168 // but this is okay because the directory determined by `path.pop()` will
169 // be empty, so the working directory will be used.
170 let unmapped_path = PathBuf::from(filename.clone());
172 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
173 let filemap = Rc::new(FileMap::new(
178 Pos::from_usize(start_pos),
181 files.push(filemap.clone());
186 /// Creates a new filemap and sets its line information.
187 pub fn new_filemap_and_lines(&self, filename: &str, src: &str) -> Rc<FileMap> {
188 let fm = self.new_filemap(filename.to_string(), src.to_owned());
189 let mut byte_pos: u32 = fm.start_pos.0;
190 for line in src.lines() {
191 // register the start of this line
192 fm.next_line(BytePos(byte_pos));
194 // update byte_pos to include this line and the \n at the end
195 byte_pos += line.len() as u32 + 1;
201 /// Allocates a new FileMap representing a source file from an external
202 /// crate. The source code of such an "imported filemap" is not available,
203 /// but we still know enough to generate accurate debuginfo location
204 /// information for things inlined from other crates.
205 pub fn new_imported_filemap(&self,
207 name_was_remapped: bool,
208 crate_of_origin: u32,
211 mut file_local_lines: Vec<BytePos>,
212 mut file_local_multibyte_chars: Vec<MultiByteChar>)
214 let start_pos = self.next_start_pos();
215 let mut files = self.files.borrow_mut();
217 let end_pos = Pos::from_usize(start_pos + source_len);
218 let start_pos = Pos::from_usize(start_pos);
220 for pos in &mut file_local_lines {
221 *pos = *pos + start_pos;
224 for mbc in &mut file_local_multibyte_chars {
225 mbc.pos = mbc.pos + start_pos;
228 let filemap = Rc::new(FileMap {
235 external_src: RefCell::new(ExternalSource::AbsentOk),
238 lines: RefCell::new(file_local_lines),
239 multibyte_chars: RefCell::new(file_local_multibyte_chars),
242 files.push(filemap.clone());
247 pub fn mk_substr_filename(&self, sp: Span) -> String {
248 let pos = self.lookup_char_pos(sp.lo());
249 (format!("<{}:{}:{}>",
252 pos.col.to_usize() + 1)).to_string()
255 /// Lookup source information about a BytePos
256 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
257 let chpos = self.bytepos_to_file_charpos(pos);
258 match self.lookup_line(pos) {
259 Ok(FileMapAndLine { fm: f, line: a }) => {
260 let line = a + 1; // Line numbers start at 1
261 let linebpos = (*f.lines.borrow())[a];
262 let linechpos = self.bytepos_to_file_charpos(linebpos);
263 debug!("byte pos {:?} is on the line at byte pos {:?}",
265 debug!("char pos {:?} is on the line at char pos {:?}",
267 debug!("byte is on line: {}", line);
268 assert!(chpos >= linechpos);
272 col: chpos - linechpos,
285 // If the relevant filemap is empty, we don't return a line number.
286 fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> {
287 let idx = self.lookup_filemap_idx(pos);
289 let files = self.files.borrow();
290 let f = (*files)[idx].clone();
292 match f.lookup_line(pos) {
293 Some(line) => Ok(FileMapAndLine { fm: f, line: line }),
298 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
299 let loc = self.lookup_char_pos(pos);
301 filename: loc.file.name.to_string(),
308 /// Returns `Some(span)`, a union of the lhs and rhs span. The lhs must precede the rhs. If
309 /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
310 /// For this to work, the spans have to be:
311 /// * the ctxt of both spans much match
312 /// * the lhs span needs to end on the same line the rhs span begins
313 /// * the lhs span must start at or before the rhs span
314 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
315 // make sure we're at the same expansion id
316 if sp_lhs.ctxt() != sp_rhs.ctxt() {
320 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
322 Err(_) => return None
324 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
326 Err(_) => return None
329 // if we must cross lines to merge, don't merge
330 if lhs_end.line != rhs_begin.line {
334 // ensure these follow the expected order and we don't overlap
335 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
336 Some(sp_lhs.to(sp_rhs))
342 pub fn span_to_string(&self, sp: Span) -> String {
343 if self.files.borrow().is_empty() && sp.source_equal(&DUMMY_SP) {
344 return "no-location".to_string();
347 let lo = self.lookup_char_pos_adj(sp.lo());
348 let hi = self.lookup_char_pos_adj(sp.hi());
349 return (format!("{}:{}:{}: {}:{}",
352 lo.col.to_usize() + 1,
354 hi.col.to_usize() + 1)).to_string()
357 pub fn span_to_filename(&self, sp: Span) -> FileName {
358 self.lookup_char_pos(sp.lo()).file.name.clone()
361 pub fn span_to_unmapped_path(&self, sp: Span) -> PathBuf {
362 self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
363 .expect("CodeMap::span_to_unmapped_path called for imported FileMap?")
366 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
367 debug!("span_to_lines(sp={:?})", sp);
369 if sp.lo() > sp.hi() {
370 return Err(SpanLinesError::IllFormedSpan(sp));
373 let lo = self.lookup_char_pos(sp.lo());
374 debug!("span_to_lines: lo={:?}", lo);
375 let hi = self.lookup_char_pos(sp.hi());
376 debug!("span_to_lines: hi={:?}", hi);
378 if lo.file.start_pos != hi.file.start_pos {
379 return Err(SpanLinesError::DistinctSources(DistinctSources {
380 begin: (lo.file.name.clone(), lo.file.start_pos),
381 end: (hi.file.name.clone(), hi.file.start_pos),
384 assert!(hi.line >= lo.line);
386 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
388 // The span starts partway through the first line,
389 // but after that it starts from offset 0.
390 let mut start_col = lo.col;
392 // For every line but the last, it extends from `start_col`
393 // and to the end of the line. Be careful because the line
394 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
396 for line_index in lo.line-1 .. hi.line-1 {
397 let line_len = lo.file.get_line(line_index)
398 .map(|s| s.chars().count())
400 lines.push(LineInfo { line_index,
402 end_col: CharPos::from_usize(line_len) });
403 start_col = CharPos::from_usize(0);
406 // For the last line, it extends from `start_col` to `hi.col`:
407 lines.push(LineInfo { line_index: hi.line - 1,
411 Ok(FileLines {file: lo.file, lines: lines})
414 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
415 if sp.lo() > sp.hi() {
416 return Err(SpanSnippetError::IllFormedSpan(sp));
419 let local_begin = self.lookup_byte_offset(sp.lo());
420 let local_end = self.lookup_byte_offset(sp.hi());
422 if local_begin.fm.start_pos != local_end.fm.start_pos {
423 return Err(SpanSnippetError::DistinctSources(DistinctSources {
424 begin: (local_begin.fm.name.clone(),
425 local_begin.fm.start_pos),
426 end: (local_end.fm.name.clone(),
427 local_end.fm.start_pos)
430 self.ensure_filemap_source_present(local_begin.fm.clone());
432 let start_index = local_begin.pos.to_usize();
433 let end_index = local_end.pos.to_usize();
434 let source_len = (local_begin.fm.end_pos -
435 local_begin.fm.start_pos).to_usize();
437 if start_index > end_index || end_index > source_len {
438 return Err(SpanSnippetError::MalformedForCodemap(
439 MalformedCodemapPositions {
440 name: local_begin.fm.name.clone(),
442 begin_pos: local_begin.pos,
443 end_pos: local_end.pos,
447 if let Some(ref src) = local_begin.fm.src {
448 return Ok((&src[start_index..end_index]).to_string());
449 } else if let Some(src) = local_begin.fm.external_src.borrow().get_source() {
450 return Ok((&src[start_index..end_index]).to_string());
452 return Err(SpanSnippetError::SourceNotAvailable {
453 filename: local_begin.fm.name.clone()
459 /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
460 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
461 match self.span_to_snippet(sp) {
463 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right();
464 if !snippet.is_empty() && !snippet.contains('\n') {
465 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
474 pub fn def_span(&self, sp: Span) -> Span {
475 self.span_until_char(sp, '{')
478 pub fn get_filemap(&self, filename: &str) -> Option<Rc<FileMap>> {
479 for fm in self.files.borrow().iter() {
480 if filename == fm.name {
481 return Some(fm.clone());
487 /// For a global BytePos compute the local offset within the containing FileMap
488 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
489 let idx = self.lookup_filemap_idx(bpos);
490 let fm = (*self.files.borrow())[idx].clone();
491 let offset = bpos - fm.start_pos;
492 FileMapAndBytePos {fm: fm, pos: offset}
495 /// Converts an absolute BytePos to a CharPos relative to the filemap.
496 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
497 let idx = self.lookup_filemap_idx(bpos);
498 let files = self.files.borrow();
499 let map = &(*files)[idx];
501 // The number of extra bytes due to multibyte chars in the FileMap
502 let mut total_extra_bytes = 0;
504 for mbc in map.multibyte_chars.borrow().iter() {
505 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
507 // every character is at least one byte, so we only
508 // count the actual extra bytes.
509 total_extra_bytes += mbc.bytes - 1;
510 // We should never see a byte position in the middle of a
512 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
518 assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
519 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
522 // Return the index of the filemap (in self.files) which contains pos.
523 pub fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
524 let files = self.files.borrow();
526 let count = files.len();
528 // Binary search for the filemap.
533 if files[m].start_pos > pos {
540 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
545 pub fn count_lines(&self) -> usize {
546 self.files().iter().fold(0, |a, f| a + f.count_lines())
550 impl CodeMapper for CodeMap {
551 fn lookup_char_pos(&self, pos: BytePos) -> Loc {
552 self.lookup_char_pos(pos)
554 fn span_to_lines(&self, sp: Span) -> FileLinesResult {
555 self.span_to_lines(sp)
557 fn span_to_string(&self, sp: Span) -> String {
558 self.span_to_string(sp)
560 fn span_to_filename(&self, sp: Span) -> FileName {
561 self.span_to_filename(sp)
563 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
564 self.merge_spans(sp_lhs, sp_rhs)
566 fn call_span_if_macro(&self, sp: Span) -> Span {
567 if self.span_to_filename(sp.clone()).contains("macros>") {
568 let v = sp.macro_backtrace();
569 if let Some(use_site) = v.last() {
570 return use_site.call_site;
575 fn ensure_filemap_source_present(&self, file_map: Rc<FileMap>) -> bool {
576 file_map.add_external_src(
577 || self.file_loader.read_file(Path::new(&file_map.name)).ok()
583 pub struct FilePathMapping {
584 mapping: Vec<(String, String)>,
587 impl FilePathMapping {
588 pub fn empty() -> FilePathMapping {
594 pub fn new(mapping: Vec<(String, String)>) -> FilePathMapping {
600 /// Applies any path prefix substitution as defined by the mapping.
601 /// The return value is the remapped path and a boolean indicating whether
602 /// the path was affected by the mapping.
603 pub fn map_prefix(&self, path: String) -> (String, bool) {
604 // NOTE: We are iterating over the mapping entries from last to first
605 // because entries specified later on the command line should
607 for &(ref from, ref to) in self.mapping.iter().rev() {
608 if path.starts_with(from) {
609 let mapped = path.replacen(from, to, 1);
610 return (mapped, true);
618 // _____________________________________________________________________________
625 use std::borrow::Cow;
630 let cm = CodeMap::new(FilePathMapping::empty());
631 let fm = cm.new_filemap("blork.rs".to_string(),
632 "first line.\nsecond line".to_string());
633 fm.next_line(BytePos(0));
634 // Test we can get lines with partial line info.
635 assert_eq!(fm.get_line(0), Some(Cow::from("first line.")));
636 // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
637 fm.next_line(BytePos(10));
638 assert_eq!(fm.get_line(1), Some(Cow::from(".")));
639 fm.next_line(BytePos(12));
640 assert_eq!(fm.get_line(2), Some(Cow::from("second line")));
646 let cm = CodeMap::new(FilePathMapping::empty());
647 let fm = cm.new_filemap("blork.rs".to_string(),
648 "first line.\nsecond line".to_string());
649 // TESTING *REALLY* BROKEN BEHAVIOR:
650 fm.next_line(BytePos(0));
651 fm.next_line(BytePos(10));
652 fm.next_line(BytePos(2));
655 fn init_code_map() -> CodeMap {
656 let cm = CodeMap::new(FilePathMapping::empty());
657 let fm1 = cm.new_filemap("blork.rs".to_string(),
658 "first line.\nsecond line".to_string());
659 let fm2 = cm.new_filemap("empty.rs".to_string(),
661 let fm3 = cm.new_filemap("blork2.rs".to_string(),
662 "first line.\nsecond line".to_string());
664 fm1.next_line(BytePos(0));
665 fm1.next_line(BytePos(12));
666 fm2.next_line(fm2.start_pos);
667 fm3.next_line(fm3.start_pos);
668 fm3.next_line(fm3.start_pos + BytePos(12));
675 // Test lookup_byte_offset
676 let cm = init_code_map();
678 let fmabp1 = cm.lookup_byte_offset(BytePos(23));
679 assert_eq!(fmabp1.fm.name, "blork.rs");
680 assert_eq!(fmabp1.pos, BytePos(23));
682 let fmabp1 = cm.lookup_byte_offset(BytePos(24));
683 assert_eq!(fmabp1.fm.name, "empty.rs");
684 assert_eq!(fmabp1.pos, BytePos(0));
686 let fmabp2 = cm.lookup_byte_offset(BytePos(25));
687 assert_eq!(fmabp2.fm.name, "blork2.rs");
688 assert_eq!(fmabp2.pos, BytePos(0));
693 // Test bytepos_to_file_charpos
694 let cm = init_code_map();
696 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
697 assert_eq!(cp1, CharPos(22));
699 let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
700 assert_eq!(cp2, CharPos(0));
705 // Test zero-length filemaps.
706 let cm = init_code_map();
708 let loc1 = cm.lookup_char_pos(BytePos(22));
709 assert_eq!(loc1.file.name, "blork.rs");
710 assert_eq!(loc1.line, 2);
711 assert_eq!(loc1.col, CharPos(10));
713 let loc2 = cm.lookup_char_pos(BytePos(25));
714 assert_eq!(loc2.file.name, "blork2.rs");
715 assert_eq!(loc2.line, 1);
716 assert_eq!(loc2.col, CharPos(0));
719 fn init_code_map_mbc() -> CodeMap {
720 let cm = CodeMap::new(FilePathMapping::empty());
721 // € is a three byte utf8 char.
723 cm.new_filemap("blork.rs".to_string(),
724 "fir€st €€€€ line.\nsecond line".to_string());
725 let fm2 = cm.new_filemap("blork2.rs".to_string(),
726 "first line€€.\n€ second line".to_string());
728 fm1.next_line(BytePos(0));
729 fm1.next_line(BytePos(28));
730 fm2.next_line(fm2.start_pos);
731 fm2.next_line(fm2.start_pos + BytePos(20));
733 fm1.record_multibyte_char(BytePos(3), 3);
734 fm1.record_multibyte_char(BytePos(9), 3);
735 fm1.record_multibyte_char(BytePos(12), 3);
736 fm1.record_multibyte_char(BytePos(15), 3);
737 fm1.record_multibyte_char(BytePos(18), 3);
738 fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
739 fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
740 fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
747 // Test bytepos_to_file_charpos in the presence of multi-byte chars
748 let cm = init_code_map_mbc();
750 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
751 assert_eq!(cp1, CharPos(3));
753 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
754 assert_eq!(cp2, CharPos(4));
756 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
757 assert_eq!(cp3, CharPos(12));
759 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
760 assert_eq!(cp4, CharPos(15));
765 // Test span_to_lines for a span ending at the end of filemap
766 let cm = init_code_map();
767 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
768 let file_lines = cm.span_to_lines(span).unwrap();
770 assert_eq!(file_lines.file.name, "blork.rs");
771 assert_eq!(file_lines.lines.len(), 1);
772 assert_eq!(file_lines.lines[0].line_index, 1);
775 /// Given a string like " ~~~~~~~~~~~~ ", produces a span
776 /// converting that range. The idea is that the string has the same
777 /// length as the input, and we uncover the byte positions. Note
778 /// that this can span lines and so on.
779 fn span_from_selection(input: &str, selection: &str) -> Span {
780 assert_eq!(input.len(), selection.len());
781 let left_index = selection.find('~').unwrap() as u32;
782 let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
783 Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
786 /// Test span_to_snippet and span_to_lines for a span converting 3
787 /// lines in the middle of a file.
789 fn span_to_snippet_and_lines_spanning_multiple_lines() {
790 let cm = CodeMap::new(FilePathMapping::empty());
791 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
792 let selection = " \n ~~\n~~~\n~~~~~ \n \n";
793 cm.new_filemap_and_lines("blork.rs", inputtext);
794 let span = span_from_selection(inputtext, selection);
796 // check that we are extracting the text we thought we were extracting
797 assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
799 // check that span_to_lines gives us the complete result with the lines/cols we expected
800 let lines = cm.span_to_lines(span).unwrap();
802 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
803 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
804 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
806 assert_eq!(lines.lines, expected);
811 // Test span_to_snippet for a span ending at the end of filemap
812 let cm = init_code_map();
813 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
814 let snippet = cm.span_to_snippet(span);
816 assert_eq!(snippet, Ok("second line".to_string()));
821 // Test span_to_str for a span ending at the end of filemap
822 let cm = init_code_map();
823 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
824 let sstr = cm.span_to_string(span);
826 assert_eq!(sstr, "blork.rs:2:1: 2:12");
829 /// Test failing to merge two spans on different lines
831 fn span_merging_fail() {
832 let cm = CodeMap::new(FilePathMapping::empty());
833 let inputtext = "bbbb BB\ncc CCC\n";
834 let selection1 = " ~~\n \n";
835 let selection2 = " \n ~~~\n";
836 cm.new_filemap_and_lines("blork.rs", inputtext);
837 let span1 = span_from_selection(inputtext, selection1);
838 let span2 = span_from_selection(inputtext, selection2);
840 assert!(cm.merge_spans(span1, span2).is_none());
843 /// Returns the span corresponding to the `n`th occurrence of
844 /// `substring` in `source_text`.
845 trait CodeMapExtension {
846 fn span_substr(&self,
854 impl CodeMapExtension for CodeMap {
855 fn span_substr(&self,
862 println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
863 file.name, file.start_pos, substring, n);
867 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
868 panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
869 source_text, n, substring, i);
871 let lo = hi + offset;
872 hi = lo + substring.len();
874 let span = Span::new(
875 BytePos(lo as u32 + file.start_pos.0),
876 BytePos(hi as u32 + file.start_pos.0),
879 assert_eq!(&self.span_to_snippet(span).unwrap()[..],