]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/codemap.rs
Add an unstable FileTypeExt extension trait for Windows
[rust.git] / src / libsyntax / codemap.rs
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.
4 //
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.
10
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.
19
20
21 pub use syntax_pos::*;
22 pub use syntax_pos::hygiene::{ExpnFormat, ExpnInfo, NameAndSpan};
23 pub use self::ExpnFormat::*;
24
25 use rustc_data_structures::fx::FxHashMap;
26 use rustc_data_structures::stable_hasher::StableHasher;
27 use std::cell::{RefCell, Ref};
28 use std::cmp;
29 use std::hash::Hash;
30 use std::path::{Path, PathBuf};
31 use std::rc::Rc;
32
33 use std::env;
34 use std::fs;
35 use std::io::{self, Read};
36 use errors::CodeMapper;
37
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) {
45         (None, _) => sp,
46         (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
47         (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
48     }
49 }
50
51 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
52 pub struct Spanned<T> {
53     pub node: T,
54     pub span: Span,
55 }
56
57 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
58     Spanned {node: t, span: sp}
59 }
60
61 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
62     respan(DUMMY_SP, t)
63 }
64
65 // _____________________________________________________________________________
66 // FileMap, MultiByteChar, FileName, FileLines
67 //
68
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;
73
74     /// Return an absolute path to a file, if possible.
75     fn abs_path(&self, path: &Path) -> Option<PathBuf>;
76
77     /// Read the contents of an UTF-8 file into memory.
78     fn read_file(&self, path: &Path) -> io::Result<String>;
79 }
80
81 /// A FileLoader that uses std::fs to load real files.
82 pub struct RealFileLoader;
83
84 impl FileLoader for RealFileLoader {
85     fn file_exists(&self, path: &Path) -> bool {
86         fs::metadata(path).is_ok()
87     }
88
89     fn abs_path(&self, path: &Path) -> Option<PathBuf> {
90         if path.is_absolute() {
91             Some(path.to_path_buf())
92         } else {
93             env::current_dir()
94                 .ok()
95                 .map(|cwd| cwd.join(path))
96         }
97     }
98
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)?;
102         Ok(src)
103     }
104 }
105
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);
111
112 impl StableFilemapId {
113     pub fn new(filemap: &FileMap) -> StableFilemapId {
114         let mut hasher = StableHasher::new();
115
116         filemap.name.hash(&mut hasher);
117         filemap.name_was_remapped.hash(&mut hasher);
118         filemap.unmapped_path.hash(&mut hasher);
119
120         StableFilemapId(hasher.finish())
121     }
122 }
123
124 // _____________________________________________________________________________
125 // CodeMap
126 //
127
128 pub struct CodeMap {
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)>,
138 }
139
140 impl CodeMap {
141     pub fn new(path_mapping: FilePathMapping) -> CodeMap {
142         CodeMap {
143             files: RefCell::new(Vec::new()),
144             file_loader: Box::new(RealFileLoader),
145             path_mapping,
146             stable_id_to_filemap: RefCell::new(FxHashMap()),
147             doctest_offset: None,
148         }
149     }
150
151     pub fn new_doctest(path_mapping: FilePathMapping,
152                        file: FileName, line: isize) -> CodeMap {
153         CodeMap {
154             doctest_offset: Some((file, line)),
155             ..CodeMap::new(path_mapping)
156         }
157
158     }
159
160     pub fn with_file_loader(file_loader: Box<FileLoader>,
161                             path_mapping: FilePathMapping)
162                             -> CodeMap {
163         CodeMap {
164             files: RefCell::new(Vec::new()),
165             file_loader,
166             path_mapping,
167             stable_id_to_filemap: RefCell::new(FxHashMap()),
168             doctest_offset: None,
169         }
170     }
171
172     pub fn path_mapping(&self) -> &FilePathMapping {
173         &self.path_mapping
174     }
175
176     pub fn file_exists(&self, path: &Path) -> bool {
177         self.file_loader.file_exists(path)
178     }
179
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 {
183             name.clone()
184         } else {
185             path.to_owned().into()
186         };
187         Ok(self.new_filemap(filename, src))
188     }
189
190     pub fn files(&self) -> Ref<Vec<Rc<FileMap>>> {
191         self.files.borrow()
192     }
193
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())
196     }
197
198     fn next_start_pos(&self) -> usize {
199         let files = self.files.borrow();
200         match files.last() {
201             None => 0,
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,
205         }
206     }
207
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();
213
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();
220
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)
225             },
226             other => (other, false),
227         };
228         let filemap = Rc::new(FileMap::new(
229             filename,
230             was_remapped,
231             unmapped_path,
232             src,
233             Pos::from_usize(start_pos),
234         ));
235
236         files.push(filemap.clone());
237
238         self.stable_id_to_filemap
239             .borrow_mut()
240             .insert(StableFilemapId::new(&filemap), filemap.clone());
241
242         filemap
243     }
244
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));
252
253             // update byte_pos to include this line and the \n at the end
254             byte_pos += line.len() as u32 + 1;
255         }
256         fm
257     }
258
259
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,
265                                 filename: FileName,
266                                 name_was_remapped: bool,
267                                 crate_of_origin: u32,
268                                 src_hash: u128,
269                                 name_hash: u128,
270                                 source_len: usize,
271                                 mut file_local_lines: Vec<BytePos>,
272                                 mut file_local_multibyte_chars: Vec<MultiByteChar>,
273                                 mut file_local_non_narrow_chars: Vec<NonNarrowChar>)
274                                 -> Rc<FileMap> {
275         let start_pos = self.next_start_pos();
276         let mut files = self.files.borrow_mut();
277
278         let end_pos = Pos::from_usize(start_pos + source_len);
279         let start_pos = Pos::from_usize(start_pos);
280
281         for pos in &mut file_local_lines {
282             *pos = *pos + start_pos;
283         }
284
285         for mbc in &mut file_local_multibyte_chars {
286             mbc.pos = mbc.pos + start_pos;
287         }
288
289         for swc in &mut file_local_non_narrow_chars {
290             *swc = *swc + start_pos;
291         }
292
293         let filemap = Rc::new(FileMap {
294             name: filename,
295             name_was_remapped,
296             unmapped_path: None,
297             crate_of_origin,
298             src: None,
299             src_hash,
300             external_src: RefCell::new(ExternalSource::AbsentOk),
301             start_pos,
302             end_pos,
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),
306             name_hash,
307         });
308
309         files.push(filemap.clone());
310
311         self.stable_id_to_filemap
312             .borrow_mut()
313             .insert(StableFilemapId::new(&filemap), filemap.clone());
314
315         filemap
316     }
317
318     pub fn mk_substr_filename(&self, sp: Span) -> String {
319         let pos = self.lookup_char_pos(sp.lo());
320         (format!("<{}:{}:{}>",
321                  pos.file.name,
322                  pos.line,
323                  pos.col.to_usize() + 1)).to_string()
324     }
325
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 {
329             if line >= 0 {
330                 orig = orig + line as usize;
331             } else {
332                 orig = orig - (-line) as usize;
333             }
334         }
335         orig
336     }
337
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;
347
348                 let col_display = {
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]
359                         .into_iter()
360                         .map(|x| x.width())
361                         .sum();
362                     col.0 - special_chars + non_narrow
363                 };
364                 debug!("byte pos {:?} is on the line at byte pos {:?}",
365                        pos, linebpos);
366                 debug!("char pos {:?} is on the line at char pos {:?}",
367                        chpos, linechpos);
368                 debug!("byte is on line: {}", line);
369                 assert!(chpos >= linechpos);
370                 Loc {
371                     file: f,
372                     line,
373                     col,
374                     col_display,
375                 }
376             }
377             Err(f) => {
378                 let col_display = {
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]
385                         .into_iter()
386                         .map(|x| x.width())
387                         .sum();
388                     chpos.0 - end_width_idx + non_narrow
389                 };
390                 Loc {
391                     file: f,
392                     line: 0,
393                     col: chpos,
394                     col_display,
395                 }
396             }
397         }
398     }
399
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);
403
404         let files = self.files.borrow();
405         let f = (*files)[idx].clone();
406
407         match f.lookup_line(pos) {
408             Some(line) => Ok(FileMapAndLine { fm: f, line: line }),
409             None => Err(f)
410         }
411     }
412
413     pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
414         let loc = self.lookup_char_pos(pos);
415         LocWithOpt {
416             filename: loc.file.name.clone(),
417             line: loc.line,
418             col: loc.col,
419             file: Some(loc.file)
420         }
421     }
422
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:
426     ///
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() {
433             return None;
434         }
435
436         let lhs_end = match self.lookup_line(sp_lhs.hi()) {
437             Ok(x) => x,
438             Err(_) => return None
439         };
440         let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
441             Ok(x) => x,
442             Err(_) => return None
443         };
444
445         // if we must cross lines to merge, don't merge
446         if lhs_end.line != rhs_begin.line {
447             return None;
448         }
449
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))
453         } else {
454             None
455         }
456     }
457
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();
461         }
462
463         let lo = self.lookup_char_pos_adj(sp.lo());
464         let hi = self.lookup_char_pos_adj(sp.hi());
465         return (format!("{}:{}:{}: {}:{}",
466                         lo.filename,
467                         lo.line,
468                         lo.col.to_usize() + 1,
469                         hi.line,
470                         hi.col.to_usize() + 1)).to_string()
471     }
472
473     pub fn span_to_filename(&self, sp: Span) -> FileName {
474         self.lookup_char_pos(sp.lo()).file.name.clone()
475     }
476
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?")
480     }
481
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());
485         lo.line != hi.line
486     }
487
488     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
489         debug!("span_to_lines(sp={:?})", sp);
490
491         if sp.lo() > sp.hi() {
492             return Err(SpanLinesError::IllFormedSpan(sp));
493         }
494
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);
499
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),
504             }));
505         }
506         assert!(hi.line >= lo.line);
507
508         let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
509
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;
513
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
517         // lines.
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())
521                                   .unwrap_or(0);
522             lines.push(LineInfo { line_index,
523                                   start_col,
524                                   end_col: CharPos::from_usize(line_len) });
525             start_col = CharPos::from_usize(0);
526         }
527
528         // For the last line, it extends from `start_col` to `hi.col`:
529         lines.push(LineInfo { line_index: hi.line - 1,
530                               start_col,
531                               end_col: hi.col });
532
533         Ok(FileLines {file: lo.file, lines: lines})
534     }
535
536     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
537         if sp.lo() > sp.hi() {
538             return Err(SpanSnippetError::IllFormedSpan(sp));
539         }
540
541         let local_begin = self.lookup_byte_offset(sp.lo());
542         let local_end = self.lookup_byte_offset(sp.hi());
543
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)
550             }));
551         } else {
552             self.ensure_filemap_source_present(local_begin.fm.clone());
553
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();
558
559             if start_index > end_index || end_index > source_len {
560                 return Err(SpanSnippetError::MalformedForCodemap(
561                     MalformedCodemapPositions {
562                         name: local_begin.fm.name.clone(),
563                         source_len,
564                         begin_pos: local_begin.pos,
565                         end_pos: local_end.pos,
566                     }));
567             }
568
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());
573             } else {
574                 return Err(SpanSnippetError::SourceNotAvailable {
575                     filename: local_begin.fm.name.clone()
576                 });
577             }
578         }
579     }
580
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) {
584             Ok(snippet) => {
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))
588                 } else {
589                     sp
590                 }
591             }
592             _ => sp,
593         }
594     }
595
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));
602             }
603         }
604         sp
605     }
606
607     pub fn def_span(&self, sp: Span) -> Span {
608         self.span_until_char(sp, '{')
609     }
610
611     /// Returns a new span representing just the end-point of this span
612     pub fn end_point(&self, sp: Span) -> Span {
613         let pos = sp.hi().0;
614
615         let width = self.find_width_of_character_at_span(sp, false);
616         let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
617
618         let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
619         sp.with_lo(end_point)
620     }
621
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;
625
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);
632
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())
635     }
636
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");
642             return 1;
643         }
644
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);
649
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);
654
655         // Disregard indexes that are at the start or end of their spans, they can't fit bigger
656         // characters.
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");
660             return 1;
661         }
662
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");
668             return 1;
669         }
670
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 {
674             let len = src.len();
675             (&src[start_index..len]).to_string()
676         } else if let Some(src) = local_begin.fm.external_src.borrow().get_source() {
677             let len = src.len();
678             (&src[start_index..len]).to_string()
679         } else {
680             return 1;
681         };
682         debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
683
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);
688
689         let mut target = if forwards { end_index + 1 } else { end_index - 1 };
690         debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
691
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);
696         }
697         debug!("find_width_of_character_at_span: final target=`{:?}`", target);
698
699         if forwards {
700             (target - end_index) as u32
701         } else {
702             (end_index - target) as u32
703         }
704     }
705
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());
710             }
711         }
712         None
713     }
714
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}
721     }
722
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];
728
729         // The number of extra bytes due to multibyte chars in the FileMap
730         let mut total_extra_bytes = 0;
731
732         for mbc in map.multibyte_chars.borrow().iter() {
733             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
734             if mbc.pos < bpos {
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
739                 // character
740                 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
741             } else {
742                 break;
743             }
744         }
745
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)
748     }
749
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();
753         let files = &*files;
754         let count = files.len();
755
756         // Binary search for the filemap.
757         let mut a = 0;
758         let mut b = count;
759         while b - a > 1 {
760             let m = (a + b) / 2;
761             if files[m].start_pos > pos {
762                 b = m;
763             } else {
764                 a = m;
765             }
766         }
767
768         assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
769
770         return a;
771     }
772
773     pub fn count_lines(&self) -> usize {
774         self.files().iter().fold(0, |a, f| a + f.count_lines())
775     }
776 }
777
778 impl CodeMapper for CodeMap {
779     fn lookup_char_pos(&self, pos: BytePos) -> Loc {
780         self.lookup_char_pos(pos)
781     }
782     fn span_to_lines(&self, sp: Span) -> FileLinesResult {
783         self.span_to_lines(sp)
784     }
785     fn span_to_string(&self, sp: Span) -> String {
786         self.span_to_string(sp)
787     }
788     fn span_to_filename(&self, sp: Span) -> FileName {
789         self.span_to_filename(sp)
790     }
791     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
792         self.merge_spans(sp_lhs, sp_rhs)
793     }
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;
799             }
800         }
801         sp
802     }
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(),
807                 _ => None,
808             }
809         )
810     }
811     fn doctest_offset_line(&self, line: usize) -> usize {
812         self.doctest_offset_line(line)
813     }
814 }
815
816 #[derive(Clone)]
817 pub struct FilePathMapping {
818     mapping: Vec<(PathBuf, PathBuf)>,
819 }
820
821 impl FilePathMapping {
822     pub fn empty() -> FilePathMapping {
823         FilePathMapping {
824             mapping: vec![]
825         }
826     }
827
828     pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
829         FilePathMapping {
830             mapping,
831         }
832     }
833
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
840         //       take precedence.
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);
844             }
845         }
846
847         (path, false)
848     }
849 }
850
851 // _____________________________________________________________________________
852 // Tests
853 //
854
855 #[cfg(test)]
856 mod tests {
857     use super::*;
858     use std::borrow::Cow;
859     use std::rc::Rc;
860
861     #[test]
862     fn t1 () {
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")));
874     }
875
876     #[test]
877     #[should_panic]
878     fn t2 () {
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));
886     }
887
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(),
893                                  "".to_string());
894         let fm3 = cm.new_filemap(PathBuf::from("blork2.rs").into(),
895                                  "first line.\nsecond line".to_string());
896
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));
902
903         cm
904     }
905
906     #[test]
907     fn t3() {
908         // Test lookup_byte_offset
909         let cm = init_code_map();
910
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));
914
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));
918
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));
922     }
923
924     #[test]
925     fn t4() {
926         // Test bytepos_to_file_charpos
927         let cm = init_code_map();
928
929         let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
930         assert_eq!(cp1, CharPos(22));
931
932         let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
933         assert_eq!(cp2, CharPos(0));
934     }
935
936     #[test]
937     fn t5() {
938         // Test zero-length filemaps.
939         let cm = init_code_map();
940
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));
945
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));
950     }
951
952     fn init_code_map_mbc() -> CodeMap {
953         let cm = CodeMap::new(FilePathMapping::empty());
954         // € is a three byte utf8 char.
955         let fm1 =
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());
960
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));
965
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);
974
975         cm
976     }
977
978     #[test]
979     fn t6() {
980         // Test bytepos_to_file_charpos in the presence of multi-byte chars
981         let cm = init_code_map_mbc();
982
983         let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
984         assert_eq!(cp1, CharPos(3));
985
986         let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
987         assert_eq!(cp2, CharPos(4));
988
989         let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
990         assert_eq!(cp3, CharPos(12));
991
992         let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
993         assert_eq!(cp4, CharPos(15));
994     }
995
996     #[test]
997     fn t7() {
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();
1002
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);
1006     }
1007
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)
1017     }
1018
1019     /// Test span_to_snippet and span_to_lines for a span converting 3
1020     /// lines in the middle of a file.
1021     #[test]
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);
1028
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");
1031
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) }
1038             ];
1039         assert_eq!(lines.lines, expected);
1040     }
1041
1042     #[test]
1043     fn t8() {
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);
1048
1049         assert_eq!(snippet, Ok("second line".to_string()));
1050     }
1051
1052     #[test]
1053     fn t9() {
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);
1058
1059         assert_eq!(sstr, "blork.rs:2:1: 2:12");
1060     }
1061
1062     /// Test failing to merge two spans on different lines
1063     #[test]
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);
1072
1073         assert!(cm.merge_spans(span1, span2).is_none());
1074     }
1075
1076     /// Returns the span corresponding to the `n`th occurrence of
1077     /// `substring` in `source_text`.
1078     trait CodeMapExtension {
1079         fn span_substr(&self,
1080                     file: &Rc<FileMap>,
1081                     source_text: &str,
1082                     substring: &str,
1083                     n: usize)
1084                     -> Span;
1085     }
1086
1087     impl CodeMapExtension for CodeMap {
1088         fn span_substr(&self,
1089                     file: &Rc<FileMap>,
1090                     source_text: &str,
1091                     substring: &str,
1092                     n: usize)
1093                     -> Span
1094         {
1095             println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
1096                     file.name, file.start_pos, substring, n);
1097             let mut i = 0;
1098             let mut hi = 0;
1099             loop {
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);
1103                 });
1104                 let lo = hi + offset;
1105                 hi = lo + substring.len();
1106                 if i == n {
1107                     let span = Span::new(
1108                         BytePos(lo as u32 + file.start_pos.0),
1109                         BytePos(hi as u32 + file.start_pos.0),
1110                         NO_EXPANSION,
1111                     );
1112                     assert_eq!(&self.span_to_snippet(span).unwrap()[..],
1113                             substring);
1114                     return span;
1115                 }
1116                 i += 1;
1117             }
1118         }
1119     }
1120 }