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