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