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};
32 use parse::token::intern;
35 // _____________________________________________________________________________
36 // Pos, BytePos, CharPos
40 fn from_usize(n: usize) -> Self;
41 fn to_usize(&self) -> usize;
44 /// A byte offset. Keep this small (currently 32-bits), as AST contains
46 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Debug)]
47 pub struct BytePos(pub u32);
49 /// A character offset. Because of multibyte utf8 characters, a byte offset
50 /// is not equivalent to a character offset. The CodeMap will convert BytePos
51 /// values to CharPos values as necessary.
52 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Debug)]
53 pub struct CharPos(pub usize);
55 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
56 // have been unsuccessful
58 impl Pos for BytePos {
59 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
60 fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
63 impl Add for BytePos {
64 type Output = BytePos;
66 fn add(self, rhs: BytePos) -> BytePos {
67 BytePos((self.to_usize() + rhs.to_usize()) as u32)
71 impl Sub for BytePos {
72 type Output = BytePos;
74 fn sub(self, rhs: BytePos) -> BytePos {
75 BytePos((self.to_usize() - rhs.to_usize()) as u32)
79 impl Encodable for BytePos {
80 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
85 impl Decodable for BytePos {
86 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
87 Ok(BytePos(try!{ d.read_u32() }))
91 impl Pos for CharPos {
92 fn from_usize(n: usize) -> CharPos { CharPos(n) }
93 fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
96 impl Add for CharPos {
97 type Output = CharPos;
99 fn add(self, rhs: CharPos) -> CharPos {
100 CharPos(self.to_usize() + rhs.to_usize())
104 impl Sub for CharPos {
105 type Output = CharPos;
107 fn sub(self, rhs: CharPos) -> CharPos {
108 CharPos(self.to_usize() - rhs.to_usize())
112 // _____________________________________________________________________________
116 /// Spans represent a region of code, used for error reporting. Positions in spans
117 /// are *absolute* positions from the beginning of the codemap, not positions
118 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
119 /// to the original source.
120 /// You must be careful if the span crosses more than one file - you will not be
121 /// able to use many of the functions on spans in codemap and you cannot assume
122 /// that the length of the span = hi - lo; there may be space in the BytePos
123 /// range between files.
124 #[derive(Clone, Copy, Hash)]
128 /// Information about where the macro came from, if this piece of
129 /// code was created by a macro expansion.
133 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
135 // Generic span to be used for code originating from the command line
136 pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0),
138 expn_id: COMMAND_LINE_EXPN };
141 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
142 pub fn substitute_dummy(self, other: Span) -> Span {
143 if self == DUMMY_SP { other } else { self }
147 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
148 pub struct Spanned<T> {
153 impl PartialEq for Span {
154 fn eq(&self, other: &Span) -> bool {
155 return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
157 fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
162 impl Encodable for Span {
163 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
164 // Encode spans as a single u64 in order to cut down on tagging overhead
165 // added by the RBML metadata encoding. The should be solved differently
166 // altogether some time (FIXME #21482)
167 s.emit_u64( (self.lo.0 as u64) | ((self.hi.0 as u64) << 32) )
171 impl Decodable for Span {
172 fn decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
173 let lo_hi: u64 = try! { d.read_u64() };
174 let lo = BytePos(lo_hi as u32);
175 let hi = BytePos((lo_hi >> 32) as u32);
180 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
181 write!(f, "Span {{ lo: {:?}, hi: {:?}, expn_id: {:?} }}",
182 span.lo, span.hi, span.expn_id)
185 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
186 Cell::new(default_span_debug));
188 impl fmt::Debug for Span {
189 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
190 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
194 pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
195 respan(mk_sp(lo, hi), t)
198 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
199 Spanned {node: t, span: sp}
202 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
206 /* assuming that we're not in macro expansion */
207 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
208 Span {lo: lo, hi: hi, expn_id: NO_EXPANSION}
211 /// Return the span itself if it doesn't come from a macro expansion,
212 /// otherwise return the call site span up to the `enclosing_sp` by
213 /// following the `expn_info` chain.
214 pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span {
215 let call_site1 = cm.with_expn_info(sp.expn_id, |ei| ei.map(|ei| ei.call_site));
216 let call_site2 = cm.with_expn_info(enclosing_sp.expn_id, |ei| ei.map(|ei| ei.call_site));
217 match (call_site1, call_site2) {
219 (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
220 (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp),
224 // _____________________________________________________________________________
225 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
228 /// A source code location used for error reporting
231 /// Information about the original source
232 pub file: Rc<FileMap>,
233 /// The (1-based) line number
235 /// The (0-based) column offset
239 /// A source code location used as the result of lookup_char_pos_adj
240 // Actually, *none* of the clients use the filename *or* file field;
241 // perhaps they should just be removed.
243 pub struct LocWithOpt {
244 pub filename: FileName,
247 pub file: Option<Rc<FileMap>>,
250 // used to be structural records. Better names, anyone?
252 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
254 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
257 // _____________________________________________________________________________
258 // ExpnFormat, NameAndSpan, ExpnInfo, ExpnId
261 /// The source of expansion.
262 #[derive(Clone, Hash, Debug, PartialEq, Eq)]
263 pub enum ExpnFormat {
264 /// e.g. #[derive(...)] <item>
265 MacroAttribute(Name),
268 /// Syntax sugar expansion performed by the compiler (libsyntax::expand).
269 CompilerExpansion(CompilerExpansionFormat),
272 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
273 pub enum CompilerExpansionFormat {
280 impl CompilerExpansionFormat {
281 pub fn name(self) -> &'static str {
283 CompilerExpansionFormat::IfLet => "if let expansion",
284 CompilerExpansionFormat::PlacementIn => "placement-in expansion",
285 CompilerExpansionFormat::WhileLet => "while let expansion",
286 CompilerExpansionFormat::ForLoop => "for loop expansion",
290 #[derive(Clone, Hash, Debug)]
291 pub struct NameAndSpan {
292 /// The format with which the macro was invoked.
293 pub format: ExpnFormat,
294 /// Whether the macro is allowed to use #[unstable]/feature-gated
295 /// features internally without forcing the whole crate to opt-in
297 pub allow_internal_unstable: bool,
298 /// The span of the macro definition itself. The macro may not
299 /// have a sensible definition span (e.g. something defined
300 /// completely inside libsyntax) in which case this is None.
301 pub span: Option<Span>
305 pub fn name(&self) -> Name {
307 ExpnFormat::MacroAttribute(s) => s,
308 ExpnFormat::MacroBang(s) => s,
309 ExpnFormat::CompilerExpansion(ce) => intern(ce.name()),
314 /// Extra information for tracking spans of macro and syntax sugar expansion
315 #[derive(Hash, Debug)]
316 pub struct ExpnInfo {
317 /// The location of the actual macro invocation or syntax sugar , e.g.
318 /// `let x = foo!();` or `if let Some(y) = x {}`
320 /// This may recursively refer to other macro invocations, e.g. if
321 /// `foo!()` invoked `bar!()` internally, and there was an
322 /// expression inside `bar!`; the call_site of the expression in
323 /// the expansion would point to the `bar!` invocation; that
324 /// call_site span would have its own ExpnInfo, with the call_site
325 /// pointing to the `foo!` invocation.
327 /// Information about the expansion.
328 pub callee: NameAndSpan
331 #[derive(PartialEq, Eq, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Copy)]
332 pub struct ExpnId(u32);
334 pub const NO_EXPANSION: ExpnId = ExpnId(!0);
335 // For code appearing from the command line
336 pub const COMMAND_LINE_EXPN: ExpnId = ExpnId(!1);
339 pub fn from_u32(id: u32) -> ExpnId {
343 pub fn into_u32(self) -> u32 {
348 // _____________________________________________________________________________
349 // FileMap, MultiByteChar, FileName, FileLines
352 pub type FileName = String;
354 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
355 pub struct LineInfo {
356 /// Index of line, starting from 0.
357 pub line_index: usize,
359 /// Column in line where span begins, starting from 0.
360 pub start_col: CharPos,
362 /// Column in line where span ends, starting from 0, exclusive.
363 pub end_col: CharPos,
366 pub struct FileLines {
367 pub file: Rc<FileMap>,
368 pub lines: Vec<LineInfo>
371 /// Identifies an offset of a multi-byte character in a FileMap
372 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
373 pub struct MultiByteChar {
374 /// The absolute offset of the character in the CodeMap
376 /// The number of bytes, >=2
380 /// A single source in the CodeMap.
382 /// The name of the file that the source came from, source that doesn't
383 /// originate from files has names between angle brackets by convention,
386 /// The complete source code
387 pub src: Option<Rc<String>>,
388 /// The start position of this source in the CodeMap
389 pub start_pos: BytePos,
390 /// The end position of this source in the CodeMap
391 pub end_pos: BytePos,
392 /// Locations of lines beginnings in the source code
393 pub lines: RefCell<Vec<BytePos>>,
394 /// Locations of multi-byte characters in the source code
395 pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
398 impl Encodable for FileMap {
399 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
400 s.emit_struct("FileMap", 5, |s| {
401 try! { s.emit_struct_field("name", 0, |s| self.name.encode(s)) };
402 try! { s.emit_struct_field("start_pos", 1, |s| self.start_pos.encode(s)) };
403 try! { s.emit_struct_field("end_pos", 2, |s| self.end_pos.encode(s)) };
404 try! { s.emit_struct_field("lines", 3, |s| {
405 let lines = self.lines.borrow();
407 try! { s.emit_u32(lines.len() as u32) };
409 if !lines.is_empty() {
410 // In order to preserve some space, we exploit the fact that
411 // the lines list is sorted and individual lines are
412 // probably not that long. Because of that we can store lines
413 // as a difference list, using as little space as possible
414 // for the differences.
415 let max_line_length = if lines.len() == 1 {
419 .map(|w| w[1] - w[0])
420 .map(|bp| bp.to_usize())
425 let bytes_per_diff: u8 = match max_line_length {
427 0x100 ... 0xFFFF => 2,
431 // Encode the number of bytes used per diff.
432 try! { bytes_per_diff.encode(s) };
434 // Encode the first element.
435 try! { lines[0].encode(s) };
437 let diff_iter = (&lines[..]).windows(2)
438 .map(|w| (w[1] - w[0]));
440 match bytes_per_diff {
441 1 => for diff in diff_iter { try! { (diff.0 as u8).encode(s) } },
442 2 => for diff in diff_iter { try! { (diff.0 as u16).encode(s) } },
443 4 => for diff in diff_iter { try! { diff.0.encode(s) } },
451 s.emit_struct_field("multibyte_chars", 4, |s| {
452 (*self.multibyte_chars.borrow()).encode(s)
458 impl Decodable for FileMap {
459 fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
461 d.read_struct("FileMap", 5, |d| {
462 let name: String = try! {
463 d.read_struct_field("name", 0, |d| Decodable::decode(d))
465 let start_pos: BytePos = try! {
466 d.read_struct_field("start_pos", 1, |d| Decodable::decode(d))
468 let end_pos: BytePos = try! {
469 d.read_struct_field("end_pos", 2, |d| Decodable::decode(d))
471 let lines: Vec<BytePos> = try! {
472 d.read_struct_field("lines", 3, |d| {
473 let num_lines: u32 = try! { Decodable::decode(d) };
474 let mut lines = Vec::with_capacity(num_lines as usize);
477 // Read the number of bytes used per diff.
478 let bytes_per_diff: u8 = try! { Decodable::decode(d) };
480 // Read the first element.
481 let mut line_start: BytePos = try! { Decodable::decode(d) };
482 lines.push(line_start);
484 for _ in 1..num_lines {
485 let diff = match bytes_per_diff {
486 1 => try! { d.read_u8() } as u32,
487 2 => try! { d.read_u16() } as u32,
488 4 => try! { d.read_u32() },
492 line_start = line_start + BytePos(diff);
494 lines.push(line_start);
501 let multibyte_chars: Vec<MultiByteChar> = try! {
502 d.read_struct_field("multibyte_chars", 4, |d| Decodable::decode(d))
506 start_pos: start_pos,
509 lines: RefCell::new(lines),
510 multibyte_chars: RefCell::new(multibyte_chars)
516 impl fmt::Debug for FileMap {
517 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
518 write!(fmt, "FileMap({})", self.name)
523 /// EFFECT: register a start-of-line offset in the
524 /// table of line-beginnings.
525 /// UNCHECKED INVARIANT: these offsets must be added in the right
526 /// order and must be in the right places; there is shared knowledge
527 /// about what ends a line between this file and parse.rs
528 /// WARNING: pos param here is the offset relative to start of CodeMap,
529 /// and CodeMap will append a newline when adding a filemap without a newline at the end,
530 /// so the safe way to call this is with value calculated as
531 /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
532 pub fn next_line(&self, pos: BytePos) {
533 // the new charpos must be > the last one (or it's the first one).
534 let mut lines = self.lines.borrow_mut();
535 let line_len = lines.len();
536 assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
540 /// get a line from the list of pre-computed line-beginnings.
541 /// line-number here is 0-based.
542 pub fn get_line(&self, line_number: usize) -> Option<&str> {
545 let lines = self.lines.borrow();
546 lines.get(line_number).map(|&line| {
547 let begin: BytePos = line - self.start_pos;
548 let begin = begin.to_usize();
549 // We can't use `lines.get(line_number+1)` because we might
550 // be parsing when we call this function and thus the current
551 // line is the last one we have line info for.
552 let slice = &src[begin..];
553 match slice.find('\n') {
554 Some(e) => &slice[..e],
563 pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
564 assert!(bytes >=2 && bytes <= 4);
565 let mbc = MultiByteChar {
569 self.multibyte_chars.borrow_mut().push(mbc);
572 pub fn is_real_file(&self) -> bool {
573 !(self.name.starts_with("<") &&
574 self.name.ends_with(">"))
577 pub fn is_imported(&self) -> bool {
582 /// An abstraction over the fs operations used by the Parser.
583 pub trait FileLoader {
584 /// Query the existence of a file.
585 fn file_exists(&self, path: &Path) -> bool;
587 /// Read the contents of an UTF-8 file into memory.
588 fn read_file(&self, path: &Path) -> io::Result<String>;
591 /// A FileLoader that uses std::fs to load real files.
592 pub struct RealFileLoader;
594 impl FileLoader for RealFileLoader {
595 fn file_exists(&self, path: &Path) -> bool {
596 fs::metadata(path).is_ok()
599 fn read_file(&self, path: &Path) -> io::Result<String> {
600 let mut src = String::new();
601 try!(try!(fs::File::open(path)).read_to_string(&mut src));
606 // _____________________________________________________________________________
611 pub files: RefCell<Vec<Rc<FileMap>>>,
612 expansions: RefCell<Vec<ExpnInfo>>,
613 file_loader: Box<FileLoader>
617 pub fn new() -> CodeMap {
619 files: RefCell::new(Vec::new()),
620 expansions: RefCell::new(Vec::new()),
621 file_loader: Box::new(RealFileLoader)
625 pub fn with_file_loader(file_loader: Box<FileLoader>) -> CodeMap {
627 files: RefCell::new(Vec::new()),
628 expansions: RefCell::new(Vec::new()),
629 file_loader: file_loader
633 pub fn file_exists(&self, path: &Path) -> bool {
634 self.file_loader.file_exists(path)
637 pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> {
638 let src = try!(self.file_loader.read_file(path));
639 Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
642 fn next_start_pos(&self) -> usize {
643 let files = self.files.borrow();
646 // Add one so there is some space between files. This lets us distinguish
647 // positions in the codemap, even in the presence of zero-length files.
648 Some(last) => last.end_pos.to_usize() + 1,
652 /// Creates a new filemap without setting its line information. If you don't
653 /// intend to set the line information yourself, you should use new_filemap_and_lines.
654 pub fn new_filemap(&self, filename: FileName, mut src: String) -> Rc<FileMap> {
655 let start_pos = self.next_start_pos();
656 let mut files = self.files.borrow_mut();
658 // Remove utf-8 BOM if any.
659 if src.starts_with("\u{feff}") {
663 let end_pos = start_pos + src.len();
665 let filemap = Rc::new(FileMap {
667 src: Some(Rc::new(src)),
668 start_pos: Pos::from_usize(start_pos),
669 end_pos: Pos::from_usize(end_pos),
670 lines: RefCell::new(Vec::new()),
671 multibyte_chars: RefCell::new(Vec::new()),
674 files.push(filemap.clone());
679 /// Creates a new filemap and sets its line information.
680 pub fn new_filemap_and_lines(&self, filename: &str, src: &str) -> Rc<FileMap> {
681 let fm = self.new_filemap(filename.to_string(), src.to_owned());
682 let mut byte_pos: u32 = 0;
683 for line in src.lines() {
684 // register the start of this line
685 fm.next_line(BytePos(byte_pos));
687 // update byte_pos to include this line and the \n at the end
688 byte_pos += line.len() as u32 + 1;
694 /// Allocates a new FileMap representing a source file from an external
695 /// crate. The source code of such an "imported filemap" is not available,
696 /// but we still know enough to generate accurate debuginfo location
697 /// information for things inlined from other crates.
698 pub fn new_imported_filemap(&self,
701 mut file_local_lines: Vec<BytePos>,
702 mut file_local_multibyte_chars: Vec<MultiByteChar>)
704 let start_pos = self.next_start_pos();
705 let mut files = self.files.borrow_mut();
707 let end_pos = Pos::from_usize(start_pos + source_len);
708 let start_pos = Pos::from_usize(start_pos);
710 for pos in &mut file_local_lines {
711 *pos = *pos + start_pos;
714 for mbc in &mut file_local_multibyte_chars {
715 mbc.pos = mbc.pos + start_pos;
718 let filemap = Rc::new(FileMap {
721 start_pos: start_pos,
723 lines: RefCell::new(file_local_lines),
724 multibyte_chars: RefCell::new(file_local_multibyte_chars),
727 files.push(filemap.clone());
732 pub fn mk_substr_filename(&self, sp: Span) -> String {
733 let pos = self.lookup_char_pos(sp.lo);
734 (format!("<{}:{}:{}>",
737 pos.col.to_usize() + 1)).to_string()
740 /// Lookup source information about a BytePos
741 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
742 let chpos = self.bytepos_to_file_charpos(pos);
743 match self.lookup_line(pos) {
744 Ok(FileMapAndLine { fm: f, line: a }) => {
745 let line = a + 1; // Line numbers start at 1
746 let linebpos = (*f.lines.borrow())[a];
747 let linechpos = self.bytepos_to_file_charpos(linebpos);
748 debug!("byte pos {:?} is on the line at byte pos {:?}",
750 debug!("char pos {:?} is on the line at char pos {:?}",
752 debug!("byte is on line: {}", line);
753 assert!(chpos >= linechpos);
757 col: chpos - linechpos,
770 // If the relevant filemap is empty, we don't return a line number.
771 fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> {
772 let idx = self.lookup_filemap_idx(pos);
774 let files = self.files.borrow();
775 let f = (*files)[idx].clone();
777 let len = f.lines.borrow().len();
784 let lines = f.lines.borrow();
785 let mut b = lines.len();
788 if (*lines)[m] > pos {
794 assert!(a <= lines.len());
796 Ok(FileMapAndLine { fm: f, line: a })
799 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
800 let loc = self.lookup_char_pos(pos);
802 filename: loc.file.name.to_string(),
809 pub fn span_to_string(&self, sp: Span) -> String {
810 if self.files.borrow().is_empty() && sp == DUMMY_SP {
811 return "no-location".to_string();
814 let lo = self.lookup_char_pos_adj(sp.lo);
815 let hi = self.lookup_char_pos_adj(sp.hi);
816 return (format!("{}:{}:{}: {}:{}",
819 lo.col.to_usize() + 1,
821 hi.col.to_usize() + 1)).to_string()
824 pub fn span_to_filename(&self, sp: Span) -> FileName {
825 self.lookup_char_pos(sp.lo).file.name.to_string()
828 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
830 return Err(SpanLinesError::IllFormedSpan(sp));
833 let lo = self.lookup_char_pos(sp.lo);
834 let hi = self.lookup_char_pos(sp.hi);
836 if lo.file.start_pos != hi.file.start_pos {
837 return Err(SpanLinesError::DistinctSources(DistinctSources {
838 begin: (lo.file.name.clone(), lo.file.start_pos),
839 end: (hi.file.name.clone(), hi.file.start_pos),
842 assert!(hi.line >= lo.line);
844 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
846 // The span starts partway through the first line,
847 // but after that it starts from offset 0.
848 let mut start_col = lo.col;
850 // For every line but the last, it extends from `start_col`
851 // and to the end of the line. Be careful because the line
852 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
854 for line_index in lo.line-1 .. hi.line-1 {
855 let line_len = lo.file.get_line(line_index).map(|s| s.len()).unwrap_or(0);
856 lines.push(LineInfo { line_index: line_index,
857 start_col: start_col,
858 end_col: CharPos::from_usize(line_len) });
859 start_col = CharPos::from_usize(0);
862 // For the last line, it extends from `start_col` to `hi.col`:
863 lines.push(LineInfo { line_index: hi.line - 1,
864 start_col: start_col,
867 Ok(FileLines {file: lo.file, lines: lines})
870 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
872 return Err(SpanSnippetError::IllFormedSpan(sp));
875 let local_begin = self.lookup_byte_offset(sp.lo);
876 let local_end = self.lookup_byte_offset(sp.hi);
878 if local_begin.fm.start_pos != local_end.fm.start_pos {
879 return Err(SpanSnippetError::DistinctSources(DistinctSources {
880 begin: (local_begin.fm.name.clone(),
881 local_begin.fm.start_pos),
882 end: (local_end.fm.name.clone(),
883 local_end.fm.start_pos)
886 match local_begin.fm.src {
888 let start_index = local_begin.pos.to_usize();
889 let end_index = local_end.pos.to_usize();
890 let source_len = (local_begin.fm.end_pos -
891 local_begin.fm.start_pos).to_usize();
893 if start_index > end_index || end_index > source_len {
894 return Err(SpanSnippetError::MalformedForCodemap(
895 MalformedCodemapPositions {
896 name: local_begin.fm.name.clone(),
897 source_len: source_len,
898 begin_pos: local_begin.pos,
899 end_pos: local_end.pos,
903 return Ok((&src[start_index..end_index]).to_string())
906 return Err(SpanSnippetError::SourceNotAvailable {
907 filename: local_begin.fm.name.clone()
914 pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> {
915 for fm in self.files.borrow().iter() {
916 if filename == fm.name {
920 panic!("asking for {} which we don't know about", filename);
923 /// For a global BytePos compute the local offset within the containing FileMap
924 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
925 let idx = self.lookup_filemap_idx(bpos);
926 let fm = (*self.files.borrow())[idx].clone();
927 let offset = bpos - fm.start_pos;
928 FileMapAndBytePos {fm: fm, pos: offset}
931 /// Converts an absolute BytePos to a CharPos relative to the filemap.
932 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
933 let idx = self.lookup_filemap_idx(bpos);
934 let files = self.files.borrow();
935 let map = &(*files)[idx];
937 // The number of extra bytes due to multibyte chars in the FileMap
938 let mut total_extra_bytes = 0;
940 for mbc in map.multibyte_chars.borrow().iter() {
941 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
943 // every character is at least one byte, so we only
944 // count the actual extra bytes.
945 total_extra_bytes += mbc.bytes - 1;
946 // We should never see a byte position in the middle of a
948 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
954 assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
955 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
958 // Return the index of the filemap (in self.files) which contains pos.
959 fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
960 let files = self.files.borrow();
962 let count = files.len();
964 // Binary search for the filemap.
969 if files[m].start_pos > pos {
976 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
981 pub fn record_expansion(&self, expn_info: ExpnInfo) -> ExpnId {
982 let mut expansions = self.expansions.borrow_mut();
983 expansions.push(expn_info);
984 let len = expansions.len();
985 if len > u32::max_value() as usize {
986 panic!("too many ExpnInfo's!");
988 ExpnId(len as u32 - 1)
991 pub fn with_expn_info<T, F>(&self, id: ExpnId, f: F) -> T where
992 F: FnOnce(Option<&ExpnInfo>) -> T,
995 NO_EXPANSION | COMMAND_LINE_EXPN => f(None),
996 ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as usize]))
1000 /// Check if a span is "internal" to a macro in which #[unstable]
1001 /// items can be used (that is, a macro marked with
1002 /// `#[allow_internal_unstable]`).
1003 pub fn span_allows_unstable(&self, span: Span) -> bool {
1004 debug!("span_allows_unstable(span = {:?})", span);
1005 let mut allows_unstable = false;
1006 let mut expn_id = span.expn_id;
1008 let quit = self.with_expn_info(expn_id, |expninfo| {
1009 debug!("span_allows_unstable: expninfo = {:?}", expninfo);
1010 expninfo.map_or(/* hit the top level */ true, |info| {
1012 let span_comes_from_this_expansion =
1013 info.callee.span.map_or(span == info.call_site, |mac_span| {
1014 mac_span.lo <= span.lo && span.hi <= mac_span.hi
1017 debug!("span_allows_unstable: span: {:?} call_site: {:?} callee: {:?}",
1019 (info.call_site.lo, info.call_site.hi),
1020 info.callee.span.map(|x| (x.lo, x.hi)));
1021 debug!("span_allows_unstable: from this expansion? {}, allows unstable? {}",
1022 span_comes_from_this_expansion,
1023 info.callee.allow_internal_unstable);
1024 if span_comes_from_this_expansion {
1025 allows_unstable = info.callee.allow_internal_unstable;
1026 // we've found the right place, stop looking
1029 // not the right place, keep looking
1030 expn_id = info.call_site.expn_id;
1039 debug!("span_allows_unstable? {}", allows_unstable);
1044 // _____________________________________________________________________________
1045 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
1048 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1050 #[derive(Clone, PartialEq, Eq, Debug)]
1051 pub enum SpanLinesError {
1052 IllFormedSpan(Span),
1053 DistinctSources(DistinctSources),
1056 #[derive(Clone, PartialEq, Eq, Debug)]
1057 pub enum SpanSnippetError {
1058 IllFormedSpan(Span),
1059 DistinctSources(DistinctSources),
1060 MalformedForCodemap(MalformedCodemapPositions),
1061 SourceNotAvailable { filename: String }
1064 #[derive(Clone, PartialEq, Eq, Debug)]
1065 pub struct DistinctSources {
1066 begin: (String, BytePos),
1067 end: (String, BytePos)
1070 #[derive(Clone, PartialEq, Eq, Debug)]
1071 pub struct MalformedCodemapPositions {
1079 // _____________________________________________________________________________
1090 let cm = CodeMap::new();
1091 let fm = cm.new_filemap("blork.rs".to_string(),
1092 "first line.\nsecond line".to_string());
1093 fm.next_line(BytePos(0));
1094 // Test we can get lines with partial line info.
1095 assert_eq!(fm.get_line(0), Some("first line."));
1096 // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
1097 fm.next_line(BytePos(10));
1098 assert_eq!(fm.get_line(1), Some("."));
1099 fm.next_line(BytePos(12));
1100 assert_eq!(fm.get_line(2), Some("second line"));
1106 let cm = CodeMap::new();
1107 let fm = cm.new_filemap("blork.rs".to_string(),
1108 "first line.\nsecond line".to_string());
1109 // TESTING *REALLY* BROKEN BEHAVIOR:
1110 fm.next_line(BytePos(0));
1111 fm.next_line(BytePos(10));
1112 fm.next_line(BytePos(2));
1115 fn init_code_map() -> CodeMap {
1116 let cm = CodeMap::new();
1117 let fm1 = cm.new_filemap("blork.rs".to_string(),
1118 "first line.\nsecond line".to_string());
1119 let fm2 = cm.new_filemap("empty.rs".to_string(),
1121 let fm3 = cm.new_filemap("blork2.rs".to_string(),
1122 "first line.\nsecond line".to_string());
1124 fm1.next_line(BytePos(0));
1125 fm1.next_line(BytePos(12));
1126 fm2.next_line(fm2.start_pos);
1127 fm3.next_line(fm3.start_pos);
1128 fm3.next_line(fm3.start_pos + BytePos(12));
1135 // Test lookup_byte_offset
1136 let cm = init_code_map();
1138 let fmabp1 = cm.lookup_byte_offset(BytePos(23));
1139 assert_eq!(fmabp1.fm.name, "blork.rs");
1140 assert_eq!(fmabp1.pos, BytePos(23));
1142 let fmabp1 = cm.lookup_byte_offset(BytePos(24));
1143 assert_eq!(fmabp1.fm.name, "empty.rs");
1144 assert_eq!(fmabp1.pos, BytePos(0));
1146 let fmabp2 = cm.lookup_byte_offset(BytePos(25));
1147 assert_eq!(fmabp2.fm.name, "blork2.rs");
1148 assert_eq!(fmabp2.pos, BytePos(0));
1153 // Test bytepos_to_file_charpos
1154 let cm = init_code_map();
1156 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
1157 assert_eq!(cp1, CharPos(22));
1159 let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
1160 assert_eq!(cp2, CharPos(0));
1165 // Test zero-length filemaps.
1166 let cm = init_code_map();
1168 let loc1 = cm.lookup_char_pos(BytePos(22));
1169 assert_eq!(loc1.file.name, "blork.rs");
1170 assert_eq!(loc1.line, 2);
1171 assert_eq!(loc1.col, CharPos(10));
1173 let loc2 = cm.lookup_char_pos(BytePos(25));
1174 assert_eq!(loc2.file.name, "blork2.rs");
1175 assert_eq!(loc2.line, 1);
1176 assert_eq!(loc2.col, CharPos(0));
1179 fn init_code_map_mbc() -> CodeMap {
1180 let cm = CodeMap::new();
1181 // € is a three byte utf8 char.
1183 cm.new_filemap("blork.rs".to_string(),
1184 "fir€st €€€€ line.\nsecond line".to_string());
1185 let fm2 = cm.new_filemap("blork2.rs".to_string(),
1186 "first line€€.\n€ second line".to_string());
1188 fm1.next_line(BytePos(0));
1189 fm1.next_line(BytePos(28));
1190 fm2.next_line(fm2.start_pos);
1191 fm2.next_line(fm2.start_pos + BytePos(20));
1193 fm1.record_multibyte_char(BytePos(3), 3);
1194 fm1.record_multibyte_char(BytePos(9), 3);
1195 fm1.record_multibyte_char(BytePos(12), 3);
1196 fm1.record_multibyte_char(BytePos(15), 3);
1197 fm1.record_multibyte_char(BytePos(18), 3);
1198 fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
1199 fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
1200 fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
1207 // Test bytepos_to_file_charpos in the presence of multi-byte chars
1208 let cm = init_code_map_mbc();
1210 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
1211 assert_eq!(cp1, CharPos(3));
1213 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
1214 assert_eq!(cp2, CharPos(4));
1216 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
1217 assert_eq!(cp3, CharPos(12));
1219 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
1220 assert_eq!(cp4, CharPos(15));
1225 // Test span_to_lines for a span ending at the end of filemap
1226 let cm = init_code_map();
1227 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1228 let file_lines = cm.span_to_lines(span).unwrap();
1230 assert_eq!(file_lines.file.name, "blork.rs");
1231 assert_eq!(file_lines.lines.len(), 1);
1232 assert_eq!(file_lines.lines[0].line_index, 1);
1235 /// Given a string like " ^~~~~~~~~~~~ ", produces a span
1236 /// coverting that range. The idea is that the string has the same
1237 /// length as the input, and we uncover the byte positions. Note
1238 /// that this can span lines and so on.
1239 fn span_from_selection(input: &str, selection: &str) -> Span {
1240 assert_eq!(input.len(), selection.len());
1241 let left_index = selection.find('^').unwrap() as u32;
1242 let right_index = selection.rfind('~').unwrap() as u32;
1243 Span { lo: BytePos(left_index), hi: BytePos(right_index + 1), expn_id: NO_EXPANSION }
1246 /// Test span_to_snippet and span_to_lines for a span coverting 3
1247 /// lines in the middle of a file.
1249 fn span_to_snippet_and_lines_spanning_multiple_lines() {
1250 let cm = CodeMap::new();
1251 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1252 let selection = " \n ^~\n~~~\n~~~~~ \n \n";
1253 cm.new_filemap_and_lines("blork.rs", inputtext);
1254 let span = span_from_selection(inputtext, selection);
1256 // check that we are extracting the text we thought we were extracting
1257 assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1259 // check that span_to_lines gives us the complete result with the lines/cols we expected
1260 let lines = cm.span_to_lines(span).unwrap();
1261 let expected = vec![
1262 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1263 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1264 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1266 assert_eq!(lines.lines, expected);
1271 // Test span_to_snippet for a span ending at the end of filemap
1272 let cm = init_code_map();
1273 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1274 let snippet = cm.span_to_snippet(span);
1276 assert_eq!(snippet, Ok("second line".to_string()));
1281 // Test span_to_str for a span ending at the end of filemap
1282 let cm = init_code_map();
1283 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1284 let sstr = cm.span_to_string(span);
1286 assert_eq!(sstr, "blork.rs:2:1: 2:12");