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