]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/codemap.rs
run EndRegion when unwinding otherwise-empty scopes
[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 CodeMap 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 //! CodeMap 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 CodeMap, which upon request can be converted to line and column
18 //! information, source code snippets, etc.
19
20 pub use syntax_pos::*;
21 pub use syntax_pos::hygiene::{ExpnFormat, ExpnInfo, NameAndSpan};
22 pub use self::ExpnFormat::*;
23
24 use std::cell::{RefCell, Ref};
25 use std::path::{Path, PathBuf};
26 use std::rc::Rc;
27
28 use std::env;
29 use std::fs;
30 use std::io::{self, Read};
31 use errors::CodeMapper;
32
33 /// Return the span itself if it doesn't come from a macro expansion,
34 /// otherwise return the call site span up to the `enclosing_sp` by
35 /// following the `expn_info` chain.
36 pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
37     let call_site1 = sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
38     let call_site2 = enclosing_sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
39     match (call_site1, call_site2) {
40         (None, _) => sp,
41         (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
42         (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
43     }
44 }
45
46 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
47 pub struct Spanned<T> {
48     pub node: T,
49     pub span: Span,
50 }
51
52 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
53     Spanned {node: t, span: sp}
54 }
55
56 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
57     respan(DUMMY_SP, t)
58 }
59
60 // _____________________________________________________________________________
61 // FileMap, MultiByteChar, FileName, FileLines
62 //
63
64 /// An abstraction over the fs operations used by the Parser.
65 pub trait FileLoader {
66     /// Query the existence of a file.
67     fn file_exists(&self, path: &Path) -> bool;
68
69     /// Return an absolute path to a file, if possible.
70     fn abs_path(&self, path: &Path) -> Option<PathBuf>;
71
72     /// Read the contents of an UTF-8 file into memory.
73     fn read_file(&self, path: &Path) -> io::Result<String>;
74 }
75
76 /// A FileLoader that uses std::fs to load real files.
77 pub struct RealFileLoader;
78
79 impl FileLoader for RealFileLoader {
80     fn file_exists(&self, path: &Path) -> bool {
81         fs::metadata(path).is_ok()
82     }
83
84     fn abs_path(&self, path: &Path) -> Option<PathBuf> {
85         if path.is_absolute() {
86             Some(path.to_path_buf())
87         } else {
88             env::current_dir()
89                 .ok()
90                 .map(|cwd| cwd.join(path))
91         }
92     }
93
94     fn read_file(&self, path: &Path) -> io::Result<String> {
95         let mut src = String::new();
96         fs::File::open(path)?.read_to_string(&mut src)?;
97         Ok(src)
98     }
99 }
100
101 // _____________________________________________________________________________
102 // CodeMap
103 //
104
105 pub struct CodeMap {
106     pub(super) files: RefCell<Vec<Rc<FileMap>>>,
107     file_loader: Box<FileLoader>,
108     // This is used to apply the file path remapping as specified via
109     // -Zremap-path-prefix to all FileMaps allocated within this CodeMap.
110     path_mapping: FilePathMapping,
111 }
112
113 impl CodeMap {
114     pub fn new(path_mapping: FilePathMapping) -> CodeMap {
115         CodeMap {
116             files: RefCell::new(Vec::new()),
117             file_loader: Box::new(RealFileLoader),
118             path_mapping,
119         }
120     }
121
122     pub fn with_file_loader(file_loader: Box<FileLoader>,
123                             path_mapping: FilePathMapping)
124                             -> CodeMap {
125         CodeMap {
126             files: RefCell::new(Vec::new()),
127             file_loader,
128             path_mapping,
129         }
130     }
131
132     pub fn path_mapping(&self) -> &FilePathMapping {
133         &self.path_mapping
134     }
135
136     pub fn file_exists(&self, path: &Path) -> bool {
137         self.file_loader.file_exists(path)
138     }
139
140     pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> {
141         let src = self.file_loader.read_file(path)?;
142         Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
143     }
144
145     pub fn files(&self) -> Ref<Vec<Rc<FileMap>>> {
146         self.files.borrow()
147     }
148
149     fn next_start_pos(&self) -> usize {
150         let files = self.files.borrow();
151         match files.last() {
152             None => 0,
153             // Add one so there is some space between files. This lets us distinguish
154             // positions in the codemap, even in the presence of zero-length files.
155             Some(last) => last.end_pos.to_usize() + 1,
156         }
157     }
158
159     /// Creates a new filemap without setting its line information. If you don't
160     /// intend to set the line information yourself, you should use new_filemap_and_lines.
161     pub fn new_filemap(&self, filename: FileName, src: String) -> Rc<FileMap> {
162         let start_pos = self.next_start_pos();
163         let mut files = self.files.borrow_mut();
164
165         // The path is used to determine the directory for loading submodules and
166         // include files, so it must be before remapping.
167         // Note that filename may not be a valid path, eg it may be `<anon>` etc,
168         // but this is okay because the directory determined by `path.pop()` will
169         // be empty, so the working directory will be used.
170         let unmapped_path = PathBuf::from(filename.clone());
171
172         let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
173         let filemap = Rc::new(FileMap::new(
174             filename,
175             was_remapped,
176             unmapped_path,
177             src,
178             Pos::from_usize(start_pos),
179         ));
180
181         files.push(filemap.clone());
182
183         filemap
184     }
185
186     /// Creates a new filemap and sets its line information.
187     pub fn new_filemap_and_lines(&self, filename: &str, src: &str) -> Rc<FileMap> {
188         let fm = self.new_filemap(filename.to_string(), src.to_owned());
189         let mut byte_pos: u32 = fm.start_pos.0;
190         for line in src.lines() {
191             // register the start of this line
192             fm.next_line(BytePos(byte_pos));
193
194             // update byte_pos to include this line and the \n at the end
195             byte_pos += line.len() as u32 + 1;
196         }
197         fm
198     }
199
200
201     /// Allocates a new FileMap representing a source file from an external
202     /// crate. The source code of such an "imported filemap" is not available,
203     /// but we still know enough to generate accurate debuginfo location
204     /// information for things inlined from other crates.
205     pub fn new_imported_filemap(&self,
206                                 filename: FileName,
207                                 name_was_remapped: bool,
208                                 crate_of_origin: u32,
209                                 src_hash: u128,
210                                 source_len: usize,
211                                 mut file_local_lines: Vec<BytePos>,
212                                 mut file_local_multibyte_chars: Vec<MultiByteChar>)
213                                 -> Rc<FileMap> {
214         let start_pos = self.next_start_pos();
215         let mut files = self.files.borrow_mut();
216
217         let end_pos = Pos::from_usize(start_pos + source_len);
218         let start_pos = Pos::from_usize(start_pos);
219
220         for pos in &mut file_local_lines {
221             *pos = *pos + start_pos;
222         }
223
224         for mbc in &mut file_local_multibyte_chars {
225             mbc.pos = mbc.pos + start_pos;
226         }
227
228         let filemap = Rc::new(FileMap {
229             name: filename,
230             name_was_remapped,
231             unmapped_path: None,
232             crate_of_origin,
233             src: None,
234             src_hash,
235             external_src: RefCell::new(ExternalSource::AbsentOk),
236             start_pos,
237             end_pos,
238             lines: RefCell::new(file_local_lines),
239             multibyte_chars: RefCell::new(file_local_multibyte_chars),
240         });
241
242         files.push(filemap.clone());
243
244         filemap
245     }
246
247     pub fn mk_substr_filename(&self, sp: Span) -> String {
248         let pos = self.lookup_char_pos(sp.lo());
249         (format!("<{}:{}:{}>",
250                  pos.file.name,
251                  pos.line,
252                  pos.col.to_usize() + 1)).to_string()
253     }
254
255     /// Lookup source information about a BytePos
256     pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
257         let chpos = self.bytepos_to_file_charpos(pos);
258         match self.lookup_line(pos) {
259             Ok(FileMapAndLine { fm: f, line: a }) => {
260                 let line = a + 1; // Line numbers start at 1
261                 let linebpos = (*f.lines.borrow())[a];
262                 let linechpos = self.bytepos_to_file_charpos(linebpos);
263                 debug!("byte pos {:?} is on the line at byte pos {:?}",
264                        pos, linebpos);
265                 debug!("char pos {:?} is on the line at char pos {:?}",
266                        chpos, linechpos);
267                 debug!("byte is on line: {}", line);
268                 assert!(chpos >= linechpos);
269                 Loc {
270                     file: f,
271                     line,
272                     col: chpos - linechpos,
273                 }
274             }
275             Err(f) => {
276                 Loc {
277                     file: f,
278                     line: 0,
279                     col: chpos,
280                 }
281             }
282         }
283     }
284
285     // If the relevant filemap is empty, we don't return a line number.
286     fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> {
287         let idx = self.lookup_filemap_idx(pos);
288
289         let files = self.files.borrow();
290         let f = (*files)[idx].clone();
291
292         match f.lookup_line(pos) {
293             Some(line) => Ok(FileMapAndLine { fm: f, line: line }),
294             None => Err(f)
295         }
296     }
297
298     pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
299         let loc = self.lookup_char_pos(pos);
300         LocWithOpt {
301             filename: loc.file.name.to_string(),
302             line: loc.line,
303             col: loc.col,
304             file: Some(loc.file)
305         }
306     }
307
308     /// Returns `Some(span)`, a union of the lhs and rhs span.  The lhs must precede the rhs. If
309     /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
310     /// For this to work, the spans have to be:
311     ///    * the ctxt of both spans much match
312     ///    * the lhs span needs to end on the same line the rhs span begins
313     ///    * the lhs span must start at or before the rhs span
314     pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
315         // make sure we're at the same expansion id
316         if sp_lhs.ctxt() != sp_rhs.ctxt() {
317             return None;
318         }
319
320         let lhs_end = match self.lookup_line(sp_lhs.hi()) {
321             Ok(x) => x,
322             Err(_) => return None
323         };
324         let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
325             Ok(x) => x,
326             Err(_) => return None
327         };
328
329         // if we must cross lines to merge, don't merge
330         if lhs_end.line != rhs_begin.line {
331             return None;
332         }
333
334         // ensure these follow the expected order and we don't overlap
335         if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
336             Some(sp_lhs.to(sp_rhs))
337         } else {
338             None
339         }
340     }
341
342     pub fn span_to_string(&self, sp: Span) -> String {
343         if self.files.borrow().is_empty() && sp.source_equal(&DUMMY_SP) {
344             return "no-location".to_string();
345         }
346
347         let lo = self.lookup_char_pos_adj(sp.lo());
348         let hi = self.lookup_char_pos_adj(sp.hi());
349         return (format!("{}:{}:{}: {}:{}",
350                         lo.filename,
351                         lo.line,
352                         lo.col.to_usize() + 1,
353                         hi.line,
354                         hi.col.to_usize() + 1)).to_string()
355     }
356
357     pub fn span_to_filename(&self, sp: Span) -> FileName {
358         self.lookup_char_pos(sp.lo()).file.name.clone()
359     }
360
361     pub fn span_to_unmapped_path(&self, sp: Span) -> PathBuf {
362         self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
363             .expect("CodeMap::span_to_unmapped_path called for imported FileMap?")
364     }
365
366     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
367         debug!("span_to_lines(sp={:?})", sp);
368
369         if sp.lo() > sp.hi() {
370             return Err(SpanLinesError::IllFormedSpan(sp));
371         }
372
373         let lo = self.lookup_char_pos(sp.lo());
374         debug!("span_to_lines: lo={:?}", lo);
375         let hi = self.lookup_char_pos(sp.hi());
376         debug!("span_to_lines: hi={:?}", hi);
377
378         if lo.file.start_pos != hi.file.start_pos {
379             return Err(SpanLinesError::DistinctSources(DistinctSources {
380                 begin: (lo.file.name.clone(), lo.file.start_pos),
381                 end: (hi.file.name.clone(), hi.file.start_pos),
382             }));
383         }
384         assert!(hi.line >= lo.line);
385
386         let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
387
388         // The span starts partway through the first line,
389         // but after that it starts from offset 0.
390         let mut start_col = lo.col;
391
392         // For every line but the last, it extends from `start_col`
393         // and to the end of the line. Be careful because the line
394         // numbers in Loc are 1-based, so we subtract 1 to get 0-based
395         // lines.
396         for line_index in lo.line-1 .. hi.line-1 {
397             let line_len = lo.file.get_line(line_index)
398                                   .map(|s| s.chars().count())
399                                   .unwrap_or(0);
400             lines.push(LineInfo { line_index,
401                                   start_col,
402                                   end_col: CharPos::from_usize(line_len) });
403             start_col = CharPos::from_usize(0);
404         }
405
406         // For the last line, it extends from `start_col` to `hi.col`:
407         lines.push(LineInfo { line_index: hi.line - 1,
408                               start_col,
409                               end_col: hi.col });
410
411         Ok(FileLines {file: lo.file, lines: lines})
412     }
413
414     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
415         if sp.lo() > sp.hi() {
416             return Err(SpanSnippetError::IllFormedSpan(sp));
417         }
418
419         let local_begin = self.lookup_byte_offset(sp.lo());
420         let local_end = self.lookup_byte_offset(sp.hi());
421
422         if local_begin.fm.start_pos != local_end.fm.start_pos {
423             return Err(SpanSnippetError::DistinctSources(DistinctSources {
424                 begin: (local_begin.fm.name.clone(),
425                         local_begin.fm.start_pos),
426                 end: (local_end.fm.name.clone(),
427                       local_end.fm.start_pos)
428             }));
429         } else {
430             self.ensure_filemap_source_present(local_begin.fm.clone());
431
432             let start_index = local_begin.pos.to_usize();
433             let end_index = local_end.pos.to_usize();
434             let source_len = (local_begin.fm.end_pos -
435                               local_begin.fm.start_pos).to_usize();
436
437             if start_index > end_index || end_index > source_len {
438                 return Err(SpanSnippetError::MalformedForCodemap(
439                     MalformedCodemapPositions {
440                         name: local_begin.fm.name.clone(),
441                         source_len,
442                         begin_pos: local_begin.pos,
443                         end_pos: local_end.pos,
444                     }));
445             }
446
447             if let Some(ref src) = local_begin.fm.src {
448                 return Ok((&src[start_index..end_index]).to_string());
449             } else if let Some(src) = local_begin.fm.external_src.borrow().get_source() {
450                 return Ok((&src[start_index..end_index]).to_string());
451             } else {
452                 return Err(SpanSnippetError::SourceNotAvailable {
453                     filename: local_begin.fm.name.clone()
454                 });
455             }
456         }
457     }
458
459     /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
460     pub fn span_until_char(&self, sp: Span, c: char) -> Span {
461         match self.span_to_snippet(sp) {
462             Ok(snippet) => {
463                 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right();
464                 if !snippet.is_empty() && !snippet.contains('\n') {
465                     sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
466                 } else {
467                     sp
468                 }
469             }
470             _ => sp,
471         }
472     }
473
474     pub fn def_span(&self, sp: Span) -> Span {
475         self.span_until_char(sp, '{')
476     }
477
478     pub fn get_filemap(&self, filename: &str) -> Option<Rc<FileMap>> {
479         for fm in self.files.borrow().iter() {
480             if filename == fm.name {
481                 return Some(fm.clone());
482             }
483         }
484         None
485     }
486
487     /// For a global BytePos compute the local offset within the containing FileMap
488     pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
489         let idx = self.lookup_filemap_idx(bpos);
490         let fm = (*self.files.borrow())[idx].clone();
491         let offset = bpos - fm.start_pos;
492         FileMapAndBytePos {fm: fm, pos: offset}
493     }
494
495     /// Converts an absolute BytePos to a CharPos relative to the filemap.
496     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
497         let idx = self.lookup_filemap_idx(bpos);
498         let files = self.files.borrow();
499         let map = &(*files)[idx];
500
501         // The number of extra bytes due to multibyte chars in the FileMap
502         let mut total_extra_bytes = 0;
503
504         for mbc in map.multibyte_chars.borrow().iter() {
505             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
506             if mbc.pos < bpos {
507                 // every character is at least one byte, so we only
508                 // count the actual extra bytes.
509                 total_extra_bytes += mbc.bytes - 1;
510                 // We should never see a byte position in the middle of a
511                 // character
512                 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
513             } else {
514                 break;
515             }
516         }
517
518         assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
519         CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
520     }
521
522     // Return the index of the filemap (in self.files) which contains pos.
523     pub fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
524         let files = self.files.borrow();
525         let files = &*files;
526         let count = files.len();
527
528         // Binary search for the filemap.
529         let mut a = 0;
530         let mut b = count;
531         while b - a > 1 {
532             let m = (a + b) / 2;
533             if files[m].start_pos > pos {
534                 b = m;
535             } else {
536                 a = m;
537             }
538         }
539
540         assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
541
542         return a;
543     }
544
545     pub fn count_lines(&self) -> usize {
546         self.files().iter().fold(0, |a, f| a + f.count_lines())
547     }
548 }
549
550 impl CodeMapper for CodeMap {
551     fn lookup_char_pos(&self, pos: BytePos) -> Loc {
552         self.lookup_char_pos(pos)
553     }
554     fn span_to_lines(&self, sp: Span) -> FileLinesResult {
555         self.span_to_lines(sp)
556     }
557     fn span_to_string(&self, sp: Span) -> String {
558         self.span_to_string(sp)
559     }
560     fn span_to_filename(&self, sp: Span) -> FileName {
561         self.span_to_filename(sp)
562     }
563     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
564         self.merge_spans(sp_lhs, sp_rhs)
565     }
566     fn call_span_if_macro(&self, sp: Span) -> Span {
567         if self.span_to_filename(sp.clone()).contains("macros>") {
568             let v = sp.macro_backtrace();
569             if let Some(use_site) = v.last() {
570                 return use_site.call_site;
571             }
572         }
573         sp
574     }
575     fn ensure_filemap_source_present(&self, file_map: Rc<FileMap>) -> bool {
576         file_map.add_external_src(
577             || self.file_loader.read_file(Path::new(&file_map.name)).ok()
578         )
579     }
580 }
581
582 #[derive(Clone)]
583 pub struct FilePathMapping {
584     mapping: Vec<(String, String)>,
585 }
586
587 impl FilePathMapping {
588     pub fn empty() -> FilePathMapping {
589         FilePathMapping {
590             mapping: vec![]
591         }
592     }
593
594     pub fn new(mapping: Vec<(String, String)>) -> FilePathMapping {
595         FilePathMapping {
596             mapping,
597         }
598     }
599
600     /// Applies any path prefix substitution as defined by the mapping.
601     /// The return value is the remapped path and a boolean indicating whether
602     /// the path was affected by the mapping.
603     pub fn map_prefix(&self, path: String) -> (String, bool) {
604         // NOTE: We are iterating over the mapping entries from last to first
605         //       because entries specified later on the command line should
606         //       take precedence.
607         for &(ref from, ref to) in self.mapping.iter().rev() {
608             if path.starts_with(from) {
609                 let mapped = path.replacen(from, to, 1);
610                 return (mapped, true);
611             }
612         }
613
614         (path, false)
615     }
616 }
617
618 // _____________________________________________________________________________
619 // Tests
620 //
621
622 #[cfg(test)]
623 mod tests {
624     use super::*;
625     use std::borrow::Cow;
626     use std::rc::Rc;
627
628     #[test]
629     fn t1 () {
630         let cm = CodeMap::new(FilePathMapping::empty());
631         let fm = cm.new_filemap("blork.rs".to_string(),
632                                 "first line.\nsecond line".to_string());
633         fm.next_line(BytePos(0));
634         // Test we can get lines with partial line info.
635         assert_eq!(fm.get_line(0), Some(Cow::from("first line.")));
636         // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
637         fm.next_line(BytePos(10));
638         assert_eq!(fm.get_line(1), Some(Cow::from(".")));
639         fm.next_line(BytePos(12));
640         assert_eq!(fm.get_line(2), Some(Cow::from("second line")));
641     }
642
643     #[test]
644     #[should_panic]
645     fn t2 () {
646         let cm = CodeMap::new(FilePathMapping::empty());
647         let fm = cm.new_filemap("blork.rs".to_string(),
648                                 "first line.\nsecond line".to_string());
649         // TESTING *REALLY* BROKEN BEHAVIOR:
650         fm.next_line(BytePos(0));
651         fm.next_line(BytePos(10));
652         fm.next_line(BytePos(2));
653     }
654
655     fn init_code_map() -> CodeMap {
656         let cm = CodeMap::new(FilePathMapping::empty());
657         let fm1 = cm.new_filemap("blork.rs".to_string(),
658                                  "first line.\nsecond line".to_string());
659         let fm2 = cm.new_filemap("empty.rs".to_string(),
660                                  "".to_string());
661         let fm3 = cm.new_filemap("blork2.rs".to_string(),
662                                  "first line.\nsecond line".to_string());
663
664         fm1.next_line(BytePos(0));
665         fm1.next_line(BytePos(12));
666         fm2.next_line(fm2.start_pos);
667         fm3.next_line(fm3.start_pos);
668         fm3.next_line(fm3.start_pos + BytePos(12));
669
670         cm
671     }
672
673     #[test]
674     fn t3() {
675         // Test lookup_byte_offset
676         let cm = init_code_map();
677
678         let fmabp1 = cm.lookup_byte_offset(BytePos(23));
679         assert_eq!(fmabp1.fm.name, "blork.rs");
680         assert_eq!(fmabp1.pos, BytePos(23));
681
682         let fmabp1 = cm.lookup_byte_offset(BytePos(24));
683         assert_eq!(fmabp1.fm.name, "empty.rs");
684         assert_eq!(fmabp1.pos, BytePos(0));
685
686         let fmabp2 = cm.lookup_byte_offset(BytePos(25));
687         assert_eq!(fmabp2.fm.name, "blork2.rs");
688         assert_eq!(fmabp2.pos, BytePos(0));
689     }
690
691     #[test]
692     fn t4() {
693         // Test bytepos_to_file_charpos
694         let cm = init_code_map();
695
696         let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
697         assert_eq!(cp1, CharPos(22));
698
699         let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
700         assert_eq!(cp2, CharPos(0));
701     }
702
703     #[test]
704     fn t5() {
705         // Test zero-length filemaps.
706         let cm = init_code_map();
707
708         let loc1 = cm.lookup_char_pos(BytePos(22));
709         assert_eq!(loc1.file.name, "blork.rs");
710         assert_eq!(loc1.line, 2);
711         assert_eq!(loc1.col, CharPos(10));
712
713         let loc2 = cm.lookup_char_pos(BytePos(25));
714         assert_eq!(loc2.file.name, "blork2.rs");
715         assert_eq!(loc2.line, 1);
716         assert_eq!(loc2.col, CharPos(0));
717     }
718
719     fn init_code_map_mbc() -> CodeMap {
720         let cm = CodeMap::new(FilePathMapping::empty());
721         // € is a three byte utf8 char.
722         let fm1 =
723             cm.new_filemap("blork.rs".to_string(),
724                            "fir€st €€€€ line.\nsecond line".to_string());
725         let fm2 = cm.new_filemap("blork2.rs".to_string(),
726                                  "first line€€.\n€ second line".to_string());
727
728         fm1.next_line(BytePos(0));
729         fm1.next_line(BytePos(28));
730         fm2.next_line(fm2.start_pos);
731         fm2.next_line(fm2.start_pos + BytePos(20));
732
733         fm1.record_multibyte_char(BytePos(3), 3);
734         fm1.record_multibyte_char(BytePos(9), 3);
735         fm1.record_multibyte_char(BytePos(12), 3);
736         fm1.record_multibyte_char(BytePos(15), 3);
737         fm1.record_multibyte_char(BytePos(18), 3);
738         fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
739         fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
740         fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
741
742         cm
743     }
744
745     #[test]
746     fn t6() {
747         // Test bytepos_to_file_charpos in the presence of multi-byte chars
748         let cm = init_code_map_mbc();
749
750         let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
751         assert_eq!(cp1, CharPos(3));
752
753         let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
754         assert_eq!(cp2, CharPos(4));
755
756         let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
757         assert_eq!(cp3, CharPos(12));
758
759         let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
760         assert_eq!(cp4, CharPos(15));
761     }
762
763     #[test]
764     fn t7() {
765         // Test span_to_lines for a span ending at the end of filemap
766         let cm = init_code_map();
767         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
768         let file_lines = cm.span_to_lines(span).unwrap();
769
770         assert_eq!(file_lines.file.name, "blork.rs");
771         assert_eq!(file_lines.lines.len(), 1);
772         assert_eq!(file_lines.lines[0].line_index, 1);
773     }
774
775     /// Given a string like " ~~~~~~~~~~~~ ", produces a span
776     /// converting that range. The idea is that the string has the same
777     /// length as the input, and we uncover the byte positions.  Note
778     /// that this can span lines and so on.
779     fn span_from_selection(input: &str, selection: &str) -> Span {
780         assert_eq!(input.len(), selection.len());
781         let left_index = selection.find('~').unwrap() as u32;
782         let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
783         Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
784     }
785
786     /// Test span_to_snippet and span_to_lines for a span converting 3
787     /// lines in the middle of a file.
788     #[test]
789     fn span_to_snippet_and_lines_spanning_multiple_lines() {
790         let cm = CodeMap::new(FilePathMapping::empty());
791         let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
792         let selection = "     \n    ~~\n~~~\n~~~~~     \n   \n";
793         cm.new_filemap_and_lines("blork.rs", inputtext);
794         let span = span_from_selection(inputtext, selection);
795
796         // check that we are extracting the text we thought we were extracting
797         assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
798
799         // check that span_to_lines gives us the complete result with the lines/cols we expected
800         let lines = cm.span_to_lines(span).unwrap();
801         let expected = vec![
802             LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
803             LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
804             LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
805             ];
806         assert_eq!(lines.lines, expected);
807     }
808
809     #[test]
810     fn t8() {
811         // Test span_to_snippet for a span ending at the end of filemap
812         let cm = init_code_map();
813         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
814         let snippet = cm.span_to_snippet(span);
815
816         assert_eq!(snippet, Ok("second line".to_string()));
817     }
818
819     #[test]
820     fn t9() {
821         // Test span_to_str for a span ending at the end of filemap
822         let cm = init_code_map();
823         let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
824         let sstr =  cm.span_to_string(span);
825
826         assert_eq!(sstr, "blork.rs:2:1: 2:12");
827     }
828
829     /// Test failing to merge two spans on different lines
830     #[test]
831     fn span_merging_fail() {
832         let cm = CodeMap::new(FilePathMapping::empty());
833         let inputtext  = "bbbb BB\ncc CCC\n";
834         let selection1 = "     ~~\n      \n";
835         let selection2 = "       \n   ~~~\n";
836         cm.new_filemap_and_lines("blork.rs", inputtext);
837         let span1 = span_from_selection(inputtext, selection1);
838         let span2 = span_from_selection(inputtext, selection2);
839
840         assert!(cm.merge_spans(span1, span2).is_none());
841     }
842
843     /// Returns the span corresponding to the `n`th occurrence of
844     /// `substring` in `source_text`.
845     trait CodeMapExtension {
846         fn span_substr(&self,
847                     file: &Rc<FileMap>,
848                     source_text: &str,
849                     substring: &str,
850                     n: usize)
851                     -> Span;
852     }
853
854     impl CodeMapExtension for CodeMap {
855         fn span_substr(&self,
856                     file: &Rc<FileMap>,
857                     source_text: &str,
858                     substring: &str,
859                     n: usize)
860                     -> Span
861         {
862             println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
863                     file.name, file.start_pos, substring, n);
864             let mut i = 0;
865             let mut hi = 0;
866             loop {
867                 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
868                     panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
869                         source_text, n, substring, i);
870                 });
871                 let lo = hi + offset;
872                 hi = lo + substring.len();
873                 if i == n {
874                     let span = Span::new(
875                         BytePos(lo as u32 + file.start_pos.0),
876                         BytePos(hi as u32 + file.start_pos.0),
877                         NO_EXPANSION,
878                     );
879                     assert_eq!(&self.span_to_snippet(span).unwrap()[..],
880                             substring);
881                     return span;
882                 }
883                 i += 1;
884             }
885         }
886     }
887 }