]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/source_map.rs
Rollup merge of #62692 - eddyb:precompute-niches, r=oli-obk
[rust.git] / src / libsyntax / 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 SourceFiles. Byte positions are stored in
6 //! `spans` 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 syntax_pos::*;
11 pub use syntax_pos::hygiene::{ExpnKind, ExpnInfo};
12
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::stable_hasher::StableHasher;
15 use rustc_data_structures::sync::{Lrc, Lock, LockGuard, MappedLockGuard};
16 use std::cmp;
17 use std::hash::Hash;
18 use std::path::{Path, PathBuf};
19
20 use std::env;
21 use std::fs;
22 use std::io;
23 use log::debug;
24
25 use errors::SourceMapper;
26
27 /// Returns the span itself if it doesn't come from a macro expansion,
28 /// otherwise return the call site span up to the `enclosing_sp` by
29 /// following the `expn_info` chain.
30 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
31     let call_site1 = sp.ctxt().outer_expn_info().map(|ei| ei.call_site);
32     let call_site2 = enclosing_sp.ctxt().outer_expn_info().map(|ei| ei.call_site);
33     match (call_site1, call_site2) {
34         (None, _) => sp,
35         (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
36         (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
37     }
38 }
39
40 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
41 pub struct Spanned<T> {
42     pub node: T,
43     pub span: Span,
44 }
45
46 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
47     Spanned {node: t, span: sp}
48 }
49
50 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
51     respan(DUMMY_SP, t)
52 }
53
54 // _____________________________________________________________________________
55 // SourceFile, MultiByteChar, FileName, FileLines
56 //
57
58 /// An abstraction over the fs operations used by the Parser.
59 pub trait FileLoader {
60     /// Query the existence of a file.
61     fn file_exists(&self, path: &Path) -> bool;
62
63     /// Returns an absolute path to a file, if possible.
64     fn abs_path(&self, path: &Path) -> Option<PathBuf>;
65
66     /// Read the contents of an UTF-8 file into memory.
67     fn read_file(&self, path: &Path) -> io::Result<String>;
68 }
69
70 /// A FileLoader that uses std::fs to load real files.
71 pub struct RealFileLoader;
72
73 impl FileLoader for RealFileLoader {
74     fn file_exists(&self, path: &Path) -> bool {
75         fs::metadata(path).is_ok()
76     }
77
78     fn abs_path(&self, path: &Path) -> Option<PathBuf> {
79         if path.is_absolute() {
80             Some(path.to_path_buf())
81         } else {
82             env::current_dir()
83                 .ok()
84                 .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 SourceFiles 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(&source_file.name,
102                                          source_file.name_was_remapped,
103                                          source_file.unmapped_path.as_ref())
104     }
105
106     pub fn new_from_pieces(name: &FileName,
107                            name_was_remapped: bool,
108                            unmapped_path: Option<&FileName>) -> StableSourceFileId {
109         let mut hasher = StableHasher::new();
110
111         name.hash(&mut hasher);
112         name_was_remapped.hash(&mut hasher);
113         unmapped_path.hash(&mut hasher);
114
115         StableSourceFileId(hasher.finish())
116     }
117 }
118
119 // _____________________________________________________________________________
120 // SourceMap
121 //
122
123 #[derive(Default)]
124 pub(super) struct SourceMapFiles {
125     pub(super) source_files: Vec<Lrc<SourceFile>>,
126     stable_id_to_source_file: FxHashMap<StableSourceFileId, Lrc<SourceFile>>
127 }
128
129 pub struct SourceMap {
130     pub(super) files: Lock<SourceMapFiles>,
131     file_loader: Box<dyn FileLoader + Sync + Send>,
132     // This is used to apply the file path remapping as specified via
133     // --remap-path-prefix to all SourceFiles allocated within this SourceMap.
134     path_mapping: FilePathMapping,
135 }
136
137 impl SourceMap {
138     pub fn new(path_mapping: FilePathMapping) -> SourceMap {
139         SourceMap {
140             files: Default::default(),
141             file_loader: Box::new(RealFileLoader),
142             path_mapping,
143         }
144     }
145
146     pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
147                             path_mapping: FilePathMapping)
148                             -> SourceMap {
149         SourceMap {
150             files: Default::default(),
151             file_loader,
152             path_mapping,
153         }
154     }
155
156     pub fn path_mapping(&self) -> &FilePathMapping {
157         &self.path_mapping
158     }
159
160     pub fn file_exists(&self, path: &Path) -> bool {
161         self.file_loader.file_exists(path)
162     }
163
164     pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
165         let src = self.file_loader.read_file(path)?;
166         let filename = path.to_owned().into();
167         Ok(self.new_source_file(filename, src))
168     }
169
170     pub fn files(&self) -> MappedLockGuard<'_, Vec<Lrc<SourceFile>>> {
171         LockGuard::map(self.files.borrow(), |files| &mut files.source_files)
172     }
173
174     pub fn source_file_by_stable_id(&self, stable_id: StableSourceFileId) ->
175     Option<Lrc<SourceFile>> {
176         self.files.borrow().stable_id_to_source_file.get(&stable_id).map(|sf| sf.clone())
177     }
178
179     fn next_start_pos(&self) -> usize {
180         match self.files.borrow().source_files.last() {
181             None => 0,
182             // Add one so there is some space between files. This lets us distinguish
183             // positions in the source_map, even in the presence of zero-length files.
184             Some(last) => last.end_pos.to_usize() + 1,
185         }
186     }
187
188     /// Creates a new source_file.
189     /// If a file already exists in the source_map with the same id, that file is returned
190     /// unmodified
191     pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc<SourceFile> {
192         self.try_new_source_file(filename, src)
193             .unwrap_or_else(|OffsetOverflowError| {
194                 eprintln!("fatal error: rustc does not support files larger than 4GB");
195                 errors::FatalError.raise()
196             })
197     }
198
199     fn try_new_source_file(
200         &self,
201         filename: FileName,
202         src: String
203     ) -> Result<Lrc<SourceFile>, OffsetOverflowError> {
204         let start_pos = self.next_start_pos();
205
206         // The path is used to determine the directory for loading submodules and
207         // include files, so it must be before remapping.
208         // Note that filename may not be a valid path, eg it may be `<anon>` etc,
209         // but this is okay because the directory determined by `path.pop()` will
210         // be empty, so the working directory will be used.
211         let unmapped_path = filename.clone();
212
213         let (filename, was_remapped) = match filename {
214             FileName::Real(filename) => {
215                 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
216                 (FileName::Real(filename), was_remapped)
217             },
218             other => (other, false),
219         };
220
221         let file_id = StableSourceFileId::new_from_pieces(&filename,
222                                                        was_remapped,
223                                                        Some(&unmapped_path));
224
225         let lrc_sf = match self.source_file_by_stable_id(file_id) {
226             Some(lrc_sf) => lrc_sf,
227             None => {
228                 let source_file = Lrc::new(SourceFile::new(
229                     filename,
230                     was_remapped,
231                     unmapped_path,
232                     src,
233                     Pos::from_usize(start_pos),
234                 )?);
235
236                 let mut files = self.files.borrow_mut();
237
238                 files.source_files.push(source_file.clone());
239                 files.stable_id_to_source_file.insert(file_id, source_file.clone());
240
241                 source_file
242             }
243         };
244         Ok(lrc_sf)
245     }
246
247     /// Allocates a new SourceFile representing a source file from an external
248     /// crate. The source code of such an "imported source_file" is not available,
249     /// but we still know enough to generate accurate debuginfo location
250     /// information for things inlined from other crates.
251     pub fn new_imported_source_file(
252         &self,
253         filename: FileName,
254         name_was_remapped: bool,
255         crate_of_origin: u32,
256         src_hash: u128,
257         name_hash: u128,
258         source_len: usize,
259         mut file_local_lines: Vec<BytePos>,
260         mut file_local_multibyte_chars: Vec<MultiByteChar>,
261         mut file_local_non_narrow_chars: Vec<NonNarrowChar>,
262     ) -> Lrc<SourceFile> {
263         let start_pos = self.next_start_pos();
264
265         let end_pos = Pos::from_usize(start_pos + source_len);
266         let start_pos = Pos::from_usize(start_pos);
267
268         for pos in &mut file_local_lines {
269             *pos = *pos + start_pos;
270         }
271
272         for mbc in &mut file_local_multibyte_chars {
273             mbc.pos = mbc.pos + start_pos;
274         }
275
276         for swc in &mut file_local_non_narrow_chars {
277             *swc = *swc + start_pos;
278         }
279
280         let source_file = Lrc::new(SourceFile {
281             name: filename,
282             name_was_remapped,
283             unmapped_path: None,
284             crate_of_origin,
285             src: None,
286             src_hash,
287             external_src: Lock::new(ExternalSource::AbsentOk),
288             start_pos,
289             end_pos,
290             lines: file_local_lines,
291             multibyte_chars: file_local_multibyte_chars,
292             non_narrow_chars: file_local_non_narrow_chars,
293             name_hash,
294         });
295
296         let mut files = self.files.borrow_mut();
297
298         files.source_files.push(source_file.clone());
299         files.stable_id_to_source_file.insert(StableSourceFileId::new(&source_file),
300                                               source_file.clone());
301
302         source_file
303     }
304
305     pub fn mk_substr_filename(&self, sp: Span) -> String {
306         let pos = self.lookup_char_pos(sp.lo());
307         format!("<{}:{}:{}>",
308                  pos.file.name,
309                  pos.line,
310                  pos.col.to_usize() + 1)
311     }
312
313     // If there is a doctest_offset, apply it to the line
314     pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
315         return match file {
316             FileName::DocTest(_, offset) => {
317                 return if *offset >= 0 {
318                     orig + *offset as usize
319                 } else {
320                     orig - (-(*offset)) as usize
321                 }
322             },
323             _ => orig
324         }
325     }
326
327     /// Lookup source information about a BytePos
328     pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
329         let chpos = self.bytepos_to_file_charpos(pos);
330         match self.lookup_line(pos) {
331             Ok(SourceFileAndLine { sf: f, line: a }) => {
332                 let line = a + 1; // Line numbers start at 1
333                 let linebpos = f.lines[a];
334                 let linechpos = self.bytepos_to_file_charpos(linebpos);
335                 let col = chpos - linechpos;
336
337                 let col_display = {
338                     let start_width_idx = f
339                         .non_narrow_chars
340                         .binary_search_by_key(&linebpos, |x| x.pos())
341                         .unwrap_or_else(|x| x);
342                     let end_width_idx = f
343                         .non_narrow_chars
344                         .binary_search_by_key(&pos, |x| x.pos())
345                         .unwrap_or_else(|x| x);
346                     let special_chars = end_width_idx - start_width_idx;
347                     let non_narrow: usize = f
348                         .non_narrow_chars[start_width_idx..end_width_idx]
349                         .into_iter()
350                         .map(|x| x.width())
351                         .sum();
352                     col.0 - special_chars + non_narrow
353                 };
354                 debug!("byte pos {:?} is on the line at byte pos {:?}",
355                        pos, linebpos);
356                 debug!("char pos {:?} is on the line at char pos {:?}",
357                        chpos, linechpos);
358                 debug!("byte is on line: {}", line);
359                 assert!(chpos >= linechpos);
360                 Loc {
361                     file: f,
362                     line,
363                     col,
364                     col_display,
365                 }
366             }
367             Err(f) => {
368                 let col_display = {
369                     let end_width_idx = f
370                         .non_narrow_chars
371                         .binary_search_by_key(&pos, |x| x.pos())
372                         .unwrap_or_else(|x| x);
373                     let non_narrow: usize = f
374                         .non_narrow_chars[0..end_width_idx]
375                         .into_iter()
376                         .map(|x| x.width())
377                         .sum();
378                     chpos.0 - end_width_idx + non_narrow
379                 };
380                 Loc {
381                     file: f,
382                     line: 0,
383                     col: chpos,
384                     col_display,
385                 }
386             }
387         }
388     }
389
390     // If the relevant source_file is empty, we don't return a line number.
391     pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Lrc<SourceFile>> {
392         let idx = self.lookup_source_file_idx(pos);
393
394         let f = (*self.files.borrow().source_files)[idx].clone();
395
396         match f.lookup_line(pos) {
397             Some(line) => Ok(SourceFileAndLine { sf: f, line }),
398             None => Err(f)
399         }
400     }
401
402     /// Returns `Some(span)`, a union of the lhs and rhs span. The lhs must precede the rhs. If
403     /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
404     /// For this to work, the spans have to be:
405     ///
406     ///    * the ctxt of both spans much match
407     ///    * the lhs span needs to end on the same line the rhs span begins
408     ///    * the lhs span must start at or before the rhs span
409     pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
410         // make sure we're at the same expansion id
411         if sp_lhs.ctxt() != sp_rhs.ctxt() {
412             return None;
413         }
414
415         let lhs_end = match self.lookup_line(sp_lhs.hi()) {
416             Ok(x) => x,
417             Err(_) => return None
418         };
419         let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
420             Ok(x) => x,
421             Err(_) => return None
422         };
423
424         // if we must cross lines to merge, don't merge
425         if lhs_end.line != rhs_begin.line {
426             return None;
427         }
428
429         // ensure these follow the expected order and we don't overlap
430         if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
431             Some(sp_lhs.to(sp_rhs))
432         } else {
433             None
434         }
435     }
436
437     pub fn span_to_string(&self, sp: Span) -> String {
438         if self.files.borrow().source_files.is_empty() && sp.is_dummy() {
439             return "no-location".to_string();
440         }
441
442         let lo = self.lookup_char_pos(sp.lo());
443         let hi = self.lookup_char_pos(sp.hi());
444         format!("{}:{}:{}: {}:{}",
445                         lo.file.name,
446                         lo.line,
447                         lo.col.to_usize() + 1,
448                         hi.line,
449                         hi.col.to_usize() + 1)
450     }
451
452     pub fn span_to_filename(&self, sp: Span) -> FileName {
453         self.lookup_char_pos(sp.lo()).file.name.clone()
454     }
455
456     pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
457         self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
458             .expect("SourceMap::span_to_unmapped_path called for imported SourceFile?")
459     }
460
461     pub fn is_multiline(&self, sp: Span) -> bool {
462         let lo = self.lookup_char_pos(sp.lo());
463         let hi = self.lookup_char_pos(sp.hi());
464         lo.line != hi.line
465     }
466
467     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
468         debug!("span_to_lines(sp={:?})", sp);
469
470         if sp.lo() > sp.hi() {
471             return Err(SpanLinesError::IllFormedSpan(sp));
472         }
473
474         let lo = self.lookup_char_pos(sp.lo());
475         debug!("span_to_lines: lo={:?}", lo);
476         let hi = self.lookup_char_pos(sp.hi());
477         debug!("span_to_lines: hi={:?}", hi);
478
479         if lo.file.start_pos != hi.file.start_pos {
480             return Err(SpanLinesError::DistinctSources(DistinctSources {
481                 begin: (lo.file.name.clone(), lo.file.start_pos),
482                 end: (hi.file.name.clone(), hi.file.start_pos),
483             }));
484         }
485         assert!(hi.line >= lo.line);
486
487         let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
488
489         // The span starts partway through the first line,
490         // but after that it starts from offset 0.
491         let mut start_col = lo.col;
492
493         // For every line but the last, it extends from `start_col`
494         // and to the end of the line. Be careful because the line
495         // numbers in Loc are 1-based, so we subtract 1 to get 0-based
496         // lines.
497         for line_index in lo.line-1 .. hi.line-1 {
498             let line_len = lo.file.get_line(line_index)
499                                   .map(|s| s.chars().count())
500                                   .unwrap_or(0);
501             lines.push(LineInfo { line_index,
502                                   start_col,
503                                   end_col: CharPos::from_usize(line_len) });
504             start_col = CharPos::from_usize(0);
505         }
506
507         // For the last line, it extends from `start_col` to `hi.col`:
508         lines.push(LineInfo { line_index: hi.line - 1,
509                               start_col,
510                               end_col: hi.col });
511
512         Ok(FileLines {file: lo.file, lines})
513     }
514
515     /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
516     /// extract function takes three arguments: a string slice containing the source, an index in
517     /// the slice for the beginning of the span and an index in the slice for the end of the span.
518     fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
519         where F: Fn(&str, usize, usize) -> String
520     {
521         if sp.lo() > sp.hi() {
522             return Err(SpanSnippetError::IllFormedSpan(sp));
523         }
524
525         let local_begin = self.lookup_byte_offset(sp.lo());
526         let local_end = self.lookup_byte_offset(sp.hi());
527
528         if local_begin.sf.start_pos != local_end.sf.start_pos {
529             return Err(SpanSnippetError::DistinctSources(DistinctSources {
530                 begin: (local_begin.sf.name.clone(),
531                         local_begin.sf.start_pos),
532                 end: (local_end.sf.name.clone(),
533                       local_end.sf.start_pos)
534             }));
535         } else {
536             self.ensure_source_file_source_present(local_begin.sf.clone());
537
538             let start_index = local_begin.pos.to_usize();
539             let end_index = local_end.pos.to_usize();
540             let source_len = (local_begin.sf.end_pos -
541                               local_begin.sf.start_pos).to_usize();
542
543             if start_index > end_index || end_index > source_len {
544                 return Err(SpanSnippetError::MalformedForSourcemap(
545                     MalformedSourceMapPositions {
546                         name: local_begin.sf.name.clone(),
547                         source_len,
548                         begin_pos: local_begin.pos,
549                         end_pos: local_end.pos,
550                     }));
551             }
552
553             if let Some(ref src) = local_begin.sf.src {
554                 return Ok(extract_source(src, start_index, end_index));
555             } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() {
556                 return Ok(extract_source(src, start_index, end_index));
557             } else {
558                 return Err(SpanSnippetError::SourceNotAvailable {
559                     filename: local_begin.sf.name.clone()
560                 });
561             }
562         }
563     }
564
565     /// Returns the source snippet as `String` corresponding to the given `Span`
566     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
567         self.span_to_source(sp, |src, start_index, end_index| src[start_index..end_index]
568                                                                 .to_string())
569     }
570
571     pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
572         match self.span_to_prev_source(sp) {
573             Err(_) => None,
574             Ok(source) => source.split('\n').last().map(|last_line| {
575                 last_line.len() - last_line.trim_start().len()
576             })
577         }
578     }
579
580     /// Returns the source snippet as `String` before the given `Span`
581     pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
582         self.span_to_source(sp, |src, start_index, _| src[..start_index].to_string())
583     }
584
585     /// Extend 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     /// Extend the given `Span` to just after the previous occurrence of `pat` when surrounded by
599     /// whitespace. Return 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`, try to get a shorter span ending before the first occurrence of `c` `char`
620     pub fn span_until_char(&self, sp: Span, c: char) -> Span {
621         match self.span_to_snippet(sp) {
622             Ok(snippet) => {
623                 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end();
624                 if !snippet.is_empty() && !snippet.contains('\n') {
625                     sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
626                 } else {
627                     sp
628                 }
629             }
630             _ => sp,
631         }
632     }
633
634     /// Given a `Span`, try to get a shorter span ending just after the first occurrence of `char`
635     /// `c`.
636     pub fn span_through_char(&self, sp: Span, c: char) -> Span {
637         if let Ok(snippet) = self.span_to_snippet(sp) {
638             if let Some(offset) = snippet.find(c) {
639                 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
640             }
641         }
642         sp
643     }
644
645     /// Given a `Span`, get a new `Span` covering the first token and all its trailing whitespace or
646     /// the original `Span`.
647     ///
648     /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
649     pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
650         let mut whitespace_found = false;
651
652         self.span_take_while(sp, |c| {
653             if !whitespace_found && c.is_whitespace() {
654                 whitespace_found = true;
655             }
656
657             if whitespace_found && !c.is_whitespace() {
658                 false
659             } else {
660                 true
661             }
662         })
663     }
664
665     /// Given a `Span`, get a new `Span` covering the first token without its trailing whitespace or
666     /// the original `Span` in case of error.
667     ///
668     /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
669     pub fn span_until_whitespace(&self, sp: Span) -> Span {
670         self.span_take_while(sp, |c| !c.is_whitespace())
671     }
672
673     /// Given a `Span`, get a shorter one until `predicate` yields false.
674     pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
675         where P: for <'r> FnMut(&'r char) -> bool
676     {
677         if let Ok(snippet) = self.span_to_snippet(sp) {
678             let offset = snippet.chars()
679                 .take_while(predicate)
680                 .map(|c| c.len_utf8())
681                 .sum::<usize>();
682
683             sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
684         } else {
685             sp
686         }
687     }
688
689     pub fn def_span(&self, sp: Span) -> Span {
690         self.span_until_char(sp, '{')
691     }
692
693     /// Returns a new span representing just the start-point of this span
694     pub fn start_point(&self, sp: Span) -> Span {
695         let pos = sp.lo().0;
696         let width = self.find_width_of_character_at_span(sp, false);
697         let corrected_start_position = pos.checked_add(width).unwrap_or(pos);
698         let end_point = BytePos(cmp::max(corrected_start_position, sp.lo().0));
699         sp.with_hi(end_point)
700     }
701
702     /// Returns a new span representing just the end-point of this span
703     pub fn end_point(&self, sp: Span) -> Span {
704         let pos = sp.hi().0;
705
706         let width = self.find_width_of_character_at_span(sp, false);
707         let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
708
709         let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0));
710         sp.with_lo(end_point)
711     }
712
713     /// Returns a new span representing the next character after the end-point of this span
714     pub fn next_point(&self, sp: Span) -> Span {
715         let start_of_next_point = sp.hi().0;
716
717         let width = self.find_width_of_character_at_span(sp, true);
718         // If the width is 1, then the next span should point to the same `lo` and `hi`. However,
719         // in the case of a multibyte character, where the width != 1, the next span should
720         // span multiple bytes to include the whole character.
721         let end_of_next_point = start_of_next_point.checked_add(
722             width - 1).unwrap_or(start_of_next_point);
723
724         let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point));
725         Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt())
726     }
727
728     /// Finds the width of a character, either before or after the provided span.
729     fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 {
730         // Disregard malformed spans and assume a one-byte wide character.
731         if sp.lo() >= sp.hi() {
732             debug!("find_width_of_character_at_span: early return malformed span");
733             return 1;
734         }
735
736         let local_begin = self.lookup_byte_offset(sp.lo());
737         let local_end = self.lookup_byte_offset(sp.hi());
738         debug!("find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`",
739                local_begin, local_end);
740
741         if local_begin.sf.start_pos != local_end.sf.start_pos {
742             debug!("find_width_of_character_at_span: begin and end are in different files");
743             return 1;
744         }
745
746         let start_index = local_begin.pos.to_usize();
747         let end_index = local_end.pos.to_usize();
748         debug!("find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`",
749                start_index, end_index);
750
751         // Disregard indexes that are at the start or end of their spans, they can't fit bigger
752         // characters.
753         if (!forwards && end_index == usize::min_value()) ||
754             (forwards && start_index == usize::max_value()) {
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 {
801             (target - end_index) as u32
802         } else {
803             (end_index - target) as u32
804         }
805     }
806
807     pub fn get_source_file(&self, filename: &FileName) -> Option<Lrc<SourceFile>> {
808         for sf in self.files.borrow().source_files.iter() {
809             if *filename == sf.name {
810                 return Some(sf.clone());
811             }
812         }
813         None
814     }
815
816     /// For a global BytePos compute the local offset within the containing SourceFile
817     pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
818         let idx = self.lookup_source_file_idx(bpos);
819         let sf = (*self.files.borrow().source_files)[idx].clone();
820         let offset = bpos - sf.start_pos;
821         SourceFileAndBytePos {sf, pos: offset}
822     }
823
824     /// Converts an absolute BytePos to a CharPos relative to the source_file.
825     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
826         let idx = self.lookup_source_file_idx(bpos);
827         let map = &(*self.files.borrow().source_files)[idx];
828
829         // The number of extra bytes due to multibyte chars in the SourceFile
830         let mut total_extra_bytes = 0;
831
832         for mbc in map.multibyte_chars.iter() {
833             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
834             if mbc.pos < bpos {
835                 // every character is at least one byte, so we only
836                 // count the actual extra bytes.
837                 total_extra_bytes += mbc.bytes as u32 - 1;
838                 // We should never see a byte position in the middle of a
839                 // character
840                 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
841             } else {
842                 break;
843             }
844         }
845
846         assert!(map.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
847         CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes as usize)
848     }
849
850     // Return the index of the source_file (in self.files) which contains pos.
851     pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
852         let files = self.files.borrow();
853         let files = &files.source_files;
854         let count = files.len();
855
856         // Binary search for the source_file.
857         let mut a = 0;
858         let mut b = count;
859         while b - a > 1 {
860             let m = (a + b) / 2;
861             if files[m].start_pos > pos {
862                 b = m;
863             } else {
864                 a = m;
865             }
866         }
867
868         assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
869
870         return a;
871     }
872
873     pub fn count_lines(&self) -> usize {
874         self.files().iter().fold(0, |a, f| a + f.count_lines())
875     }
876
877
878     pub fn generate_fn_name_span(&self, span: Span) -> Option<Span> {
879         let prev_span = self.span_extend_to_prev_str(span, "fn", true);
880         self.span_to_snippet(prev_span).map(|snippet| {
881             let len = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
882                 .expect("no label after fn");
883             prev_span.with_hi(BytePos(prev_span.lo().0 + len as u32))
884         }).ok()
885     }
886
887     /// Take the span of a type parameter in a function signature and try to generate a span for the
888     /// function name (with generics) and a new snippet for this span with the pointed type
889     /// parameter as a new local type parameter.
890     ///
891     /// For instance:
892     /// ```rust,ignore (pseudo-Rust)
893     /// // Given span
894     /// fn my_function(param: T)
895     /// //                    ^ Original span
896     ///
897     /// // Result
898     /// fn my_function(param: T)
899     /// // ^^^^^^^^^^^ Generated span with snippet `my_function<T>`
900     /// ```
901     ///
902     /// Attention: The method used is very fragile since it essentially duplicates the work of the
903     /// parser. If you need to use this function or something similar, please consider updating the
904     /// source_map functions and this function to something more robust.
905     pub fn generate_local_type_param_snippet(&self, span: Span) -> Option<(Span, String)> {
906         // Try to extend the span to the previous "fn" keyword to retrieve the function
907         // signature
908         let sugg_span = self.span_extend_to_prev_str(span, "fn", false);
909         if sugg_span != span {
910             if let Ok(snippet) = self.span_to_snippet(sugg_span) {
911                 // Consume the function name
912                 let mut offset = snippet.find(|c: char| !c.is_alphanumeric() && c != '_')
913                     .expect("no label after fn");
914
915                 // Consume the generics part of the function signature
916                 let mut bracket_counter = 0;
917                 let mut last_char = None;
918                 for c in snippet[offset..].chars() {
919                     match c {
920                         '<' => bracket_counter += 1,
921                         '>' => bracket_counter -= 1,
922                         '(' => if bracket_counter == 0 { break; }
923                         _ => {}
924                     }
925                     offset += c.len_utf8();
926                     last_char = Some(c);
927                 }
928
929                 // Adjust the suggestion span to encompass the function name with its generics
930                 let sugg_span = sugg_span.with_hi(BytePos(sugg_span.lo().0 + offset as u32));
931
932                 // Prepare the new suggested snippet to append the type parameter that triggered
933                 // the error in the generics of the function signature
934                 let mut new_snippet = if last_char == Some('>') {
935                     format!("{}, ", &snippet[..(offset - '>'.len_utf8())])
936                 } else {
937                     format!("{}<", &snippet[..offset])
938                 };
939                 new_snippet.push_str(
940                     &self.span_to_snippet(span).unwrap_or_else(|_| "T".to_string()));
941                 new_snippet.push('>');
942
943                 return Some((sugg_span, new_snippet));
944             }
945         }
946
947         None
948     }
949 }
950
951 impl SourceMapper for SourceMap {
952     fn lookup_char_pos(&self, pos: BytePos) -> Loc {
953         self.lookup_char_pos(pos)
954     }
955     fn span_to_lines(&self, sp: Span) -> FileLinesResult {
956         self.span_to_lines(sp)
957     }
958     fn span_to_string(&self, sp: Span) -> String {
959         self.span_to_string(sp)
960     }
961     fn span_to_filename(&self, sp: Span) -> FileName {
962         self.span_to_filename(sp)
963     }
964     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
965         self.merge_spans(sp_lhs, sp_rhs)
966     }
967     fn call_span_if_macro(&self, sp: Span) -> Span {
968         if self.span_to_filename(sp.clone()).is_macros() {
969             let v = sp.macro_backtrace();
970             if let Some(use_site) = v.last() {
971                 return use_site.call_site;
972             }
973         }
974         sp
975     }
976     fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
977         source_file.add_external_src(
978             || match source_file.name {
979                 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
980                 _ => None,
981             }
982         )
983     }
984     fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize {
985         self.doctest_offset_line(file, line)
986     }
987 }
988
989 #[derive(Clone)]
990 pub struct FilePathMapping {
991     mapping: Vec<(PathBuf, PathBuf)>,
992 }
993
994 impl FilePathMapping {
995     pub fn empty() -> FilePathMapping {
996         FilePathMapping {
997             mapping: vec![]
998         }
999     }
1000
1001     pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
1002         FilePathMapping {
1003             mapping,
1004         }
1005     }
1006
1007     /// Applies any path prefix substitution as defined by the mapping.
1008     /// The return value is the remapped path and a boolean indicating whether
1009     /// the path was affected by the mapping.
1010     pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1011         // NOTE: We are iterating over the mapping entries from last to first
1012         //       because entries specified later on the command line should
1013         //       take precedence.
1014         for &(ref from, ref to) in self.mapping.iter().rev() {
1015             if let Ok(rest) = path.strip_prefix(from) {
1016                 return (to.join(rest), true);
1017             }
1018         }
1019
1020         (path, false)
1021     }
1022 }
1023
1024 // _____________________________________________________________________________
1025 // Tests
1026 //
1027
1028 #[cfg(test)]
1029 mod tests {
1030     use super::*;
1031     use rustc_data_structures::sync::Lrc;
1032
1033     fn init_source_map() -> SourceMap {
1034         let sm = SourceMap::new(FilePathMapping::empty());
1035         sm.new_source_file(PathBuf::from("blork.rs").into(),
1036                        "first line.\nsecond line".to_string());
1037         sm.new_source_file(PathBuf::from("empty.rs").into(),
1038                        String::new());
1039         sm.new_source_file(PathBuf::from("blork2.rs").into(),
1040                        "first line.\nsecond line".to_string());
1041         sm
1042     }
1043
1044     #[test]
1045     fn t3() {
1046         // Test lookup_byte_offset
1047         let sm = init_source_map();
1048
1049         let srcfbp1 = sm.lookup_byte_offset(BytePos(23));
1050         assert_eq!(srcfbp1.sf.name, PathBuf::from("blork.rs").into());
1051         assert_eq!(srcfbp1.pos, BytePos(23));
1052
1053         let srcfbp1 = sm.lookup_byte_offset(BytePos(24));
1054         assert_eq!(srcfbp1.sf.name, PathBuf::from("empty.rs").into());
1055         assert_eq!(srcfbp1.pos, BytePos(0));
1056
1057         let srcfbp2 = sm.lookup_byte_offset(BytePos(25));
1058         assert_eq!(srcfbp2.sf.name, PathBuf::from("blork2.rs").into());
1059         assert_eq!(srcfbp2.pos, BytePos(0));
1060     }
1061
1062     #[test]
1063     fn t4() {
1064         // Test bytepos_to_file_charpos
1065         let sm = init_source_map();
1066
1067         let cp1 = sm.bytepos_to_file_charpos(BytePos(22));
1068         assert_eq!(cp1, CharPos(22));
1069
1070         let cp2 = sm.bytepos_to_file_charpos(BytePos(25));
1071         assert_eq!(cp2, CharPos(0));
1072     }
1073
1074     #[test]
1075     fn t5() {
1076         // Test zero-length source_files.
1077         let sm = init_source_map();
1078
1079         let loc1 = sm.lookup_char_pos(BytePos(22));
1080         assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
1081         assert_eq!(loc1.line, 2);
1082         assert_eq!(loc1.col, CharPos(10));
1083
1084         let loc2 = sm.lookup_char_pos(BytePos(25));
1085         assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
1086         assert_eq!(loc2.line, 1);
1087         assert_eq!(loc2.col, CharPos(0));
1088     }
1089
1090     fn init_source_map_mbc() -> SourceMap {
1091         let sm = SourceMap::new(FilePathMapping::empty());
1092         // € is a three byte utf8 char.
1093         sm.new_source_file(PathBuf::from("blork.rs").into(),
1094                        "fir€st €€€€ line.\nsecond line".to_string());
1095         sm.new_source_file(PathBuf::from("blork2.rs").into(),
1096                        "first line€€.\n€ second line".to_string());
1097         sm
1098     }
1099
1100     #[test]
1101     fn t6() {
1102         // Test bytepos_to_file_charpos in the presence of multi-byte chars
1103         let sm = init_source_map_mbc();
1104
1105         let cp1 = sm.bytepos_to_file_charpos(BytePos(3));
1106         assert_eq!(cp1, CharPos(3));
1107
1108         let cp2 = sm.bytepos_to_file_charpos(BytePos(6));
1109         assert_eq!(cp2, CharPos(4));
1110
1111         let cp3 = sm.bytepos_to_file_charpos(BytePos(56));
1112         assert_eq!(cp3, CharPos(12));
1113
1114         let cp4 = sm.bytepos_to_file_charpos(BytePos(61));
1115         assert_eq!(cp4, CharPos(15));
1116     }
1117
1118     #[test]
1119     fn t7() {
1120         // Test span_to_lines for a span ending at the end of source_file
1121         let sm = init_source_map();
1122         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1123         let file_lines = sm.span_to_lines(span).unwrap();
1124
1125         assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
1126         assert_eq!(file_lines.lines.len(), 1);
1127         assert_eq!(file_lines.lines[0].line_index, 1);
1128     }
1129
1130     /// Given a string like " ~~~~~~~~~~~~ ", produces a span
1131     /// converting that range. The idea is that the string has the same
1132     /// length as the input, and we uncover the byte positions. Note
1133     /// that this can span lines and so on.
1134     fn span_from_selection(input: &str, selection: &str) -> Span {
1135         assert_eq!(input.len(), selection.len());
1136         let left_index = selection.find('~').unwrap() as u32;
1137         let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
1138         Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
1139     }
1140
1141     /// Tests span_to_snippet and span_to_lines for a span converting 3
1142     /// lines in the middle of a file.
1143     #[test]
1144     fn span_to_snippet_and_lines_spanning_multiple_lines() {
1145         let sm = SourceMap::new(FilePathMapping::empty());
1146         let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1147         let selection = "     \n    ~~\n~~~\n~~~~~     \n   \n";
1148         sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_string());
1149         let span = span_from_selection(inputtext, selection);
1150
1151         // check that we are extracting the text we thought we were extracting
1152         assert_eq!(&sm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1153
1154         // check that span_to_lines gives us the complete result with the lines/cols we expected
1155         let lines = sm.span_to_lines(span).unwrap();
1156         let expected = vec![
1157             LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1158             LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1159             LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1160             ];
1161         assert_eq!(lines.lines, expected);
1162     }
1163
1164     #[test]
1165     fn t8() {
1166         // Test span_to_snippet for a span ending at the end of source_file
1167         let sm = init_source_map();
1168         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1169         let snippet = sm.span_to_snippet(span);
1170
1171         assert_eq!(snippet, Ok("second line".to_string()));
1172     }
1173
1174     #[test]
1175     fn t9() {
1176         // Test span_to_str for a span ending at the end of source_file
1177         let sm = init_source_map();
1178         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1179         let sstr =  sm.span_to_string(span);
1180
1181         assert_eq!(sstr, "blork.rs:2:1: 2:12");
1182     }
1183
1184     /// Tests failing to merge two spans on different lines
1185     #[test]
1186     fn span_merging_fail() {
1187         let sm = SourceMap::new(FilePathMapping::empty());
1188         let inputtext  = "bbbb BB\ncc CCC\n";
1189         let selection1 = "     ~~\n      \n";
1190         let selection2 = "       \n   ~~~\n";
1191         sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_owned());
1192         let span1 = span_from_selection(inputtext, selection1);
1193         let span2 = span_from_selection(inputtext, selection2);
1194
1195         assert!(sm.merge_spans(span1, span2).is_none());
1196     }
1197
1198     /// Returns the span corresponding to the `n`th occurrence of
1199     /// `substring` in `source_text`.
1200     trait SourceMapExtension {
1201         fn span_substr(&self,
1202                     file: &Lrc<SourceFile>,
1203                     source_text: &str,
1204                     substring: &str,
1205                     n: usize)
1206                     -> Span;
1207     }
1208
1209     impl SourceMapExtension for SourceMap {
1210         fn span_substr(&self,
1211                     file: &Lrc<SourceFile>,
1212                     source_text: &str,
1213                     substring: &str,
1214                     n: usize)
1215                     -> Span
1216         {
1217             println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
1218                     file.name, file.start_pos, substring, n);
1219             let mut i = 0;
1220             let mut hi = 0;
1221             loop {
1222                 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
1223                     panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
1224                         source_text, n, substring, i);
1225                 });
1226                 let lo = hi + offset;
1227                 hi = lo + substring.len();
1228                 if i == n {
1229                     let span = Span::new(
1230                         BytePos(lo as u32 + file.start_pos.0),
1231                         BytePos(hi as u32 + file.start_pos.0),
1232                         NO_EXPANSION,
1233                     );
1234                     assert_eq!(&self.span_to_snippet(span).unwrap()[..],
1235                             substring);
1236                     return span;
1237                 }
1238                 i += 1;
1239             }
1240         }
1241     }
1242 }