]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/source_map.rs
Auto merge of #54720 - davidtwco:issue-51191, r=nikomatsakis
[rust.git] / src / libsyntax / source_map.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 SourceMap 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 //! SourceMap and are represented by SourceFiles. Byte positions are stored in
16 //! `spans` and used pervasively in the compiler. They are absolute positions
17 //! within the SourceMap, 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};
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, Lock, LockGuard, MappedLockGuard};
28 use std::cmp;
29 use std::hash::Hash;
30 use std::path::{Path, PathBuf};
31
32 use std::env;
33 use std::fs;
34 use std::io::{self, Read};
35 use errors::SourceMapper;
36
37 /// Return the span itself if it doesn't come from a macro expansion,
38 /// otherwise return the call site span up to the `enclosing_sp` by
39 /// following the `expn_info` chain.
40 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
41     let call_site1 = sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
42     let call_site2 = enclosing_sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
43     match (call_site1, call_site2) {
44         (None, _) => sp,
45         (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
46         (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
47     }
48 }
49
50 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
51 pub struct Spanned<T> {
52     pub node: T,
53     pub span: Span,
54 }
55
56 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
57     Spanned {node: t, span: sp}
58 }
59
60 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
61     respan(DUMMY_SP, t)
62 }
63
64 // _____________________________________________________________________________
65 // SourceFile, MultiByteChar, FileName, FileLines
66 //
67
68 /// An abstraction over the fs operations used by the Parser.
69 pub trait FileLoader {
70     /// Query the existence of a file.
71     fn file_exists(&self, path: &Path) -> bool;
72
73     /// Return an absolute path to a file, if possible.
74     fn abs_path(&self, path: &Path) -> Option<PathBuf>;
75
76     /// Read the contents of an UTF-8 file into memory.
77     fn read_file(&self, path: &Path) -> io::Result<String>;
78 }
79
80 /// A FileLoader that uses std::fs to load real files.
81 pub struct RealFileLoader;
82
83 impl FileLoader for RealFileLoader {
84     fn file_exists(&self, path: &Path) -> bool {
85         fs::metadata(path).is_ok()
86     }
87
88     fn abs_path(&self, path: &Path) -> Option<PathBuf> {
89         if path.is_absolute() {
90             Some(path.to_path_buf())
91         } else {
92             env::current_dir()
93                 .ok()
94                 .map(|cwd| cwd.join(path))
95         }
96     }
97
98     fn read_file(&self, path: &Path) -> io::Result<String> {
99         let mut src = String::new();
100         fs::File::open(path)?.read_to_string(&mut src)?;
101         Ok(src)
102     }
103 }
104
105 // This is a SourceFile identifier that is used to correlate SourceFiles between
106 // subsequent compilation sessions (which is something we need to do during
107 // incremental compilation).
108 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
109 pub struct StableFilemapId(u128);
110
111 impl StableFilemapId {
112     pub fn new(source_file: &SourceFile) -> StableFilemapId {
113         let mut hasher = StableHasher::new();
114
115         source_file.name.hash(&mut hasher);
116         source_file.name_was_remapped.hash(&mut hasher);
117         source_file.unmapped_path.hash(&mut hasher);
118
119         StableFilemapId(hasher.finish())
120     }
121 }
122
123 // _____________________________________________________________________________
124 // SourceMap
125 //
126
127 pub(super) struct SourceMapFiles {
128     pub(super) file_maps: Vec<Lrc<SourceFile>>,
129     stable_id_to_source_file: FxHashMap<StableFilemapId, Lrc<SourceFile>>
130 }
131
132 pub struct SourceMap {
133     pub(super) files: Lock<SourceMapFiles>,
134     file_loader: Box<dyn FileLoader + Sync + Send>,
135     // This is used to apply the file path remapping as specified via
136     // --remap-path-prefix to all SourceFiles allocated within this SourceMap.
137     path_mapping: FilePathMapping,
138     /// In case we are in a doctest, replace all file names with the PathBuf,
139     /// and add the given offsets to the line info
140     doctest_offset: Option<(FileName, isize)>,
141 }
142
143 impl SourceMap {
144     pub fn new(path_mapping: FilePathMapping) -> SourceMap {
145         SourceMap {
146             files: Lock::new(SourceMapFiles {
147                 file_maps: Vec::new(),
148                 stable_id_to_source_file: FxHashMap(),
149             }),
150             file_loader: Box::new(RealFileLoader),
151             path_mapping,
152             doctest_offset: None,
153         }
154     }
155
156     pub fn new_doctest(path_mapping: FilePathMapping,
157                        file: FileName, line: isize) -> SourceMap {
158         SourceMap {
159             doctest_offset: Some((file, line)),
160             ..SourceMap::new(path_mapping)
161         }
162
163     }
164
165     pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
166                             path_mapping: FilePathMapping)
167                             -> SourceMap {
168         SourceMap {
169             files: Lock::new(SourceMapFiles {
170                 file_maps: Vec::new(),
171                 stable_id_to_source_file: FxHashMap(),
172             }),
173             file_loader: file_loader,
174             path_mapping,
175             doctest_offset: None,
176         }
177     }
178
179     pub fn path_mapping(&self) -> &FilePathMapping {
180         &self.path_mapping
181     }
182
183     pub fn file_exists(&self, path: &Path) -> bool {
184         self.file_loader.file_exists(path)
185     }
186
187     pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
188         let src = self.file_loader.read_file(path)?;
189         let filename = if let Some((ref name, _)) = self.doctest_offset {
190             name.clone()
191         } else {
192             path.to_owned().into()
193         };
194         Ok(self.new_source_file(filename, src))
195     }
196
197     pub fn files(&self) -> MappedLockGuard<Vec<Lrc<SourceFile>>> {
198         LockGuard::map(self.files.borrow(), |files| &mut files.file_maps)
199     }
200
201     pub fn source_file_by_stable_id(&self, stable_id: StableFilemapId) -> Option<Lrc<SourceFile>> {
202         self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|fm| fm.clone())
203     }
204
205     fn next_start_pos(&self) -> usize {
206         match self.files.borrow().file_maps.last() {
207             None => 0,
208             // Add one so there is some space between files. This lets us distinguish
209             // positions in the source_map, even in the presence of zero-length files.
210             Some(last) => last.end_pos.to_usize() + 1,
211         }
212     }
213
214     /// Creates a new source_file.
215     /// This does not ensure that only one SourceFile exists per file name.
216     pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
217         let start_pos = self.next_start_pos();
218
219         // The path is used to determine the directory for loading submodules and
220         // include files, so it must be before remapping.
221         // Note that filename may not be a valid path, eg it may be `<anon>` etc,
222         // but this is okay because the directory determined by `path.pop()` will
223         // be empty, so the working directory will be used.
224         let unmapped_path = filename.clone();
225
226         let (filename, was_remapped) = match filename {
227             FileName::Real(filename) => {
228                 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
229                 (FileName::Real(filename), was_remapped)
230             },
231             other => (other, false),
232         };
233         let source_file = Lrc::new(SourceFile::new(
234             filename,
235             was_remapped,
236             unmapped_path,
237             src,
238             Pos::from_usize(start_pos),
239         ));
240
241         let mut files = self.files.borrow_mut();
242
243         files.file_maps.push(source_file.clone());
244         files.stable_id_to_source_file.insert(StableFilemapId::new(&source_file),
245                                               source_file.clone());
246
247         source_file
248     }
249
250     /// Allocates a new SourceFile representing a source file from an external
251     /// crate. The source code of such an "imported source_file" is not available,
252     /// but we still know enough to generate accurate debuginfo location
253     /// information for things inlined from other crates.
254     pub fn new_imported_source_file(
255         &self,
256         filename: FileName,
257         name_was_remapped: bool,
258         crate_of_origin: u32,
259         src_hash: u128,
260         name_hash: u128,
261         source_len: usize,
262         mut file_local_lines: Vec<BytePos>,
263         mut file_local_multibyte_chars: Vec<MultiByteChar>,
264         mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
265     ) -> Lrc<SourceFile> {
266         let start_pos = self.next_start_pos();
267
268         let end_pos = Pos::from_usize(start_pos + source_len);
269         let start_pos = Pos::from_usize(start_pos);
270
271         for pos in &mut file_local_lines {
272             *pos = *pos + start_pos;
273         }
274
275         for mbc in &mut file_local_multibyte_chars {
276             mbc.pos = mbc.pos + start_pos;
277         }
278
279         for swc in &mut file_local_non_narrow_chars {
280             *swc = *swc + start_pos;
281         }
282
283         let source_file = Lrc::new(SourceFile {
284             name: filename,
285             name_was_remapped,
286             unmapped_path: None,
287             crate_of_origin,
288             src: None,
289             src_hash,
290             external_src: Lock::new(ExternalSource::AbsentOk),
291             start_pos,
292             end_pos,
293             lines: file_local_lines,
294             multibyte_chars: file_local_multibyte_chars,
295             non_narrow_chars: file_local_non_narrow_chars,
296             name_hash,
297         });
298
299         let mut files = self.files.borrow_mut();
300
301         files.file_maps.push(source_file.clone());
302         files.stable_id_to_source_file.insert(StableFilemapId::new(&source_file),
303                                               source_file.clone());
304
305         source_file
306     }
307
308     pub fn mk_substr_filename(&self, sp: Span) -> String {
309         let pos = self.lookup_char_pos(sp.lo());
310         format!("<{}:{}:{}>",
311                  pos.file.name,
312                  pos.line,
313                  pos.col.to_usize() + 1)
314     }
315
316     // If there is a doctest_offset, apply it to the line
317     pub fn doctest_offset_line(&self, mut orig: usize) -> usize {
318         if let Some((_, line)) = self.doctest_offset {
319             if line >= 0 {
320                 orig = orig + line as usize;
321             } else {
322                 orig = orig - (-line) as usize;
323             }
324         }
325         orig
326     }
327
328     /// Lookup source information about a BytePos
329     pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
330         let chpos = self.bytepos_to_file_charpos(pos);
331         match self.lookup_line(pos) {
332             Ok(SourceFileAndLine { fm: f, line: a }) => {
333                 let line = a + 1; // Line numbers start at 1
334                 let linebpos = f.lines[a];
335                 let linechpos = self.bytepos_to_file_charpos(linebpos);
336                 let col = chpos - linechpos;
337
338                 let col_display = {
339                     let start_width_idx = f
340                         .non_narrow_chars
341                         .binary_search_by_key(&linebpos, |x| x.pos())
342                         .unwrap_or_else(|x| x);
343                     let end_width_idx = f
344                         .non_narrow_chars
345                         .binary_search_by_key(&pos, |x| x.pos())
346                         .unwrap_or_else(|x| x);
347                     let special_chars = end_width_idx - start_width_idx;
348                     let non_narrow: usize = f
349                         .non_narrow_chars[start_width_idx..end_width_idx]
350                         .into_iter()
351                         .map(|x| x.width())
352                         .sum();
353                     col.0 - special_chars + non_narrow
354                 };
355                 debug!("byte pos {:?} is on the line at byte pos {:?}",
356                        pos, linebpos);
357                 debug!("char pos {:?} is on the line at char pos {:?}",
358                        chpos, linechpos);
359                 debug!("byte is on line: {}", line);
360                 assert!(chpos >= linechpos);
361                 Loc {
362                     file: f,
363                     line,
364                     col,
365                     col_display,
366                 }
367             }
368             Err(f) => {
369                 let col_display = {
370                     let end_width_idx = f
371                         .non_narrow_chars
372                         .binary_search_by_key(&pos, |x| x.pos())
373                         .unwrap_or_else(|x| x);
374                     let non_narrow: usize = f
375                         .non_narrow_chars[0..end_width_idx]
376                         .into_iter()
377                         .map(|x| x.width())
378                         .sum();
379                     chpos.0 - end_width_idx + non_narrow
380                 };
381                 Loc {
382                     file: f,
383                     line: 0,
384                     col: chpos,
385                     col_display,
386                 }
387             }
388         }
389     }
390
391     // If the relevant source_file is empty, we don't return a line number.
392     pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
393         let idx = self.lookup_source_file_idx(pos);
394
395         let f = (*self.files.borrow().file_maps)[idx].clone();
396
397         match f.lookup_line(pos) {
398             Some(line) => Ok(SourceFileAndLine { fm: f, line: line }),
399             None => Err(f)
400         }
401     }
402
403     pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
404         let loc = self.lookup_char_pos(pos);
405         LocWithOpt {
406             filename: loc.file.name.clone(),
407             line: loc.line,
408             col: loc.col,
409             file: Some(loc.file)
410         }
411     }
412
413     /// Returns `Some(span)`, a union of the lhs and rhs span.  The lhs must precede the rhs. If
414     /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
415     /// For this to work, the spans have to be:
416     ///
417     ///    * the ctxt of both spans much match
418     ///    * the lhs span needs to end on the same line the rhs span begins
419     ///    * the lhs span must start at or before the rhs span
420     pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
421         // make sure we're at the same expansion id
422         if sp_lhs.ctxt() != sp_rhs.ctxt() {
423             return None;
424         }
425
426         let lhs_end = match self.lookup_line(sp_lhs.hi()) {
427             Ok(x) => x,
428             Err(_) => return None
429         };
430         let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
431             Ok(x) => x,
432             Err(_) => return None
433         };
434
435         // if we must cross lines to merge, don't merge
436         if lhs_end.line != rhs_begin.line {
437             return None;
438         }
439
440         // ensure these follow the expected order and we don't overlap
441         if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
442             Some(sp_lhs.to(sp_rhs))
443         } else {
444             None
445         }
446     }
447
448     pub fn span_to_string(&self, sp: Span) -> String {
449         if self.files.borrow().file_maps.is_empty() && sp.is_dummy() {
450             return "no-location".to_string();
451         }
452
453         let lo = self.lookup_char_pos_adj(sp.lo());
454         let hi = self.lookup_char_pos_adj(sp.hi());
455         format!("{}:{}:{}: {}:{}",
456                         lo.filename,
457                         lo.line,
458                         lo.col.to_usize() + 1,
459                         hi.line,
460                         hi.col.to_usize() + 1)
461     }
462
463     pub fn span_to_filename(&self, sp: Span) -> FileName {
464         self.lookup_char_pos(sp.lo()).file.name.clone()
465     }
466
467     pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
468         self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
469             .expect("SourceMap::span_to_unmapped_path called for imported SourceFile?")
470     }
471
472     pub fn is_multiline(&self, sp: Span) -> bool {
473         let lo = self.lookup_char_pos(sp.lo());
474         let hi = self.lookup_char_pos(sp.hi());
475         lo.line != hi.line
476     }
477
478     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
479         debug!("span_to_lines(sp={:?})", sp);
480
481         if sp.lo() > sp.hi() {
482             return Err(SpanLinesError::IllFormedSpan(sp));
483         }
484
485         let lo = self.lookup_char_pos(sp.lo());
486         debug!("span_to_lines: lo={:?}", lo);
487         let hi = self.lookup_char_pos(sp.hi());
488         debug!("span_to_lines: hi={:?}", hi);
489
490         if lo.file.start_pos != hi.file.start_pos {
491             return Err(SpanLinesError::DistinctSources(DistinctSources {
492                 begin: (lo.file.name.clone(), lo.file.start_pos),
493                 end: (hi.file.name.clone(), hi.file.start_pos),
494             }));
495         }
496         assert!(hi.line >= lo.line);
497
498         let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
499
500         // The span starts partway through the first line,
501         // but after that it starts from offset 0.
502         let mut start_col = lo.col;
503
504         // For every line but the last, it extends from `start_col`
505         // and to the end of the line. Be careful because the line
506         // numbers in Loc are 1-based, so we subtract 1 to get 0-based
507         // lines.
508         for line_index in lo.line-1 .. hi.line-1 {
509             let line_len = lo.file.get_line(line_index)
510                                   .map(|s| s.chars().count())
511                                   .unwrap_or(0);
512             lines.push(LineInfo { line_index,
513                                   start_col,
514                                   end_col: CharPos::from_usize(line_len) });
515             start_col = CharPos::from_usize(0);
516         }
517
518         // For the last line, it extends from `start_col` to `hi.col`:
519         lines.push(LineInfo { line_index: hi.line - 1,
520                               start_col,
521                               end_col: hi.col });
522
523         Ok(FileLines {file: lo.file, lines: lines})
524     }
525
526     /// Extract the source surrounding the given `Span` using the `extract_source` function. The
527     /// extract function takes three arguments: a string slice containing the source, an index in
528     /// the slice for the beginning of the span and an index in the slice for the end of the span.
529     fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
530         where F: Fn(&str, usize, usize) -> String
531     {
532         if sp.lo() > sp.hi() {
533             return Err(SpanSnippetError::IllFormedSpan(sp));
534         }
535
536         let local_begin = self.lookup_byte_offset(sp.lo());
537         let local_end = self.lookup_byte_offset(sp.hi());
538
539         if local_begin.fm.start_pos != local_end.fm.start_pos {
540             return Err(SpanSnippetError::DistinctSources(DistinctSources {
541                 begin: (local_begin.fm.name.clone(),
542                         local_begin.fm.start_pos),
543                 end: (local_end.fm.name.clone(),
544                       local_end.fm.start_pos)
545             }));
546         } else {
547             self.ensure_source_file_source_present(local_begin.fm.clone());
548
549             let start_index = local_begin.pos.to_usize();
550             let end_index = local_end.pos.to_usize();
551             let source_len = (local_begin.fm.end_pos -
552                               local_begin.fm.start_pos).to_usize();
553
554             if start_index > end_index || end_index > source_len {
555                 return Err(SpanSnippetError::MalformedForCodemap(
556                     MalformedCodemapPositions {
557                         name: local_begin.fm.name.clone(),
558                         source_len,
559                         begin_pos: local_begin.pos,
560                         end_pos: local_end.pos,
561                     }));
562             }
563
564             if let Some(ref src) = local_begin.fm.src {
565                 return Ok(extract_source(src, start_index, end_index));
566             } else if let Some(src) = local_begin.fm.external_src.borrow().get_source() {
567                 return Ok(extract_source(src, start_index, end_index));
568             } else {
569                 return Err(SpanSnippetError::SourceNotAvailable {
570                     filename: local_begin.fm.name.clone()
571                 });
572             }
573         }
574     }
575
576     /// Return the source snippet as `String` corresponding to the given `Span`
577     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
578         self.span_to_source(sp, |src, start_index, end_index| src[start_index..end_index]
579                                                                 .to_string())
580     }
581
582     pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
583         match self.span_to_prev_source(sp) {
584             Err(_) => None,
585             Ok(source) => source.split('\n').last().map(|last_line| {
586                 last_line.len() - last_line.trim_left().len()
587             })
588         }
589     }
590
591     /// Return the source snippet as `String` before the given `Span`
592     pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
593         self.span_to_source(sp, |src, start_index, _| src[..start_index].to_string())
594     }
595
596     /// Extend the given `Span` to just after the previous occurrence of `c`. Return the same span
597     /// if no character could be found or if an error occurred while retrieving the code snippet.
598     pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span {
599         if let Ok(prev_source) = self.span_to_prev_source(sp) {
600             let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_left();
601             if !prev_source.is_empty() && !prev_source.contains('\n') {
602                 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
603             }
604         }
605
606         sp
607     }
608
609     /// Extend the given `Span` to just after the previous occurrence of `pat` when surrounded by
610     /// whitespace. Return the same span if no character could be found or if an error occurred
611     /// while retrieving the code snippet.
612     pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
613         // assure that the pattern is delimited, to avoid the following
614         //     fn my_fn()
615         //           ^^^^ returned span without the check
616         //     ---------- correct span
617         for ws in &[" ", "\t", "\n"] {
618             let pat = pat.to_owned() + ws;
619             if let Ok(prev_source) = self.span_to_prev_source(sp) {
620                 let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_left();
621                 if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) {
622                     return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
623                 }
624             }
625         }
626
627         sp
628     }
629
630     /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
631     pub fn span_until_char(&self, sp: Span, c: char) -> Span {
632         match self.span_to_snippet(sp) {
633             Ok(snippet) => {
634                 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right();
635                 if !snippet.is_empty() && !snippet.contains('\n') {
636                     sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
637                 } else {
638                     sp
639                 }
640             }
641             _ => sp,
642         }
643     }
644
645     /// Given a `Span`, try to get a shorter span ending just after the first occurrence of `char`
646     /// `c`.
647     pub fn span_through_char(&self, sp: Span, c: char) -> Span {
648         if let Ok(snippet) = self.span_to_snippet(sp) {
649             if let Some(offset) = snippet.find(c) {
650                 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
651             }
652         }
653         sp
654     }
655
656     /// Given a `Span`, get a new `Span` covering the first token and all its trailing whitespace or
657     /// the original `Span`.
658     ///
659     /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
660     pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
661         let mut whitespace_found = false;
662
663         self.span_take_while(sp, |c| {
664             if !whitespace_found && c.is_whitespace() {
665                 whitespace_found = true;
666             }
667
668             if whitespace_found && !c.is_whitespace() {
669                 false
670             } else {
671                 true
672             }
673         })
674     }
675
676     /// Given a `Span`, get a new `Span` covering the first token without its trailing whitespace or
677     /// the original `Span` in case of error.
678     ///
679     /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
680     pub fn span_until_whitespace(&self, sp: Span) -> Span {
681         self.span_take_while(sp, |c| !c.is_whitespace())
682     }
683
684     /// Given a `Span`, get a shorter one until `predicate` yields false.
685     pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
686         where P: for <'r> FnMut(&'r char) -> bool
687     {
688         if let Ok(snippet) = self.span_to_snippet(sp) {
689             let offset = snippet.chars()
690                 .take_while(predicate)
691                 .map(|c| c.len_utf8())
692                 .sum::<usize>();
693
694             sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
695         } else {
696             sp
697         }
698     }
699
700     pub fn def_span(&self, sp: Span) -> Span {
701         self.span_until_char(sp, '{')
702     }
703
704     /// Returns a new span representing just the start-point of this span
705     pub fn start_point(&self, sp: Span) -> Span {
706         let pos = sp.lo().0;
707         let width = self.find_width_of_character_at_span(sp, false);
708         let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
709         let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
710         sp.with_hi(end_point)
711     }
712
713     /// Returns a new span representing just the end-point of this span
714     pub fn end_point(&self, sp: Span) -> Span {
715         let pos = sp.hi().0;
716
717         let width = self.find_width_of_character_at_span(sp, false);
718         let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
719
720         let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
721         sp.with_lo(end_point)
722     }
723
724     /// Returns a new span representing the next character after the end-point of this span
725     pub fn next_point(&self, sp: Span) -> Span {
726         let start_of_next_point = sp.hi().0;
727
728         let width = self.find_width_of_character_at_span(sp, true);
729         // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
730         // in the case of a multibyte character, where the width != 1, the next span should
731         // span multiple bytes to include the whole character.
732         let end_of_next_point = start_of_next_point.checked_add(
733             width - 1).unwrap_or(start_of_next_point);
734
735         let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
736         Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
737     }
738
739     /// Finds the width of a character, either before or after the provided span.
740     fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
741         // Disregard malformed spans and assume a one-byte wide character.
742         if sp.lo() >= sp.hi() {
743             debug!("find_width_of_character_at_span: early return malformed span");
744             return 1;
745         }
746
747         let local_begin = self.lookup_byte_offset(sp.lo());
748         let local_end = self.lookup_byte_offset(sp.hi());
749         debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
750                local_begin, local_end);
751
752         let start_index = local_begin.pos.to_usize();
753         let end_index = local_end.pos.to_usize();
754         debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
755                start_index, end_index);
756
757         // Disregard indexes that are at the start or end of their spans, they can't fit bigger
758         // characters.
759         if (!forwards && end_index == usize::min_value()) ||
760             (forwards && start_index == usize::max_value()) {
761             debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
762             return 1;
763         }
764
765         let source_len = (local_begin.fm.end_pos - local_begin.fm.start_pos).to_usize();
766         debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
767         // Ensure indexes are also not malformed.
768         if start_index > end_index || end_index > source_len {
769             debug!("find_width_of_character_at_span: source indexes are malformed");
770             return 1;
771         }
772
773         let src = local_begin.fm.external_src.borrow();
774
775         // We need to extend the snippet to the end of the src rather than to end_index so when
776         // searching forwards for boundaries we've got somewhere to search.
777         let snippet = if let Some(ref src) = local_begin.fm.src {
778             let len = src.len();
779             (&src[start_index..len])
780         } else if let Some(src) = src.get_source() {
781             let len = src.len();
782             (&src[start_index..len])
783         } else {
784             return 1;
785         };
786         debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
787
788         let mut target = if forwards { end_index + 1 } else { end_index - 1 };
789         debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
790
791         while !snippet.is_char_boundary(target - start_index) && target < source_len {
792             target = if forwards {
793                 target + 1
794             } else {
795                 match target.checked_sub(1) {
796                     Some(target) => target,
797                     None => {
798                         break;
799                     }
800                 }
801             };
802             debug!("find_width_of_character_at_span: target=`{:?}`", target);
803         }
804         debug!("find_width_of_character_at_span: final target=`{:?}`", target);
805
806         if forwards {
807             (target - end_index) as u32
808         } else {
809             (end_index - target) as u32
810         }
811     }
812
813     pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
814         for fm in self.files.borrow().file_maps.iter() {
815             if *filename == fm.name {
816                 return Some(fm.clone());
817             }
818         }
819         None
820     }
821
822     /// For a global BytePos compute the local offset within the containing SourceFile
823     pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
824         let idx = self.lookup_source_file_idx(bpos);
825         let fm = (*self.files.borrow().file_maps)[idx].clone();
826         let offset = bpos - fm.start_pos;
827         SourceFileAndBytePos {fm: fm, pos: offset}
828     }
829
830     /// Converts an absolute BytePos to a CharPos relative to the source_file.
831     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
832         let idx = self.lookup_source_file_idx(bpos);
833         let map = &(*self.files.borrow().file_maps)[idx];
834
835         // The number of extra bytes due to multibyte chars in the SourceFile
836         let mut total_extra_bytes = 0;
837
838         for mbc in map.multibyte_chars.iter() {
839             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
840             if mbc.pos < bpos {
841                 // every character is at least one byte, so we only
842                 // count the actual extra bytes.
843                 total_extra_bytes += mbc.bytes as u32 - 1;
844                 // We should never see a byte position in the middle of a
845                 // character
846                 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
847             } else {
848                 break;
849             }
850         }
851
852         assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
853         CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
854     }
855
856     // Return the index of the source_file (in self.files) which contains pos.
857     pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
858         let files = self.files.borrow();
859         let files = &files.file_maps;
860         let count = files.len();
861
862         // Binary search for the source_file.
863         let mut a = 0;
864         let mut b = count;
865         while b - a > 1 {
866             let m = (a + b) / 2;
867             if files[m].start_pos > pos {
868                 b = m;
869             } else {
870                 a = m;
871             }
872         }
873
874         assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
875
876         return a;
877     }
878
879     pub fn count_lines(&self) -> usize {
880         self.files().iter().fold(0, |a, f| a + f.count_lines())
881     }
882
883
884     pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
885         let prev_span = self.span_extend_to_prev_str(span, "fn", true);
886         self.span_to_snippet(prev_span).map(|snippet| {
887             let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
888                 .expect("no label after fn");
889             prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
890         }).ok()
891     }
892
893     /// Take the span of a type parameter in a function signature and try to generate a span for the
894     /// function name (with generics) and a new snippet for this span with the pointed type
895     /// parameter as a new local type parameter.
896     ///
897     /// For instance:
898     /// ```rust,ignore (pseudo-Rust)
899     /// // Given span
900     /// fn my_function(param: T)
901     /// //                    ^ Original span
902     ///
903     /// // Result
904     /// fn my_function(param: T)
905     /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
906     /// ```
907     ///
908     /// Attention: The method used is very fragile since it essentially duplicates the work of the
909     /// parser. If you need to use this function or something similar, please consider updating the
910     /// source_map functions and this function to something more robust.
911     pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
912         // Try to extend the span to the previous "fn" keyword to retrieve the function
913         // signature
914         let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
915         if sugg_span != span {
916             if let Ok(snippet) = self.span_to_snippet(sugg_span) {
917                 // Consume the function name
918                 let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
919                     .expect("no label after fn");
920
921                 // Consume the generics part of the function signature
922                 let mut bracket_counter = 0;
923                 let mut last_char = None;
924                 for c in snippet[offset..].chars() {
925                     match c {
926                         '<' => bracket_counter += 1,
927                         '>' => bracket_counter -= 1,
928                         '(' => if bracket_counter == 0 { break; }
929                         _ => {}
930                     }
931                     offset += c.len_utf8();
932                     last_char = Some(c);
933                 }
934
935                 // Adjust the suggestion span to encompass the function name with its generics
936                 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
937
938                 // Prepare the new suggested snippet to append the type parameter that triggered
939                 // the error in the generics of the function signature
940                 let mut new_snippet = if last_char == Some('>') {
941                     format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
942                 } else {
943                     format!("{}<", &snippet[..offset])
944                 };
945                 new_snippet.push_str(&self.span_to_snippet(span).unwrap_or("T".to_string()));
946                 new_snippet.push('>');
947
948                 return Some((sugg_span, new_snippet));
949             }
950         }
951
952         None
953     }
954 }
955
956 impl SourceMapper for SourceMap {
957     fn lookup_char_pos(&self, pos: BytePos) -> Loc {
958         self.lookup_char_pos(pos)
959     }
960     fn span_to_lines(&self, sp: Span) -> FileLinesResult {
961         self.span_to_lines(sp)
962     }
963     fn span_to_string(&self, sp: Span) -> String {
964         self.span_to_string(sp)
965     }
966     fn span_to_filename(&self, sp: Span) -> FileName {
967         self.span_to_filename(sp)
968     }
969     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
970         self.merge_spans(sp_lhs, sp_rhs)
971     }
972     fn call_span_if_macro(&self, sp: Span) -> Span {
973         if self.span_to_filename(sp.clone()).is_macros() {
974             let v = sp.macro_backtrace();
975             if let Some(use_site) = v.last() {
976                 return use_site.call_site;
977             }
978         }
979         sp
980     }
981     fn ensure_source_file_source_present(&self, file_map: Lrc<SourceFile>) -> bool {
982         file_map.add_external_src(
983             || match file_map.name {
984                 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
985                 _ => None,
986             }
987         )
988     }
989     fn doctest_offset_line(&self, line: usize) -> usize {
990         self.doctest_offset_line(line)
991     }
992 }
993
994 #[derive(Clone)]
995 pub struct FilePathMapping {
996     mapping: Vec<(PathBuf, PathBuf)>,
997 }
998
999 impl FilePathMapping {
1000     pub fn empty() -> FilePathMapping {
1001         FilePathMapping {
1002             mapping: vec![]
1003         }
1004     }
1005
1006     pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1007         FilePathMapping {
1008             mapping,
1009         }
1010     }
1011
1012     /// Applies any path prefix substitution as defined by the mapping.
1013     /// The return value is the remapped path and a boolean indicating whether
1014     /// the path was affected by the mapping.
1015     pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1016         // NOTE: We are iterating over the mapping entries from last to first
1017         //       because entries specified later on the command line should
1018         //       take precedence.
1019         for &(ref from, ref to) in self.mapping.iter().rev() {
1020             if let Ok(rest) = path.strip_prefix(from) {
1021                 return (to.join(rest), true);
1022             }
1023         }
1024
1025         (path, false)
1026     }
1027 }
1028
1029 // _____________________________________________________________________________
1030 // Tests
1031 //
1032
1033 #[cfg(test)]
1034 mod tests {
1035     use super::*;
1036     use rustc_data_structures::sync::Lrc;
1037
1038     fn init_code_map() -> SourceMap {
1039         let cm = SourceMap::new(FilePathMapping::empty());
1040         cm.new_source_file(PathBuf::from("blork.rs").into(),
1041                        "first line.\nsecond line".to_string());
1042         cm.new_source_file(PathBuf::from("empty.rs").into(),
1043                        String::new());
1044         cm.new_source_file(PathBuf::from("blork2.rs").into(),
1045                        "first line.\nsecond line".to_string());
1046         cm
1047     }
1048
1049     #[test]
1050     fn t3() {
1051         // Test lookup_byte_offset
1052         let cm = init_code_map();
1053
1054         let fmabp1 = cm.lookup_byte_offset(BytePos(23));
1055         assert_eq!(fmabp1.fm.name, PathBuf::from("blork.rs").into());
1056         assert_eq!(fmabp1.pos, BytePos(23));
1057
1058         let fmabp1 = cm.lookup_byte_offset(BytePos(24));
1059         assert_eq!(fmabp1.fm.name, PathBuf::from("empty.rs").into());
1060         assert_eq!(fmabp1.pos, BytePos(0));
1061
1062         let fmabp2 = cm.lookup_byte_offset(BytePos(25));
1063         assert_eq!(fmabp2.fm.name, PathBuf::from("blork2.rs").into());
1064         assert_eq!(fmabp2.pos, BytePos(0));
1065     }
1066
1067     #[test]
1068     fn t4() {
1069         // Test bytepos_to_file_charpos
1070         let cm = init_code_map();
1071
1072         let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
1073         assert_eq!(cp1, CharPos(22));
1074
1075         let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
1076         assert_eq!(cp2, CharPos(0));
1077     }
1078
1079     #[test]
1080     fn t5() {
1081         // Test zero-length source_files.
1082         let cm = init_code_map();
1083
1084         let loc1 = cm.lookup_char_pos(BytePos(22));
1085         assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
1086         assert_eq!(loc1.line, 2);
1087         assert_eq!(loc1.col, CharPos(10));
1088
1089         let loc2 = cm.lookup_char_pos(BytePos(25));
1090         assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
1091         assert_eq!(loc2.line, 1);
1092         assert_eq!(loc2.col, CharPos(0));
1093     }
1094
1095     fn init_code_map_mbc() -> SourceMap {
1096         let cm = SourceMap::new(FilePathMapping::empty());
1097         // € is a three byte utf8 char.
1098         cm.new_source_file(PathBuf::from("blork.rs").into(),
1099                        "fir€st €€€€ line.\nsecond line".to_string());
1100         cm.new_source_file(PathBuf::from("blork2.rs").into(),
1101                        "first line€€.\n€ second line".to_string());
1102         cm
1103     }
1104
1105     #[test]
1106     fn t6() {
1107         // Test bytepos_to_file_charpos in the presence of multi-byte chars
1108         let cm = init_code_map_mbc();
1109
1110         let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
1111         assert_eq!(cp1, CharPos(3));
1112
1113         let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
1114         assert_eq!(cp2, CharPos(4));
1115
1116         let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
1117         assert_eq!(cp3, CharPos(12));
1118
1119         let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
1120         assert_eq!(cp4, CharPos(15));
1121     }
1122
1123     #[test]
1124     fn t7() {
1125         // Test span_to_lines for a span ending at the end of source_file
1126         let cm = init_code_map();
1127         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1128         let file_lines = cm.span_to_lines(span).unwrap();
1129
1130         assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
1131         assert_eq!(file_lines.lines.len(), 1);
1132         assert_eq!(file_lines.lines[0].line_index, 1);
1133     }
1134
1135     /// Given a string like " ~~~~~~~~~~~~ ", produces a span
1136     /// converting that range. The idea is that the string has the same
1137     /// length as the input, and we uncover the byte positions.  Note
1138     /// that this can span lines and so on.
1139     fn span_from_selection(input: &str, selection: &str) -> Span {
1140         assert_eq!(input.len(), selection.len());
1141         let left_index = selection.find('~').unwrap() as u32;
1142         let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
1143         Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
1144     }
1145
1146     /// Test span_to_snippet and span_to_lines for a span converting 3
1147     /// lines in the middle of a file.
1148     #[test]
1149     fn span_to_snippet_and_lines_spanning_multiple_lines() {
1150         let cm = SourceMap::new(FilePathMapping::empty());
1151         let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1152         let selection = "     \n    ~~\n~~~\n~~~~~     \n   \n";
1153         cm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_string());
1154         let span = span_from_selection(inputtext, selection);
1155
1156         // check that we are extracting the text we thought we were extracting
1157         assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1158
1159         // check that span_to_lines gives us the complete result with the lines/cols we expected
1160         let lines = cm.span_to_lines(span).unwrap();
1161         let expected = vec![
1162             LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1163             LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1164             LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1165             ];
1166         assert_eq!(lines.lines, expected);
1167     }
1168
1169     #[test]
1170     fn t8() {
1171         // Test span_to_snippet for a span ending at the end of source_file
1172         let cm = init_code_map();
1173         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1174         let snippet = cm.span_to_snippet(span);
1175
1176         assert_eq!(snippet, Ok("second line".to_string()));
1177     }
1178
1179     #[test]
1180     fn t9() {
1181         // Test span_to_str for a span ending at the end of source_file
1182         let cm = init_code_map();
1183         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1184         let sstr =  cm.span_to_string(span);
1185
1186         assert_eq!(sstr, "blork.rs:2:1: 2:12");
1187     }
1188
1189     /// Test failing to merge two spans on different lines
1190     #[test]
1191     fn span_merging_fail() {
1192         let cm = SourceMap::new(FilePathMapping::empty());
1193         let inputtext  = "bbbb BB\ncc CCC\n";
1194         let selection1 = "     ~~\n      \n";
1195         let selection2 = "       \n   ~~~\n";
1196         cm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_owned());
1197         let span1 = span_from_selection(inputtext, selection1);
1198         let span2 = span_from_selection(inputtext, selection2);
1199
1200         assert!(cm.merge_spans(span1, span2).is_none());
1201     }
1202
1203     /// Returns the span corresponding to the `n`th occurrence of
1204     /// `substring` in `source_text`.
1205     trait SourceMapExtension {
1206         fn span_substr(&self,
1207                     file: &Lrc<SourceFile>,
1208                     source_text: &str,
1209                     substring: &str,
1210                     n: usize)
1211                     -> Span;
1212     }
1213
1214     impl SourceMapExtension for SourceMap {
1215         fn span_substr(&self,
1216                     file: &Lrc<SourceFile>,
1217                     source_text: &str,
1218                     substring: &str,
1219                     n: usize)
1220                     -> Span
1221         {
1222             println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
1223                     file.name, file.start_pos, substring, n);
1224             let mut i = 0;
1225             let mut hi = 0;
1226             loop {
1227                 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
1228                     panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
1229                         source_text, n, substring, i);
1230                 });
1231                 let lo = hi + offset;
1232                 hi = lo + substring.len();
1233                 if i == n {
1234                     let span = Span::new(
1235                         BytePos(lo as u32 + file.start_pos.0),
1236                         BytePos(hi as u32 + file.start_pos.0),
1237                         NO_EXPANSION,
1238                     );
1239                     assert_eq!(&self.span_to_snippet(span).unwrap()[..],
1240                             substring);
1241                     return span;
1242                 }
1243                 i += 1;
1244             }
1245         }
1246     }
1247 }