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 {
281 impl CompilerExpansionFormat {
282 pub fn name(self) -> &'static str {
284 CompilerExpansionFormat::IfLet => "if let expansion",
285 CompilerExpansionFormat::PlacementIn => "placement-in expansion",
286 CompilerExpansionFormat::WhileLet => "while let expansion",
287 CompilerExpansionFormat::ForLoop => "for loop expansion",
288 CompilerExpansionFormat::Closure => "closure expansion",
292 #[derive(Clone, Hash, Debug)]
293 pub struct NameAndSpan {
294 /// The format with which the macro was invoked.
295 pub format: ExpnFormat,
296 /// Whether the macro is allowed to use #[unstable]/feature-gated
297 /// features internally without forcing the whole crate to opt-in
299 pub allow_internal_unstable: bool,
300 /// The span of the macro definition itself. The macro may not
301 /// have a sensible definition span (e.g. something defined
302 /// completely inside libsyntax) in which case this is None.
303 pub span: Option<Span>
307 pub fn name(&self) -> Name {
309 ExpnFormat::MacroAttribute(s) => s,
310 ExpnFormat::MacroBang(s) => s,
311 ExpnFormat::CompilerExpansion(ce) => intern(ce.name()),
316 /// Extra information for tracking spans of macro and syntax sugar expansion
317 #[derive(Hash, Debug)]
318 pub struct ExpnInfo {
319 /// The location of the actual macro invocation or syntax sugar , e.g.
320 /// `let x = foo!();` or `if let Some(y) = x {}`
322 /// This may recursively refer to other macro invocations, e.g. if
323 /// `foo!()` invoked `bar!()` internally, and there was an
324 /// expression inside `bar!`; the call_site of the expression in
325 /// the expansion would point to the `bar!` invocation; that
326 /// call_site span would have its own ExpnInfo, with the call_site
327 /// pointing to the `foo!` invocation.
329 /// Information about the expansion.
330 pub callee: NameAndSpan
333 #[derive(PartialEq, Eq, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Copy)]
334 pub struct ExpnId(u32);
336 pub const NO_EXPANSION: ExpnId = ExpnId(!0);
337 // For code appearing from the command line
338 pub const COMMAND_LINE_EXPN: ExpnId = ExpnId(!1);
341 pub fn from_u32(id: u32) -> ExpnId {
345 pub fn into_u32(self) -> u32 {
350 // _____________________________________________________________________________
351 // FileMap, MultiByteChar, FileName, FileLines
354 pub type FileName = String;
356 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
357 pub struct LineInfo {
358 /// Index of line, starting from 0.
359 pub line_index: usize,
361 /// Column in line where span begins, starting from 0.
362 pub start_col: CharPos,
364 /// Column in line where span ends, starting from 0, exclusive.
365 pub end_col: CharPos,
368 pub struct FileLines {
369 pub file: Rc<FileMap>,
370 pub lines: Vec<LineInfo>
373 /// Identifies an offset of a multi-byte character in a FileMap
374 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
375 pub struct MultiByteChar {
376 /// The absolute offset of the character in the CodeMap
378 /// The number of bytes, >=2
382 /// A single source in the CodeMap.
384 /// The name of the file that the source came from, source that doesn't
385 /// originate from files has names between angle brackets by convention,
388 /// The complete source code
389 pub src: Option<Rc<String>>,
390 /// The start position of this source in the CodeMap
391 pub start_pos: BytePos,
392 /// The end position of this source in the CodeMap
393 pub end_pos: BytePos,
394 /// Locations of lines beginnings in the source code
395 pub lines: RefCell<Vec<BytePos>>,
396 /// Locations of multi-byte characters in the source code
397 pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
400 impl Encodable for FileMap {
401 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
402 s.emit_struct("FileMap", 5, |s| {
403 try! { s.emit_struct_field("name", 0, |s| self.name.encode(s)) };
404 try! { s.emit_struct_field("start_pos", 1, |s| self.start_pos.encode(s)) };
405 try! { s.emit_struct_field("end_pos", 2, |s| self.end_pos.encode(s)) };
406 try! { s.emit_struct_field("lines", 3, |s| {
407 let lines = self.lines.borrow();
409 try! { s.emit_u32(lines.len() as u32) };
411 if !lines.is_empty() {
412 // In order to preserve some space, we exploit the fact that
413 // the lines list is sorted and individual lines are
414 // probably not that long. Because of that we can store lines
415 // as a difference list, using as little space as possible
416 // for the differences.
417 let max_line_length = if lines.len() == 1 {
421 .map(|w| w[1] - w[0])
422 .map(|bp| bp.to_usize())
427 let bytes_per_diff: u8 = match max_line_length {
429 0x100 ... 0xFFFF => 2,
433 // Encode the number of bytes used per diff.
434 try! { bytes_per_diff.encode(s) };
436 // Encode the first element.
437 try! { lines[0].encode(s) };
439 let diff_iter = (&lines[..]).windows(2)
440 .map(|w| (w[1] - w[0]));
442 match bytes_per_diff {
443 1 => for diff in diff_iter { try! { (diff.0 as u8).encode(s) } },
444 2 => for diff in diff_iter { try! { (diff.0 as u16).encode(s) } },
445 4 => for diff in diff_iter { try! { diff.0.encode(s) } },
453 s.emit_struct_field("multibyte_chars", 4, |s| {
454 (*self.multibyte_chars.borrow()).encode(s)
460 impl Decodable for FileMap {
461 fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
463 d.read_struct("FileMap", 5, |d| {
464 let name: String = try! {
465 d.read_struct_field("name", 0, |d| Decodable::decode(d))
467 let start_pos: BytePos = try! {
468 d.read_struct_field("start_pos", 1, |d| Decodable::decode(d))
470 let end_pos: BytePos = try! {
471 d.read_struct_field("end_pos", 2, |d| Decodable::decode(d))
473 let lines: Vec<BytePos> = try! {
474 d.read_struct_field("lines", 3, |d| {
475 let num_lines: u32 = try! { Decodable::decode(d) };
476 let mut lines = Vec::with_capacity(num_lines as usize);
479 // Read the number of bytes used per diff.
480 let bytes_per_diff: u8 = try! { Decodable::decode(d) };
482 // Read the first element.
483 let mut line_start: BytePos = try! { Decodable::decode(d) };
484 lines.push(line_start);
486 for _ in 1..num_lines {
487 let diff = match bytes_per_diff {
488 1 => try! { d.read_u8() } as u32,
489 2 => try! { d.read_u16() } as u32,
490 4 => try! { d.read_u32() },
494 line_start = line_start + BytePos(diff);
496 lines.push(line_start);
503 let multibyte_chars: Vec<MultiByteChar> = try! {
504 d.read_struct_field("multibyte_chars", 4, |d| Decodable::decode(d))
508 start_pos: start_pos,
511 lines: RefCell::new(lines),
512 multibyte_chars: RefCell::new(multibyte_chars)
518 impl fmt::Debug for FileMap {
519 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
520 write!(fmt, "FileMap({})", self.name)
525 /// EFFECT: register a start-of-line offset in the
526 /// table of line-beginnings.
527 /// UNCHECKED INVARIANT: these offsets must be added in the right
528 /// order and must be in the right places; there is shared knowledge
529 /// about what ends a line between this file and parse.rs
530 /// WARNING: pos param here is the offset relative to start of CodeMap,
531 /// and CodeMap will append a newline when adding a filemap without a newline at the end,
532 /// so the safe way to call this is with value calculated as
533 /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
534 pub fn next_line(&self, pos: BytePos) {
535 // the new charpos must be > the last one (or it's the first one).
536 let mut lines = self.lines.borrow_mut();
537 let line_len = lines.len();
538 assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
542 /// get a line from the list of pre-computed line-beginnings.
543 /// line-number here is 0-based.
544 pub fn get_line(&self, line_number: usize) -> Option<&str> {
547 let lines = self.lines.borrow();
548 lines.get(line_number).map(|&line| {
549 let begin: BytePos = line - self.start_pos;
550 let begin = begin.to_usize();
551 // We can't use `lines.get(line_number+1)` because we might
552 // be parsing when we call this function and thus the current
553 // line is the last one we have line info for.
554 let slice = &src[begin..];
555 match slice.find('\n') {
556 Some(e) => &slice[..e],
565 pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
566 assert!(bytes >=2 && bytes <= 4);
567 let mbc = MultiByteChar {
571 self.multibyte_chars.borrow_mut().push(mbc);
574 pub fn is_real_file(&self) -> bool {
575 !(self.name.starts_with("<") &&
576 self.name.ends_with(">"))
579 pub fn is_imported(&self) -> bool {
584 /// An abstraction over the fs operations used by the Parser.
585 pub trait FileLoader {
586 /// Query the existence of a file.
587 fn file_exists(&self, path: &Path) -> bool;
589 /// Read the contents of an UTF-8 file into memory.
590 fn read_file(&self, path: &Path) -> io::Result<String>;
593 /// A FileLoader that uses std::fs to load real files.
594 pub struct RealFileLoader;
596 impl FileLoader for RealFileLoader {
597 fn file_exists(&self, path: &Path) -> bool {
598 fs::metadata(path).is_ok()
601 fn read_file(&self, path: &Path) -> io::Result<String> {
602 let mut src = String::new();
603 try!(try!(fs::File::open(path)).read_to_string(&mut src));
608 // _____________________________________________________________________________
613 pub files: RefCell<Vec<Rc<FileMap>>>,
614 expansions: RefCell<Vec<ExpnInfo>>,
615 file_loader: Box<FileLoader>
619 pub fn new() -> CodeMap {
621 files: RefCell::new(Vec::new()),
622 expansions: RefCell::new(Vec::new()),
623 file_loader: Box::new(RealFileLoader)
627 pub fn with_file_loader(file_loader: Box<FileLoader>) -> CodeMap {
629 files: RefCell::new(Vec::new()),
630 expansions: RefCell::new(Vec::new()),
631 file_loader: file_loader
635 pub fn file_exists(&self, path: &Path) -> bool {
636 self.file_loader.file_exists(path)
639 pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> {
640 let src = try!(self.file_loader.read_file(path));
641 Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
644 fn next_start_pos(&self) -> usize {
645 let files = self.files.borrow();
648 // Add one so there is some space between files. This lets us distinguish
649 // positions in the codemap, even in the presence of zero-length files.
650 Some(last) => last.end_pos.to_usize() + 1,
654 /// Creates a new filemap without setting its line information. If you don't
655 /// intend to set the line information yourself, you should use new_filemap_and_lines.
656 pub fn new_filemap(&self, filename: FileName, mut src: String) -> Rc<FileMap> {
657 let start_pos = self.next_start_pos();
658 let mut files = self.files.borrow_mut();
660 // Remove utf-8 BOM if any.
661 if src.starts_with("\u{feff}") {
665 let end_pos = start_pos + src.len();
667 let filemap = Rc::new(FileMap {
669 src: Some(Rc::new(src)),
670 start_pos: Pos::from_usize(start_pos),
671 end_pos: Pos::from_usize(end_pos),
672 lines: RefCell::new(Vec::new()),
673 multibyte_chars: RefCell::new(Vec::new()),
676 files.push(filemap.clone());
681 /// Creates a new filemap and sets its line information.
682 pub fn new_filemap_and_lines(&self, filename: &str, src: &str) -> Rc<FileMap> {
683 let fm = self.new_filemap(filename.to_string(), src.to_owned());
684 let mut byte_pos: u32 = 0;
685 for line in src.lines() {
686 // register the start of this line
687 fm.next_line(BytePos(byte_pos));
689 // update byte_pos to include this line and the \n at the end
690 byte_pos += line.len() as u32 + 1;
696 /// Allocates a new FileMap representing a source file from an external
697 /// crate. The source code of such an "imported filemap" is not available,
698 /// but we still know enough to generate accurate debuginfo location
699 /// information for things inlined from other crates.
700 pub fn new_imported_filemap(&self,
703 mut file_local_lines: Vec<BytePos>,
704 mut file_local_multibyte_chars: Vec<MultiByteChar>)
706 let start_pos = self.next_start_pos();
707 let mut files = self.files.borrow_mut();
709 let end_pos = Pos::from_usize(start_pos + source_len);
710 let start_pos = Pos::from_usize(start_pos);
712 for pos in &mut file_local_lines {
713 *pos = *pos + start_pos;
716 for mbc in &mut file_local_multibyte_chars {
717 mbc.pos = mbc.pos + start_pos;
720 let filemap = Rc::new(FileMap {
723 start_pos: start_pos,
725 lines: RefCell::new(file_local_lines),
726 multibyte_chars: RefCell::new(file_local_multibyte_chars),
729 files.push(filemap.clone());
734 pub fn mk_substr_filename(&self, sp: Span) -> String {
735 let pos = self.lookup_char_pos(sp.lo);
736 (format!("<{}:{}:{}>",
739 pos.col.to_usize() + 1)).to_string()
742 /// Lookup source information about a BytePos
743 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
744 let chpos = self.bytepos_to_file_charpos(pos);
745 match self.lookup_line(pos) {
746 Ok(FileMapAndLine { fm: f, line: a }) => {
747 let line = a + 1; // Line numbers start at 1
748 let linebpos = (*f.lines.borrow())[a];
749 let linechpos = self.bytepos_to_file_charpos(linebpos);
750 debug!("byte pos {:?} is on the line at byte pos {:?}",
752 debug!("char pos {:?} is on the line at char pos {:?}",
754 debug!("byte is on line: {}", line);
755 assert!(chpos >= linechpos);
759 col: chpos - linechpos,
772 // If the relevant filemap is empty, we don't return a line number.
773 fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> {
774 let idx = self.lookup_filemap_idx(pos);
776 let files = self.files.borrow();
777 let f = (*files)[idx].clone();
779 let len = f.lines.borrow().len();
786 let lines = f.lines.borrow();
787 let mut b = lines.len();
790 if (*lines)[m] > pos {
796 assert!(a <= lines.len());
798 Ok(FileMapAndLine { fm: f, line: a })
801 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
802 let loc = self.lookup_char_pos(pos);
804 filename: loc.file.name.to_string(),
811 pub fn span_to_string(&self, sp: Span) -> String {
812 if self.files.borrow().is_empty() && sp == DUMMY_SP {
813 return "no-location".to_string();
816 let lo = self.lookup_char_pos_adj(sp.lo);
817 let hi = self.lookup_char_pos_adj(sp.hi);
818 return (format!("{}:{}:{}: {}:{}",
821 lo.col.to_usize() + 1,
823 hi.col.to_usize() + 1)).to_string()
826 pub fn span_to_filename(&self, sp: Span) -> FileName {
827 self.lookup_char_pos(sp.lo).file.name.to_string()
830 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
832 return Err(SpanLinesError::IllFormedSpan(sp));
835 let lo = self.lookup_char_pos(sp.lo);
836 let hi = self.lookup_char_pos(sp.hi);
838 if lo.file.start_pos != hi.file.start_pos {
839 return Err(SpanLinesError::DistinctSources(DistinctSources {
840 begin: (lo.file.name.clone(), lo.file.start_pos),
841 end: (hi.file.name.clone(), hi.file.start_pos),
844 assert!(hi.line >= lo.line);
846 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
848 // The span starts partway through the first line,
849 // but after that it starts from offset 0.
850 let mut start_col = lo.col;
852 // For every line but the last, it extends from `start_col`
853 // and to the end of the line. Be careful because the line
854 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
856 for line_index in lo.line-1 .. hi.line-1 {
857 let line_len = lo.file.get_line(line_index).map(|s| s.len()).unwrap_or(0);
858 lines.push(LineInfo { line_index: line_index,
859 start_col: start_col,
860 end_col: CharPos::from_usize(line_len) });
861 start_col = CharPos::from_usize(0);
864 // For the last line, it extends from `start_col` to `hi.col`:
865 lines.push(LineInfo { line_index: hi.line - 1,
866 start_col: start_col,
869 Ok(FileLines {file: lo.file, lines: lines})
872 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
874 return Err(SpanSnippetError::IllFormedSpan(sp));
877 let local_begin = self.lookup_byte_offset(sp.lo);
878 let local_end = self.lookup_byte_offset(sp.hi);
880 if local_begin.fm.start_pos != local_end.fm.start_pos {
881 return Err(SpanSnippetError::DistinctSources(DistinctSources {
882 begin: (local_begin.fm.name.clone(),
883 local_begin.fm.start_pos),
884 end: (local_end.fm.name.clone(),
885 local_end.fm.start_pos)
888 match local_begin.fm.src {
890 let start_index = local_begin.pos.to_usize();
891 let end_index = local_end.pos.to_usize();
892 let source_len = (local_begin.fm.end_pos -
893 local_begin.fm.start_pos).to_usize();
895 if start_index > end_index || end_index > source_len {
896 return Err(SpanSnippetError::MalformedForCodemap(
897 MalformedCodemapPositions {
898 name: local_begin.fm.name.clone(),
899 source_len: source_len,
900 begin_pos: local_begin.pos,
901 end_pos: local_end.pos,
905 return Ok((&src[start_index..end_index]).to_string())
908 return Err(SpanSnippetError::SourceNotAvailable {
909 filename: local_begin.fm.name.clone()
916 pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> {
917 for fm in self.files.borrow().iter() {
918 if filename == fm.name {
922 panic!("asking for {} which we don't know about", filename);
925 /// For a global BytePos compute the local offset within the containing FileMap
926 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
927 let idx = self.lookup_filemap_idx(bpos);
928 let fm = (*self.files.borrow())[idx].clone();
929 let offset = bpos - fm.start_pos;
930 FileMapAndBytePos {fm: fm, pos: offset}
933 /// Converts an absolute BytePos to a CharPos relative to the filemap.
934 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
935 let idx = self.lookup_filemap_idx(bpos);
936 let files = self.files.borrow();
937 let map = &(*files)[idx];
939 // The number of extra bytes due to multibyte chars in the FileMap
940 let mut total_extra_bytes = 0;
942 for mbc in map.multibyte_chars.borrow().iter() {
943 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
945 // every character is at least one byte, so we only
946 // count the actual extra bytes.
947 total_extra_bytes += mbc.bytes - 1;
948 // We should never see a byte position in the middle of a
950 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
956 assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
957 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
960 // Return the index of the filemap (in self.files) which contains pos.
961 fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
962 let files = self.files.borrow();
964 let count = files.len();
966 // Binary search for the filemap.
971 if files[m].start_pos > pos {
978 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
983 pub fn record_expansion(&self, expn_info: ExpnInfo) -> ExpnId {
984 let mut expansions = self.expansions.borrow_mut();
985 expansions.push(expn_info);
986 let len = expansions.len();
987 if len > u32::max_value() as usize {
988 panic!("too many ExpnInfo's!");
990 ExpnId(len as u32 - 1)
993 pub fn with_expn_info<T, F>(&self, id: ExpnId, f: F) -> T where
994 F: FnOnce(Option<&ExpnInfo>) -> T,
997 NO_EXPANSION | COMMAND_LINE_EXPN => f(None),
998 ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as usize]))
1002 /// Check if a span is "internal" to a macro in which #[unstable]
1003 /// items can be used (that is, a macro marked with
1004 /// `#[allow_internal_unstable]`).
1005 pub fn span_allows_unstable(&self, span: Span) -> bool {
1006 debug!("span_allows_unstable(span = {:?})", span);
1007 let mut allows_unstable = false;
1008 let mut expn_id = span.expn_id;
1010 let quit = self.with_expn_info(expn_id, |expninfo| {
1011 debug!("span_allows_unstable: expninfo = {:?}", expninfo);
1012 expninfo.map_or(/* hit the top level */ true, |info| {
1014 let span_comes_from_this_expansion =
1015 info.callee.span.map_or(span == info.call_site, |mac_span| {
1016 mac_span.lo <= span.lo && span.hi <= mac_span.hi
1019 debug!("span_allows_unstable: span: {:?} call_site: {:?} callee: {:?}",
1021 (info.call_site.lo, info.call_site.hi),
1022 info.callee.span.map(|x| (x.lo, x.hi)));
1023 debug!("span_allows_unstable: from this expansion? {}, allows unstable? {}",
1024 span_comes_from_this_expansion,
1025 info.callee.allow_internal_unstable);
1026 if span_comes_from_this_expansion {
1027 allows_unstable = info.callee.allow_internal_unstable;
1028 // we've found the right place, stop looking
1031 // not the right place, keep looking
1032 expn_id = info.call_site.expn_id;
1041 debug!("span_allows_unstable? {}", allows_unstable);
1046 // _____________________________________________________________________________
1047 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
1050 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1052 #[derive(Clone, PartialEq, Eq, Debug)]
1053 pub enum SpanLinesError {
1054 IllFormedSpan(Span),
1055 DistinctSources(DistinctSources),
1058 #[derive(Clone, PartialEq, Eq, Debug)]
1059 pub enum SpanSnippetError {
1060 IllFormedSpan(Span),
1061 DistinctSources(DistinctSources),
1062 MalformedForCodemap(MalformedCodemapPositions),
1063 SourceNotAvailable { filename: String }
1066 #[derive(Clone, PartialEq, Eq, Debug)]
1067 pub struct DistinctSources {
1068 begin: (String, BytePos),
1069 end: (String, BytePos)
1072 #[derive(Clone, PartialEq, Eq, Debug)]
1073 pub struct MalformedCodemapPositions {
1081 // _____________________________________________________________________________
1092 let cm = CodeMap::new();
1093 let fm = cm.new_filemap("blork.rs".to_string(),
1094 "first line.\nsecond line".to_string());
1095 fm.next_line(BytePos(0));
1096 // Test we can get lines with partial line info.
1097 assert_eq!(fm.get_line(0), Some("first line."));
1098 // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
1099 fm.next_line(BytePos(10));
1100 assert_eq!(fm.get_line(1), Some("."));
1101 fm.next_line(BytePos(12));
1102 assert_eq!(fm.get_line(2), Some("second line"));
1108 let cm = CodeMap::new();
1109 let fm = cm.new_filemap("blork.rs".to_string(),
1110 "first line.\nsecond line".to_string());
1111 // TESTING *REALLY* BROKEN BEHAVIOR:
1112 fm.next_line(BytePos(0));
1113 fm.next_line(BytePos(10));
1114 fm.next_line(BytePos(2));
1117 fn init_code_map() -> CodeMap {
1118 let cm = CodeMap::new();
1119 let fm1 = cm.new_filemap("blork.rs".to_string(),
1120 "first line.\nsecond line".to_string());
1121 let fm2 = cm.new_filemap("empty.rs".to_string(),
1123 let fm3 = cm.new_filemap("blork2.rs".to_string(),
1124 "first line.\nsecond line".to_string());
1126 fm1.next_line(BytePos(0));
1127 fm1.next_line(BytePos(12));
1128 fm2.next_line(fm2.start_pos);
1129 fm3.next_line(fm3.start_pos);
1130 fm3.next_line(fm3.start_pos + BytePos(12));
1137 // Test lookup_byte_offset
1138 let cm = init_code_map();
1140 let fmabp1 = cm.lookup_byte_offset(BytePos(23));
1141 assert_eq!(fmabp1.fm.name, "blork.rs");
1142 assert_eq!(fmabp1.pos, BytePos(23));
1144 let fmabp1 = cm.lookup_byte_offset(BytePos(24));
1145 assert_eq!(fmabp1.fm.name, "empty.rs");
1146 assert_eq!(fmabp1.pos, BytePos(0));
1148 let fmabp2 = cm.lookup_byte_offset(BytePos(25));
1149 assert_eq!(fmabp2.fm.name, "blork2.rs");
1150 assert_eq!(fmabp2.pos, BytePos(0));
1155 // Test bytepos_to_file_charpos
1156 let cm = init_code_map();
1158 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
1159 assert_eq!(cp1, CharPos(22));
1161 let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
1162 assert_eq!(cp2, CharPos(0));
1167 // Test zero-length filemaps.
1168 let cm = init_code_map();
1170 let loc1 = cm.lookup_char_pos(BytePos(22));
1171 assert_eq!(loc1.file.name, "blork.rs");
1172 assert_eq!(loc1.line, 2);
1173 assert_eq!(loc1.col, CharPos(10));
1175 let loc2 = cm.lookup_char_pos(BytePos(25));
1176 assert_eq!(loc2.file.name, "blork2.rs");
1177 assert_eq!(loc2.line, 1);
1178 assert_eq!(loc2.col, CharPos(0));
1181 fn init_code_map_mbc() -> CodeMap {
1182 let cm = CodeMap::new();
1183 // € is a three byte utf8 char.
1185 cm.new_filemap("blork.rs".to_string(),
1186 "fir€st €€€€ line.\nsecond line".to_string());
1187 let fm2 = cm.new_filemap("blork2.rs".to_string(),
1188 "first line€€.\n€ second line".to_string());
1190 fm1.next_line(BytePos(0));
1191 fm1.next_line(BytePos(28));
1192 fm2.next_line(fm2.start_pos);
1193 fm2.next_line(fm2.start_pos + BytePos(20));
1195 fm1.record_multibyte_char(BytePos(3), 3);
1196 fm1.record_multibyte_char(BytePos(9), 3);
1197 fm1.record_multibyte_char(BytePos(12), 3);
1198 fm1.record_multibyte_char(BytePos(15), 3);
1199 fm1.record_multibyte_char(BytePos(18), 3);
1200 fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
1201 fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
1202 fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
1209 // Test bytepos_to_file_charpos in the presence of multi-byte chars
1210 let cm = init_code_map_mbc();
1212 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
1213 assert_eq!(cp1, CharPos(3));
1215 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
1216 assert_eq!(cp2, CharPos(4));
1218 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
1219 assert_eq!(cp3, CharPos(12));
1221 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
1222 assert_eq!(cp4, CharPos(15));
1227 // Test span_to_lines for a span ending at the end of filemap
1228 let cm = init_code_map();
1229 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1230 let file_lines = cm.span_to_lines(span).unwrap();
1232 assert_eq!(file_lines.file.name, "blork.rs");
1233 assert_eq!(file_lines.lines.len(), 1);
1234 assert_eq!(file_lines.lines[0].line_index, 1);
1237 /// Given a string like " ^~~~~~~~~~~~ ", produces a span
1238 /// coverting that range. The idea is that the string has the same
1239 /// length as the input, and we uncover the byte positions. Note
1240 /// that this can span lines and so on.
1241 fn span_from_selection(input: &str, selection: &str) -> Span {
1242 assert_eq!(input.len(), selection.len());
1243 let left_index = selection.find('^').unwrap() as u32;
1244 let right_index = selection.rfind('~').unwrap() as u32;
1245 Span { lo: BytePos(left_index), hi: BytePos(right_index + 1), expn_id: NO_EXPANSION }
1248 /// Test span_to_snippet and span_to_lines for a span coverting 3
1249 /// lines in the middle of a file.
1251 fn span_to_snippet_and_lines_spanning_multiple_lines() {
1252 let cm = CodeMap::new();
1253 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
1254 let selection = " \n ^~\n~~~\n~~~~~ \n \n";
1255 cm.new_filemap_and_lines("blork.rs", inputtext);
1256 let span = span_from_selection(inputtext, selection);
1258 // check that we are extracting the text we thought we were extracting
1259 assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
1261 // check that span_to_lines gives us the complete result with the lines/cols we expected
1262 let lines = cm.span_to_lines(span).unwrap();
1263 let expected = vec![
1264 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
1265 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
1266 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
1268 assert_eq!(lines.lines, expected);
1273 // Test span_to_snippet for a span ending at the end of filemap
1274 let cm = init_code_map();
1275 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1276 let snippet = cm.span_to_snippet(span);
1278 assert_eq!(snippet, Ok("second line".to_string()));
1283 // Test span_to_str for a span ending at the end of filemap
1284 let cm = init_code_map();
1285 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
1286 let sstr = cm.span_to_string(span);
1288 assert_eq!(sstr, "blork.rs:2:1: 2:12");