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