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