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