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.
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.
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.
20 pub use self::ExpnFormat::*;
22 use std::cell::{Cell, RefCell};
23 use std::ops::{Add, Sub};
28 use std::io::{self, Read};
30 use serialize::{Encodable, Decodable, Encoder, Decoder};
33 // _____________________________________________________________________________
34 // Pos, BytePos, CharPos
38 fn from_usize(n: usize) -> Self;
39 fn to_usize(&self) -> usize;
42 /// A byte offset. Keep this small (currently 32-bits), as AST contains
44 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Debug)]
45 pub struct BytePos(pub u32);
47 /// A character offset. Because of multibyte utf8 characters, a byte offset
48 /// is not equivalent to a character offset. The CodeMap will convert BytePos
49 /// values to CharPos values as necessary.
50 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Debug)]
51 pub struct CharPos(pub usize);
53 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
54 // have been unsuccessful
56 impl Pos for BytePos {
57 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
58 fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
61 impl Add for BytePos {
62 type Output = BytePos;
64 fn add(self, rhs: BytePos) -> BytePos {
65 BytePos((self.to_usize() + rhs.to_usize()) as u32)
69 impl Sub for BytePos {
70 type Output = BytePos;
72 fn sub(self, rhs: BytePos) -> BytePos {
73 BytePos((self.to_usize() - rhs.to_usize()) as u32)
77 impl Encodable for BytePos {
78 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
83 impl Decodable for BytePos {
84 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
85 Ok(BytePos(try!{ d.read_u32() }))
89 impl Pos for CharPos {
90 fn from_usize(n: usize) -> CharPos { CharPos(n) }
91 fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
94 impl Add for CharPos {
95 type Output = CharPos;
97 fn add(self, rhs: CharPos) -> CharPos {
98 CharPos(self.to_usize() + rhs.to_usize())
102 impl Sub for CharPos {
103 type Output = CharPos;
105 fn sub(self, rhs: CharPos) -> CharPos {
106 CharPos(self.to_usize() - rhs.to_usize())
110 // _____________________________________________________________________________
114 /// Spans represent a region of code, used for error reporting. Positions in spans
115 /// are *absolute* positions from the beginning of the codemap, not positions
116 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
117 /// to the original source.
118 /// You must be careful if the span crosses more than one file - you will not be
119 /// able to use many of the functions on spans in codemap and you cannot assume
120 /// that the length of the span = hi - lo; there may be space in the BytePos
121 /// range between files.
122 #[derive(Clone, Copy, Hash)]
126 /// Information about where the macro came from, if this piece of
127 /// code was created by a macro expansion.
131 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
133 // Generic span to be used for code originating from the command line
134 pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0),
136 expn_id: COMMAND_LINE_EXPN };
138 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
139 pub struct Spanned<T> {
144 impl PartialEq for Span {
145 fn eq(&self, other: &Span) -> bool {
146 return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
148 fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
153 impl Encodable for Span {
154 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
155 // Encode spans as a single u64 in order to cut down on tagging overhead
156 // added by the RBML metadata encoding. The should be solved differently
157 // altogether some time (FIXME #21482)
158 s.emit_u64( (self.lo.0 as u64) | ((self.hi.0 as u64) << 32) )
162 impl Decodable for Span {
163 fn decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
164 let lo_hi: u64 = try! { d.read_u64() };
165 let lo = BytePos(lo_hi as u32);
166 let hi = BytePos((lo_hi >> 32) as u32);
171 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
172 write!(f, "Span {{ lo: {:?}, hi: {:?}, expn_id: {:?} }}",
173 span.lo, span.hi, span.expn_id)
176 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
177 Cell::new(default_span_debug));
179 impl fmt::Debug for Span {
180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
181 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
185 pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
186 respan(mk_sp(lo, hi), t)
189 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
190 Spanned {node: t, span: sp}
193 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
197 /* assuming that we're not in macro expansion */
198 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
199 Span {lo: lo, hi: hi, expn_id: NO_EXPANSION}
202 /// Return the span itself if it doesn't come from a macro expansion,
203 /// otherwise return the call site span up to the `enclosing_sp` by
204 /// following the `expn_info` chain.
205 pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span {
206 let call_site1 = cm.with_expn_info(sp.expn_id, |ei| ei.map(|ei| ei.call_site));
207 let call_site2 = cm.with_expn_info(enclosing_sp.expn_id, |ei| ei.map(|ei| ei.call_site));
208 match (call_site1, call_site2) {
210 (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
211 (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp),
215 // _____________________________________________________________________________
216 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
219 /// A source code location used for error reporting
222 /// Information about the original source
223 pub file: Rc<FileMap>,
224 /// The (1-based) line number
226 /// The (0-based) column offset
230 /// A source code location used as the result of lookup_char_pos_adj
231 // Actually, *none* of the clients use the filename *or* file field;
232 // perhaps they should just be removed.
234 pub struct LocWithOpt {
235 pub filename: FileName,
238 pub file: Option<Rc<FileMap>>,
241 // used to be structural records. Better names, anyone?
243 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
245 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
248 // _____________________________________________________________________________
249 // ExpnFormat, NameAndSpan, ExpnInfo, ExpnId
252 /// The source of expansion.
253 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
254 pub enum ExpnFormat {
255 /// e.g. #[derive(...)] <item>
259 /// Syntax sugar expansion performed by the compiler (libsyntax::expand).
263 #[derive(Clone, Hash, Debug)]
264 pub struct NameAndSpan {
265 /// The name of the macro that was invoked to create the thing
268 /// The format with which the macro was invoked.
269 pub format: ExpnFormat,
270 /// Whether the macro is allowed to use #[unstable]/feature-gated
271 /// features internally without forcing the whole crate to opt-in
273 pub allow_internal_unstable: bool,
274 /// The span of the macro definition itself. The macro may not
275 /// have a sensible definition span (e.g. something defined
276 /// completely inside libsyntax) in which case this is None.
277 pub span: Option<Span>
280 /// Extra information for tracking spans of macro and syntax sugar expansion
281 #[derive(Hash, Debug)]
282 pub struct ExpnInfo {
283 /// The location of the actual macro invocation or syntax sugar , e.g.
284 /// `let x = foo!();` or `if let Some(y) = x {}`
286 /// This may recursively refer to other macro invocations, e.g. if
287 /// `foo!()` invoked `bar!()` internally, and there was an
288 /// expression inside `bar!`; the call_site of the expression in
289 /// the expansion would point to the `bar!` invocation; that
290 /// call_site span would have its own ExpnInfo, with the call_site
291 /// pointing to the `foo!` invocation.
293 /// Information about the expansion.
294 pub callee: NameAndSpan
297 #[derive(PartialEq, Eq, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Copy)]
298 pub struct ExpnId(u32);
300 pub const NO_EXPANSION: ExpnId = ExpnId(!0);
301 // For code appearing from the command line
302 pub const COMMAND_LINE_EXPN: ExpnId = ExpnId(!1);
305 pub fn from_u32(id: u32) -> ExpnId {
309 pub fn into_u32(self) -> u32 {
314 // _____________________________________________________________________________
315 // FileMap, MultiByteChar, FileName, FileLines
318 pub type FileName = String;
320 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
321 pub struct LineInfo {
322 /// Index of line, starting from 0.
323 pub line_index: usize,
325 /// Column in line where span begins, starting from 0.
326 pub start_col: CharPos,
328 /// Column in line where span ends, starting from 0, exclusive.
329 pub end_col: CharPos,
332 pub struct FileLines {
333 pub file: Rc<FileMap>,
334 pub lines: Vec<LineInfo>
337 /// Identifies an offset of a multi-byte character in a FileMap
338 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
339 pub struct MultiByteChar {
340 /// The absolute offset of the character in the CodeMap
342 /// The number of bytes, >=2
346 /// A single source in the CodeMap.
348 /// The name of the file that the source came from, source that doesn't
349 /// originate from files has names between angle brackets by convention,
352 /// The complete source code
353 pub src: Option<Rc<String>>,
354 /// The start position of this source in the CodeMap
355 pub start_pos: BytePos,
356 /// The end position of this source in the CodeMap
357 pub end_pos: BytePos,
358 /// Locations of lines beginnings in the source code
359 pub lines: RefCell<Vec<BytePos>>,
360 /// Locations of multi-byte characters in the source code
361 pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
364 impl Encodable for FileMap {
365 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
366 s.emit_struct("FileMap", 5, |s| {
367 try! { s.emit_struct_field("name", 0, |s| self.name.encode(s)) };
368 try! { s.emit_struct_field("start_pos", 1, |s| self.start_pos.encode(s)) };
369 try! { s.emit_struct_field("end_pos", 2, |s| self.end_pos.encode(s)) };
370 try! { s.emit_struct_field("lines", 3, |s| {
371 let lines = self.lines.borrow();
373 try! { s.emit_u32(lines.len() as u32) };
375 if !lines.is_empty() {
376 // In order to preserve some space, we exploit the fact that
377 // the lines list is sorted and individual lines are
378 // probably not that long. Because of that we can store lines
379 // as a difference list, using as little space as possible
380 // for the differences.
381 let max_line_length = if lines.len() == 1 {
385 .map(|w| w[1] - w[0])
386 .map(|bp| bp.to_usize())
391 let bytes_per_diff: u8 = match max_line_length {
393 0x100 ... 0xFFFF => 2,
397 // Encode the number of bytes used per diff.
398 try! { bytes_per_diff.encode(s) };
400 // Encode the first element.
401 try! { lines[0].encode(s) };
403 let diff_iter = (&lines[..]).windows(2)
404 .map(|w| (w[1] - w[0]));
406 match bytes_per_diff {
407 1 => for diff in diff_iter { try! { (diff.0 as u8).encode(s) } },
408 2 => for diff in diff_iter { try! { (diff.0 as u16).encode(s) } },
409 4 => for diff in diff_iter { try! { diff.0.encode(s) } },
417 s.emit_struct_field("multibyte_chars", 4, |s| {
418 (*self.multibyte_chars.borrow()).encode(s)
424 impl Decodable for FileMap {
425 fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
427 d.read_struct("FileMap", 5, |d| {
428 let name: String = try! {
429 d.read_struct_field("name", 0, |d| Decodable::decode(d))
431 let start_pos: BytePos = try! {
432 d.read_struct_field("start_pos", 1, |d| Decodable::decode(d))
434 let end_pos: BytePos = try! {
435 d.read_struct_field("end_pos", 2, |d| Decodable::decode(d))
437 let lines: Vec<BytePos> = try! {
438 d.read_struct_field("lines", 3, |d| {
439 let num_lines: u32 = try! { Decodable::decode(d) };
440 let mut lines = Vec::with_capacity(num_lines as usize);
443 // Read the number of bytes used per diff.
444 let bytes_per_diff: u8 = try! { Decodable::decode(d) };
446 // Read the first element.
447 let mut line_start: BytePos = try! { Decodable::decode(d) };
448 lines.push(line_start);
450 for _ in 1..num_lines {
451 let diff = match bytes_per_diff {
452 1 => try! { d.read_u8() } as u32,
453 2 => try! { d.read_u16() } as u32,
454 4 => try! { d.read_u32() },
458 line_start = line_start + BytePos(diff);
460 lines.push(line_start);
467 let multibyte_chars: Vec<MultiByteChar> = try! {
468 d.read_struct_field("multibyte_chars", 4, |d| Decodable::decode(d))
472 start_pos: start_pos,
475 lines: RefCell::new(lines),
476 multibyte_chars: RefCell::new(multibyte_chars)
482 impl fmt::Debug for FileMap {
483 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
484 write!(fmt, "FileMap({})", self.name)
489 /// EFFECT: register a start-of-line offset in the
490 /// table of line-beginnings.
491 /// UNCHECKED INVARIANT: these offsets must be added in the right
492 /// order and must be in the right places; there is shared knowledge
493 /// about what ends a line between this file and parse.rs
494 /// WARNING: pos param here is the offset relative to start of CodeMap,
495 /// and CodeMap will append a newline when adding a filemap without a newline at the end,
496 /// so the safe way to call this is with value calculated as
497 /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
498 pub fn next_line(&self, pos: BytePos) {
499 // the new charpos must be > the last one (or it's the first one).
500 let mut lines = self.lines.borrow_mut();
501 let line_len = lines.len();
502 assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
506 /// get a line from the list of pre-computed line-beginnings.
507 /// line-number here is 0-based.
508 pub fn get_line(&self, line_number: usize) -> Option<&str> {
511 let lines = self.lines.borrow();
512 lines.get(line_number).map(|&line| {
513 let begin: BytePos = line - self.start_pos;
514 let begin = begin.to_usize();
515 // We can't use `lines.get(line_number+1)` because we might
516 // be parsing when we call this function and thus the current
517 // line is the last one we have line info for.
518 let slice = &src[begin..];
519 match slice.find('\n') {
520 Some(e) => &slice[..e],
529 pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
530 assert!(bytes >=2 && bytes <= 4);
531 let mbc = MultiByteChar {
535 self.multibyte_chars.borrow_mut().push(mbc);
538 pub fn is_real_file(&self) -> bool {
539 !(self.name.starts_with("<") &&
540 self.name.ends_with(">"))
543 pub fn is_imported(&self) -> bool {
548 /// An abstraction over the fs operations used by the Parser.
549 pub trait FileLoader {
550 /// Query the existence of a file.
551 fn file_exists(&self, path: &Path) -> bool;
553 /// Read the contents of an UTF-8 file into memory.
554 fn read_file(&self, path: &Path) -> io::Result<String>;
557 /// A FileLoader that uses std::fs to load real files.
558 pub struct RealFileLoader;
560 impl FileLoader for RealFileLoader {
561 fn file_exists(&self, path: &Path) -> bool {
562 fs::metadata(path).is_ok()
565 fn read_file(&self, path: &Path) -> io::Result<String> {
566 let mut src = String::new();
567 try!(try!(fs::File::open(path)).read_to_string(&mut src));
572 // _____________________________________________________________________________
577 pub files: RefCell<Vec<Rc<FileMap>>>,
578 expansions: RefCell<Vec<ExpnInfo>>,
579 file_loader: Box<FileLoader>
583 pub fn new() -> CodeMap {
585 files: RefCell::new(Vec::new()),
586 expansions: RefCell::new(Vec::new()),
587 file_loader: Box::new(RealFileLoader)
591 pub fn with_file_loader(file_loader: Box<FileLoader>) -> CodeMap {
593 files: RefCell::new(Vec::new()),
594 expansions: RefCell::new(Vec::new()),
595 file_loader: file_loader
599 pub fn file_exists(&self, path: &Path) -> bool {
600 self.file_loader.file_exists(path)
603 pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> {
604 let src = try!(self.file_loader.read_file(path));
605 Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
608 fn next_start_pos(&self) -> usize {
609 let files = self.files.borrow();
612 // Add one so there is some space between files. This lets us distinguish
613 // positions in the codemap, even in the presence of zero-length files.
614 Some(last) => last.end_pos.to_usize() + 1,
618 /// Creates a new filemap without setting its line information. If you don't
619 /// intend to set the line information yourself, you should use new_filemap_and_lines.
620 pub fn new_filemap(&self, filename: FileName, mut src: String) -> Rc<FileMap> {
621 let start_pos = self.next_start_pos();
622 let mut files = self.files.borrow_mut();
624 // Remove utf-8 BOM if any.
625 if src.starts_with("\u{feff}") {
629 let end_pos = start_pos + src.len();
631 let filemap = Rc::new(FileMap {
633 src: Some(Rc::new(src)),
634 start_pos: Pos::from_usize(start_pos),
635 end_pos: Pos::from_usize(end_pos),
636 lines: RefCell::new(Vec::new()),
637 multibyte_chars: RefCell::new(Vec::new()),
640 files.push(filemap.clone());
645 /// Creates a new filemap and sets its line information.
646 pub fn new_filemap_and_lines(&self, filename: &str, src: &str) -> Rc<FileMap> {
647 let fm = self.new_filemap(filename.to_string(), src.to_owned());
648 let mut byte_pos: u32 = 0;
649 for line in src.lines() {
650 // register the start of this line
651 fm.next_line(BytePos(byte_pos));
653 // update byte_pos to include this line and the \n at the end
654 byte_pos += line.len() as u32 + 1;
660 /// Allocates a new FileMap representing a source file from an external
661 /// crate. The source code of such an "imported filemap" is not available,
662 /// but we still know enough to generate accurate debuginfo location
663 /// information for things inlined from other crates.
664 pub fn new_imported_filemap(&self,
667 mut file_local_lines: Vec<BytePos>,
668 mut file_local_multibyte_chars: Vec<MultiByteChar>)
670 let start_pos = self.next_start_pos();
671 let mut files = self.files.borrow_mut();
673 let end_pos = Pos::from_usize(start_pos + source_len);
674 let start_pos = Pos::from_usize(start_pos);
676 for pos in &mut file_local_lines {
677 *pos = *pos + start_pos;
680 for mbc in &mut file_local_multibyte_chars {
681 mbc.pos = mbc.pos + start_pos;
684 let filemap = Rc::new(FileMap {
687 start_pos: start_pos,
689 lines: RefCell::new(file_local_lines),
690 multibyte_chars: RefCell::new(file_local_multibyte_chars),
693 files.push(filemap.clone());
698 pub fn mk_substr_filename(&self, sp: Span) -> String {
699 let pos = self.lookup_char_pos(sp.lo);
700 (format!("<{}:{}:{}>",
703 pos.col.to_usize() + 1)).to_string()
706 /// Lookup source information about a BytePos
707 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
708 let chpos = self.bytepos_to_file_charpos(pos);
709 match self.lookup_line(pos) {
710 Ok(FileMapAndLine { fm: f, line: a }) => {
711 let line = a + 1; // Line numbers start at 1
712 let linebpos = (*f.lines.borrow())[a];
713 let linechpos = self.bytepos_to_file_charpos(linebpos);
714 debug!("byte pos {:?} is on the line at byte pos {:?}",
716 debug!("char pos {:?} is on the line at char pos {:?}",
718 debug!("byte is on line: {}", line);
719 assert!(chpos >= linechpos);
723 col: chpos - linechpos,
736 // If the relevant filemap is empty, we don't return a line number.
737 fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> {
738 let idx = self.lookup_filemap_idx(pos);
740 let files = self.files.borrow();
741 let f = (*files)[idx].clone();
743 let len = f.lines.borrow().len();
750 let lines = f.lines.borrow();
751 let mut b = lines.len();
754 if (*lines)[m] > pos {
760 assert!(a <= lines.len());
762 Ok(FileMapAndLine { fm: f, line: a })
765 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
766 let loc = self.lookup_char_pos(pos);
768 filename: loc.file.name.to_string(),
775 pub fn span_to_string(&self, sp: Span) -> String {
776 if self.files.borrow().is_empty() && sp == DUMMY_SP {
777 return "no-location".to_string();
780 let lo = self.lookup_char_pos_adj(sp.lo);
781 let hi = self.lookup_char_pos_adj(sp.hi);
782 return (format!("{}:{}:{}: {}:{}",
785 lo.col.to_usize() + 1,
787 hi.col.to_usize() + 1)).to_string()
790 pub fn span_to_filename(&self, sp: Span) -> FileName {
791 self.lookup_char_pos(sp.lo).file.name.to_string()
794 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
796 return Err(SpanLinesError::IllFormedSpan(sp));
799 let lo = self.lookup_char_pos(sp.lo);
800 let hi = self.lookup_char_pos(sp.hi);
802 if lo.file.start_pos != hi.file.start_pos {
803 return Err(SpanLinesError::DistinctSources(DistinctSources {
804 begin: (lo.file.name.clone(), lo.file.start_pos),
805 end: (hi.file.name.clone(), hi.file.start_pos),
808 assert!(hi.line >= lo.line);
810 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
812 // The span starts partway through the first line,
813 // but after that it starts from offset 0.
814 let mut start_col = lo.col;
816 // For every line but the last, it extends from `start_col`
817 // and to the end of the line. Be careful because the line
818 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
820 for line_index in lo.line-1 .. hi.line-1 {
821 let line_len = lo.file.get_line(line_index).map(|s| s.len()).unwrap_or(0);
822 lines.push(LineInfo { line_index: line_index,
823 start_col: start_col,
824 end_col: CharPos::from_usize(line_len) });
825 start_col = CharPos::from_usize(0);
828 // For the last line, it extends from `start_col` to `hi.col`:
829 lines.push(LineInfo { line_index: hi.line - 1,
830 start_col: start_col,
833 Ok(FileLines {file: lo.file, lines: lines})
836 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
838 return Err(SpanSnippetError::IllFormedSpan(sp));
841 let local_begin = self.lookup_byte_offset(sp.lo);
842 let local_end = self.lookup_byte_offset(sp.hi);
844 if local_begin.fm.start_pos != local_end.fm.start_pos {
845 return Err(SpanSnippetError::DistinctSources(DistinctSources {
846 begin: (local_begin.fm.name.clone(),
847 local_begin.fm.start_pos),
848 end: (local_end.fm.name.clone(),
849 local_end.fm.start_pos)
852 match local_begin.fm.src {
854 let start_index = local_begin.pos.to_usize();
855 let end_index = local_end.pos.to_usize();
856 let source_len = (local_begin.fm.end_pos -
857 local_begin.fm.start_pos).to_usize();
859 if start_index > end_index || end_index > source_len {
860 return Err(SpanSnippetError::MalformedForCodemap(
861 MalformedCodemapPositions {
862 name: local_begin.fm.name.clone(),
863 source_len: source_len,
864 begin_pos: local_begin.pos,
865 end_pos: local_end.pos,
869 return Ok((&src[start_index..end_index]).to_string())
872 return Err(SpanSnippetError::SourceNotAvailable {
873 filename: local_begin.fm.name.clone()
880 pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> {
881 for fm in self.files.borrow().iter() {
882 if filename == fm.name {
886 panic!("asking for {} which we don't know about", filename);
889 /// For a global BytePos compute the local offset within the containing FileMap
890 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
891 let idx = self.lookup_filemap_idx(bpos);
892 let fm = (*self.files.borrow())[idx].clone();
893 let offset = bpos - fm.start_pos;
894 FileMapAndBytePos {fm: fm, pos: offset}
897 /// Converts an absolute BytePos to a CharPos relative to the filemap and above.
898 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
899 let idx = self.lookup_filemap_idx(bpos);
900 let files = self.files.borrow();
901 let map = &(*files)[idx];
903 // The number of extra bytes due to multibyte chars in the FileMap
904 let mut total_extra_bytes = 0;
906 for mbc in map.multibyte_chars.borrow().iter() {
907 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
909 // every character is at least one byte, so we only
910 // count the actual extra bytes.
911 total_extra_bytes += mbc.bytes - 1;
912 // We should never see a byte position in the middle of a
914 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
920 assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
921 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
924 // Return the index of the filemap (in self.files) which contains pos.
925 fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
926 let files = self.files.borrow();
928 let count = files.len();
930 // Binary search for the filemap.
935 if files[m].start_pos > pos {
942 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
947 pub fn record_expansion(&self, expn_info: ExpnInfo) -> ExpnId {
948 let mut expansions = self.expansions.borrow_mut();
949 expansions.push(expn_info);
950 let len = expansions.len();
951 if len > u32::max_value() as usize {
952 panic!("too many ExpnInfo's!");
954 ExpnId(len as u32 - 1)
957 pub fn with_expn_info<T, F>(&self, id: ExpnId, f: F) -> T where
958 F: FnOnce(Option<&ExpnInfo>) -> T,
961 NO_EXPANSION | COMMAND_LINE_EXPN => f(None),
962 ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as usize]))
966 /// Check if a span is "internal" to a macro in which #[unstable]
967 /// items can be used (that is, a macro marked with
968 /// `#[allow_internal_unstable]`).
969 pub fn span_allows_unstable(&self, span: Span) -> bool {
970 debug!("span_allows_unstable(span = {:?})", span);
971 let mut allows_unstable = false;
972 let mut expn_id = span.expn_id;
974 let quit = self.with_expn_info(expn_id, |expninfo| {
975 debug!("span_allows_unstable: expninfo = {:?}", expninfo);
976 expninfo.map_or(/* hit the top level */ true, |info| {
978 let span_comes_from_this_expansion =
979 info.callee.span.map_or(span == info.call_site, |mac_span| {
980 mac_span.lo <= span.lo && span.hi <= mac_span.hi
983 debug!("span_allows_unstable: from this expansion? {}, allows unstable? {}",
984 span_comes_from_this_expansion,
985 info.callee.allow_internal_unstable);
986 if span_comes_from_this_expansion {
987 allows_unstable = info.callee.allow_internal_unstable;
988 // we've found the right place, stop looking
991 // not the right place, keep looking
992 expn_id = info.call_site.expn_id;
1001 debug!("span_allows_unstable? {}", allows_unstable);
1006 // _____________________________________________________________________________
1007 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
1010 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1012 #[derive(Clone, PartialEq, Eq, Debug)]
1013 pub enum SpanLinesError {
1014 IllFormedSpan(Span),
1015 DistinctSources(DistinctSources),
1018 #[derive(Clone, PartialEq, Eq, Debug)]
1019 pub enum SpanSnippetError {
1020 IllFormedSpan(Span),
1021 DistinctSources(DistinctSources),
1022 MalformedForCodemap(MalformedCodemapPositions),
1023 SourceNotAvailable { filename: String }
1026 #[derive(Clone, PartialEq, Eq, Debug)]
1027 pub struct DistinctSources {
1028 begin: (String, BytePos),
1029 end: (String, BytePos)
1032 #[derive(Clone, PartialEq, Eq, Debug)]
1033 pub struct MalformedCodemapPositions {
1041 // _____________________________________________________________________________
1052 let cm = CodeMap::new();
1053 let fm = cm.new_filemap("blork.rs".to_string(),
1054 "first line.\nsecond line".to_string());
1055 fm.next_line(BytePos(0));
1056 // Test we can get lines with partial line info.
1057 assert_eq!(fm.get_line(0), Some("first line."));
1058 // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
1059 fm.next_line(BytePos(10));
1060 assert_eq!(fm.get_line(1), Some("."));
1061 fm.next_line(BytePos(12));
1062 assert_eq!(fm.get_line(2), Some("second line"));
1068 let cm = CodeMap::new();
1069 let fm = cm.new_filemap("blork.rs".to_string(),
1070 "first line.\nsecond line".to_string());
1071 // TESTING *REALLY* BROKEN BEHAVIOR:
1072 fm.next_line(BytePos(0));
1073 fm.next_line(BytePos(10));
1074 fm.next_line(BytePos(2));
1077 fn init_code_map() -> CodeMap {
1078 let cm = CodeMap::new();
1079 let fm1 = cm.new_filemap("blork.rs".to_string(),
1080 "first line.\nsecond line".to_string());
1081 let fm2 = cm.new_filemap("empty.rs".to_string(),
1083 let fm3 = cm.new_filemap("blork2.rs".to_string(),
1084 "first line.\nsecond line".to_string());
1086 fm1.next_line(BytePos(0));
1087 fm1.next_line(BytePos(12));
1088 fm2.next_line(fm2.start_pos);
1089 fm3.next_line(fm3.start_pos);
1090 fm3.next_line(fm3.start_pos + BytePos(12));
1097 // Test lookup_byte_offset
1098 let cm = init_code_map();
1100 let fmabp1 = cm.lookup_byte_offset(BytePos(23));
1101 assert_eq!(fmabp1.fm.name, "blork.rs");
1102 assert_eq!(fmabp1.pos, BytePos(23));
1104 let fmabp1 = cm.lookup_byte_offset(BytePos(24));
1105 assert_eq!(fmabp1.fm.name, "empty.rs");
1106 assert_eq!(fmabp1.pos, BytePos(0));
1108 let fmabp2 = cm.lookup_byte_offset(BytePos(25));
1109 assert_eq!(fmabp2.fm.name, "blork2.rs");
1110 assert_eq!(fmabp2.pos, BytePos(0));
1115 // Test bytepos_to_file_charpos
1116 let cm = init_code_map();
1118 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
1119 assert_eq!(cp1, CharPos(22));
1121 let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
1122 assert_eq!(cp2, CharPos(0));
1127 // Test zero-length filemaps.
1128 let cm = init_code_map();
1130 let loc1 = cm.lookup_char_pos(BytePos(22));
1131 assert_eq!(loc1.file.name, "blork.rs");
1132 assert_eq!(loc1.line, 2);
1133 assert_eq!(loc1.col, CharPos(10));
1135 let loc2 = cm.lookup_char_pos(BytePos(25));
1136 assert_eq!(loc2.file.name, "blork2.rs");
1137 assert_eq!(loc2.line, 1);
1138 assert_eq!(loc2.col, CharPos(0));
1141 fn init_code_map_mbc() -> CodeMap {
1142 let cm = CodeMap::new();
1143 // € is a three byte utf8 char.
1145 cm.new_filemap("blork.rs".to_string(),
1146 "fir€st €€€€ line.\nsecond line".to_string());
1147 let fm2 = cm.new_filemap("blork2.rs".to_string(),
1148 "first line€€.\n€ second line".to_string());
1150 fm1.next_line(BytePos(0));
1151 fm1.next_line(BytePos(28));
1152 fm2.next_line(fm2.start_pos);
1153 fm2.next_line(fm2.start_pos + BytePos(20));
1155 fm1.record_multibyte_char(BytePos(3), 3);
1156 fm1.record_multibyte_char(BytePos(9), 3);
1157 fm1.record_multibyte_char(BytePos(12), 3);
1158 fm1.record_multibyte_char(BytePos(15), 3);
1159 fm1.record_multibyte_char(BytePos(18), 3);
1160 fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
1161 fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
1162 fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
1169 // Test bytepos_to_file_charpos in the presence of multi-byte chars
1170 let cm = init_code_map_mbc();
1172 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
1173 assert_eq!(cp1, CharPos(3));
1175 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
1176 assert_eq!(cp2, CharPos(4));
1178 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
1179 assert_eq!(cp3, CharPos(12));
1181 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
1182 assert_eq!(cp4, CharPos(15));
1187 // Test span_to_lines for a span ending at the end of filemap
1188 let cm = init_code_map();
1189 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1190 let file_lines = cm.span_to_lines(span).unwrap();
1192 assert_eq!(file_lines.file.name, "blork.rs");
1193 assert_eq!(file_lines.lines.len(), 1);
1194 assert_eq!(file_lines.lines[0].line_index, 1);
1197 /// Given a string like " ^~~~~~~~~~~~ ", produces a span
1198 /// coverting that range. The idea is that the string has the same
1199 /// length as the input, and we uncover the byte positions. Note
1200 /// that this can span lines and so on.
1201 fn span_from_selection(input: &str, selection: &str) -> Span {
1202 assert_eq!(input.len(), selection.len());
1203 let left_index = selection.find('^').unwrap() as u32;
1204 let right_index = selection.rfind('~').unwrap() as u32;
1205 Span { lo: BytePos(left_index), hi: BytePos(right_index + 1), expn_id: NO_EXPANSION }
1208 /// Test span_to_snippet and span_to_lines for a span coverting 3
1209 /// lines in the middle of a file.
1211 fn span_to_snippet_and_lines_spanning_multiple_lines() {
1212 let cm = CodeMap::new();
1213 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1214 let selection = " \n ^~\n~~~\n~~~~~ \n \n";
1215 cm.new_filemap_and_lines("blork.rs", inputtext);
1216 let span = span_from_selection(inputtext, selection);
1218 // check that we are extracting the text we thought we were extracting
1219 assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1221 // check that span_to_lines gives us the complete result with the lines/cols we expected
1222 let lines = cm.span_to_lines(span).unwrap();
1223 let expected = vec![
1224 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1225 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1226 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1228 assert_eq!(lines.lines, expected);
1233 // Test span_to_snippet for a span ending at the end of filemap
1234 let cm = init_code_map();
1235 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1236 let snippet = cm.span_to_snippet(span);
1238 assert_eq!(snippet, Ok("second line".to_string()));
1243 // Test span_to_str for a span ending at the end of filemap
1244 let cm = init_code_map();
1245 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1246 let sstr = cm.span_to_string(span);
1248 assert_eq!(sstr, "blork.rs:2:1: 2:12");