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