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 // The `files` field should not be visible outside of libsyntax so that we
107 // can do proper dependency tracking.
108 pub(super) files: RefCell<Vec<Rc<FileMap>>>,
109 file_loader: Box<FileLoader>,
110 // This is used to apply the file path remapping as specified via
111 // -Zremap-path-prefix to all FileMaps allocated within this CodeMap.
112 path_mapping: FilePathMapping,
113 // The CodeMap will invoke this callback whenever a specific FileMap is
114 // accessed. The callback starts out as a no-op but when the dependency
115 // graph becomes available later during the compilation process, it is
116 // be replaced with something that notifies the dep-tracking system.
117 dep_tracking_callback: RefCell<Box<Fn(&FileMap)>>,
121 pub fn new(path_mapping: FilePathMapping) -> CodeMap {
123 files: RefCell::new(Vec::new()),
124 file_loader: Box::new(RealFileLoader),
125 path_mapping: path_mapping,
126 dep_tracking_callback: RefCell::new(Box::new(|_| {})),
130 pub fn with_file_loader(file_loader: Box<FileLoader>,
131 path_mapping: FilePathMapping)
134 files: RefCell::new(Vec::new()),
135 file_loader: file_loader,
136 path_mapping: path_mapping,
137 dep_tracking_callback: RefCell::new(Box::new(|_| {})),
141 pub fn path_mapping(&self) -> &FilePathMapping {
145 pub fn set_dep_tracking_callback(&self, cb: Box<Fn(&FileMap)>) {
146 *self.dep_tracking_callback.borrow_mut() = cb;
149 pub fn file_exists(&self, path: &Path) -> bool {
150 self.file_loader.file_exists(path)
153 pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> {
154 let src = self.file_loader.read_file(path)?;
155 Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
158 pub fn files(&self) -> Ref<Vec<Rc<FileMap>>> {
159 let files = self.files.borrow();
160 for file in files.iter() {
161 (self.dep_tracking_callback.borrow())(file);
166 /// Only use this if you do your own dependency tracking!
167 pub fn files_untracked(&self) -> Ref<Vec<Rc<FileMap>>> {
171 fn next_start_pos(&self) -> usize {
172 let files = self.files.borrow();
175 // Add one so there is some space between files. This lets us distinguish
176 // positions in the codemap, even in the presence of zero-length files.
177 Some(last) => last.end_pos.to_usize() + 1,
181 /// Creates a new filemap without setting its line information. If you don't
182 /// intend to set the line information yourself, you should use new_filemap_and_lines.
183 pub fn new_filemap(&self, filename: FileName, mut src: String) -> Rc<FileMap> {
184 let start_pos = self.next_start_pos();
185 let mut files = self.files.borrow_mut();
187 // Remove utf-8 BOM if any.
188 if src.starts_with("\u{feff}") {
192 let end_pos = start_pos + src.len();
194 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
196 let filemap = Rc::new(FileMap {
198 name_was_remapped: was_remapped,
200 src: Some(Rc::new(src)),
201 start_pos: Pos::from_usize(start_pos),
202 end_pos: Pos::from_usize(end_pos),
203 lines: RefCell::new(Vec::new()),
204 multibyte_chars: RefCell::new(Vec::new()),
207 files.push(filemap.clone());
212 /// Creates a new filemap and sets its line information.
213 pub fn new_filemap_and_lines(&self, filename: &str, src: &str) -> Rc<FileMap> {
214 let fm = self.new_filemap(filename.to_string(), src.to_owned());
215 let mut byte_pos: u32 = fm.start_pos.0;
216 for line in src.lines() {
217 // register the start of this line
218 fm.next_line(BytePos(byte_pos));
220 // update byte_pos to include this line and the \n at the end
221 byte_pos += line.len() as u32 + 1;
227 /// Allocates a new FileMap representing a source file from an external
228 /// crate. The source code of such an "imported filemap" is not available,
229 /// but we still know enough to generate accurate debuginfo location
230 /// information for things inlined from other crates.
231 pub fn new_imported_filemap(&self,
233 name_was_remapped: bool,
234 crate_of_origin: u32,
236 mut file_local_lines: Vec<BytePos>,
237 mut file_local_multibyte_chars: Vec<MultiByteChar>)
239 let start_pos = self.next_start_pos();
240 let mut files = self.files.borrow_mut();
242 let end_pos = Pos::from_usize(start_pos + source_len);
243 let start_pos = Pos::from_usize(start_pos);
245 for pos in &mut file_local_lines {
246 *pos = *pos + start_pos;
249 for mbc in &mut file_local_multibyte_chars {
250 mbc.pos = mbc.pos + start_pos;
253 let filemap = Rc::new(FileMap {
255 name_was_remapped: name_was_remapped,
256 crate_of_origin: crate_of_origin,
258 start_pos: start_pos,
260 lines: RefCell::new(file_local_lines),
261 multibyte_chars: RefCell::new(file_local_multibyte_chars),
264 files.push(filemap.clone());
269 pub fn mk_substr_filename(&self, sp: Span) -> String {
270 let pos = self.lookup_char_pos(sp.lo);
271 (format!("<{}:{}:{}>",
274 pos.col.to_usize() + 1)).to_string()
277 /// Lookup source information about a BytePos
278 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
279 let chpos = self.bytepos_to_file_charpos(pos);
280 match self.lookup_line(pos) {
281 Ok(FileMapAndLine { fm: f, line: a }) => {
282 let line = a + 1; // Line numbers start at 1
283 let linebpos = (*f.lines.borrow())[a];
284 let linechpos = self.bytepos_to_file_charpos(linebpos);
285 debug!("byte pos {:?} is on the line at byte pos {:?}",
287 debug!("char pos {:?} is on the line at char pos {:?}",
289 debug!("byte is on line: {}", line);
290 assert!(chpos >= linechpos);
294 col: chpos - linechpos,
307 // If the relevant filemap is empty, we don't return a line number.
308 fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> {
309 let idx = self.lookup_filemap_idx(pos);
311 let files = self.files.borrow();
312 let f = (*files)[idx].clone();
314 (self.dep_tracking_callback.borrow())(&f);
316 match f.lookup_line(pos) {
317 Some(line) => Ok(FileMapAndLine { fm: f, line: line }),
322 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
323 let loc = self.lookup_char_pos(pos);
325 filename: loc.file.name.to_string(),
332 /// Returns `Some(span)`, a union of the lhs and rhs span. The lhs must precede the rhs. If
333 /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
334 /// For this to work, the spans have to be:
335 /// * the ctxt of both spans much match
336 /// * the lhs span needs to end on the same line the rhs span begins
337 /// * the lhs span must start at or before the rhs span
338 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
341 // make sure we're at the same expansion id
342 if sp_lhs.ctxt != sp_rhs.ctxt {
346 let lhs_end = match self.lookup_line(sp_lhs.hi) {
348 Err(_) => return None
350 let rhs_begin = match self.lookup_line(sp_rhs.lo) {
352 Err(_) => return None
355 // if we must cross lines to merge, don't merge
356 if lhs_end.line != rhs_begin.line {
360 // ensure these follow the expected order and we don't overlap
361 if (sp_lhs.lo <= sp_rhs.lo) && (sp_lhs.hi <= sp_rhs.lo) {
363 lo: cmp::min(sp_lhs.lo, sp_rhs.lo),
364 hi: cmp::max(sp_lhs.hi, sp_rhs.hi),
372 pub fn span_to_string(&self, sp: Span) -> String {
373 if self.files.borrow().is_empty() && sp.source_equal(&DUMMY_SP) {
374 return "no-location".to_string();
377 let lo = self.lookup_char_pos_adj(sp.lo);
378 let hi = self.lookup_char_pos_adj(sp.hi);
379 return (format!("{}:{}:{}: {}:{}",
382 lo.col.to_usize() + 1,
384 hi.col.to_usize() + 1)).to_string()
387 pub fn span_to_filename(&self, sp: Span) -> FileName {
388 self.lookup_char_pos(sp.lo).file.name.to_string()
391 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
392 debug!("span_to_lines(sp={:?})", sp);
395 return Err(SpanLinesError::IllFormedSpan(sp));
398 let lo = self.lookup_char_pos(sp.lo);
399 debug!("span_to_lines: lo={:?}", lo);
400 let hi = self.lookup_char_pos(sp.hi);
401 debug!("span_to_lines: hi={:?}", hi);
403 if lo.file.start_pos != hi.file.start_pos {
404 return Err(SpanLinesError::DistinctSources(DistinctSources {
405 begin: (lo.file.name.clone(), lo.file.start_pos),
406 end: (hi.file.name.clone(), hi.file.start_pos),
409 assert!(hi.line >= lo.line);
411 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
413 // The span starts partway through the first line,
414 // but after that it starts from offset 0.
415 let mut start_col = lo.col;
417 // For every line but the last, it extends from `start_col`
418 // and to the end of the line. Be careful because the line
419 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
421 for line_index in lo.line-1 .. hi.line-1 {
422 let line_len = lo.file.get_line(line_index)
423 .map(|s| s.chars().count())
425 lines.push(LineInfo { line_index: line_index,
426 start_col: start_col,
427 end_col: CharPos::from_usize(line_len) });
428 start_col = CharPos::from_usize(0);
431 // For the last line, it extends from `start_col` to `hi.col`:
432 lines.push(LineInfo { line_index: hi.line - 1,
433 start_col: start_col,
436 Ok(FileLines {file: lo.file, lines: lines})
439 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
441 return Err(SpanSnippetError::IllFormedSpan(sp));
444 let local_begin = self.lookup_byte_offset(sp.lo);
445 let local_end = self.lookup_byte_offset(sp.hi);
447 if local_begin.fm.start_pos != local_end.fm.start_pos {
448 return Err(SpanSnippetError::DistinctSources(DistinctSources {
449 begin: (local_begin.fm.name.clone(),
450 local_begin.fm.start_pos),
451 end: (local_end.fm.name.clone(),
452 local_end.fm.start_pos)
455 match local_begin.fm.src {
457 let start_index = local_begin.pos.to_usize();
458 let end_index = local_end.pos.to_usize();
459 let source_len = (local_begin.fm.end_pos -
460 local_begin.fm.start_pos).to_usize();
462 if start_index > end_index || end_index > source_len {
463 return Err(SpanSnippetError::MalformedForCodemap(
464 MalformedCodemapPositions {
465 name: local_begin.fm.name.clone(),
466 source_len: source_len,
467 begin_pos: local_begin.pos,
468 end_pos: local_end.pos,
472 return Ok((&src[start_index..end_index]).to_string())
475 return Err(SpanSnippetError::SourceNotAvailable {
476 filename: local_begin.fm.name.clone()
483 /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
484 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
485 match self.span_to_snippet(sp) {
487 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right();
488 if !snippet.is_empty() && !snippet.contains('\n') {
489 Span { hi: BytePos(sp.lo.0 + snippet.len() as u32), ..sp }
498 pub fn def_span(&self, sp: Span) -> Span {
499 self.span_until_char(sp, '{')
502 pub fn get_filemap(&self, filename: &str) -> Option<Rc<FileMap>> {
503 for fm in self.files.borrow().iter() {
504 if filename == fm.name {
505 (self.dep_tracking_callback.borrow())(fm);
506 return Some(fm.clone());
512 /// For a global BytePos compute the local offset within the containing FileMap
513 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
514 let idx = self.lookup_filemap_idx(bpos);
515 let fm = (*self.files.borrow())[idx].clone();
516 (self.dep_tracking_callback.borrow())(&fm);
517 let offset = bpos - fm.start_pos;
518 FileMapAndBytePos {fm: fm, pos: offset}
521 /// Converts an absolute BytePos to a CharPos relative to the filemap.
522 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
523 let idx = self.lookup_filemap_idx(bpos);
524 let files = self.files.borrow();
525 let map = &(*files)[idx];
527 (self.dep_tracking_callback.borrow())(map);
529 // The number of extra bytes due to multibyte chars in the FileMap
530 let mut total_extra_bytes = 0;
532 for mbc in map.multibyte_chars.borrow().iter() {
533 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
535 // every character is at least one byte, so we only
536 // count the actual extra bytes.
537 total_extra_bytes += mbc.bytes - 1;
538 // We should never see a byte position in the middle of a
540 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
546 assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
547 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
550 // Return the index of the filemap (in self.files) which contains pos.
551 pub fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
552 let files = self.files.borrow();
554 let count = files.len();
556 // Binary search for the filemap.
561 if files[m].start_pos > pos {
568 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
573 pub fn count_lines(&self) -> usize {
574 self.files().iter().fold(0, |a, f| a + f.count_lines())
578 impl CodeMapper for CodeMap {
579 fn lookup_char_pos(&self, pos: BytePos) -> Loc {
580 self.lookup_char_pos(pos)
582 fn span_to_lines(&self, sp: Span) -> FileLinesResult {
583 self.span_to_lines(sp)
585 fn span_to_string(&self, sp: Span) -> String {
586 self.span_to_string(sp)
588 fn span_to_filename(&self, sp: Span) -> FileName {
589 self.span_to_filename(sp)
591 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
592 self.merge_spans(sp_lhs, sp_rhs)
597 pub struct FilePathMapping {
598 mapping: Vec<(String, String)>,
601 impl FilePathMapping {
602 pub fn empty() -> FilePathMapping {
608 pub fn new(mapping: Vec<(String, String)>) -> FilePathMapping {
614 /// Applies any path prefix substitution as defined by the mapping.
615 /// The return value is the remapped path and a boolean indicating whether
616 /// the path was affected by the mapping.
617 pub fn map_prefix(&self, path: String) -> (String, bool) {
618 // NOTE: We are iterating over the mapping entries from last to first
619 // because entries specified later on the command line should
621 for &(ref from, ref to) in self.mapping.iter().rev() {
622 if path.starts_with(from) {
623 let mapped = path.replacen(from, to, 1);
624 return (mapped, true);
632 // _____________________________________________________________________________
643 let cm = CodeMap::new(FilePathMapping::empty());
644 let fm = cm.new_filemap("blork.rs".to_string(),
645 "first line.\nsecond line".to_string());
646 fm.next_line(BytePos(0));
647 // Test we can get lines with partial line info.
648 assert_eq!(fm.get_line(0), Some("first line."));
649 // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
650 fm.next_line(BytePos(10));
651 assert_eq!(fm.get_line(1), Some("."));
652 fm.next_line(BytePos(12));
653 assert_eq!(fm.get_line(2), Some("second line"));
659 let cm = CodeMap::new(FilePathMapping::empty());
660 let fm = cm.new_filemap("blork.rs".to_string(),
661 "first line.\nsecond line".to_string());
662 // TESTING *REALLY* BROKEN BEHAVIOR:
663 fm.next_line(BytePos(0));
664 fm.next_line(BytePos(10));
665 fm.next_line(BytePos(2));
668 fn init_code_map() -> CodeMap {
669 let cm = CodeMap::new(FilePathMapping::empty());
670 let fm1 = cm.new_filemap("blork.rs".to_string(),
671 "first line.\nsecond line".to_string());
672 let fm2 = cm.new_filemap("empty.rs".to_string(),
674 let fm3 = cm.new_filemap("blork2.rs".to_string(),
675 "first line.\nsecond line".to_string());
677 fm1.next_line(BytePos(0));
678 fm1.next_line(BytePos(12));
679 fm2.next_line(fm2.start_pos);
680 fm3.next_line(fm3.start_pos);
681 fm3.next_line(fm3.start_pos + BytePos(12));
688 // Test lookup_byte_offset
689 let cm = init_code_map();
691 let fmabp1 = cm.lookup_byte_offset(BytePos(23));
692 assert_eq!(fmabp1.fm.name, "blork.rs");
693 assert_eq!(fmabp1.pos, BytePos(23));
695 let fmabp1 = cm.lookup_byte_offset(BytePos(24));
696 assert_eq!(fmabp1.fm.name, "empty.rs");
697 assert_eq!(fmabp1.pos, BytePos(0));
699 let fmabp2 = cm.lookup_byte_offset(BytePos(25));
700 assert_eq!(fmabp2.fm.name, "blork2.rs");
701 assert_eq!(fmabp2.pos, BytePos(0));
706 // Test bytepos_to_file_charpos
707 let cm = init_code_map();
709 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
710 assert_eq!(cp1, CharPos(22));
712 let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
713 assert_eq!(cp2, CharPos(0));
718 // Test zero-length filemaps.
719 let cm = init_code_map();
721 let loc1 = cm.lookup_char_pos(BytePos(22));
722 assert_eq!(loc1.file.name, "blork.rs");
723 assert_eq!(loc1.line, 2);
724 assert_eq!(loc1.col, CharPos(10));
726 let loc2 = cm.lookup_char_pos(BytePos(25));
727 assert_eq!(loc2.file.name, "blork2.rs");
728 assert_eq!(loc2.line, 1);
729 assert_eq!(loc2.col, CharPos(0));
732 fn init_code_map_mbc() -> CodeMap {
733 let cm = CodeMap::new(FilePathMapping::empty());
734 // € is a three byte utf8 char.
736 cm.new_filemap("blork.rs".to_string(),
737 "fir€st €€€€ line.\nsecond line".to_string());
738 let fm2 = cm.new_filemap("blork2.rs".to_string(),
739 "first line€€.\n€ second line".to_string());
741 fm1.next_line(BytePos(0));
742 fm1.next_line(BytePos(28));
743 fm2.next_line(fm2.start_pos);
744 fm2.next_line(fm2.start_pos + BytePos(20));
746 fm1.record_multibyte_char(BytePos(3), 3);
747 fm1.record_multibyte_char(BytePos(9), 3);
748 fm1.record_multibyte_char(BytePos(12), 3);
749 fm1.record_multibyte_char(BytePos(15), 3);
750 fm1.record_multibyte_char(BytePos(18), 3);
751 fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
752 fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
753 fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
760 // Test bytepos_to_file_charpos in the presence of multi-byte chars
761 let cm = init_code_map_mbc();
763 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
764 assert_eq!(cp1, CharPos(3));
766 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
767 assert_eq!(cp2, CharPos(4));
769 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
770 assert_eq!(cp3, CharPos(12));
772 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
773 assert_eq!(cp4, CharPos(15));
778 // Test span_to_lines for a span ending at the end of filemap
779 let cm = init_code_map();
780 let span = Span {lo: BytePos(12), hi: BytePos(23), ctxt: NO_EXPANSION};
781 let file_lines = cm.span_to_lines(span).unwrap();
783 assert_eq!(file_lines.file.name, "blork.rs");
784 assert_eq!(file_lines.lines.len(), 1);
785 assert_eq!(file_lines.lines[0].line_index, 1);
788 /// Given a string like " ~~~~~~~~~~~~ ", produces a span
789 /// coverting that range. The idea is that the string has the same
790 /// length as the input, and we uncover the byte positions. Note
791 /// that this can span lines and so on.
792 fn span_from_selection(input: &str, selection: &str) -> Span {
793 assert_eq!(input.len(), selection.len());
794 let left_index = selection.find('~').unwrap() as u32;
795 let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
796 Span { lo: BytePos(left_index), hi: BytePos(right_index + 1), ctxt: NO_EXPANSION }
799 /// Test span_to_snippet and span_to_lines for a span coverting 3
800 /// lines in the middle of a file.
802 fn span_to_snippet_and_lines_spanning_multiple_lines() {
803 let cm = CodeMap::new(FilePathMapping::empty());
804 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
805 let selection = " \n ~~\n~~~\n~~~~~ \n \n";
806 cm.new_filemap_and_lines("blork.rs", inputtext);
807 let span = span_from_selection(inputtext, selection);
809 // check that we are extracting the text we thought we were extracting
810 assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
812 // check that span_to_lines gives us the complete result with the lines/cols we expected
813 let lines = cm.span_to_lines(span).unwrap();
815 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
816 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
817 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
819 assert_eq!(lines.lines, expected);
824 // Test span_to_snippet for a span ending at the end of filemap
825 let cm = init_code_map();
826 let span = Span {lo: BytePos(12), hi: BytePos(23), ctxt: NO_EXPANSION};
827 let snippet = cm.span_to_snippet(span);
829 assert_eq!(snippet, Ok("second line".to_string()));
834 // Test span_to_str for a span ending at the end of filemap
835 let cm = init_code_map();
836 let span = Span {lo: BytePos(12), hi: BytePos(23), ctxt: NO_EXPANSION};
837 let sstr = cm.span_to_string(span);
839 assert_eq!(sstr, "blork.rs:2:1: 2:12");
842 /// Test failing to merge two spans on different lines
844 fn span_merging_fail() {
845 let cm = CodeMap::new(FilePathMapping::empty());
846 let inputtext = "bbbb BB\ncc CCC\n";
847 let selection1 = " ~~\n \n";
848 let selection2 = " \n ~~~\n";
849 cm.new_filemap_and_lines("blork.rs", inputtext);
850 let span1 = span_from_selection(inputtext, selection1);
851 let span2 = span_from_selection(inputtext, selection2);
853 assert!(cm.merge_spans(span1, span2).is_none());
856 /// Returns the span corresponding to the `n`th occurrence of
857 /// `substring` in `source_text`.
858 trait CodeMapExtension {
859 fn span_substr(&self,
867 impl CodeMapExtension for CodeMap {
868 fn span_substr(&self,
875 println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
876 file.name, file.start_pos, substring, n);
880 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
881 panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
882 source_text, n, substring, i);
884 let lo = hi + offset;
885 hi = lo + substring.len();
888 lo: BytePos(lo as u32 + file.start_pos.0),
889 hi: BytePos(hi as u32 + file.start_pos.0),
892 assert_eq!(&self.span_to_snippet(span).unwrap()[..],