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