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