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