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