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