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