]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/codemap.rs
Auto merge of #30859 - aliclark:musl-nx-issue, r=brson
[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 self::ExpnFormat::*;
21
22 use std::cell::{Cell, RefCell};
23 use std::ops::{Add, Sub};
24 use std::path::Path;
25 use std::rc::Rc;
26
27 use std::{fmt, fs};
28 use std::io::{self, Read};
29
30 use serialize::{Encodable, Decodable, Encoder, Decoder};
31
32 use ast::Name;
33
34 // _____________________________________________________________________________
35 // Pos, BytePos, CharPos
36 //
37
38 pub trait Pos {
39     fn from_usize(n: usize) -> Self;
40     fn to_usize(&self) -> usize;
41 }
42
43 /// A byte offset. Keep this small (currently 32-bits), as AST contains
44 /// a lot of them.
45 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Debug)]
46 pub struct BytePos(pub u32);
47
48 /// A character offset. Because of multibyte utf8 characters, a byte offset
49 /// is not equivalent to a character offset. The CodeMap will convert BytePos
50 /// values to CharPos values as necessary.
51 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Debug)]
52 pub struct CharPos(pub usize);
53
54 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
55 // have been unsuccessful
56
57 impl Pos for BytePos {
58     fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
59     fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
60 }
61
62 impl Add for BytePos {
63     type Output = BytePos;
64
65     fn add(self, rhs: BytePos) -> BytePos {
66         BytePos((self.to_usize() + rhs.to_usize()) as u32)
67     }
68 }
69
70 impl Sub for BytePos {
71     type Output = BytePos;
72
73     fn sub(self, rhs: BytePos) -> BytePos {
74         BytePos((self.to_usize() - rhs.to_usize()) as u32)
75     }
76 }
77
78 impl Encodable for BytePos {
79     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
80         s.emit_u32(self.0)
81     }
82 }
83
84 impl Decodable for BytePos {
85     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
86         Ok(BytePos(try!{ d.read_u32() }))
87     }
88 }
89
90 impl Pos for CharPos {
91     fn from_usize(n: usize) -> CharPos { CharPos(n) }
92     fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
93 }
94
95 impl Add for CharPos {
96     type Output = CharPos;
97
98     fn add(self, rhs: CharPos) -> CharPos {
99         CharPos(self.to_usize() + rhs.to_usize())
100     }
101 }
102
103 impl Sub for CharPos {
104     type Output = CharPos;
105
106     fn sub(self, rhs: CharPos) -> CharPos {
107         CharPos(self.to_usize() - rhs.to_usize())
108     }
109 }
110
111 // _____________________________________________________________________________
112 // Span, Spanned
113 //
114
115 /// Spans represent a region of code, used for error reporting. Positions in spans
116 /// are *absolute* positions from the beginning of the codemap, not positions
117 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
118 /// to the original source.
119 /// You must be careful if the span crosses more than one file - you will not be
120 /// able to use many of the functions on spans in codemap and you cannot assume
121 /// that the length of the span = hi - lo; there may be space in the BytePos
122 /// range between files.
123 #[derive(Clone, Copy, Hash)]
124 pub struct Span {
125     pub lo: BytePos,
126     pub hi: BytePos,
127     /// Information about where the macro came from, if this piece of
128     /// code was created by a macro expansion.
129     pub expn_id: ExpnId
130 }
131
132 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
133
134 // Generic span to be used for code originating from the command line
135 pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0),
136                                          hi: BytePos(0),
137                                          expn_id: COMMAND_LINE_EXPN };
138
139 impl Span {
140     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
141     pub fn substitute_dummy(self, other: Span) -> Span {
142         if self == DUMMY_SP { other } else { self }
143     }
144
145     pub fn contains(self, other: Span) -> bool {
146         self.lo <= other.lo && other.hi <= self.hi
147     }
148 }
149
150 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
151 pub struct Spanned<T> {
152     pub node: T,
153     pub span: Span,
154 }
155
156 impl PartialEq for Span {
157     fn eq(&self, other: &Span) -> bool {
158         return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
159     }
160     fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
161 }
162
163 impl Eq for Span {}
164
165 impl Encodable for Span {
166     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
167         s.emit_struct("Span", 2, |s| {
168             try!(s.emit_struct_field("lo", 0, |s| {
169                 self.lo.encode(s)
170             }));
171
172             s.emit_struct_field("hi", 1, |s| {
173                 self.hi.encode(s)
174             })
175         })
176     }
177 }
178
179 impl Decodable for Span {
180     fn decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
181         d.read_struct("Span", 2, |d| {
182             let lo = try!(d.read_struct_field("lo", 0, |d| {
183                 BytePos::decode(d)
184             }));
185
186             let hi = try!(d.read_struct_field("hi", 1, |d| {
187                 BytePos::decode(d)
188             }));
189
190             Ok(mk_sp(lo, hi))
191         })
192     }
193 }
194
195 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
196     write!(f, "Span {{ lo: {:?}, hi: {:?}, expn_id: {:?} }}",
197            span.lo, span.hi, span.expn_id)
198 }
199
200 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
201                 Cell::new(default_span_debug));
202
203 impl fmt::Debug for Span {
204     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
205         SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
206     }
207 }
208
209 pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
210     respan(mk_sp(lo, hi), t)
211 }
212
213 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
214     Spanned {node: t, span: sp}
215 }
216
217 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
218     respan(DUMMY_SP, t)
219 }
220
221 /* assuming that we're not in macro expansion */
222 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
223     Span {lo: lo, hi: hi, expn_id: NO_EXPANSION}
224 }
225
226 /// Return the span itself if it doesn't come from a macro expansion,
227 /// otherwise return the call site span up to the `enclosing_sp` by
228 /// following the `expn_info` chain.
229 pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span {
230     let call_site1 = cm.with_expn_info(sp.expn_id, |ei| ei.map(|ei| ei.call_site));
231     let call_site2 = cm.with_expn_info(enclosing_sp.expn_id, |ei| ei.map(|ei| ei.call_site));
232     match (call_site1, call_site2) {
233         (None, _) => sp,
234         (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
235         (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp),
236     }
237 }
238
239 // _____________________________________________________________________________
240 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
241 //
242
243 /// A source code location used for error reporting
244 #[derive(Debug)]
245 pub struct Loc {
246     /// Information about the original source
247     pub file: Rc<FileMap>,
248     /// The (1-based) line number
249     pub line: usize,
250     /// The (0-based) column offset
251     pub col: CharPos
252 }
253
254 /// A source code location used as the result of lookup_char_pos_adj
255 // Actually, *none* of the clients use the filename *or* file field;
256 // perhaps they should just be removed.
257 #[derive(Debug)]
258 pub struct LocWithOpt {
259     pub filename: FileName,
260     pub line: usize,
261     pub col: CharPos,
262     pub file: Option<Rc<FileMap>>,
263 }
264
265 // used to be structural records. Better names, anyone?
266 #[derive(Debug)]
267 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
268 #[derive(Debug)]
269 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
270
271
272 // _____________________________________________________________________________
273 // ExpnFormat, NameAndSpan, ExpnInfo, ExpnId
274 //
275
276 /// The source of expansion.
277 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
278 pub enum ExpnFormat {
279     /// e.g. #[derive(...)] <item>
280     MacroAttribute(Name),
281     /// e.g. `format!()`
282     MacroBang(Name),
283 }
284
285 #[derive(Clone, Hash, Debug)]
286 pub struct NameAndSpan {
287     /// The format with which the macro was invoked.
288     pub format: ExpnFormat,
289     /// Whether the macro is allowed to use #[unstable]/feature-gated
290     /// features internally without forcing the whole crate to opt-in
291     /// to them.
292     pub allow_internal_unstable: bool,
293     /// The span of the macro definition itself. The macro may not
294     /// have a sensible definition span (e.g. something defined
295     /// completely inside libsyntax) in which case this is None.
296     pub span: Option<Span>
297 }
298
299 impl NameAndSpan {
300     pub fn name(&self) -> Name {
301         match self.format {
302             ExpnFormat::MacroAttribute(s) => s,
303             ExpnFormat::MacroBang(s) => s,
304         }
305     }
306 }
307
308 /// Extra information for tracking spans of macro and syntax sugar expansion
309 #[derive(Hash, Debug)]
310 pub struct ExpnInfo {
311     /// The location of the actual macro invocation or syntax sugar , e.g.
312     /// `let x = foo!();` or `if let Some(y) = x {}`
313     ///
314     /// This may recursively refer to other macro invocations, e.g. if
315     /// `foo!()` invoked `bar!()` internally, and there was an
316     /// expression inside `bar!`; the call_site of the expression in
317     /// the expansion would point to the `bar!` invocation; that
318     /// call_site span would have its own ExpnInfo, with the call_site
319     /// pointing to the `foo!` invocation.
320     pub call_site: Span,
321     /// Information about the expansion.
322     pub callee: NameAndSpan
323 }
324
325 #[derive(PartialEq, Eq, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Copy)]
326 pub struct ExpnId(u32);
327
328 pub const NO_EXPANSION: ExpnId = ExpnId(!0);
329 // For code appearing from the command line
330 pub const COMMAND_LINE_EXPN: ExpnId = ExpnId(!1);
331
332 impl ExpnId {
333     pub fn from_u32(id: u32) -> ExpnId {
334         ExpnId(id)
335     }
336
337     pub fn into_u32(self) -> u32 {
338         self.0
339     }
340 }
341
342 // _____________________________________________________________________________
343 // FileMap, MultiByteChar, FileName, FileLines
344 //
345
346 pub type FileName = String;
347
348 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
349 pub struct LineInfo {
350     /// Index of line, starting from 0.
351     pub line_index: usize,
352
353     /// Column in line where span begins, starting from 0.
354     pub start_col: CharPos,
355
356     /// Column in line where span ends, starting from 0, exclusive.
357     pub end_col: CharPos,
358 }
359
360 pub struct FileLines {
361     pub file: Rc<FileMap>,
362     pub lines: Vec<LineInfo>
363 }
364
365 /// Identifies an offset of a multi-byte character in a FileMap
366 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
367 pub struct MultiByteChar {
368     /// The absolute offset of the character in the CodeMap
369     pub pos: BytePos,
370     /// The number of bytes, >=2
371     pub bytes: usize,
372 }
373
374 /// A single source in the CodeMap.
375 pub struct FileMap {
376     /// The name of the file that the source came from, source that doesn't
377     /// originate from files has names between angle brackets by convention,
378     /// e.g. `<anon>`
379     pub name: FileName,
380     /// The complete source code
381     pub src: Option<Rc<String>>,
382     /// The start position of this source in the CodeMap
383     pub start_pos: BytePos,
384     /// The end position of this source in the CodeMap
385     pub end_pos: BytePos,
386     /// Locations of lines beginnings in the source code
387     pub lines: RefCell<Vec<BytePos>>,
388     /// Locations of multi-byte characters in the source code
389     pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
390 }
391
392 impl Encodable for FileMap {
393     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
394         s.emit_struct("FileMap", 5, |s| {
395             try! { s.emit_struct_field("name", 0, |s| self.name.encode(s)) };
396             try! { s.emit_struct_field("start_pos", 1, |s| self.start_pos.encode(s)) };
397             try! { s.emit_struct_field("end_pos", 2, |s| self.end_pos.encode(s)) };
398             try! { s.emit_struct_field("lines", 3, |s| {
399                     let lines = self.lines.borrow();
400                     // store the length
401                     try! { s.emit_u32(lines.len() as u32) };
402
403                     if !lines.is_empty() {
404                         // In order to preserve some space, we exploit the fact that
405                         // the lines list is sorted and individual lines are
406                         // probably not that long. Because of that we can store lines
407                         // as a difference list, using as little space as possible
408                         // for the differences.
409                         let max_line_length = if lines.len() == 1 {
410                             0
411                         } else {
412                             lines.windows(2)
413                                  .map(|w| w[1] - w[0])
414                                  .map(|bp| bp.to_usize())
415                                  .max()
416                                  .unwrap()
417                         };
418
419                         let bytes_per_diff: u8 = match max_line_length {
420                             0 ... 0xFF => 1,
421                             0x100 ... 0xFFFF => 2,
422                             _ => 4
423                         };
424
425                         // Encode the number of bytes used per diff.
426                         try! { bytes_per_diff.encode(s) };
427
428                         // Encode the first element.
429                         try! { lines[0].encode(s) };
430
431                         let diff_iter = (&lines[..]).windows(2)
432                                                     .map(|w| (w[1] - w[0]));
433
434                         match bytes_per_diff {
435                             1 => for diff in diff_iter { try! { (diff.0 as u8).encode(s) } },
436                             2 => for diff in diff_iter { try! { (diff.0 as u16).encode(s) } },
437                             4 => for diff in diff_iter { try! { diff.0.encode(s) } },
438                             _ => unreachable!()
439                         }
440                     }
441
442                     Ok(())
443                 })
444             };
445             s.emit_struct_field("multibyte_chars", 4, |s| {
446                 (*self.multibyte_chars.borrow()).encode(s)
447             })
448         })
449     }
450 }
451
452 impl Decodable for FileMap {
453     fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
454
455         d.read_struct("FileMap", 5, |d| {
456             let name: String = try! {
457                 d.read_struct_field("name", 0, |d| Decodable::decode(d))
458             };
459             let start_pos: BytePos = try! {
460                 d.read_struct_field("start_pos", 1, |d| Decodable::decode(d))
461             };
462             let end_pos: BytePos = try! {
463                 d.read_struct_field("end_pos", 2, |d| Decodable::decode(d))
464             };
465             let lines: Vec<BytePos> = try! {
466                 d.read_struct_field("lines", 3, |d| {
467                     let num_lines: u32 = try! { Decodable::decode(d) };
468                     let mut lines = Vec::with_capacity(num_lines as usize);
469
470                     if num_lines > 0 {
471                         // Read the number of bytes used per diff.
472                         let bytes_per_diff: u8 = try! { Decodable::decode(d) };
473
474                         // Read the first element.
475                         let mut line_start: BytePos = try! { Decodable::decode(d) };
476                         lines.push(line_start);
477
478                         for _ in 1..num_lines {
479                             let diff = match bytes_per_diff {
480                                 1 => try! { d.read_u8() } as u32,
481                                 2 => try! { d.read_u16() } as u32,
482                                 4 => try! { d.read_u32() },
483                                 _ => unreachable!()
484                             };
485
486                             line_start = line_start + BytePos(diff);
487
488                             lines.push(line_start);
489                         }
490                     }
491
492                     Ok(lines)
493                 })
494             };
495             let multibyte_chars: Vec<MultiByteChar> = try! {
496                 d.read_struct_field("multibyte_chars", 4, |d| Decodable::decode(d))
497             };
498             Ok(FileMap {
499                 name: name,
500                 start_pos: start_pos,
501                 end_pos: end_pos,
502                 src: None,
503                 lines: RefCell::new(lines),
504                 multibyte_chars: RefCell::new(multibyte_chars)
505             })
506         })
507     }
508 }
509
510 impl fmt::Debug for FileMap {
511     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
512         write!(fmt, "FileMap({})", self.name)
513     }
514 }
515
516 impl FileMap {
517     /// EFFECT: register a start-of-line offset in the
518     /// table of line-beginnings.
519     /// UNCHECKED INVARIANT: these offsets must be added in the right
520     /// order and must be in the right places; there is shared knowledge
521     /// about what ends a line between this file and parse.rs
522     /// WARNING: pos param here is the offset relative to start of CodeMap,
523     /// and CodeMap will append a newline when adding a filemap without a newline at the end,
524     /// so the safe way to call this is with value calculated as
525     /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
526     pub fn next_line(&self, pos: BytePos) {
527         // the new charpos must be > the last one (or it's the first one).
528         let mut lines = self.lines.borrow_mut();
529         let line_len = lines.len();
530         assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
531         lines.push(pos);
532     }
533
534     /// get a line from the list of pre-computed line-beginnings.
535     /// line-number here is 0-based.
536     pub fn get_line(&self, line_number: usize) -> Option<&str> {
537         match self.src {
538             Some(ref src) => {
539                 let lines = self.lines.borrow();
540                 lines.get(line_number).map(|&line| {
541                     let begin: BytePos = line - self.start_pos;
542                     let begin = begin.to_usize();
543                     // We can't use `lines.get(line_number+1)` because we might
544                     // be parsing when we call this function and thus the current
545                     // line is the last one we have line info for.
546                     let slice = &src[begin..];
547                     match slice.find('\n') {
548                         Some(e) => &slice[..e],
549                         None => slice
550                     }
551                 })
552             }
553             None => None
554         }
555     }
556
557     pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
558         assert!(bytes >=2 && bytes <= 4);
559         let mbc = MultiByteChar {
560             pos: pos,
561             bytes: bytes,
562         };
563         self.multibyte_chars.borrow_mut().push(mbc);
564     }
565
566     pub fn is_real_file(&self) -> bool {
567         !(self.name.starts_with("<") &&
568           self.name.ends_with(">"))
569     }
570
571     pub fn is_imported(&self) -> bool {
572         self.src.is_none()
573     }
574
575     fn count_lines(&self) -> usize {
576         self.lines.borrow().len()
577     }
578 }
579
580 /// An abstraction over the fs operations used by the Parser.
581 pub trait FileLoader {
582     /// Query the existence of a file.
583     fn file_exists(&self, path: &Path) -> bool;
584
585     /// Read the contents of an UTF-8 file into memory.
586     fn read_file(&self, path: &Path) -> io::Result<String>;
587 }
588
589 /// A FileLoader that uses std::fs to load real files.
590 pub struct RealFileLoader;
591
592 impl FileLoader for RealFileLoader {
593     fn file_exists(&self, path: &Path) -> bool {
594         fs::metadata(path).is_ok()
595     }
596
597     fn read_file(&self, path: &Path) -> io::Result<String> {
598         let mut src = String::new();
599         try!(try!(fs::File::open(path)).read_to_string(&mut src));
600         Ok(src)
601     }
602 }
603
604 // _____________________________________________________________________________
605 // CodeMap
606 //
607
608 pub struct CodeMap {
609     pub files: RefCell<Vec<Rc<FileMap>>>,
610     expansions: RefCell<Vec<ExpnInfo>>,
611     file_loader: Box<FileLoader>
612 }
613
614 impl CodeMap {
615     pub fn new() -> CodeMap {
616         CodeMap {
617             files: RefCell::new(Vec::new()),
618             expansions: RefCell::new(Vec::new()),
619             file_loader: Box::new(RealFileLoader)
620         }
621     }
622
623     pub fn with_file_loader(file_loader: Box<FileLoader>) -> CodeMap {
624         CodeMap {
625             files: RefCell::new(Vec::new()),
626             expansions: RefCell::new(Vec::new()),
627             file_loader: file_loader
628         }
629     }
630
631     pub fn file_exists(&self, path: &Path) -> bool {
632         self.file_loader.file_exists(path)
633     }
634
635     pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> {
636         let src = try!(self.file_loader.read_file(path));
637         Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
638     }
639
640     fn next_start_pos(&self) -> usize {
641         let files = self.files.borrow();
642         match files.last() {
643             None => 0,
644             // Add one so there is some space between files. This lets us distinguish
645             // positions in the codemap, even in the presence of zero-length files.
646             Some(last) => last.end_pos.to_usize() + 1,
647         }
648     }
649
650     /// Creates a new filemap without setting its line information. If you don't
651     /// intend to set the line information yourself, you should use new_filemap_and_lines.
652     pub fn new_filemap(&self, filename: FileName, mut src: String) -> Rc<FileMap> {
653         let start_pos = self.next_start_pos();
654         let mut files = self.files.borrow_mut();
655
656         // Remove utf-8 BOM if any.
657         if src.starts_with("\u{feff}") {
658             src.drain(..3);
659         }
660
661         let end_pos = start_pos + src.len();
662
663         let filemap = Rc::new(FileMap {
664             name: filename,
665             src: Some(Rc::new(src)),
666             start_pos: Pos::from_usize(start_pos),
667             end_pos: Pos::from_usize(end_pos),
668             lines: RefCell::new(Vec::new()),
669             multibyte_chars: RefCell::new(Vec::new()),
670         });
671
672         files.push(filemap.clone());
673
674         filemap
675     }
676
677     /// Creates a new filemap and sets its line information.
678     pub fn new_filemap_and_lines(&self, filename: &str, src: &str) -> Rc<FileMap> {
679         let fm = self.new_filemap(filename.to_string(), src.to_owned());
680         let mut byte_pos: u32 = 0;
681         for line in src.lines() {
682             // register the start of this line
683             fm.next_line(BytePos(byte_pos));
684
685             // update byte_pos to include this line and the \n at the end
686             byte_pos += line.len() as u32 + 1;
687         }
688         fm
689     }
690
691
692     /// Allocates a new FileMap representing a source file from an external
693     /// crate. The source code of such an "imported filemap" is not available,
694     /// but we still know enough to generate accurate debuginfo location
695     /// information for things inlined from other crates.
696     pub fn new_imported_filemap(&self,
697                                 filename: FileName,
698                                 source_len: usize,
699                                 mut file_local_lines: Vec<BytePos>,
700                                 mut file_local_multibyte_chars: Vec<MultiByteChar>)
701                                 -> Rc<FileMap> {
702         let start_pos = self.next_start_pos();
703         let mut files = self.files.borrow_mut();
704
705         let end_pos = Pos::from_usize(start_pos + source_len);
706         let start_pos = Pos::from_usize(start_pos);
707
708         for pos in &mut file_local_lines {
709             *pos = *pos + start_pos;
710         }
711
712         for mbc in &mut file_local_multibyte_chars {
713             mbc.pos = mbc.pos + start_pos;
714         }
715
716         let filemap = Rc::new(FileMap {
717             name: filename,
718             src: None,
719             start_pos: start_pos,
720             end_pos: end_pos,
721             lines: RefCell::new(file_local_lines),
722             multibyte_chars: RefCell::new(file_local_multibyte_chars),
723         });
724
725         files.push(filemap.clone());
726
727         filemap
728     }
729
730     pub fn mk_substr_filename(&self, sp: Span) -> String {
731         let pos = self.lookup_char_pos(sp.lo);
732         (format!("<{}:{}:{}>",
733                  pos.file.name,
734                  pos.line,
735                  pos.col.to_usize() + 1)).to_string()
736     }
737
738     /// Lookup source information about a BytePos
739     pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
740         let chpos = self.bytepos_to_file_charpos(pos);
741         match self.lookup_line(pos) {
742             Ok(FileMapAndLine { fm: f, line: a }) => {
743                 let line = a + 1; // Line numbers start at 1
744                 let linebpos = (*f.lines.borrow())[a];
745                 let linechpos = self.bytepos_to_file_charpos(linebpos);
746                 debug!("byte pos {:?} is on the line at byte pos {:?}",
747                        pos, linebpos);
748                 debug!("char pos {:?} is on the line at char pos {:?}",
749                        chpos, linechpos);
750                 debug!("byte is on line: {}", line);
751                 assert!(chpos >= linechpos);
752                 Loc {
753                     file: f,
754                     line: line,
755                     col: chpos - linechpos,
756                 }
757             }
758             Err(f) => {
759                 Loc {
760                     file: f,
761                     line: 0,
762                     col: chpos,
763                 }
764             }
765         }
766     }
767
768     // If the relevant filemap is empty, we don't return a line number.
769     fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> {
770         let idx = self.lookup_filemap_idx(pos);
771
772         let files = self.files.borrow();
773         let f = (*files)[idx].clone();
774
775         let len = f.lines.borrow().len();
776         if len == 0 {
777             return Err(f);
778         }
779
780         let mut a = 0;
781         {
782             let lines = f.lines.borrow();
783             let mut b = lines.len();
784             while b - a > 1 {
785                 let m = (a + b) / 2;
786                 if (*lines)[m] > pos {
787                     b = m;
788                 } else {
789                     a = m;
790                 }
791             }
792             assert!(a <= lines.len());
793         }
794         Ok(FileMapAndLine { fm: f, line: a })
795     }
796
797     pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
798         let loc = self.lookup_char_pos(pos);
799         LocWithOpt {
800             filename: loc.file.name.to_string(),
801             line: loc.line,
802             col: loc.col,
803             file: Some(loc.file)
804         }
805     }
806
807     pub fn span_to_string(&self, sp: Span) -> String {
808         if self.files.borrow().is_empty() && sp == DUMMY_SP {
809             return "no-location".to_string();
810         }
811
812         let lo = self.lookup_char_pos_adj(sp.lo);
813         let hi = self.lookup_char_pos_adj(sp.hi);
814         return (format!("{}:{}:{}: {}:{}",
815                         lo.filename,
816                         lo.line,
817                         lo.col.to_usize() + 1,
818                         hi.line,
819                         hi.col.to_usize() + 1)).to_string()
820     }
821
822     // Returns true if two spans have the same callee
823     // (Assumes the same ExpnFormat implies same callee)
824     fn match_callees(&self, sp_a: &Span, sp_b: &Span) -> bool {
825         let fmt_a = self
826             .with_expn_info(sp_a.expn_id,
827                             |ei| ei.map(|ei| ei.callee.format.clone()));
828
829         let fmt_b = self
830             .with_expn_info(sp_b.expn_id,
831                             |ei| ei.map(|ei| ei.callee.format.clone()));
832         fmt_a == fmt_b
833     }
834
835     /// Returns a formatted string showing the expansion chain of a span
836     ///
837     /// Spans are printed in the following format:
838     ///
839     /// filename:start_line:col: end_line:col
840     /// snippet
841     ///   Callee:
842     ///   Callee span
843     ///   Callsite:
844     ///   Callsite span
845     ///
846     /// Callees and callsites are printed recursively (if available, otherwise header
847     /// and span is omitted), expanding into their own callee/callsite spans.
848     /// Each layer of recursion has an increased indent, and snippets are truncated
849     /// to at most 50 characters. Finally, recursive calls to the same macro are squashed,
850     /// with '...' used to represent any number of recursive calls.
851     pub fn span_to_expanded_string(&self, sp: Span) -> String {
852         self.span_to_expanded_string_internal(sp, "")
853     }
854
855     fn span_to_expanded_string_internal(&self, sp:Span, indent: &str) -> String {
856         let mut indent = indent.to_owned();
857         let mut output = "".to_owned();
858         let span_str = self.span_to_string(sp);
859         let mut span_snip = self.span_to_snippet(sp)
860             .unwrap_or("Snippet unavailable".to_owned());
861
862         // Truncate by code points - in worst case this will be more than 50 characters,
863         // but ensures at least 50 characters and respects byte boundaries.
864         let char_vec: Vec<(usize, char)> = span_snip.char_indices().collect();
865         if char_vec.len() > 50 {
866             span_snip.truncate(char_vec[49].0);
867             span_snip.push_str("...");
868         }
869
870         output.push_str(&format!("{}{}\n{}`{}`\n", indent, span_str, indent, span_snip));
871
872         if sp.expn_id == NO_EXPANSION || sp.expn_id == COMMAND_LINE_EXPN {
873             return output;
874         }
875
876         let mut callee = self.with_expn_info(sp.expn_id,
877                                              |ei| ei.and_then(|ei| ei.callee.span.clone()));
878         let mut callsite = self.with_expn_info(sp.expn_id,
879                                                |ei| ei.map(|ei| ei.call_site.clone()));
880
881         indent.push_str("  ");
882         let mut is_recursive = false;
883
884         while callee.is_some() && self.match_callees(&sp, &callee.unwrap()) {
885             callee = self.with_expn_info(callee.unwrap().expn_id,
886                                          |ei| ei.and_then(|ei| ei.callee.span.clone()));
887             is_recursive = true;
888         }
889         if let Some(span) = callee {
890             output.push_str(&indent);
891             output.push_str("Callee:\n");
892             if is_recursive {
893                 output.push_str(&indent);
894                 output.push_str("...\n");
895             }
896             output.push_str(&(self.span_to_expanded_string_internal(span, &indent)));
897         }
898
899         is_recursive = false;
900         while callsite.is_some() && self.match_callees(&sp, &callsite.unwrap()) {
901             callsite = self.with_expn_info(callsite.unwrap().expn_id,
902                                            |ei| ei.map(|ei| ei.call_site.clone()));
903             is_recursive = true;
904         }
905         if let Some(span) = callsite {
906             output.push_str(&indent);
907             output.push_str("Callsite:\n");
908             if is_recursive {
909                 output.push_str(&indent);
910                 output.push_str("...\n");
911             }
912             output.push_str(&(self.span_to_expanded_string_internal(span, &indent)));
913         }
914         output
915     }
916
917     /// Return the source span - this is either the supplied span, or the span for
918     /// the macro callsite that expanded to it.
919     pub fn source_callsite(&self, sp: Span) -> Span {
920         let mut span = sp;
921         while span.expn_id != NO_EXPANSION && span.expn_id != COMMAND_LINE_EXPN {
922             if let Some(callsite) = self.with_expn_info(span.expn_id,
923                                                |ei| ei.map(|ei| ei.call_site.clone())) {
924                 span = callsite;
925             }
926             else {
927                 break;
928             }
929         }
930         span
931     }
932
933     pub fn span_to_filename(&self, sp: Span) -> FileName {
934         self.lookup_char_pos(sp.lo).file.name.to_string()
935     }
936
937     pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
938         if sp.lo > sp.hi {
939             return Err(SpanLinesError::IllFormedSpan(sp));
940         }
941
942         let lo = self.lookup_char_pos(sp.lo);
943         let hi = self.lookup_char_pos(sp.hi);
944
945         if lo.file.start_pos != hi.file.start_pos {
946             return Err(SpanLinesError::DistinctSources(DistinctSources {
947                 begin: (lo.file.name.clone(), lo.file.start_pos),
948                 end: (hi.file.name.clone(), hi.file.start_pos),
949             }));
950         }
951         assert!(hi.line >= lo.line);
952
953         let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
954
955         // The span starts partway through the first line,
956         // but after that it starts from offset 0.
957         let mut start_col = lo.col;
958
959         // For every line but the last, it extends from `start_col`
960         // and to the end of the line. Be careful because the line
961         // numbers in Loc are 1-based, so we subtract 1 to get 0-based
962         // lines.
963         for line_index in lo.line-1 .. hi.line-1 {
964             let line_len = lo.file.get_line(line_index).map(|s| s.len()).unwrap_or(0);
965             lines.push(LineInfo { line_index: line_index,
966                                   start_col: start_col,
967                                   end_col: CharPos::from_usize(line_len) });
968             start_col = CharPos::from_usize(0);
969         }
970
971         // For the last line, it extends from `start_col` to `hi.col`:
972         lines.push(LineInfo { line_index: hi.line - 1,
973                               start_col: start_col,
974                               end_col: hi.col });
975
976         Ok(FileLines {file: lo.file, lines: lines})
977     }
978
979     pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
980         if sp.lo > sp.hi {
981             return Err(SpanSnippetError::IllFormedSpan(sp));
982         }
983
984         let local_begin = self.lookup_byte_offset(sp.lo);
985         let local_end = self.lookup_byte_offset(sp.hi);
986
987         if local_begin.fm.start_pos != local_end.fm.start_pos {
988             return Err(SpanSnippetError::DistinctSources(DistinctSources {
989                 begin: (local_begin.fm.name.clone(),
990                         local_begin.fm.start_pos),
991                 end: (local_end.fm.name.clone(),
992                       local_end.fm.start_pos)
993             }));
994         } else {
995             match local_begin.fm.src {
996                 Some(ref src) => {
997                     let start_index = local_begin.pos.to_usize();
998                     let end_index = local_end.pos.to_usize();
999                     let source_len = (local_begin.fm.end_pos -
1000                                       local_begin.fm.start_pos).to_usize();
1001
1002                     if start_index > end_index || end_index > source_len {
1003                         return Err(SpanSnippetError::MalformedForCodemap(
1004                             MalformedCodemapPositions {
1005                                 name: local_begin.fm.name.clone(),
1006                                 source_len: source_len,
1007                                 begin_pos: local_begin.pos,
1008                                 end_pos: local_end.pos,
1009                             }));
1010                     }
1011
1012                     return Ok((&src[start_index..end_index]).to_string())
1013                 }
1014                 None => {
1015                     return Err(SpanSnippetError::SourceNotAvailable {
1016                         filename: local_begin.fm.name.clone()
1017                     });
1018                 }
1019             }
1020         }
1021     }
1022
1023     pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> {
1024         for fm in self.files.borrow().iter() {
1025             if filename == fm.name {
1026                 return fm.clone();
1027             }
1028         }
1029         panic!("asking for {} which we don't know about", filename);
1030     }
1031
1032     /// For a global BytePos compute the local offset within the containing FileMap
1033     pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
1034         let idx = self.lookup_filemap_idx(bpos);
1035         let fm = (*self.files.borrow())[idx].clone();
1036         let offset = bpos - fm.start_pos;
1037         FileMapAndBytePos {fm: fm, pos: offset}
1038     }
1039
1040     /// Converts an absolute BytePos to a CharPos relative to the filemap.
1041     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1042         let idx = self.lookup_filemap_idx(bpos);
1043         let files = self.files.borrow();
1044         let map = &(*files)[idx];
1045
1046         // The number of extra bytes due to multibyte chars in the FileMap
1047         let mut total_extra_bytes = 0;
1048
1049         for mbc in map.multibyte_chars.borrow().iter() {
1050             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1051             if mbc.pos < bpos {
1052                 // every character is at least one byte, so we only
1053                 // count the actual extra bytes.
1054                 total_extra_bytes += mbc.bytes - 1;
1055                 // We should never see a byte position in the middle of a
1056                 // character
1057                 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
1058             } else {
1059                 break;
1060             }
1061         }
1062
1063         assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
1064         CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
1065     }
1066
1067     // Return the index of the filemap (in self.files) which contains pos.
1068     fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
1069         let files = self.files.borrow();
1070         let files = &*files;
1071         let count = files.len();
1072
1073         // Binary search for the filemap.
1074         let mut a = 0;
1075         let mut b = count;
1076         while b - a > 1 {
1077             let m = (a + b) / 2;
1078             if files[m].start_pos > pos {
1079                 b = m;
1080             } else {
1081                 a = m;
1082             }
1083         }
1084
1085         assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
1086
1087         return a;
1088     }
1089
1090     pub fn record_expansion(&self, expn_info: ExpnInfo) -> ExpnId {
1091         let mut expansions = self.expansions.borrow_mut();
1092         expansions.push(expn_info);
1093         let len = expansions.len();
1094         if len > u32::max_value() as usize {
1095             panic!("too many ExpnInfo's!");
1096         }
1097         ExpnId(len as u32 - 1)
1098     }
1099
1100     pub fn with_expn_info<T, F>(&self, id: ExpnId, f: F) -> T where
1101         F: FnOnce(Option<&ExpnInfo>) -> T,
1102     {
1103         match id {
1104             NO_EXPANSION | COMMAND_LINE_EXPN => f(None),
1105             ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as usize]))
1106         }
1107     }
1108
1109     /// Check if a span is "internal" to a macro in which #[unstable]
1110     /// items can be used (that is, a macro marked with
1111     /// `#[allow_internal_unstable]`).
1112     pub fn span_allows_unstable(&self, span: Span) -> bool {
1113         debug!("span_allows_unstable(span = {:?})", span);
1114         let mut allows_unstable = false;
1115         let mut expn_id = span.expn_id;
1116         loop {
1117             let quit = self.with_expn_info(expn_id, |expninfo| {
1118                 debug!("span_allows_unstable: expninfo = {:?}", expninfo);
1119                 expninfo.map_or(/* hit the top level */ true, |info| {
1120
1121                     let span_comes_from_this_expansion =
1122                         info.callee.span.map_or(span == info.call_site, |mac_span| {
1123                             mac_span.contains(span)
1124                         });
1125
1126                     debug!("span_allows_unstable: span: {:?} call_site: {:?} callee: {:?}",
1127                            (span.lo, span.hi),
1128                            (info.call_site.lo, info.call_site.hi),
1129                            info.callee.span.map(|x| (x.lo, x.hi)));
1130                     debug!("span_allows_unstable: from this expansion? {}, allows unstable? {}",
1131                            span_comes_from_this_expansion,
1132                            info.callee.allow_internal_unstable);
1133                     if span_comes_from_this_expansion {
1134                         allows_unstable = info.callee.allow_internal_unstable;
1135                         // we've found the right place, stop looking
1136                         true
1137                     } else {
1138                         // not the right place, keep looking
1139                         expn_id = info.call_site.expn_id;
1140                         false
1141                     }
1142                 })
1143             });
1144             if quit {
1145                 break
1146             }
1147         }
1148         debug!("span_allows_unstable? {}", allows_unstable);
1149         allows_unstable
1150     }
1151
1152     pub fn count_lines(&self) -> usize {
1153         self.files.borrow().iter().fold(0, |a, f| a + f.count_lines())
1154     }
1155 }
1156
1157 // _____________________________________________________________________________
1158 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
1159 //
1160
1161 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1162
1163 #[derive(Clone, PartialEq, Eq, Debug)]
1164 pub enum SpanLinesError {
1165     IllFormedSpan(Span),
1166     DistinctSources(DistinctSources),
1167 }
1168
1169 #[derive(Clone, PartialEq, Eq, Debug)]
1170 pub enum SpanSnippetError {
1171     IllFormedSpan(Span),
1172     DistinctSources(DistinctSources),
1173     MalformedForCodemap(MalformedCodemapPositions),
1174     SourceNotAvailable { filename: String }
1175 }
1176
1177 #[derive(Clone, PartialEq, Eq, Debug)]
1178 pub struct DistinctSources {
1179     begin: (String, BytePos),
1180     end: (String, BytePos)
1181 }
1182
1183 #[derive(Clone, PartialEq, Eq, Debug)]
1184 pub struct MalformedCodemapPositions {
1185     name: String,
1186     source_len: usize,
1187     begin_pos: BytePos,
1188     end_pos: BytePos
1189 }
1190
1191
1192 // _____________________________________________________________________________
1193 // Tests
1194 //
1195
1196 #[cfg(test)]
1197 mod tests {
1198     use super::*;
1199
1200     #[test]
1201     fn t1 () {
1202         let cm = CodeMap::new();
1203         let fm = cm.new_filemap("blork.rs".to_string(),
1204                                 "first line.\nsecond line".to_string());
1205         fm.next_line(BytePos(0));
1206         // Test we can get lines with partial line info.
1207         assert_eq!(fm.get_line(0), Some("first line."));
1208         // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
1209         fm.next_line(BytePos(10));
1210         assert_eq!(fm.get_line(1), Some("."));
1211         fm.next_line(BytePos(12));
1212         assert_eq!(fm.get_line(2), Some("second line"));
1213     }
1214
1215     #[test]
1216     #[should_panic]
1217     fn t2 () {
1218         let cm = CodeMap::new();
1219         let fm = cm.new_filemap("blork.rs".to_string(),
1220                                 "first line.\nsecond line".to_string());
1221         // TESTING *REALLY* BROKEN BEHAVIOR:
1222         fm.next_line(BytePos(0));
1223         fm.next_line(BytePos(10));
1224         fm.next_line(BytePos(2));
1225     }
1226
1227     fn init_code_map() -> CodeMap {
1228         let cm = CodeMap::new();
1229         let fm1 = cm.new_filemap("blork.rs".to_string(),
1230                                  "first line.\nsecond line".to_string());
1231         let fm2 = cm.new_filemap("empty.rs".to_string(),
1232                                  "".to_string());
1233         let fm3 = cm.new_filemap("blork2.rs".to_string(),
1234                                  "first line.\nsecond line".to_string());
1235
1236         fm1.next_line(BytePos(0));
1237         fm1.next_line(BytePos(12));
1238         fm2.next_line(fm2.start_pos);
1239         fm3.next_line(fm3.start_pos);
1240         fm3.next_line(fm3.start_pos + BytePos(12));
1241
1242         cm
1243     }
1244
1245     #[test]
1246     fn t3() {
1247         // Test lookup_byte_offset
1248         let cm = init_code_map();
1249
1250         let fmabp1 = cm.lookup_byte_offset(BytePos(23));
1251         assert_eq!(fmabp1.fm.name, "blork.rs");
1252         assert_eq!(fmabp1.pos, BytePos(23));
1253
1254         let fmabp1 = cm.lookup_byte_offset(BytePos(24));
1255         assert_eq!(fmabp1.fm.name, "empty.rs");
1256         assert_eq!(fmabp1.pos, BytePos(0));
1257
1258         let fmabp2 = cm.lookup_byte_offset(BytePos(25));
1259         assert_eq!(fmabp2.fm.name, "blork2.rs");
1260         assert_eq!(fmabp2.pos, BytePos(0));
1261     }
1262
1263     #[test]
1264     fn t4() {
1265         // Test bytepos_to_file_charpos
1266         let cm = init_code_map();
1267
1268         let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
1269         assert_eq!(cp1, CharPos(22));
1270
1271         let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
1272         assert_eq!(cp2, CharPos(0));
1273     }
1274
1275     #[test]
1276     fn t5() {
1277         // Test zero-length filemaps.
1278         let cm = init_code_map();
1279
1280         let loc1 = cm.lookup_char_pos(BytePos(22));
1281         assert_eq!(loc1.file.name, "blork.rs");
1282         assert_eq!(loc1.line, 2);
1283         assert_eq!(loc1.col, CharPos(10));
1284
1285         let loc2 = cm.lookup_char_pos(BytePos(25));
1286         assert_eq!(loc2.file.name, "blork2.rs");
1287         assert_eq!(loc2.line, 1);
1288         assert_eq!(loc2.col, CharPos(0));
1289     }
1290
1291     fn init_code_map_mbc() -> CodeMap {
1292         let cm = CodeMap::new();
1293         // € is a three byte utf8 char.
1294         let fm1 =
1295             cm.new_filemap("blork.rs".to_string(),
1296                            "fir€st €€€€ line.\nsecond line".to_string());
1297         let fm2 = cm.new_filemap("blork2.rs".to_string(),
1298                                  "first line€€.\n€ second line".to_string());
1299
1300         fm1.next_line(BytePos(0));
1301         fm1.next_line(BytePos(28));
1302         fm2.next_line(fm2.start_pos);
1303         fm2.next_line(fm2.start_pos + BytePos(20));
1304
1305         fm1.record_multibyte_char(BytePos(3), 3);
1306         fm1.record_multibyte_char(BytePos(9), 3);
1307         fm1.record_multibyte_char(BytePos(12), 3);
1308         fm1.record_multibyte_char(BytePos(15), 3);
1309         fm1.record_multibyte_char(BytePos(18), 3);
1310         fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
1311         fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
1312         fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
1313
1314         cm
1315     }
1316
1317     #[test]
1318     fn t6() {
1319         // Test bytepos_to_file_charpos in the presence of multi-byte chars
1320         let cm = init_code_map_mbc();
1321
1322         let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
1323         assert_eq!(cp1, CharPos(3));
1324
1325         let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
1326         assert_eq!(cp2, CharPos(4));
1327
1328         let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
1329         assert_eq!(cp3, CharPos(12));
1330
1331         let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
1332         assert_eq!(cp4, CharPos(15));
1333     }
1334
1335     #[test]
1336     fn t7() {
1337         // Test span_to_lines for a span ending at the end of filemap
1338         let cm = init_code_map();
1339         let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1340         let file_lines = cm.span_to_lines(span).unwrap();
1341
1342         assert_eq!(file_lines.file.name, "blork.rs");
1343         assert_eq!(file_lines.lines.len(), 1);
1344         assert_eq!(file_lines.lines[0].line_index, 1);
1345     }
1346
1347     /// Given a string like " ^~~~~~~~~~~~ ", produces a span
1348     /// coverting that range. The idea is that the string has the same
1349     /// length as the input, and we uncover the byte positions.  Note
1350     /// that this can span lines and so on.
1351     fn span_from_selection(input: &str, selection: &str) -> Span {
1352         assert_eq!(input.len(), selection.len());
1353         let left_index = selection.find('^').unwrap() as u32;
1354         let right_index = selection.rfind('~').unwrap() as u32;
1355         Span { lo: BytePos(left_index), hi: BytePos(right_index + 1), expn_id: NO_EXPANSION }
1356     }
1357
1358     /// Test span_to_snippet and span_to_lines for a span coverting 3
1359     /// lines in the middle of a file.
1360     #[test]
1361     fn span_to_snippet_and_lines_spanning_multiple_lines() {
1362         let cm = CodeMap::new();
1363         let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1364         let selection = "     \n    ^~\n~~~\n~~~~~     \n   \n";
1365         cm.new_filemap_and_lines("blork.rs", inputtext);
1366         let span = span_from_selection(inputtext, selection);
1367
1368         // check that we are extracting the text we thought we were extracting
1369         assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1370
1371         // check that span_to_lines gives us the complete result with the lines/cols we expected
1372         let lines = cm.span_to_lines(span).unwrap();
1373         let expected = vec![
1374             LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1375             LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1376             LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1377             ];
1378         assert_eq!(lines.lines, expected);
1379     }
1380
1381     #[test]
1382     fn t8() {
1383         // Test span_to_snippet for a span ending at the end of filemap
1384         let cm = init_code_map();
1385         let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1386         let snippet = cm.span_to_snippet(span);
1387
1388         assert_eq!(snippet, Ok("second line".to_string()));
1389     }
1390
1391     #[test]
1392     fn t9() {
1393         // Test span_to_str for a span ending at the end of filemap
1394         let cm = init_code_map();
1395         let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1396         let sstr =  cm.span_to_string(span);
1397
1398         assert_eq!(sstr, "blork.rs:2:1: 2:12");
1399     }
1400
1401     #[test]
1402     fn t10() {
1403         // Test span_to_expanded_string works in base case (no expansion)
1404         let cm = init_code_map();
1405         let span = Span { lo: BytePos(0), hi: BytePos(11), expn_id: NO_EXPANSION };
1406         let sstr = cm.span_to_expanded_string(span);
1407         assert_eq!(sstr, "blork.rs:1:1: 1:12\n`first line.`\n");
1408
1409         let span = Span { lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION };
1410         let sstr =  cm.span_to_expanded_string(span);
1411         assert_eq!(sstr, "blork.rs:2:1: 2:12\n`second line`\n");
1412     }
1413
1414     #[test]
1415     fn t11() {
1416         // Test span_to_expanded_string works with expansion
1417         use ast::Name;
1418         let cm = init_code_map();
1419         let root = Span { lo: BytePos(0), hi: BytePos(11), expn_id: NO_EXPANSION };
1420         let format = ExpnFormat::MacroBang(Name(0u32));
1421         let callee = NameAndSpan { format: format,
1422                                    allow_internal_unstable: false,
1423                                    span: None };
1424
1425         let info = ExpnInfo { call_site: root, callee: callee };
1426         let id = cm.record_expansion(info);
1427         let sp = Span { lo: BytePos(12), hi: BytePos(23), expn_id: id };
1428
1429         let sstr = cm.span_to_expanded_string(sp);
1430         assert_eq!(sstr,
1431                    "blork.rs:2:1: 2:12\n`second line`\n  Callsite:\n  \
1432                     blork.rs:1:1: 1:12\n  `first line.`\n");
1433     }
1434
1435     fn init_expansion_chain(cm: &CodeMap) -> Span {
1436         // Creates an expansion chain containing two recursive calls
1437         // root -> expA -> expA -> expB -> expB -> end
1438         use ast::Name;
1439
1440         let root = Span { lo: BytePos(0), hi: BytePos(11), expn_id: NO_EXPANSION };
1441
1442         let format_root = ExpnFormat::MacroBang(Name(0u32));
1443         let callee_root = NameAndSpan { format: format_root,
1444                                         allow_internal_unstable: false,
1445                                         span: Some(root) };
1446
1447         let info_a1 = ExpnInfo { call_site: root, callee: callee_root };
1448         let id_a1 = cm.record_expansion(info_a1);
1449         let span_a1 = Span { lo: BytePos(12), hi: BytePos(23), expn_id: id_a1 };
1450
1451         let format_a = ExpnFormat::MacroBang(Name(1u32));
1452         let callee_a = NameAndSpan { format: format_a,
1453                                       allow_internal_unstable: false,
1454                                       span: Some(span_a1) };
1455
1456         let info_a2 = ExpnInfo { call_site: span_a1, callee: callee_a.clone() };
1457         let id_a2 = cm.record_expansion(info_a2);
1458         let span_a2 = Span { lo: BytePos(12), hi: BytePos(23), expn_id: id_a2 };
1459
1460         let info_b1 = ExpnInfo { call_site: span_a2, callee: callee_a };
1461         let id_b1 = cm.record_expansion(info_b1);
1462         let span_b1 = Span { lo: BytePos(25), hi: BytePos(36), expn_id: id_b1 };
1463
1464         let format_b = ExpnFormat::MacroBang(Name(2u32));
1465         let callee_b = NameAndSpan { format: format_b,
1466                                      allow_internal_unstable: false,
1467                                      span: None };
1468
1469         let info_b2 = ExpnInfo { call_site: span_b1, callee: callee_b.clone() };
1470         let id_b2 = cm.record_expansion(info_b2);
1471         let span_b2 = Span { lo: BytePos(25), hi: BytePos(36), expn_id: id_b2 };
1472
1473         let info_end = ExpnInfo { call_site: span_b2, callee: callee_b };
1474         let id_end = cm.record_expansion(info_end);
1475         Span { lo: BytePos(37), hi: BytePos(48), expn_id: id_end }
1476     }
1477
1478     #[test]
1479     fn t12() {
1480         // Test span_to_expanded_string collapses recursive macros and handles
1481         // recursive callsite and callee expansions
1482         let cm = init_code_map();
1483         let end = init_expansion_chain(&cm);
1484         let sstr = cm.span_to_expanded_string(end);
1485         let res_str =
1486 r"blork2.rs:2:1: 2:12
1487 `second line`
1488   Callsite:
1489   ...
1490   blork2.rs:1:1: 1:12
1491   `first line.`
1492     Callee:
1493     blork.rs:2:1: 2:12
1494     `second line`
1495       Callee:
1496       blork.rs:1:1: 1:12
1497       `first line.`
1498       Callsite:
1499       blork.rs:1:1: 1:12
1500       `first line.`
1501     Callsite:
1502     ...
1503     blork.rs:2:1: 2:12
1504     `second line`
1505       Callee:
1506       blork.rs:1:1: 1:12
1507       `first line.`
1508       Callsite:
1509       blork.rs:1:1: 1:12
1510       `first line.`
1511 ";
1512         assert_eq!(sstr, res_str);
1513     }
1514 }