]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/source_map.rs
pprust: Do not print spaces before some tokens
[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 SourceFiles. Byte positions are stored in
6 //! `spans` 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 SourceFiles 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 SourceFiles 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 source_map, even in the presence of zero-length files.
208             Some(last) => last.end_pos.to_usize() + 1,
209         }
210     }
211
212     /// Creates a new source_file.
213     /// If a file already exists in the source_map 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 source_file" 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, apply 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     /// Lookup 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 relevant source_file is empty, we don't 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, the spans have to be:
429     ///
430     ///    * the ctxt 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         // make sure 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 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     pub fn span_to_filename(&self, sp: Span) -> FileName {
477         self.lookup_char_pos(sp.lo()).file.name.clone()
478     }
479
480     pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
481         self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
482             .expect("SourceMap::span_to_unmapped_path called for imported SourceFile?")
483     }
484
485     pub fn is_multiline(&self, sp: Span) -> bool {
486         let lo = self.lookup_char_pos(sp.lo());
487         let hi = self.lookup_char_pos(sp.hi());
488         lo.line != hi.line
489     }
490
491     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
492         debug!("span_to_lines(sp={:?})", sp);
493
494         if sp.lo() > sp.hi() {
495             return Err(SpanLinesError::IllFormedSpan(sp));
496         }
497
498         let lo = self.lookup_char_pos(sp.lo());
499         debug!("span_to_lines: lo={:?}", lo);
500         let hi = self.lookup_char_pos(sp.hi());
501         debug!("span_to_lines: hi={:?}", hi);
502
503         if lo.file.start_pos != hi.file.start_pos {
504             return Err(SpanLinesError::DistinctSources(DistinctSources {
505                 begin: (lo.file.name.clone(), lo.file.start_pos),
506                 end: (hi.file.name.clone(), hi.file.start_pos),
507             }));
508         }
509         assert!(hi.line >= lo.line);
510
511         let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
512
513         // The span starts partway through the first line,
514         // but after that it starts from offset 0.
515         let mut start_col = lo.col;
516
517         // For every line but the last, it extends from `start_col`
518         // and to the end of the line. Be careful because the line
519         // numbers in Loc are 1-based, so we subtract 1 to get 0-based
520         // lines.
521         for line_index in lo.line-1 .. hi.line-1 {
522             let line_len = lo.file.get_line(line_index)
523                                   .map(|s| s.chars().count())
524                                   .unwrap_or(0);
525             lines.push(LineInfo { line_index,
526                                   start_col,
527                                   end_col: CharPos::from_usize(line_len) });
528             start_col = CharPos::from_usize(0);
529         }
530
531         // For the last line, it extends from `start_col` to `hi.col`:
532         lines.push(LineInfo { line_index: hi.line - 1,
533                               start_col,
534                               end_col: hi.col });
535
536         Ok(FileLines {file: lo.file, lines})
537     }
538
539     /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
540     /// extract function takes three arguments: a string slice containing the source, an index in
541     /// the slice for the beginning of the span and an index in the slice for the end of the span.
542     fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
543         where F: Fn(&str, usize, usize) -> Result<String, SpanSnippetError>
544     {
545         if sp.lo() > sp.hi() {
546             return Err(SpanSnippetError::IllFormedSpan(sp));
547         }
548
549         let local_begin = self.lookup_byte_offset(sp.lo());
550         let local_end = self.lookup_byte_offset(sp.hi());
551
552         if local_begin.sf.start_pos != local_end.sf.start_pos {
553             return Err(SpanSnippetError::DistinctSources(DistinctSources {
554                 begin: (local_begin.sf.name.clone(),
555                         local_begin.sf.start_pos),
556                 end: (local_end.sf.name.clone(),
557                       local_end.sf.start_pos)
558             }));
559         } else {
560             self.ensure_source_file_source_present(local_begin.sf.clone());
561
562             let start_index = local_begin.pos.to_usize();
563             let end_index = local_end.pos.to_usize();
564             let source_len = (local_begin.sf.end_pos -
565                               local_begin.sf.start_pos).to_usize();
566
567             if start_index > end_index || end_index > source_len {
568                 return Err(SpanSnippetError::MalformedForSourcemap(
569                     MalformedSourceMapPositions {
570                         name: local_begin.sf.name.clone(),
571                         source_len,
572                         begin_pos: local_begin.pos,
573                         end_pos: local_end.pos,
574                     }));
575             }
576
577             if let Some(ref src) = local_begin.sf.src {
578                 return extract_source(src, start_index, end_index);
579             } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
580                 return extract_source(src, start_index, end_index);
581             } else {
582                 return Err(SpanSnippetError::SourceNotAvailable {
583                     filename: local_begin.sf.name.clone()
584                 });
585             }
586         }
587     }
588
589     /// Returns the source snippet as `String` corresponding to the given `Span`
590     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
591         self.span_to_source(sp, |src, start_index, end_index| src.get(start_index..end_index)
592             .map(|s| s.to_string())
593             .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)))
594     }
595
596     pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
597         match self.span_to_prev_source(sp) {
598             Err(_) => None,
599             Ok(source) => source.split('\n').last().map(|last_line| {
600                 last_line.len() - last_line.trim_start().len()
601             })
602         }
603     }
604
605     /// Returns the source snippet as `String` before the given `Span`
606     pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
607         self.span_to_source(sp, |src, start_index, _| src.get(..start_index)
608             .map(|s| s.to_string())
609             .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp)))
610     }
611
612     /// Extend the given `Span` to just after the previous occurrence of `c`. Return the same span
613     /// if no character could be found or if an error occurred while retrieving the code snippet.
614     pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span {
615         if let Ok(prev_source) = self.span_to_prev_source(sp) {
616             let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_start();
617             if !prev_source.is_empty() && !prev_source.contains('\n') {
618                 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
619             }
620         }
621
622         sp
623     }
624
625     /// Extend the given `Span` to just after the previous occurrence of `pat` when surrounded by
626     /// whitespace. Return the same span if no character could be found or if an error occurred
627     /// while retrieving the code snippet.
628     pub fn span_extend_to_prev_str(&self, sp: Span, pat: &str, accept_newlines: bool) -> Span {
629         // assure that the pattern is delimited, to avoid the following
630         //     fn my_fn()
631         //           ^^^^ returned span without the check
632         //     ---------- correct span
633         for ws in &[" ", "\t", "\n"] {
634             let pat = pat.to_owned() + ws;
635             if let Ok(prev_source) = self.span_to_prev_source(sp) {
636                 let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_start();
637                 if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) {
638                     return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
639                 }
640             }
641         }
642
643         sp
644     }
645
646     /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
647     pub fn span_until_char(&self, sp: Span, c: char) -> Span {
648         match self.span_to_snippet(sp) {
649             Ok(snippet) => {
650                 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end();
651                 if !snippet.is_empty() && !snippet.contains('\n') {
652                     sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
653                 } else {
654                     sp
655                 }
656             }
657             _ => sp,
658         }
659     }
660
661     /// Given a `Span`, try to get a shorter span ending just after the first occurrence of `char`
662     /// `c`.
663     pub fn span_through_char(&self, sp: Span, c: char) -> Span {
664         if let Ok(snippet) = self.span_to_snippet(sp) {
665             if let Some(offset) = snippet.find(c) {
666                 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
667             }
668         }
669         sp
670     }
671
672     /// Given a `Span`, get a new `Span` covering the first token and all its trailing whitespace or
673     /// the original `Span`.
674     ///
675     /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
676     pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
677         let mut whitespace_found = false;
678
679         self.span_take_while(sp, |c| {
680             if !whitespace_found && c.is_whitespace() {
681                 whitespace_found = true;
682             }
683
684             if whitespace_found && !c.is_whitespace() {
685                 false
686             } else {
687                 true
688             }
689         })
690     }
691
692     /// Given a `Span`, get a new `Span` covering the first token without its trailing whitespace or
693     /// the original `Span` in case of error.
694     ///
695     /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
696     pub fn span_until_whitespace(&self, sp: Span) -> Span {
697         self.span_take_while(sp, |c| !c.is_whitespace())
698     }
699
700     /// Given a `Span`, get a shorter one until `predicate` yields false.
701     pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
702         where P: for <'r> FnMut(&'r char) -> bool
703     {
704         if let Ok(snippet) = self.span_to_snippet(sp) {
705             let offset = snippet.chars()
706                 .take_while(predicate)
707                 .map(|c| c.len_utf8())
708                 .sum::<usize>();
709
710             sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
711         } else {
712             sp
713         }
714     }
715
716     pub fn def_span(&self, sp: Span) -> Span {
717         self.span_until_char(sp, '{')
718     }
719
720     /// Returns a new span representing just the start-point of this span
721     pub fn start_point(&self, sp: Span) -> Span {
722         let pos = sp.lo().0;
723         let width = self.find_width_of_character_at_span(sp, false);
724         let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
725         let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
726         sp.with_hi(end_point)
727     }
728
729     /// Returns a new span representing just the end-point of this span
730     pub fn end_point(&self, sp: Span) -> Span {
731         let pos = sp.hi().0;
732
733         let width = self.find_width_of_character_at_span(sp, false);
734         let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
735
736         let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
737         sp.with_lo(end_point)
738     }
739
740     /// Returns a new span representing the next character after the end-point of this span
741     pub fn next_point(&self, sp: Span) -> Span {
742         let start_of_next_point = sp.hi().0;
743
744         let width = self.find_width_of_character_at_span(sp, true);
745         // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
746         // in the case of a multibyte character, where the width != 1, the next span should
747         // span multiple bytes to include the whole character.
748         let end_of_next_point = start_of_next_point.checked_add(
749             width - 1).unwrap_or(start_of_next_point);
750
751         let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
752         Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
753     }
754
755     /// Finds the width of a character, either before or after the provided span.
756     fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
757         // Disregard malformed spans and assume a one-byte wide character.
758         if sp.lo() >= sp.hi() {
759             debug!("find_width_of_character_at_span: early return malformed span");
760             return 1;
761         }
762
763         let local_begin = self.lookup_byte_offset(sp.lo());
764         let local_end = self.lookup_byte_offset(sp.hi());
765         debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
766                local_begin, local_end);
767
768         if local_begin.sf.start_pos != local_end.sf.start_pos {
769             debug!("find_width_of_character_at_span: begin and end are in different files");
770             return 1;
771         }
772
773         let start_index = local_begin.pos.to_usize();
774         let end_index = local_end.pos.to_usize();
775         debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
776                start_index, end_index);
777
778         // Disregard indexes that are at the start or end of their spans, they can't fit bigger
779         // characters.
780         if (!forwards && end_index == usize::min_value()) ||
781             (forwards && start_index == usize::max_value()) {
782             debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte");
783             return 1;
784         }
785
786         let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize();
787         debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len);
788         // Ensure indexes are also not malformed.
789         if start_index > end_index || end_index > source_len {
790             debug!("find_width_of_character_at_span: source indexes are malformed");
791             return 1;
792         }
793
794         let src = local_begin.sf.external_src.borrow();
795
796         // We need to extend the snippet to the end of the src rather than to end_index so when
797         // searching forwards for boundaries we've got somewhere to search.
798         let snippet = if let Some(ref src) = local_begin.sf.src {
799             let len = src.len();
800             (&src[start_index..len])
801         } else if let Some(src) = src.get_source() {
802             let len = src.len();
803             (&src[start_index..len])
804         } else {
805             return 1;
806         };
807         debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet);
808
809         let mut target = if forwards { end_index + 1 } else { end_index - 1 };
810         debug!("find_width_of_character_at_span: initial target=`{:?}`", target);
811
812         while !snippet.is_char_boundary(target - start_index) && target < source_len {
813             target = if forwards {
814                 target + 1
815             } else {
816                 match target.checked_sub(1) {
817                     Some(target) => target,
818                     None => {
819                         break;
820                     }
821                 }
822             };
823             debug!("find_width_of_character_at_span: target=`{:?}`", target);
824         }
825         debug!("find_width_of_character_at_span: final target=`{:?}`", target);
826
827         if forwards {
828             (target - end_index) as u32
829         } else {
830             (end_index - target) as u32
831         }
832     }
833
834     pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
835         for sf in self.files.borrow().source_files.iter() {
836             if *filename == sf.name {
837                 return Some(sf.clone());
838             }
839         }
840         None
841     }
842
843     /// For a global BytePos compute the local offset within the containing SourceFile
844     pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
845         let idx = self.lookup_source_file_idx(bpos);
846         let sf = (*self.files.borrow().source_files)[idx].clone();
847         let offset = bpos - sf.start_pos;
848         SourceFileAndBytePos {sf, pos: offset}
849     }
850
851     /// Converts an absolute BytePos to a CharPos relative to the source_file.
852     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
853         let idx = self.lookup_source_file_idx(bpos);
854         let map = &(*self.files.borrow().source_files)[idx];
855
856         // The number of extra bytes due to multibyte chars in the SourceFile
857         let mut total_extra_bytes = 0;
858
859         for mbc in map.multibyte_chars.iter() {
860             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
861             if mbc.pos < bpos {
862                 // every character is at least one byte, so we only
863                 // count the actual extra bytes.
864                 total_extra_bytes += mbc.bytes as u32 - 1;
865                 // We should never see a byte position in the middle of a
866                 // character
867                 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
868             } else {
869                 break;
870             }
871         }
872
873         assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
874         CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
875     }
876
877     // Return the index of the source_file (in self.files) which contains pos.
878     pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
879         let files = self.files.borrow();
880         let files = &files.source_files;
881         let count = files.len();
882
883         // Binary search for the source_file.
884         let mut a = 0;
885         let mut b = count;
886         while b - a > 1 {
887             let m = (a + b) / 2;
888             if files[m].start_pos > pos {
889                 b = m;
890             } else {
891                 a = m;
892             }
893         }
894
895         assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
896
897         return a;
898     }
899
900     pub fn count_lines(&self) -> usize {
901         self.files().iter().fold(0, |a, f| a + f.count_lines())
902     }
903
904
905     pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
906         let prev_span = self.span_extend_to_prev_str(span, "fn", true);
907         self.span_to_snippet(prev_span).map(|snippet| {
908             let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
909                 .expect("no label after fn");
910             prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
911         }).ok()
912     }
913
914     /// Take the span of a type parameter in a function signature and try to generate a span for the
915     /// function name (with generics) and a new snippet for this span with the pointed type
916     /// parameter as a new local type parameter.
917     ///
918     /// For instance:
919     /// ```rust,ignore (pseudo-Rust)
920     /// // Given span
921     /// fn my_function(param: T)
922     /// //                    ^ Original span
923     ///
924     /// // Result
925     /// fn my_function(param: T)
926     /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
927     /// ```
928     ///
929     /// Attention: The method used is very fragile since it essentially duplicates the work of the
930     /// parser. If you need to use this function or something similar, please consider updating the
931     /// source_map functions and this function to something more robust.
932     pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
933         // Try to extend the span to the previous "fn" keyword to retrieve the function
934         // signature
935         let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
936         if sugg_span != span {
937             if let Ok(snippet) = self.span_to_snippet(sugg_span) {
938                 // Consume the function name
939                 let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
940                     .expect("no label after fn");
941
942                 // Consume the generics part of the function signature
943                 let mut bracket_counter = 0;
944                 let mut last_char = None;
945                 for c in snippet[offset..].chars() {
946                     match c {
947                         '<' => bracket_counter += 1,
948                         '>' => bracket_counter -= 1,
949                         '(' => if bracket_counter == 0 { break; }
950                         _ => {}
951                     }
952                     offset += c.len_utf8();
953                     last_char = Some(c);
954                 }
955
956                 // Adjust the suggestion span to encompass the function name with its generics
957                 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
958
959                 // Prepare the new suggested snippet to append the type parameter that triggered
960                 // the error in the generics of the function signature
961                 let mut new_snippet = if last_char == Some('>') {
962                     format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
963                 } else {
964                     format!("{}<", &snippet[..offset])
965                 };
966                 new_snippet.push_str(
967                     &self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
968                 new_snippet.push('>');
969
970                 return Some((sugg_span, new_snippet));
971             }
972         }
973
974         None
975     }
976 }
977
978 impl SourceMapper for SourceMap {
979     fn lookup_char_pos(&self, pos: BytePos) -> Loc {
980         self.lookup_char_pos(pos)
981     }
982     fn span_to_lines(&self, sp: Span) -> FileLinesResult {
983         self.span_to_lines(sp)
984     }
985     fn span_to_string(&self, sp: Span) -> String {
986         self.span_to_string(sp)
987     }
988     fn span_to_filename(&self, sp: Span) -> FileName {
989         self.span_to_filename(sp)
990     }
991     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
992         self.merge_spans(sp_lhs, sp_rhs)
993     }
994     fn call_span_if_macro(&self, sp: Span) -> Span {
995         if self.span_to_filename(sp.clone()).is_macros() {
996             let v = sp.macro_backtrace();
997             if let Some(use_site) = v.last() {
998                 return use_site.call_site;
999             }
1000         }
1001         sp
1002     }
1003     fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
1004         source_file.add_external_src(
1005             || match source_file.name {
1006                 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
1007                 _ => None,
1008             }
1009         )
1010     }
1011     fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize {
1012         self.doctest_offset_line(file, line)
1013     }
1014 }
1015
1016 #[derive(Clone)]
1017 pub struct FilePathMapping {
1018     mapping: Vec<(PathBuf, PathBuf)>,
1019 }
1020
1021 impl FilePathMapping {
1022     pub fn empty() -> FilePathMapping {
1023         FilePathMapping {
1024             mapping: vec![]
1025         }
1026     }
1027
1028     pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1029         FilePathMapping {
1030             mapping,
1031         }
1032     }
1033
1034     /// Applies any path prefix substitution as defined by the mapping.
1035     /// The return value is the remapped path and a boolean indicating whether
1036     /// the path was affected by the mapping.
1037     pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1038         // NOTE: We are iterating over the mapping entries from last to first
1039         //       because entries specified later on the command line should
1040         //       take precedence.
1041         for &(ref from, ref to) in self.mapping.iter().rev() {
1042             if let Ok(rest) = path.strip_prefix(from) {
1043                 return (to.join(rest), true);
1044             }
1045         }
1046
1047         (path, false)
1048     }
1049 }