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