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