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