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