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