]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/codemap.rs
mv CodeMap SourceMap
[rust.git] / src / libsyntax / codemap.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The SourceMap tracks all the source code used within a single crate, mapping
12 //! from integer byte positions to the original source code location. Each bit
13 //! of source parsed during crate parsing (typically files, in-memory strings,
14 //! or various bits of macro expansion) cover a continuous range of bytes in the
15 //! SourceMap and are represented by FileMaps. Byte positions are stored in
16 //! `spans` and used pervasively in the compiler. They are absolute positions
17 //! within the SourceMap, which upon request can be converted to line and column
18 //! information, source code snippets, etc.
19
20
21 pub use syntax_pos::*;
22 pub use syntax_pos::hygiene::{ExpnFormat, ExpnInfo};
23 pub use self::ExpnFormat::*;
24
25 use rustc_data_structures::fx::FxHashMap;
26 use rustc_data_structures::stable_hasher::StableHasher;
27 use rustc_data_structures::sync::{Lrc, Lock, LockGuard};
28 use std::cmp;
29 use std::hash::Hash;
30 use std::path::{Path, PathBuf};
31
32 use std::env;
33 use std::fs;
34 use std::io::{self, Read};
35 use errors::SourceMapper;
36
37 /// Return the span itself if it doesn't come from a macro expansion,
38 /// otherwise return the call site span up to the `enclosing_sp` by
39 /// following the `expn_info` chain.
40 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
41     let call_site1 = sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
42     let call_site2 = enclosing_sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
43     match (call_site1, call_site2) {
44         (None, _) => sp,
45         (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
46         (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
47     }
48 }
49
50 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
51 pub struct Spanned<T> {
52     pub node: T,
53     pub span: Span,
54 }
55
56 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
57     Spanned {node: t, span: sp}
58 }
59
60 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
61     respan(DUMMY_SP, t)
62 }
63
64 // _____________________________________________________________________________
65 // FileMap, MultiByteChar, FileName, FileLines
66 //
67
68 /// An abstraction over the fs operations used by the Parser.
69 pub trait FileLoader {
70     /// Query the existence of a file.
71     fn file_exists(&self, path: &Path) -> bool;
72
73     /// Return an absolute path to a file, if possible.
74     fn abs_path(&self, path: &Path) -> Option<PathBuf>;
75
76     /// Read the contents of an UTF-8 file into memory.
77     fn read_file(&self, path: &Path) -> io::Result<String>;
78 }
79
80 /// A FileLoader that uses std::fs to load real files.
81 pub struct RealFileLoader;
82
83 impl FileLoader for RealFileLoader {
84     fn file_exists(&self, path: &Path) -> bool {
85         fs::metadata(path).is_ok()
86     }
87
88     fn abs_path(&self, path: &Path) -> Option<PathBuf> {
89         if path.is_absolute() {
90             Some(path.to_path_buf())
91         } else {
92             env::current_dir()
93                 .ok()
94                 .map(|cwd| cwd.join(path))
95         }
96     }
97
98     fn read_file(&self, path: &Path) -> io::Result<String> {
99         let mut src = String::new();
100         fs::File::open(path)?.read_to_string(&mut src)?;
101         Ok(src)
102     }
103 }
104
105 // This is a FileMap identifier that is used to correlate FileMaps between
106 // subsequent compilation sessions (which is something we need to do during
107 // incremental compilation).
108 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
109 pub struct StableFilemapId(u128);
110
111 impl StableFilemapId {
112     pub fn new(filemap: &FileMap) -> StableFilemapId {
113         let mut hasher = StableHasher::new();
114
115         filemap.name.hash(&mut hasher);
116         filemap.name_was_remapped.hash(&mut hasher);
117         filemap.unmapped_path.hash(&mut hasher);
118
119         StableFilemapId(hasher.finish())
120     }
121 }
122
123 // _____________________________________________________________________________
124 // SourceMap
125 //
126
127 pub(super) struct SourceMapFiles {
128     pub(super) file_maps: Vec<Lrc<FileMap>>,
129     stable_id_to_filemap: FxHashMap<StableFilemapId, Lrc<FileMap>>
130 }
131
132 pub struct SourceMap {
133     pub(super) files: Lock<SourceMapFiles>,
134     file_loader: Box<dyn FileLoader + Sync + Send>,
135     // This is used to apply the file path remapping as specified via
136     // --remap-path-prefix to all FileMaps allocated within this SourceMap.
137     path_mapping: FilePathMapping,
138     /// In case we are in a doctest, replace all file names with the PathBuf,
139     /// and add the given offsets to the line info
140     doctest_offset: Option<(FileName, isize)>,
141 }
142
143 impl SourceMap {
144     pub fn new(path_mapping: FilePathMapping) -> SourceMap {
145         SourceMap {
146             files: Lock::new(SourceMapFiles {
147                 file_maps: Vec::new(),
148                 stable_id_to_filemap: FxHashMap(),
149             }),
150             file_loader: Box::new(RealFileLoader),
151             path_mapping,
152             doctest_offset: None,
153         }
154     }
155
156     pub fn new_doctest(path_mapping: FilePathMapping,
157                        file: FileName, line: isize) -> SourceMap {
158         SourceMap {
159             doctest_offset: Some((file, line)),
160             ..SourceMap::new(path_mapping)
161         }
162
163     }
164
165     pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
166                             path_mapping: FilePathMapping)
167                             -> SourceMap {
168         SourceMap {
169             files: Lock::new(SourceMapFiles {
170                 file_maps: Vec::new(),
171                 stable_id_to_filemap: FxHashMap(),
172             }),
173             file_loader: file_loader,
174             path_mapping,
175             doctest_offset: None,
176         }
177     }
178
179     pub fn path_mapping(&self) -> &FilePathMapping {
180         &self.path_mapping
181     }
182
183     pub fn file_exists(&self, path: &Path) -> bool {
184         self.file_loader.file_exists(path)
185     }
186
187     pub fn load_file(&self, path: &Path) -> io::Result<Lrc<FileMap>> {
188         let src = self.file_loader.read_file(path)?;
189         let filename = if let Some((ref name, _)) = self.doctest_offset {
190             name.clone()
191         } else {
192             path.to_owned().into()
193         };
194         Ok(self.new_filemap(filename, src))
195     }
196
197     pub fn files(&self) -> LockGuard<Vec<Lrc<FileMap>>> {
198         LockGuard::map(self.files.borrow(), |files| &mut files.file_maps)
199     }
200
201     pub fn filemap_by_stable_id(&self, stable_id: StableFilemapId) -> Option<Lrc<FileMap>> {
202         self.files.borrow().stable_id_to_filemap.get(&stable_id).map(|fm| fm.clone())
203     }
204
205     fn next_start_pos(&self) -> usize {
206         match self.files.borrow().file_maps.last() {
207             None => 0,
208             // Add one so there is some space between files. This lets us distinguish
209             // positions in the codemap, even in the presence of zero-length files.
210             Some(last) => last.end_pos.to_usize() + 1,
211         }
212     }
213
214     /// Creates a new filemap.
215     /// This does not ensure that only one FileMap exists per file name.
216     pub fn new_filemap(&self, filename: FileName, src: String) -> Lrc<FileMap> {
217         let start_pos = self.next_start_pos();
218
219         // The path is used to determine the directory for loading submodules and
220         // include files, so it must be before remapping.
221         // Note that filename may not be a valid path, eg it may be `<anon>` etc,
222         // but this is okay because the directory determined by `path.pop()` will
223         // be empty, so the working directory will be used.
224         let unmapped_path = filename.clone();
225
226         let (filename, was_remapped) = match filename {
227             FileName::Real(filename) => {
228                 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
229                 (FileName::Real(filename), was_remapped)
230             },
231             other => (other, false),
232         };
233         let filemap = Lrc::new(FileMap::new(
234             filename,
235             was_remapped,
236             unmapped_path,
237             src,
238             Pos::from_usize(start_pos),
239         ));
240
241         let mut files = self.files.borrow_mut();
242
243         files.file_maps.push(filemap.clone());
244         files.stable_id_to_filemap.insert(StableFilemapId::new(&filemap), filemap.clone());
245
246         filemap
247     }
248
249     /// Allocates a new FileMap representing a source file from an external
250     /// crate. The source code of such an "imported filemap" is not available,
251     /// but we still know enough to generate accurate debuginfo location
252     /// information for things inlined from other crates.
253     pub fn new_imported_filemap(&self,
254                                 filename: FileName,
255                                 name_was_remapped: bool,
256                                 crate_of_origin: u32,
257                                 src_hash: u128,
258                                 name_hash: u128,
259                                 source_len: usize,
260                                 mut file_local_lines: Vec<BytePos>,
261                                 mut file_local_multibyte_chars: Vec<MultiByteChar>,
262                                 mut file_local_non_narrow_chars: Vec<NonNarrowChar>)
263                                 -> Lrc<FileMap> {
264         let start_pos = self.next_start_pos();
265
266         let end_pos = Pos::from_usize(start_pos + source_len);
267         let start_pos = Pos::from_usize(start_pos);
268
269         for pos in &mut file_local_lines {
270             *pos = *pos + start_pos;
271         }
272
273         for mbc in &mut file_local_multibyte_chars {
274             mbc.pos = mbc.pos + start_pos;
275         }
276
277         for swc in &mut file_local_non_narrow_chars {
278             *swc = *swc + start_pos;
279         }
280
281         let filemap = Lrc::new(FileMap {
282             name: filename,
283             name_was_remapped,
284             unmapped_path: None,
285             crate_of_origin,
286             src: None,
287             src_hash,
288             external_src: Lock::new(ExternalSource::AbsentOk),
289             start_pos,
290             end_pos,
291             lines: file_local_lines,
292             multibyte_chars: file_local_multibyte_chars,
293             non_narrow_chars: file_local_non_narrow_chars,
294             name_hash,
295         });
296
297         let mut files = self.files.borrow_mut();
298
299         files.file_maps.push(filemap.clone());
300         files.stable_id_to_filemap.insert(StableFilemapId::new(&filemap), filemap.clone());
301
302         filemap
303     }
304
305     pub fn mk_substr_filename(&self, sp: Span) -> String {
306         let pos = self.lookup_char_pos(sp.lo());
307         format!("<{}:{}:{}>",
308                  pos.file.name,
309                  pos.line,
310                  pos.col.to_usize() + 1)
311     }
312
313     // If there is a doctest_offset, apply it to the line
314     pub fn doctest_offset_line(&self, mut orig: usize) -> usize {
315         if let Some((_, line)) = self.doctest_offset {
316             if line >= 0 {
317                 orig = orig + line as usize;
318             } else {
319                 orig = orig - (-line) as usize;
320             }
321         }
322         orig
323     }
324
325     /// Lookup source information about a BytePos
326     pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
327         let chpos = self.bytepos_to_file_charpos(pos);
328         match self.lookup_line(pos) {
329             Ok(FileMapAndLine { fm: f, line: a }) => {
330                 let line = a + 1; // Line numbers start at 1
331                 let linebpos = f.lines[a];
332                 let linechpos = self.bytepos_to_file_charpos(linebpos);
333                 let col = chpos - linechpos;
334
335                 let col_display = {
336                     let start_width_idx = f
337                         .non_narrow_chars
338                         .binary_search_by_key(&linebpos, |x| x.pos())
339                         .unwrap_or_else(|x| x);
340                     let end_width_idx = f
341                         .non_narrow_chars
342                         .binary_search_by_key(&pos, |x| x.pos())
343                         .unwrap_or_else(|x| x);
344                     let special_chars = end_width_idx - start_width_idx;
345                     let non_narrow: usize = f
346                         .non_narrow_chars[start_width_idx..end_width_idx]
347                         .into_iter()
348                         .map(|x| x.width())
349                         .sum();
350                     col.0 - special_chars + non_narrow
351                 };
352                 debug!("byte pos {:?} is on the line at byte pos {:?}",
353                        pos, linebpos);
354                 debug!("char pos {:?} is on the line at char pos {:?}",
355                        chpos, linechpos);
356                 debug!("byte is on line: {}", line);
357                 assert!(chpos >= linechpos);
358                 Loc {
359                     file: f,
360                     line,
361                     col,
362                     col_display,
363                 }
364             }
365             Err(f) => {
366                 let col_display = {
367                     let end_width_idx = f
368                         .non_narrow_chars
369                         .binary_search_by_key(&pos, |x| x.pos())
370                         .unwrap_or_else(|x| x);
371                     let non_narrow: usize = f
372                         .non_narrow_chars[0..end_width_idx]
373                         .into_iter()
374                         .map(|x| x.width())
375                         .sum();
376                     chpos.0 - end_width_idx + non_narrow
377                 };
378                 Loc {
379                     file: f,
380                     line: 0,
381                     col: chpos,
382                     col_display,
383                 }
384             }
385         }
386     }
387
388     // If the relevant filemap is empty, we don't return a line number.
389     pub fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Lrc<FileMap>> {
390         let idx = self.lookup_filemap_idx(pos);
391
392         let f = (*self.files.borrow().file_maps)[idx].clone();
393
394         match f.lookup_line(pos) {
395             Some(line) => Ok(FileMapAndLine { fm: f, line: line }),
396             None => Err(f)
397         }
398     }
399
400     pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
401         let loc = self.lookup_char_pos(pos);
402         LocWithOpt {
403             filename: loc.file.name.clone(),
404             line: loc.line,
405             col: loc.col,
406             file: Some(loc.file)
407         }
408     }
409
410     /// Returns `Some(span)`, a union of the lhs and rhs span.  The lhs must precede the rhs. If
411     /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
412     /// For this to work, the spans have to be:
413     ///
414     ///    * the ctxt of both spans much match
415     ///    * the lhs span needs to end on the same line the rhs span begins
416     ///    * the lhs span must start at or before the rhs span
417     pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
418         // make sure we're at the same expansion id
419         if sp_lhs.ctxt() != sp_rhs.ctxt() {
420             return None;
421         }
422
423         let lhs_end = match self.lookup_line(sp_lhs.hi()) {
424             Ok(x) => x,
425             Err(_) => return None
426         };
427         let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
428             Ok(x) => x,
429             Err(_) => return None
430         };
431
432         // if we must cross lines to merge, don't merge
433         if lhs_end.line != rhs_begin.line {
434             return None;
435         }
436
437         // ensure these follow the expected order and we don't overlap
438         if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
439             Some(sp_lhs.to(sp_rhs))
440         } else {
441             None
442         }
443     }
444
445     pub fn span_to_string(&self, sp: Span) -> String {
446         if self.files.borrow().file_maps.is_empty() && sp.is_dummy() {
447             return "no-location".to_string();
448         }
449
450         let lo = self.lookup_char_pos_adj(sp.lo());
451         let hi = self.lookup_char_pos_adj(sp.hi());
452         format!("{}:{}:{}: {}:{}",
453                         lo.filename,
454                         lo.line,
455                         lo.col.to_usize() + 1,
456                         hi.line,
457                         hi.col.to_usize() + 1)
458     }
459
460     pub fn span_to_filename(&self, sp: Span) -> FileName {
461         self.lookup_char_pos(sp.lo()).file.name.clone()
462     }
463
464     pub fn span_to_unmapped_path(&self, sp: Span) -> FileName {
465         self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
466             .expect("SourceMap::span_to_unmapped_path called for imported FileMap?")
467     }
468
469     pub fn is_multiline(&self, sp: Span) -> bool {
470         let lo = self.lookup_char_pos(sp.lo());
471         let hi = self.lookup_char_pos(sp.hi());
472         lo.line != hi.line
473     }
474
475     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
476         debug!("span_to_lines(sp={:?})", sp);
477
478         if sp.lo() > sp.hi() {
479             return Err(SpanLinesError::IllFormedSpan(sp));
480         }
481
482         let lo = self.lookup_char_pos(sp.lo());
483         debug!("span_to_lines: lo={:?}", lo);
484         let hi = self.lookup_char_pos(sp.hi());
485         debug!("span_to_lines: hi={:?}", hi);
486
487         if lo.file.start_pos != hi.file.start_pos {
488             return Err(SpanLinesError::DistinctSources(DistinctSources {
489                 begin: (lo.file.name.clone(), lo.file.start_pos),
490                 end: (hi.file.name.clone(), hi.file.start_pos),
491             }));
492         }
493         assert!(hi.line >= lo.line);
494
495         let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
496
497         // The span starts partway through the first line,
498         // but after that it starts from offset 0.
499         let mut start_col = lo.col;
500
501         // For every line but the last, it extends from `start_col`
502         // and to the end of the line. Be careful because the line
503         // numbers in Loc are 1-based, so we subtract 1 to get 0-based
504         // lines.
505         for line_index in lo.line-1 .. hi.line-1 {
506             let line_len = lo.file.get_line(line_index)
507                                   .map(|s| s.chars().count())
508                                   .unwrap_or(0);
509             lines.push(LineInfo { line_index,
510                                   start_col,
511                                   end_col: CharPos::from_usize(line_len) });
512             start_col = CharPos::from_usize(0);
513         }
514
515         // For the last line, it extends from `start_col` to `hi.col`:
516         lines.push(LineInfo { line_index: hi.line - 1,
517                               start_col,
518                               end_col: hi.col });
519
520         Ok(FileLines {file: lo.file, lines: lines})
521     }
522
523     /// Extract the source surrounding the given `Span` using the `extract_source` function. The
524     /// extract function takes three arguments: a string slice containing the source, an index in
525     /// the slice for the beginning of the span and an index in the slice for the end of the span.
526     fn span_to_source<F>(&self, sp: Span, extract_source: F) -> Result<String, SpanSnippetError>
527         where F: Fn(&str, usize, usize) -> String
528     {
529         if sp.lo() > sp.hi() {
530             return Err(SpanSnippetError::IllFormedSpan(sp));
531         }
532
533         let local_begin = self.lookup_byte_offset(sp.lo());
534         let local_end = self.lookup_byte_offset(sp.hi());
535
536         if local_begin.fm.start_pos != local_end.fm.start_pos {
537             return Err(SpanSnippetError::DistinctSources(DistinctSources {
538                 begin: (local_begin.fm.name.clone(),
539                         local_begin.fm.start_pos),
540                 end: (local_end.fm.name.clone(),
541                       local_end.fm.start_pos)
542             }));
543         } else {
544             self.ensure_filemap_source_present(local_begin.fm.clone());
545
546             let start_index = local_begin.pos.to_usize();
547             let end_index = local_end.pos.to_usize();
548             let source_len = (local_begin.fm.end_pos -
549                               local_begin.fm.start_pos).to_usize();
550
551             if start_index > end_index || end_index > source_len {
552                 return Err(SpanSnippetError::MalformedForCodemap(
553                     MalformedCodemapPositions {
554                         name: local_begin.fm.name.clone(),
555                         source_len,
556                         begin_pos: local_begin.pos,
557                         end_pos: local_end.pos,
558                     }));
559             }
560
561             if let Some(ref src) = local_begin.fm.src {
562                 return Ok(extract_source(src, start_index, end_index));
563             } else if let Some(src) = local_begin.fm.external_src.borrow().get_source() {
564                 return Ok(extract_source(src, start_index, end_index));
565             } else {
566                 return Err(SpanSnippetError::SourceNotAvailable {
567                     filename: local_begin.fm.name.clone()
568                 });
569             }
570         }
571     }
572
573     /// Return the source snippet as `String` corresponding to the given `Span`
574     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
575         self.span_to_source(sp, |src, start_index, end_index| src[start_index..end_index]
576                                                                 .to_string())
577     }
578
579     /// Return 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_left();
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_left();
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_right();
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.fm.end_pos - local_begin.fm.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.fm.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.fm.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_filemap(&self, filename: &FileName) -> Option<Lrc<FileMap>> {
802         for fm in self.files.borrow().file_maps.iter() {
803             if *filename == fm.name {
804                 return Some(fm.clone());
805             }
806         }
807         None
808     }
809
810     /// For a global BytePos compute the local offset within the containing FileMap
811     pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
812         let idx = self.lookup_filemap_idx(bpos);
813         let fm = (*self.files.borrow().file_maps)[idx].clone();
814         let offset = bpos - fm.start_pos;
815         FileMapAndBytePos {fm: fm, pos: offset}
816     }
817
818     /// Converts an absolute BytePos to a CharPos relative to the filemap.
819     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
820         let idx = self.lookup_filemap_idx(bpos);
821         let map = &(*self.files.borrow().file_maps)[idx];
822
823         // The number of extra bytes due to multibyte chars in the FileMap
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 filemap (in self.files) which contains pos.
845     pub fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
846         let files = self.files.borrow();
847         let files = &files.file_maps;
848         let count = files.len();
849
850         // Binary search for the filemap.
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     /// codemap 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(&self.span_to_snippet(span).unwrap_or("T".to_string()));
934                 new_snippet.push('>');
935
936                 return Some((sugg_span, new_snippet));
937             }
938         }
939
940         None
941     }
942 }
943
944 impl SourceMapper for SourceMap {
945     fn lookup_char_pos(&self, pos: BytePos) -> Loc {
946         self.lookup_char_pos(pos)
947     }
948     fn span_to_lines(&self, sp: Span) -> FileLinesResult {
949         self.span_to_lines(sp)
950     }
951     fn span_to_string(&self, sp: Span) -> String {
952         self.span_to_string(sp)
953     }
954     fn span_to_filename(&self, sp: Span) -> FileName {
955         self.span_to_filename(sp)
956     }
957     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
958         self.merge_spans(sp_lhs, sp_rhs)
959     }
960     fn call_span_if_macro(&self, sp: Span) -> Span {
961         if self.span_to_filename(sp.clone()).is_macros() {
962             let v = sp.macro_backtrace();
963             if let Some(use_site) = v.last() {
964                 return use_site.call_site;
965             }
966         }
967         sp
968     }
969     fn ensure_filemap_source_present(&self, file_map: Lrc<FileMap>) -> bool {
970         file_map.add_external_src(
971             || match file_map.name {
972                 FileName::Real(ref name) => self.file_loader.read_file(name).ok(),
973                 _ => None,
974             }
975         )
976     }
977     fn doctest_offset_line(&self, line: usize) -> usize {
978         self.doctest_offset_line(line)
979     }
980 }
981
982 #[derive(Clone)]
983 pub struct FilePathMapping {
984     mapping: Vec<(PathBuf, PathBuf)>,
985 }
986
987 impl FilePathMapping {
988     pub fn empty() -> FilePathMapping {
989         FilePathMapping {
990             mapping: vec![]
991         }
992     }
993
994     pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping {
995         FilePathMapping {
996             mapping,
997         }
998     }
999
1000     /// Applies any path prefix substitution as defined by the mapping.
1001     /// The return value is the remapped path and a boolean indicating whether
1002     /// the path was affected by the mapping.
1003     pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) {
1004         // NOTE: We are iterating over the mapping entries from last to first
1005         //       because entries specified later on the command line should
1006         //       take precedence.
1007         for &(ref from, ref to) in self.mapping.iter().rev() {
1008             if let Ok(rest) = path.strip_prefix(from) {
1009                 return (to.join(rest), true);
1010             }
1011         }
1012
1013         (path, false)
1014     }
1015 }
1016
1017 // _____________________________________________________________________________
1018 // Tests
1019 //
1020
1021 #[cfg(test)]
1022 mod tests {
1023     use super::*;
1024     use rustc_data_structures::sync::Lrc;
1025
1026     fn init_code_map() -> SourceMap {
1027         let cm = SourceMap::new(FilePathMapping::empty());
1028         cm.new_filemap(PathBuf::from("blork.rs").into(),
1029                        "first line.\nsecond line".to_string());
1030         cm.new_filemap(PathBuf::from("empty.rs").into(),
1031                        "".to_string());
1032         cm.new_filemap(PathBuf::from("blork2.rs").into(),
1033                        "first line.\nsecond line".to_string());
1034         cm
1035     }
1036
1037     #[test]
1038     fn t3() {
1039         // Test lookup_byte_offset
1040         let cm = init_code_map();
1041
1042         let fmabp1 = cm.lookup_byte_offset(BytePos(23));
1043         assert_eq!(fmabp1.fm.name, PathBuf::from("blork.rs").into());
1044         assert_eq!(fmabp1.pos, BytePos(23));
1045
1046         let fmabp1 = cm.lookup_byte_offset(BytePos(24));
1047         assert_eq!(fmabp1.fm.name, PathBuf::from("empty.rs").into());
1048         assert_eq!(fmabp1.pos, BytePos(0));
1049
1050         let fmabp2 = cm.lookup_byte_offset(BytePos(25));
1051         assert_eq!(fmabp2.fm.name, PathBuf::from("blork2.rs").into());
1052         assert_eq!(fmabp2.pos, BytePos(0));
1053     }
1054
1055     #[test]
1056     fn t4() {
1057         // Test bytepos_to_file_charpos
1058         let cm = init_code_map();
1059
1060         let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
1061         assert_eq!(cp1, CharPos(22));
1062
1063         let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
1064         assert_eq!(cp2, CharPos(0));
1065     }
1066
1067     #[test]
1068     fn t5() {
1069         // Test zero-length filemaps.
1070         let cm = init_code_map();
1071
1072         let loc1 = cm.lookup_char_pos(BytePos(22));
1073         assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
1074         assert_eq!(loc1.line, 2);
1075         assert_eq!(loc1.col, CharPos(10));
1076
1077         let loc2 = cm.lookup_char_pos(BytePos(25));
1078         assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
1079         assert_eq!(loc2.line, 1);
1080         assert_eq!(loc2.col, CharPos(0));
1081     }
1082
1083     fn init_code_map_mbc() -> SourceMap {
1084         let cm = SourceMap::new(FilePathMapping::empty());
1085         // € is a three byte utf8 char.
1086         cm.new_filemap(PathBuf::from("blork.rs").into(),
1087                        "fir€st €€€€ line.\nsecond line".to_string());
1088         cm.new_filemap(PathBuf::from("blork2.rs").into(),
1089                        "first line€€.\n€ second line".to_string());
1090         cm
1091     }
1092
1093     #[test]
1094     fn t6() {
1095         // Test bytepos_to_file_charpos in the presence of multi-byte chars
1096         let cm = init_code_map_mbc();
1097
1098         let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
1099         assert_eq!(cp1, CharPos(3));
1100
1101         let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
1102         assert_eq!(cp2, CharPos(4));
1103
1104         let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
1105         assert_eq!(cp3, CharPos(12));
1106
1107         let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
1108         assert_eq!(cp4, CharPos(15));
1109     }
1110
1111     #[test]
1112     fn t7() {
1113         // Test span_to_lines for a span ending at the end of filemap
1114         let cm = init_code_map();
1115         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1116         let file_lines = cm.span_to_lines(span).unwrap();
1117
1118         assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
1119         assert_eq!(file_lines.lines.len(), 1);
1120         assert_eq!(file_lines.lines[0].line_index, 1);
1121     }
1122
1123     /// Given a string like " ~~~~~~~~~~~~ ", produces a span
1124     /// converting that range. The idea is that the string has the same
1125     /// length as the input, and we uncover the byte positions.  Note
1126     /// that this can span lines and so on.
1127     fn span_from_selection(input: &str, selection: &str) -> Span {
1128         assert_eq!(input.len(), selection.len());
1129         let left_index = selection.find('~').unwrap() as u32;
1130         let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
1131         Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
1132     }
1133
1134     /// Test span_to_snippet and span_to_lines for a span converting 3
1135     /// lines in the middle of a file.
1136     #[test]
1137     fn span_to_snippet_and_lines_spanning_multiple_lines() {
1138         let cm = SourceMap::new(FilePathMapping::empty());
1139         let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1140         let selection = "     \n    ~~\n~~~\n~~~~~     \n   \n";
1141         cm.new_filemap(Path::new("blork.rs").to_owned().into(), inputtext.to_string());
1142         let span = span_from_selection(inputtext, selection);
1143
1144         // check that we are extracting the text we thought we were extracting
1145         assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1146
1147         // check that span_to_lines gives us the complete result with the lines/cols we expected
1148         let lines = cm.span_to_lines(span).unwrap();
1149         let expected = vec![
1150             LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1151             LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1152             LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1153             ];
1154         assert_eq!(lines.lines, expected);
1155     }
1156
1157     #[test]
1158     fn t8() {
1159         // Test span_to_snippet for a span ending at the end of filemap
1160         let cm = init_code_map();
1161         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1162         let snippet = cm.span_to_snippet(span);
1163
1164         assert_eq!(snippet, Ok("second line".to_string()));
1165     }
1166
1167     #[test]
1168     fn t9() {
1169         // Test span_to_str for a span ending at the end of filemap
1170         let cm = init_code_map();
1171         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1172         let sstr =  cm.span_to_string(span);
1173
1174         assert_eq!(sstr, "blork.rs:2:1: 2:12");
1175     }
1176
1177     /// Test failing to merge two spans on different lines
1178     #[test]
1179     fn span_merging_fail() {
1180         let cm = SourceMap::new(FilePathMapping::empty());
1181         let inputtext  = "bbbb BB\ncc CCC\n";
1182         let selection1 = "     ~~\n      \n";
1183         let selection2 = "       \n   ~~~\n";
1184         cm.new_filemap(Path::new("blork.rs").to_owned().into(), inputtext.to_owned());
1185         let span1 = span_from_selection(inputtext, selection1);
1186         let span2 = span_from_selection(inputtext, selection2);
1187
1188         assert!(cm.merge_spans(span1, span2).is_none());
1189     }
1190
1191     /// Returns the span corresponding to the `n`th occurrence of
1192     /// `substring` in `source_text`.
1193     trait SourceMapExtension {
1194         fn span_substr(&self,
1195                     file: &Lrc<FileMap>,
1196                     source_text: &str,
1197                     substring: &str,
1198                     n: usize)
1199                     -> Span;
1200     }
1201
1202     impl SourceMapExtension for SourceMap {
1203         fn span_substr(&self,
1204                     file: &Lrc<FileMap>,
1205                     source_text: &str,
1206                     substring: &str,
1207                     n: usize)
1208                     -> Span
1209         {
1210             println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
1211                     file.name, file.start_pos, substring, n);
1212             let mut i = 0;
1213             let mut hi = 0;
1214             loop {
1215                 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
1216                     panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
1217                         source_text, n, substring, i);
1218                 });
1219                 let lo = hi + offset;
1220                 hi = lo + substring.len();
1221                 if i == n {
1222                     let span = Span::new(
1223                         BytePos(lo as u32 + file.start_pos.0),
1224                         BytePos(hi as u32 + file.start_pos.0),
1225                         NO_EXPANSION,
1226                     );
1227                     assert_eq!(&self.span_to_snippet(span).unwrap()[..],
1228                             substring);
1229                     return span;
1230                 }
1231                 i += 1;
1232             }
1233         }
1234     }
1235 }