]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/codemap.rs
Replace Rc with Lrc for shared data
[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 rustc_data_structures::sync::Lrc;
28 use std::cell::{RefCell, Ref};
29 use std::cmp;
30 use std::hash::Hash;
31 use std::path::{Path, PathBuf};
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<Lrc<FileMap>>>,
130     file_loader: Box<FileLoader>,
131     // This is used to apply the file path remapping as specified via
132     // --remap-path-prefix to all FileMaps allocated within this CodeMap.
133     path_mapping: FilePathMapping,
134     stable_id_to_filemap: RefCell<FxHashMap<StableFilemapId, Lrc<FileMap>>>,
135     /// In case we are in a doctest, replace all file names with the PathBuf,
136     /// and add the given offsets to the line info
137     doctest_offset: Option<(FileName, isize)>,
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<Lrc<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<Lrc<FileMap>>> {
191         self.files.borrow()
192     }
193
194     pub fn filemap_by_stable_id(&self, stable_id: StableFilemapId) -> Option<Lrc<FileMap>> {
195         self.stable_id_to_filemap.borrow().get(&stable_id).map(|fm| fm.clone())
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) -> Lrc<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 = Lrc::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) -> Lrc<FileMap> {
247         let fm = self.new_filemap(filename.to_owned().into(), src.to_owned());
248         let mut byte_pos: u32 = fm.start_pos.0;
249         for line in src.lines() {
250             // register the start of this line
251             fm.next_line(BytePos(byte_pos));
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                                 -> Lrc<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 = Lrc::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)
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, Lrc<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         format!("{}:{}:{}: {}:{}",
466                         lo.filename,
467                         lo.line,
468                         lo.col.to_usize() + 1,
469                         hi.line,
470                         hi.col.to_usize() + 1)
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`, get a new `Span` covering the first token and all its trailing whitespace or
597     /// the original `Span`.
598     ///
599     /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
600     pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
601         if let Ok(snippet) = self.span_to_snippet(sp) {
602             let mut offset = 0;
603             // get the bytes width of all the non-whitespace characters
604             for c in snippet.chars().take_while(|c| !c.is_whitespace()) {
605                 offset += c.len_utf8();
606             }
607             // get the bytes width of all the whitespace characters after that
608             for c in snippet[offset..].chars().take_while(|c| c.is_whitespace()) {
609                 offset += c.len_utf8();
610             }
611             if offset > 1 {
612                 return sp.with_hi(BytePos(sp.lo().0 + offset as u32));
613             }
614         }
615         sp
616     }
617
618     /// Given a `Span`, try to get a shorter span ending just after the first occurrence of `char`
619     /// `c`.
620     pub fn span_through_char(&self, sp: Span, c: char) -> Span {
621         if let Ok(snippet) = self.span_to_snippet(sp) {
622             if let Some(offset) = snippet.find(c) {
623                 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
624             }
625         }
626         sp
627     }
628
629     pub fn def_span(&self, sp: Span) -> Span {
630         self.span_until_char(sp, '{')
631     }
632
633     /// Returns a new span representing just the end-point of this span
634     pub fn end_point(&self, sp: Span) -> Span {
635         let pos = sp.hi().0;
636
637         let width = self.find_width_of_character_at_span(sp, false);
638         let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
639
640         let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
641         sp.with_lo(end_point)
642     }
643
644     /// Returns a new span representing the next character after the end-point of this span
645     pub fn next_point(&self, sp: Span) -> Span {
646         let start_of_next_point = sp.hi().0;
647
648         let width = self.find_width_of_character_at_span(sp, true);
649         // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
650         // in the case of a multibyte character, where the width != 1, the next span should
651         // span multiple bytes to include the whole character.
652         let end_of_next_point = start_of_next_point.checked_add(
653             width - 1).unwrap_or(start_of_next_point);
654
655         let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
656         Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
657     }
658
659     /// Finds the width of a character, either before or after the provided span.
660     fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
661         // Disregard malformed spans and assume a one-byte wide character.
662         if sp.lo() >= sp.hi() {
663             debug!("find_width_of_character_at_span: early return malformed span");
664             return 1;
665         }
666
667         let local_begin = self.lookup_byte_offset(sp.lo());
668         let local_end = self.lookup_byte_offset(sp.hi());
669         debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
670                local_begin, local_end);
671
672         let start_index = local_begin.pos.to_usize();
673         let end_index = local_end.pos.to_usize();
674         debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
675                start_index, end_index);
676
677         // Disregard indexes that are at the start or end of their spans, they can't fit bigger
678         // characters.
679         if (!forwards && end_index == usize::min_value()) ||
680             (forwards && start_index == usize::max_value()) {
681             debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
682             return 1;
683         }
684
685         let source_len = (local_begin.fm.end_pos - local_begin.fm.start_pos).to_usize();
686         debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
687         // Ensure indexes are also not malformed.
688         if start_index > end_index || end_index > source_len {
689             debug!("find_width_of_character_at_span: source indexes are malformed");
690             return 1;
691         }
692
693         let src = local_begin.fm.external_src.borrow();
694
695         // We need to extend the snippet to the end of the src rather than to end_index so when
696         // searching forwards for boundaries we've got somewhere to search.
697         let snippet = if let Some(ref src) = local_begin.fm.src {
698             let len = src.len();
699             (&src[start_index..len])
700         } else if let Some(src) = src.get_source() {
701             let len = src.len();
702             (&src[start_index..len])
703         } else {
704             return 1;
705         };
706         debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
707
708         let mut target = if forwards { end_index + 1 } else { end_index - 1 };
709         debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
710
711         while !snippet.is_char_boundary(target - start_index) && target < source_len {
712             target = if forwards {
713                 target + 1
714             } else {
715                 match target.checked_sub(1) {
716                     Some(target) => target,
717                     None => {
718                         break;
719                     }
720                 }
721             };
722             debug!("find_width_of_character_at_span: target=`{:?}`", target);
723         }
724         debug!("find_width_of_character_at_span: final target=`{:?}`", target);
725
726         if forwards {
727             (target - end_index) as u32
728         } else {
729             (end_index - target) as u32
730         }
731     }
732
733     pub fn get_filemap(&self, filename: &FileName) -> Option<Lrc<FileMap>> {
734         for fm in self.files.borrow().iter() {
735             if *filename == fm.name {
736                 return Some(fm.clone());
737             }
738         }
739         None
740     }
741
742     /// For a global BytePos compute the local offset within the containing FileMap
743     pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
744         let idx = self.lookup_filemap_idx(bpos);
745         let fm = (*self.files.borrow())[idx].clone();
746         let offset = bpos - fm.start_pos;
747         FileMapAndBytePos {fm: fm, pos: offset}
748     }
749
750     /// Converts an absolute BytePos to a CharPos relative to the filemap.
751     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
752         let idx = self.lookup_filemap_idx(bpos);
753         let files = self.files.borrow();
754         let map = &(*files)[idx];
755
756         // The number of extra bytes due to multibyte chars in the FileMap
757         let mut total_extra_bytes = 0;
758
759         for mbc in map.multibyte_chars.borrow().iter() {
760             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
761             if mbc.pos < bpos {
762                 // every character is at least one byte, so we only
763                 // count the actual extra bytes.
764                 total_extra_bytes += mbc.bytes - 1;
765                 // We should never see a byte position in the middle of a
766                 // character
767                 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
768             } else {
769                 break;
770             }
771         }
772
773         assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
774         CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
775     }
776
777     // Return the index of the filemap (in self.files) which contains pos.
778     pub fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
779         let files = self.files.borrow();
780         let files = &*files;
781         let count = files.len();
782
783         // Binary search for the filemap.
784         let mut a = 0;
785         let mut b = count;
786         while b - a > 1 {
787             let m = (a + b) / 2;
788             if files[m].start_pos > pos {
789                 b = m;
790             } else {
791                 a = m;
792             }
793         }
794
795         assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
796
797         return a;
798     }
799
800     pub fn count_lines(&self) -> usize {
801         self.files().iter().fold(0, |a, f| a + f.count_lines())
802     }
803 }
804
805 impl CodeMapper for CodeMap {
806     fn lookup_char_pos(&self, pos: BytePos) -> Loc {
807         self.lookup_char_pos(pos)
808     }
809     fn span_to_lines(&self, sp: Span) -> FileLinesResult {
810         self.span_to_lines(sp)
811     }
812     fn span_to_string(&self, sp: Span) -> String {
813         self.span_to_string(sp)
814     }
815     fn span_to_filename(&self, sp: Span) -> FileName {
816         self.span_to_filename(sp)
817     }
818     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
819         self.merge_spans(sp_lhs, sp_rhs)
820     }
821     fn call_span_if_macro(&self, sp: Span) -> Span {
822         if self.span_to_filename(sp.clone()).is_macros() {
823             let v = sp.macro_backtrace();
824             if let Some(use_site) = v.last() {
825                 return use_site.call_site;
826             }
827         }
828         sp
829     }
830     fn ensure_filemap_source_present(&self, file_map: Lrc<FileMap>) -> bool {
831         file_map.add_external_src(
832             || match file_map.name {
833                 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
834                 _ => None,
835             }
836         )
837     }
838     fn doctest_offset_line(&self, line: usize) -> usize {
839         self.doctest_offset_line(line)
840     }
841 }
842
843 #[derive(Clone)]
844 pub struct FilePathMapping {
845     mapping: Vec<(PathBuf, PathBuf)>,
846 }
847
848 impl FilePathMapping {
849     pub fn empty() -> FilePathMapping {
850         FilePathMapping {
851             mapping: vec![]
852         }
853     }
854
855     pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
856         FilePathMapping {
857             mapping,
858         }
859     }
860
861     /// Applies any path prefix substitution as defined by the mapping.
862     /// The return value is the remapped path and a boolean indicating whether
863     /// the path was affected by the mapping.
864     pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
865         // NOTE: We are iterating over the mapping entries from last to first
866         //       because entries specified later on the command line should
867         //       take precedence.
868         for &(ref from, ref to) in self.mapping.iter().rev() {
869             if let Ok(rest) = path.strip_prefix(from) {
870                 return (to.join(rest), true);
871             }
872         }
873
874         (path, false)
875     }
876 }
877
878 // _____________________________________________________________________________
879 // Tests
880 //
881
882 #[cfg(test)]
883 mod tests {
884     use super::*;
885     use std::borrow::Cow;
886     use rustc_data_structures::sync::Lrc;
887
888     #[test]
889     fn t1 () {
890         let cm = CodeMap::new(FilePathMapping::empty());
891         let fm = cm.new_filemap(PathBuf::from("blork.rs").into(),
892                                 "first line.\nsecond line".to_string());
893         fm.next_line(BytePos(0));
894         // Test we can get lines with partial line info.
895         assert_eq!(fm.get_line(0), Some(Cow::from("first line.")));
896         // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
897         fm.next_line(BytePos(10));
898         assert_eq!(fm.get_line(1), Some(Cow::from(".")));
899         fm.next_line(BytePos(12));
900         assert_eq!(fm.get_line(2), Some(Cow::from("second line")));
901     }
902
903     #[test]
904     #[should_panic]
905     fn t2 () {
906         let cm = CodeMap::new(FilePathMapping::empty());
907         let fm = cm.new_filemap(PathBuf::from("blork.rs").into(),
908                                 "first line.\nsecond line".to_string());
909         // TESTING *REALLY* BROKEN BEHAVIOR:
910         fm.next_line(BytePos(0));
911         fm.next_line(BytePos(10));
912         fm.next_line(BytePos(2));
913     }
914
915     fn init_code_map() -> CodeMap {
916         let cm = CodeMap::new(FilePathMapping::empty());
917         let fm1 = cm.new_filemap(PathBuf::from("blork.rs").into(),
918                                  "first line.\nsecond line".to_string());
919         let fm2 = cm.new_filemap(PathBuf::from("empty.rs").into(),
920                                  "".to_string());
921         let fm3 = cm.new_filemap(PathBuf::from("blork2.rs").into(),
922                                  "first line.\nsecond line".to_string());
923
924         fm1.next_line(BytePos(0));
925         fm1.next_line(BytePos(12));
926         fm2.next_line(fm2.start_pos);
927         fm3.next_line(fm3.start_pos);
928         fm3.next_line(fm3.start_pos + BytePos(12));
929
930         cm
931     }
932
933     #[test]
934     fn t3() {
935         // Test lookup_byte_offset
936         let cm = init_code_map();
937
938         let fmabp1 = cm.lookup_byte_offset(BytePos(23));
939         assert_eq!(fmabp1.fm.name, PathBuf::from("blork.rs").into());
940         assert_eq!(fmabp1.pos, BytePos(23));
941
942         let fmabp1 = cm.lookup_byte_offset(BytePos(24));
943         assert_eq!(fmabp1.fm.name, PathBuf::from("empty.rs").into());
944         assert_eq!(fmabp1.pos, BytePos(0));
945
946         let fmabp2 = cm.lookup_byte_offset(BytePos(25));
947         assert_eq!(fmabp2.fm.name, PathBuf::from("blork2.rs").into());
948         assert_eq!(fmabp2.pos, BytePos(0));
949     }
950
951     #[test]
952     fn t4() {
953         // Test bytepos_to_file_charpos
954         let cm = init_code_map();
955
956         let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
957         assert_eq!(cp1, CharPos(22));
958
959         let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
960         assert_eq!(cp2, CharPos(0));
961     }
962
963     #[test]
964     fn t5() {
965         // Test zero-length filemaps.
966         let cm = init_code_map();
967
968         let loc1 = cm.lookup_char_pos(BytePos(22));
969         assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
970         assert_eq!(loc1.line, 2);
971         assert_eq!(loc1.col, CharPos(10));
972
973         let loc2 = cm.lookup_char_pos(BytePos(25));
974         assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
975         assert_eq!(loc2.line, 1);
976         assert_eq!(loc2.col, CharPos(0));
977     }
978
979     fn init_code_map_mbc() -> CodeMap {
980         let cm = CodeMap::new(FilePathMapping::empty());
981         // € is a three byte utf8 char.
982         let fm1 =
983             cm.new_filemap(PathBuf::from("blork.rs").into(),
984                            "fir€st €€€€ line.\nsecond line".to_string());
985         let fm2 = cm.new_filemap(PathBuf::from("blork2.rs").into(),
986                                  "first line€€.\n€ second line".to_string());
987
988         fm1.next_line(BytePos(0));
989         fm1.next_line(BytePos(28));
990         fm2.next_line(fm2.start_pos);
991         fm2.next_line(fm2.start_pos + BytePos(20));
992
993         fm1.record_multibyte_char(BytePos(3), 3);
994         fm1.record_multibyte_char(BytePos(9), 3);
995         fm1.record_multibyte_char(BytePos(12), 3);
996         fm1.record_multibyte_char(BytePos(15), 3);
997         fm1.record_multibyte_char(BytePos(18), 3);
998         fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
999         fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
1000         fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
1001
1002         cm
1003     }
1004
1005     #[test]
1006     fn t6() {
1007         // Test bytepos_to_file_charpos in the presence of multi-byte chars
1008         let cm = init_code_map_mbc();
1009
1010         let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
1011         assert_eq!(cp1, CharPos(3));
1012
1013         let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
1014         assert_eq!(cp2, CharPos(4));
1015
1016         let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
1017         assert_eq!(cp3, CharPos(12));
1018
1019         let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
1020         assert_eq!(cp4, CharPos(15));
1021     }
1022
1023     #[test]
1024     fn t7() {
1025         // Test span_to_lines for a span ending at the end of filemap
1026         let cm = init_code_map();
1027         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1028         let file_lines = cm.span_to_lines(span).unwrap();
1029
1030         assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
1031         assert_eq!(file_lines.lines.len(), 1);
1032         assert_eq!(file_lines.lines[0].line_index, 1);
1033     }
1034
1035     /// Given a string like " ~~~~~~~~~~~~ ", produces a span
1036     /// converting that range. The idea is that the string has the same
1037     /// length as the input, and we uncover the byte positions.  Note
1038     /// that this can span lines and so on.
1039     fn span_from_selection(input: &str, selection: &str) -> Span {
1040         assert_eq!(input.len(), selection.len());
1041         let left_index = selection.find('~').unwrap() as u32;
1042         let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
1043         Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
1044     }
1045
1046     /// Test span_to_snippet and span_to_lines for a span converting 3
1047     /// lines in the middle of a file.
1048     #[test]
1049     fn span_to_snippet_and_lines_spanning_multiple_lines() {
1050         let cm = CodeMap::new(FilePathMapping::empty());
1051         let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1052         let selection = "     \n    ~~\n~~~\n~~~~~     \n   \n";
1053         cm.new_filemap_and_lines(Path::new("blork.rs"), inputtext);
1054         let span = span_from_selection(inputtext, selection);
1055
1056         // check that we are extracting the text we thought we were extracting
1057         assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1058
1059         // check that span_to_lines gives us the complete result with the lines/cols we expected
1060         let lines = cm.span_to_lines(span).unwrap();
1061         let expected = vec![
1062             LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1063             LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1064             LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1065             ];
1066         assert_eq!(lines.lines, expected);
1067     }
1068
1069     #[test]
1070     fn t8() {
1071         // Test span_to_snippet for a span ending at the end of filemap
1072         let cm = init_code_map();
1073         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1074         let snippet = cm.span_to_snippet(span);
1075
1076         assert_eq!(snippet, Ok("second line".to_string()));
1077     }
1078
1079     #[test]
1080     fn t9() {
1081         // Test span_to_str for a span ending at the end of filemap
1082         let cm = init_code_map();
1083         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1084         let sstr =  cm.span_to_string(span);
1085
1086         assert_eq!(sstr, "blork.rs:2:1: 2:12");
1087     }
1088
1089     /// Test failing to merge two spans on different lines
1090     #[test]
1091     fn span_merging_fail() {
1092         let cm = CodeMap::new(FilePathMapping::empty());
1093         let inputtext  = "bbbb BB\ncc CCC\n";
1094         let selection1 = "     ~~\n      \n";
1095         let selection2 = "       \n   ~~~\n";
1096         cm.new_filemap_and_lines(Path::new("blork.rs"), inputtext);
1097         let span1 = span_from_selection(inputtext, selection1);
1098         let span2 = span_from_selection(inputtext, selection2);
1099
1100         assert!(cm.merge_spans(span1, span2).is_none());
1101     }
1102
1103     /// Returns the span corresponding to the `n`th occurrence of
1104     /// `substring` in `source_text`.
1105     trait CodeMapExtension {
1106         fn span_substr(&self,
1107                     file: &Lrc<FileMap>,
1108                     source_text: &str,
1109                     substring: &str,
1110                     n: usize)
1111                     -> Span;
1112     }
1113
1114     impl CodeMapExtension for CodeMap {
1115         fn span_substr(&self,
1116                     file: &Lrc<FileMap>,
1117                     source_text: &str,
1118                     substring: &str,
1119                     n: usize)
1120                     -> Span
1121         {
1122             println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
1123                     file.name, file.start_pos, substring, n);
1124             let mut i = 0;
1125             let mut hi = 0;
1126             loop {
1127                 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
1128                     panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
1129                         source_text, n, substring, i);
1130                 });
1131                 let lo = hi + offset;
1132                 hi = lo + substring.len();
1133                 if i == n {
1134                     let span = Span::new(
1135                         BytePos(lo as u32 + file.start_pos.0),
1136                         BytePos(hi as u32 + file.start_pos.0),
1137                         NO_EXPANSION,
1138                     );
1139                     assert_eq!(&self.span_to_snippet(span).unwrap()[..],
1140                             substring);
1141                     return span;
1142                 }
1143                 i += 1;
1144             }
1145         }
1146     }
1147 }