]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/source_map.rs
Rollup merge of #64229 - kawa-yoiko:unreachable-call-lint, r=estebank
[rust.git] / src / libsyntax / source_map.rs
1 //! The `SourceMap` tracks all the source code used within a single crate, mapping
2 //! from integer byte positions to the original source code location. Each bit
3 //! of source parsed during crate parsing (typically files, in-memory strings,
4 //! or various bits of macro expansion) cover a continuous range of bytes in the
5 //! `SourceMap` and are represented by `SourceFile`s. Byte positions are stored in
6 //! `Span`` and used pervasively in the compiler. They are absolute positions
7 //! within the `SourceMap`, which upon request can be converted to line and column
8 //! information, source code snippets, etc.
9
10 pub use syntax_pos::*;
11 pub use syntax_pos::hygiene::{ExpnKind, ExpnData};
12
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::stable_hasher::StableHasher;
15 use rustc_data_structures::sync::{Lrc, Lock, LockGuard, MappedLockGuard};
16 use std::cmp;
17 use std::hash::Hash;
18 use std::path::{Path, PathBuf};
19
20 use std::env;
21 use std::fs;
22 use std::io;
23 use log::debug;
24
25 use errors::SourceMapper;
26
27 #[cfg(test)]
28 mod tests;
29
30 /// Returns the span itself if it doesn't come from a macro expansion,
31 /// otherwise return the call site span up to the `enclosing_sp` by
32 /// following the `expn_data` chain.
33 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
34     let expn_data1 = sp.ctxt().outer_expn_data();
35     let expn_data2 = enclosing_sp.ctxt().outer_expn_data();
36     if expn_data1.is_root() ||
37        !expn_data2.is_root() && expn_data1.call_site == expn_data2.call_site {
38         sp
39     } else {
40         original_sp(expn_data1.call_site, enclosing_sp)
41     }
42 }
43
44 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
45 pub struct Spanned<T> {
46     pub node: T,
47     pub span: Span,
48 }
49
50 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
51     Spanned {node: t, span: sp}
52 }
53
54 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
55     respan(DUMMY_SP, t)
56 }
57
58 // _____________________________________________________________________________
59 // SourceFile, MultiByteChar, FileName, FileLines
60 //
61
62 /// An abstraction over the fs operations used by the Parser.
63 pub trait FileLoader {
64     /// Query the existence of a file.
65     fn file_exists(&self, path: &Path) -> bool;
66
67     /// Returns an absolute path to a file, if possible.
68     fn abs_path(&self, path: &Path) -> Option<PathBuf>;
69
70     /// Read the contents of an UTF-8 file into memory.
71     fn read_file(&self, path: &Path) -> io::Result<String>;
72 }
73
74 /// A FileLoader that uses std::fs to load real files.
75 pub struct RealFileLoader;
76
77 impl FileLoader for RealFileLoader {
78     fn file_exists(&self, path: &Path) -> bool {
79         fs::metadata(path).is_ok()
80     }
81
82     fn abs_path(&self, path: &Path) -> Option<PathBuf> {
83         if path.is_absolute() {
84             Some(path.to_path_buf())
85         } else {
86             env::current_dir()
87                 .ok()
88                 .map(|cwd| cwd.join(path))
89         }
90     }
91
92     fn read_file(&self, path: &Path) -> io::Result<String> {
93         fs::read_to_string(path)
94     }
95 }
96
97 // This is a `SourceFile` identifier that is used to correlate `SourceFile`s between
98 // subsequent compilation sessions (which is something we need to do during
99 // incremental compilation).
100 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
101 pub struct StableSourceFileId(u128);
102
103 impl StableSourceFileId {
104     pub fn new(source_file: &SourceFile) -> StableSourceFileId {
105         StableSourceFileId::new_from_pieces(&source_file.name,
106                                             source_file.name_was_remapped,
107                                             source_file.unmapped_path.as_ref())
108     }
109
110     pub fn new_from_pieces(name: &FileName,
111                            name_was_remapped: bool,
112                            unmapped_path: Option<&FileName>) -> StableSourceFileId {
113         let mut hasher = StableHasher::new();
114
115         name.hash(&mut hasher);
116         name_was_remapped.hash(&mut hasher);
117         unmapped_path.hash(&mut hasher);
118
119         StableSourceFileId(hasher.finish())
120     }
121 }
122
123 // _____________________________________________________________________________
124 // SourceMap
125 //
126
127 #[derive(Default)]
128 pub(super) struct SourceMapFiles {
129     source_files: Vec<Lrc<SourceFile>>,
130     stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>
131 }
132
133 pub struct SourceMap {
134     files: Lock<SourceMapFiles>,
135     file_loader: Box<dyn FileLoader + Sync + Send>,
136     // This is used to apply the file path remapping as specified via
137     // `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`.
138     path_mapping: FilePathMapping,
139 }
140
141 impl SourceMap {
142     pub fn new(path_mapping: FilePathMapping) -> SourceMap {
143         SourceMap {
144             files: Default::default(),
145             file_loader: Box::new(RealFileLoader),
146             path_mapping,
147         }
148     }
149
150     pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
151                             path_mapping: FilePathMapping)
152                             -> SourceMap {
153         SourceMap {
154             files: Default::default(),
155             file_loader,
156             path_mapping,
157         }
158     }
159
160     pub fn path_mapping(&self) -> &FilePathMapping {
161         &self.path_mapping
162     }
163
164     pub fn file_exists(&self, path: &Path) -> bool {
165         self.file_loader.file_exists(path)
166     }
167
168     pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
169         let src = self.file_loader.read_file(path)?;
170         let filename = path.to_owned().into();
171         Ok(self.new_source_file(filename, src))
172     }
173
174     /// Loads source file as a binary blob.
175     ///
176     /// Unlike `load_file`, guarantees that no normalization like BOM-removal
177     /// takes place.
178     pub fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
179         // Ideally, this should use `self.file_loader`, but it can't
180         // deal with binary files yet.
181         let bytes = fs::read(path)?;
182
183         // We need to add file to the `SourceMap`, so that it is present
184         // in dep-info. There's also an edge case that file might be both
185         // loaded as a binary via `include_bytes!` and as proper `SourceFile`
186         // via `mod`, so we try to use real file contents and not just an
187         // empty string.
188         let text = std::str::from_utf8(&bytes).unwrap_or("")
189             .to_string();
190         self.new_source_file(path.to_owned().into(), text);
191         Ok(bytes)
192     }
193
194     pub fn files(&self) -> MappedLockGuard<'_, Vec<Lrc<SourceFile>>> {
195         LockGuard::map(self.files.borrow(), |files| &mut files.source_files)
196     }
197
198     pub fn source_file_by_stable_id(&self, stable_id: StableSourceFileId) ->
199     Option<Lrc<SourceFile>> {
200         self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|sf| sf.clone())
201     }
202
203     fn next_start_pos(&self) -> usize {
204         match self.files.borrow().source_files.last() {
205             None => 0,
206             // Add one so there is some space between files. This lets us distinguish
207             // positions in the `SourceMap`, even in the presence of zero-length files.
208             Some(last) => last.end_pos.to_usize() + 1,
209         }
210     }
211
212     /// Creates a new `SourceFile`.
213     /// If a file already exists in the `SourceMap` with the same ID, that file is returned
214     /// unmodified.
215     pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
216         self.try_new_source_file(filename, src)
217             .unwrap_or_else(|OffsetOverflowError| {
218                 eprintln!("fatal error: rustc does not support files larger than 4GB");
219                 errors::FatalError.raise()
220             })
221     }
222
223     fn try_new_source_file(
224         &self,
225         filename: FileName,
226         src: String
227     ) -> Result<Lrc<SourceFile>, OffsetOverflowError> {
228         let start_pos = self.next_start_pos();
229
230         // The path is used to determine the directory for loading submodules and
231         // include files, so it must be before remapping.
232         // Note that filename may not be a valid path, eg it may be `<anon>` etc,
233         // but this is okay because the directory determined by `path.pop()` will
234         // be empty, so the working directory will be used.
235         let unmapped_path = filename.clone();
236
237         let (filename, was_remapped) = match filename {
238             FileName::Real(filename) => {
239                 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
240                 (FileName::Real(filename), was_remapped)
241             },
242             other => (other, false),
243         };
244
245         let file_id = StableSourceFileId::new_from_pieces(&filename,
246                                                        was_remapped,
247                                                        Some(&unmapped_path));
248
249         let lrc_sf = match self.source_file_by_stable_id(file_id) {
250             Some(lrc_sf) => lrc_sf,
251             None => {
252                 let source_file = Lrc::new(SourceFile::new(
253                     filename,
254                     was_remapped,
255                     unmapped_path,
256                     src,
257                     Pos::from_usize(start_pos),
258                 )?);
259
260                 let mut files = self.files.borrow_mut();
261
262                 files.source_files.push(source_file.clone());
263                 files.stable_id_to_source_file.insert(file_id, source_file.clone());
264
265                 source_file
266             }
267         };
268         Ok(lrc_sf)
269     }
270
271     /// Allocates a new `SourceFile` representing a source file from an external
272     /// crate. The source code of such an "imported `SourceFile`" is not available,
273     /// but we still know enough to generate accurate debuginfo location
274     /// information for things inlined from other crates.
275     pub fn new_imported_source_file(
276         &self,
277         filename: FileName,
278         name_was_remapped: bool,
279         crate_of_origin: u32,
280         src_hash: u128,
281         name_hash: u128,
282         source_len: usize,
283         mut file_local_lines: Vec<BytePos>,
284         mut file_local_multibyte_chars: Vec<MultiByteChar>,
285         mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
286     ) -> Lrc<SourceFile> {
287         let start_pos = self.next_start_pos();
288
289         let end_pos = Pos::from_usize(start_pos + source_len);
290         let start_pos = Pos::from_usize(start_pos);
291
292         for pos in &mut file_local_lines {
293             *pos = *pos + start_pos;
294         }
295
296         for mbc in &mut file_local_multibyte_chars {
297             mbc.pos = mbc.pos + start_pos;
298         }
299
300         for swc in &mut file_local_non_narrow_chars {
301             *swc = *swc + start_pos;
302         }
303
304         let source_file = Lrc::new(SourceFile {
305             name: filename,
306             name_was_remapped,
307             unmapped_path: None,
308             crate_of_origin,
309             src: None,
310             src_hash,
311             external_src: Lock::new(ExternalSource::AbsentOk),
312             start_pos,
313             end_pos,
314             lines: file_local_lines,
315             multibyte_chars: file_local_multibyte_chars,
316             non_narrow_chars: file_local_non_narrow_chars,
317             name_hash,
318         });
319
320         let mut files = self.files.borrow_mut();
321
322         files.source_files.push(source_file.clone());
323         files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file),
324                                               source_file.clone());
325
326         source_file
327     }
328
329     pub fn mk_substr_filename(&self, sp: Span) -> String {
330         let pos = self.lookup_char_pos(sp.lo());
331         format!("<{}:{}:{}>",
332                  pos.file.name,
333                  pos.line,
334                  pos.col.to_usize() + 1)
335     }
336
337     // If there is a doctest offset, applies it to the line.
338     pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
339         return match file {
340             FileName::DocTest(_, offset) => {
341                 return if *offset >= 0 {
342                     orig + *offset as usize
343                 } else {
344                     orig - (-(*offset)) as usize
345                 }
346             },
347             _ => orig
348         }
349     }
350
351     /// Looks up source information about a `BytePos`.
352     pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
353         let chpos = self.bytepos_to_file_charpos(pos);
354         match self.lookup_line(pos) {
355             Ok(SourceFileAndLine { sf: f, line: a }) => {
356                 let line = a + 1; // Line numbers start at 1
357                 let linebpos = f.lines[a];
358                 let linechpos = self.bytepos_to_file_charpos(linebpos);
359                 let col = chpos - linechpos;
360
361                 let col_display = {
362                     let start_width_idx = f
363                         .non_narrow_chars
364                         .binary_search_by_key(&linebpos, |x| x.pos())
365                         .unwrap_or_else(|x| x);
366                     let end_width_idx = f
367                         .non_narrow_chars
368                         .binary_search_by_key(&pos, |x| x.pos())
369                         .unwrap_or_else(|x| x);
370                     let special_chars = end_width_idx - start_width_idx;
371                     let non_narrow: usize = f
372                         .non_narrow_chars[start_width_idx..end_width_idx]
373                         .into_iter()
374                         .map(|x| x.width())
375                         .sum();
376                     col.0 - special_chars + non_narrow
377                 };
378                 debug!("byte pos {:?} is on the line at byte pos {:?}",
379                        pos, linebpos);
380                 debug!("char pos {:?} is on the line at char pos {:?}",
381                        chpos, linechpos);
382                 debug!("byte is on line: {}", line);
383                 assert!(chpos >= linechpos);
384                 Loc {
385                     file: f,
386                     line,
387                     col,
388                     col_display,
389                 }
390             }
391             Err(f) => {
392                 let col_display = {
393                     let end_width_idx = f
394                         .non_narrow_chars
395                         .binary_search_by_key(&pos, |x| x.pos())
396                         .unwrap_or_else(|x| x);
397                     let non_narrow: usize = f
398                         .non_narrow_chars[0..end_width_idx]
399                         .into_iter()
400                         .map(|x| x.width())
401                         .sum();
402                     chpos.0 - end_width_idx + non_narrow
403                 };
404                 Loc {
405                     file: f,
406                     line: 0,
407                     col: chpos,
408                     col_display,
409                 }
410             }
411         }
412     }
413
414     // If the corresponding `SourceFile` is empty, does not return a line number.
415     pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
416         let idx = self.lookup_source_file_idx(pos);
417
418         let f = (*self.files.borrow().source_files)[idx].clone();
419
420         match f.lookup_line(pos) {
421             Some(line) => Ok(SourceFileAndLine { sf: f, line }),
422             None => Err(f)
423         }
424     }
425
426     /// Returns `Some(span)`, a union of the LHS and RHS span. The LHS must precede the RHS. If
427     /// there are gaps between LHS and RHS, the resulting union will cross these gaps.
428     /// For this to work,
429     ///
430     ///    * the syntax contexts of both spans much match,
431     ///    * the LHS span needs to end on the same line the RHS span begins,
432     ///    * the LHS span must start at or before the RHS span.
433     pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
434         // Ensure we're at the same expansion ID.
435         if sp_lhs.ctxt() != sp_rhs.ctxt() {
436             return None;
437         }
438
439         let lhs_end = match self.lookup_line(sp_lhs.hi()) {
440             Ok(x) => x,
441             Err(_) => return None
442         };
443         let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
444             Ok(x) => x,
445             Err(_) => return None
446         };
447
448         // If we must cross lines to merge, don't merge.
449         if lhs_end.line != rhs_begin.line {
450             return None;
451         }
452
453         // Ensure these follow the expected order and that we don't overlap.
454         if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
455             Some(sp_lhs.to(sp_rhs))
456         } else {
457             None
458         }
459     }
460
461     pub fn span_to_string(&self, sp: Span) -> String {
462         if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
463             return "no-location".to_string();
464         }
465
466         let lo = self.lookup_char_pos(sp.lo());
467         let hi = self.lookup_char_pos(sp.hi());
468         format!("{}:{}:{}: {}:{}",
469             lo.file.name,
470             lo.line,
471             lo.col.to_usize() + 1,
472             hi.line,
473             hi.col.to_usize() + 1,
474         )
475     }
476
477     pub fn span_to_filename(&self, sp: Span) -> FileName {
478         self.lookup_char_pos(sp.lo()).file.name.clone()
479     }
480
481     pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
482         self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
483             .expect("`SourceMap::span_to_unmapped_path` called for imported `SourceFile`?")
484     }
485
486     pub fn is_multiline(&self, sp: Span) -> bool {
487         let lo = self.lookup_char_pos(sp.lo());
488         let hi = self.lookup_char_pos(sp.hi());
489         lo.line != hi.line
490     }
491
492     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
493         debug!("span_to_lines(sp={:?})", sp);
494
495         if sp.lo() > sp.hi() {
496             return Err(SpanLinesError::IllFormedSpan(sp));
497         }
498
499         let lo = self.lookup_char_pos(sp.lo());
500         debug!("span_to_lines: lo={:?}", lo);
501         let hi = self.lookup_char_pos(sp.hi());
502         debug!("span_to_lines: hi={:?}", hi);
503
504         if lo.file.start_pos != hi.file.start_pos {
505             return Err(SpanLinesError::DistinctSources(DistinctSources {
506                 begin: (lo.file.name.clone(), lo.file.start_pos),
507                 end: (hi.file.name.clone(), hi.file.start_pos),
508             }));
509         }
510         assert!(hi.line >= lo.line);
511
512         let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
513
514         // The span starts partway through the first line,
515         // but after that it starts from offset 0.
516         let mut start_col = lo.col;
517
518         // For every line but the last, it extends from `start_col`
519         // and to the end of the line. Be careful because the line
520         // numbers in Loc are 1-based, so we subtract 1 to get 0-based
521         // lines.
522         for line_index in lo.line-1 .. hi.line-1 {
523             let line_len = lo.file.get_line(line_index)
524                                   .map(|s| s.chars().count())
525                                   .unwrap_or(0);
526             lines.push(LineInfo { line_index,
527                                   start_col,
528                                   end_col: CharPos::from_usize(line_len) });
529             start_col = CharPos::from_usize(0);
530         }
531
532         // For the last line, it extends from `start_col` to `hi.col`:
533         lines.push(LineInfo { line_index: hi.line - 1,
534                               start_col,
535                               end_col: hi.col });
536
537         Ok(FileLines {file: lo.file, lines})
538     }
539
540     /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
541     /// extract function takes three arguments: a string slice containing the source, an index in
542     /// the slice for the beginning of the span and an index in the slice for the end of the span.
543     fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
544         where F: Fn(&str, usize, usize) -> Result<String, SpanSnippetError>
545     {
546         if sp.lo() > sp.hi() {
547             return Err(SpanSnippetError::IllFormedSpan(sp));
548         }
549
550         let local_begin = self.lookup_byte_offset(sp.lo());
551         let local_end = self.lookup_byte_offset(sp.hi());
552
553         if local_begin.sf.start_pos != local_end.sf.start_pos {
554             return Err(SpanSnippetError::DistinctSources(DistinctSources {
555                 begin: (local_begin.sf.name.clone(),
556                         local_begin.sf.start_pos),
557                 end: (local_end.sf.name.clone(),
558                       local_end.sf.start_pos)
559             }));
560         } else {
561             self.ensure_source_file_source_present(local_begin.sf.clone());
562
563             let start_index = local_begin.pos.to_usize();
564             let end_index = local_end.pos.to_usize();
565             let source_len = (local_begin.sf.end_pos -
566                               local_begin.sf.start_pos).to_usize();
567
568             if start_index > end_index || end_index > source_len {
569                 return Err(SpanSnippetError::MalformedForSourcemap(
570                     MalformedSourceMapPositions {
571                         name: local_begin.sf.name.clone(),
572                         source_len,
573                         begin_pos: local_begin.pos,
574                         end_pos: local_end.pos,
575                     }));
576             }
577
578             if let Some(ref src) = local_begin.sf.src {
579                 return extract_source(src, start_index, end_index);
580             } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
581                 return extract_source(src, start_index, end_index);
582             } else {
583                 return Err(SpanSnippetError::SourceNotAvailable {
584                     filename: local_begin.sf.name.clone()
585                 });
586             }
587         }
588     }
589
590     /// Returns the source snippet as `String` corresponding to the given `Span`.
591     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
592         self.span_to_source(sp, |src, start_index, end_index| src.get(start_index..end_index)
593             .map(|s| s.to_string())
594             .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)))
595     }
596
597     pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
598         match self.span_to_prev_source(sp) {
599             Err(_) => None,
600             Ok(source) => source.split('\n').last().map(|last_line| {
601                 last_line.len() - last_line.trim_start().len()
602             })
603         }
604     }
605
606     /// Returns the source snippet as `String` before the given `Span`.
607     pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
608         self.span_to_source(sp, |src, start_index, _| src.get(..start_index)
609             .map(|s| s.to_string())
610             .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)))
611     }
612
613     /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span
614     /// if no character could be found or if an error occurred while retrieving the code snippet.
615     pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span {
616         if let Ok(prev_source) = self.span_to_prev_source(sp) {
617             let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_start();
618             if !prev_source.is_empty() && !prev_source.contains('\n') {
619                 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
620             }
621         }
622
623         sp
624     }
625
626     /// Extends the given `Span` to just after the previous occurrence of `pat` when surrounded by
627     /// whitespace. Returns the same span if no character could be found or if an error occurred
628     /// while retrieving the code snippet.
629     pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
630         // assure that the pattern is delimited, to avoid the following
631         //     fn my_fn()
632         //           ^^^^ returned span without the check
633         //     ---------- correct span
634         for ws in &[" ", "\t", "\n"] {
635             let pat = pat.to_owned() + ws;
636             if let Ok(prev_source) = self.span_to_prev_source(sp) {
637                 let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_start();
638                 if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) {
639                     return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
640                 }
641             }
642         }
643
644         sp
645     }
646
647     /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char`
648     /// ``c`.
649     pub fn span_until_char(&self, sp: Span, c: char) -> Span {
650         match self.span_to_snippet(sp) {
651             Ok(snippet) => {
652                 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end();
653                 if !snippet.is_empty() && !snippet.contains('\n') {
654                     sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
655                 } else {
656                     sp
657                 }
658             }
659             _ => sp,
660         }
661     }
662
663     /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char`
664     /// `c`.
665     pub fn span_through_char(&self, sp: Span, c: char) -> Span {
666         if let Ok(snippet) = self.span_to_snippet(sp) {
667             if let Some(offset) = snippet.find(c) {
668                 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
669             }
670         }
671         sp
672     }
673
674     /// Given a `Span`, gets a new `Span` covering the first token and all its trailing whitespace
675     /// or the original `Span`.
676     ///
677     /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
678     pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
679         let mut whitespace_found = false;
680
681         self.span_take_while(sp, |c| {
682             if !whitespace_found && c.is_whitespace() {
683                 whitespace_found = true;
684             }
685
686             if whitespace_found && !c.is_whitespace() {
687                 false
688             } else {
689                 true
690             }
691         })
692     }
693
694     /// Given a `Span`, gets a new `Span` covering the first token without its trailing whitespace
695     /// or the original `Span` in case of error.
696     ///
697     /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
698     pub fn span_until_whitespace(&self, sp: Span) -> Span {
699         self.span_take_while(sp, |c| !c.is_whitespace())
700     }
701
702     /// Given a `Span`, gets a shorter one until `predicate` yields `false`.
703     pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
704         where P: for <'r> FnMut(&'r char) -> bool
705     {
706         if let Ok(snippet) = self.span_to_snippet(sp) {
707             let offset = snippet.chars()
708                 .take_while(predicate)
709                 .map(|c| c.len_utf8())
710                 .sum::<usize>();
711
712             sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
713         } else {
714             sp
715         }
716     }
717
718     pub fn def_span(&self, sp: Span) -> Span {
719         self.span_until_char(sp, '{')
720     }
721
722     /// Returns a new span representing just the start point of this span.
723     pub fn start_point(&self, sp: Span) -> Span {
724         let pos = sp.lo().0;
725         let width = self.find_width_of_character_at_span(sp, false);
726         let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
727         let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
728         sp.with_hi(end_point)
729     }
730
731     /// Returns a new span representing just the end point of this span.
732     pub fn end_point(&self, sp: Span) -> Span {
733         let pos = sp.hi().0;
734
735         let width = self.find_width_of_character_at_span(sp, false);
736         let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
737
738         let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
739         sp.with_lo(end_point)
740     }
741
742     /// Returns a new span representing the next character after the end-point of this span.
743     pub fn next_point(&self, sp: Span) -> Span {
744         let start_of_next_point = sp.hi().0;
745
746         let width = self.find_width_of_character_at_span(sp, true);
747         // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
748         // in the case of a multibyte character, where the width != 1, the next span should
749         // span multiple bytes to include the whole character.
750         let end_of_next_point = start_of_next_point.checked_add(
751             width - 1).unwrap_or(start_of_next_point);
752
753         let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
754         Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
755     }
756
757     /// Finds the width of a character, either before or after the provided span.
758     fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
759         // Disregard malformed spans and assume a one-byte wide character.
760         if sp.lo() >= sp.hi() {
761             debug!("find_width_of_character_at_span: early return malformed span");
762             return 1;
763         }
764
765         let local_begin = self.lookup_byte_offset(sp.lo());
766         let local_end = self.lookup_byte_offset(sp.hi());
767         debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
768                local_begin, local_end);
769
770         if local_begin.sf.start_pos != local_end.sf.start_pos {
771             debug!("find_width_of_character_at_span: begin and end are in different files");
772             return 1;
773         }
774
775         let start_index = local_begin.pos.to_usize();
776         let end_index = local_end.pos.to_usize();
777         debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
778                start_index, end_index);
779
780         // Disregard indexes that are at the start or end of their spans, they can't fit bigger
781         // characters.
782         if (!forwards && end_index == usize::min_value()) ||
783             (forwards && start_index == usize::max_value()) {
784             debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
785             return 1;
786         }
787
788         let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
789         debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
790         // Ensure indexes are also not malformed.
791         if start_index > end_index || end_index > source_len {
792             debug!("find_width_of_character_at_span: source indexes are malformed");
793             return 1;
794         }
795
796         let src = local_begin.sf.external_src.borrow();
797
798         // We need to extend the snippet to the end of the src rather than to end_index so when
799         // searching forwards for boundaries we've got somewhere to search.
800         let snippet = if let Some(ref src) = local_begin.sf.src {
801             let len = src.len();
802             (&src[start_index..len])
803         } else if let Some(src) = src.get_source() {
804             let len = src.len();
805             (&src[start_index..len])
806         } else {
807             return 1;
808         };
809         debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
810
811         let mut target = if forwards { end_index + 1 } else { end_index - 1 };
812         debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
813
814         while !snippet.is_char_boundary(target - start_index) && target < source_len {
815             target = if forwards {
816                 target + 1
817             } else {
818                 match target.checked_sub(1) {
819                     Some(target) => target,
820                     None => {
821                         break;
822                     }
823                 }
824             };
825             debug!("find_width_of_character_at_span: target=`{:?}`", target);
826         }
827         debug!("find_width_of_character_at_span: final target=`{:?}`", target);
828
829         if forwards {
830             (target - end_index) as u32
831         } else {
832             (end_index - target) as u32
833         }
834     }
835
836     pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
837         for sf in self.files.borrow().source_files.iter() {
838             if *filename == sf.name {
839                 return Some(sf.clone());
840             }
841         }
842         None
843     }
844
845     /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
846     pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
847         let idx = self.lookup_source_file_idx(bpos);
848         let sf = (*self.files.borrow().source_files)[idx].clone();
849         let offset = bpos - sf.start_pos;
850         SourceFileAndBytePos {sf, pos: offset}
851     }
852
853     /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
854     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
855         let idx = self.lookup_source_file_idx(bpos);
856         let map = &(*self.files.borrow().source_files)[idx];
857
858         // The number of extra bytes due to multibyte chars in the `SourceFile`.
859         let mut total_extra_bytes = 0;
860
861         for mbc in map.multibyte_chars.iter() {
862             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
863             if mbc.pos < bpos {
864                 // Every character is at least one byte, so we only
865                 // count the actual extra bytes.
866                 total_extra_bytes += mbc.bytes as u32 - 1;
867                 // We should never see a byte position in the middle of a
868                 // character.
869                 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
870             } else {
871                 break;
872             }
873         }
874
875         assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
876         CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
877     }
878
879     // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`.
880     pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
881         let files = self.files.borrow();
882         let files = &files.source_files;
883         let count = files.len();
884
885         // Binary search for the `SourceFile`.
886         let mut a = 0;
887         let mut b = count;
888         while b - a > 1 {
889             let m = (a + b) / 2;
890             if files[m].start_pos > pos {
891                 b = m;
892             } else {
893                 a = m;
894             }
895         }
896
897         assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
898
899         return a;
900     }
901
902     pub fn count_lines(&self) -> usize {
903         self.files().iter().fold(0, |a, f| a + f.count_lines())
904     }
905
906
907     pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
908         let prev_span = self.span_extend_to_prev_str(span, "fn", true);
909         self.span_to_snippet(prev_span).map(|snippet| {
910             let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
911                 .expect("no label after fn");
912             prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
913         }).ok()
914     }
915
916     /// Takes the span of a type parameter in a function signature and try to generate a span for
917     /// the function name (with generics) and a new snippet for this span with the pointed type
918     /// parameter as a new local type parameter.
919     ///
920     /// For instance:
921     /// ```rust,ignore (pseudo-Rust)
922     /// // Given span
923     /// fn my_function(param: T)
924     /// //                    ^ Original span
925     ///
926     /// // Result
927     /// fn my_function(param: T)
928     /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
929     /// ```
930     ///
931     /// Attention: The method used is very fragile since it essentially duplicates the work of the
932     /// parser. If you need to use this function or something similar, please consider updating the
933     /// `SourceMap` functions and this function to something more robust.
934     pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
935         // Try to extend the span to the previous "fn" keyword to retrieve the function
936         // signature.
937         let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
938         if sugg_span != span {
939             if let Ok(snippet) = self.span_to_snippet(sugg_span) {
940                 // Consume the function name.
941                 let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
942                     .expect("no label after fn");
943
944                 // Consume the generics part of the function signature.
945                 let mut bracket_counter = 0;
946                 let mut last_char = None;
947                 for c in snippet[offset..].chars() {
948                     match c {
949                         '<' => bracket_counter += 1,
950                         '>' => bracket_counter -= 1,
951                         '(' => if bracket_counter == 0 { break; }
952                         _ => {}
953                     }
954                     offset += c.len_utf8();
955                     last_char = Some(c);
956                 }
957
958                 // Adjust the suggestion span to encompass the function name with its generics.
959                 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
960
961                 // Prepare the new suggested snippet to append the type parameter that triggered
962                 // the error in the generics of the function signature.
963                 let mut new_snippet = if last_char == Some('>') {
964                     format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
965                 } else {
966                     format!("{}<", &snippet[..offset])
967                 };
968                 new_snippet.push_str(
969                     &self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
970                 new_snippet.push('>');
971
972                 return Some((sugg_span, new_snippet));
973             }
974         }
975
976         None
977     }
978 }
979
980 impl SourceMapper for SourceMap {
981     fn lookup_char_pos(&self, pos: BytePos) -> Loc {
982         self.lookup_char_pos(pos)
983     }
984     fn span_to_lines(&self, sp: Span) -> FileLinesResult {
985         self.span_to_lines(sp)
986     }
987     fn span_to_string(&self, sp: Span) -> String {
988         self.span_to_string(sp)
989     }
990     fn span_to_filename(&self, sp: Span) -> FileName {
991         self.span_to_filename(sp)
992     }
993     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
994         self.merge_spans(sp_lhs, sp_rhs)
995     }
996     fn call_span_if_macro(&self, sp: Span) -> Span {
997         if self.span_to_filename(sp.clone()).is_macros() {
998             let v = sp.macro_backtrace();
999             if let Some(use_site) = v.last() {
1000                 return use_site.call_site;
1001             }
1002         }
1003         sp
1004     }
1005     fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
1006         source_file.add_external_src(
1007             || match source_file.name {
1008                 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
1009                 _ => None,
1010             }
1011         )
1012     }
1013     fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize {
1014         self.doctest_offset_line(file, line)
1015     }
1016 }
1017
1018 #[derive(Clone)]
1019 pub struct FilePathMapping {
1020     mapping: Vec<(PathBuf, PathBuf)>,
1021 }
1022
1023 impl FilePathMapping {
1024     pub fn empty() -> FilePathMapping {
1025         FilePathMapping {
1026             mapping: vec![]
1027         }
1028     }
1029
1030     pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1031         FilePathMapping {
1032             mapping,
1033         }
1034     }
1035
1036     /// Applies any path prefix substitution as defined by the mapping.
1037     /// The return value is the remapped path and a boolean indicating whether
1038     /// the path was affected by the mapping.
1039     pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1040         // NOTE: We are iterating over the mapping entries from last to first
1041         //       because entries specified later on the command line should
1042         //       take precedence.
1043         for &(ref from, ref to) in self.mapping.iter().rev() {
1044             if let Ok(rest) = path.strip_prefix(from) {
1045                 return (to.join(rest), true);
1046             }
1047         }
1048
1049         (path, false)
1050     }
1051 }