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 // ignore-lexer-test FIXME #15679
13 //! The CodeMap tracks all the source code used within a single crate, mapping
14 //! from integer byte positions to the original source code location. Each bit
15 //! of source parsed during crate parsing (typically files, in-memory strings,
16 //! or various bits of macro expansion) cover a continuous range of bytes in the
17 //! CodeMap and are represented by FileMaps. Byte positions are stored in
18 //! `spans` and used pervasively in the compiler. They are absolute positions
19 //! within the CodeMap, which upon request can be converted to line and column
20 //! information, source code snippets, etc.
22 pub use self::MacroFormat::*;
24 use std::cell::RefCell;
25 use std::num::ToPrimitive;
26 use std::ops::{Add, Sub};
30 use serialize::{Encodable, Decodable, Encoder, Decoder};
33 fn from_uint(n: uint) -> Self;
34 fn to_uint(&self) -> uint;
37 /// A byte offset. Keep this small (currently 32-bits), as AST contains
39 #[deriving(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Show)]
40 pub struct BytePos(pub u32);
42 /// A character offset. Because of multibyte utf8 characters, a byte offset
43 /// is not equivalent to a character offset. The CodeMap will convert BytePos
44 /// values to CharPos values as necessary.
45 #[deriving(Copy, PartialEq, Hash, PartialOrd, Show)]
46 pub struct CharPos(pub uint);
48 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
49 // have been unsuccessful
51 impl Pos for BytePos {
52 fn from_uint(n: uint) -> BytePos { BytePos(n as u32) }
53 fn to_uint(&self) -> uint { let BytePos(n) = *self; n as uint }
56 impl Add for BytePos {
57 type Output = BytePos;
59 fn add(self, rhs: BytePos) -> BytePos {
60 BytePos((self.to_uint() + rhs.to_uint()) as u32)
64 impl Sub for BytePos {
65 type Output = BytePos;
67 fn sub(self, rhs: BytePos) -> BytePos {
68 BytePos((self.to_uint() - rhs.to_uint()) as u32)
72 impl Pos for CharPos {
73 fn from_uint(n: uint) -> CharPos { CharPos(n) }
74 fn to_uint(&self) -> uint { let CharPos(n) = *self; n }
77 impl Add for CharPos {
78 type Output = CharPos;
80 fn add(self, rhs: CharPos) -> CharPos {
81 CharPos(self.to_uint() + rhs.to_uint())
85 impl Sub for CharPos {
86 type Output = CharPos;
88 fn sub(self, rhs: CharPos) -> CharPos {
89 CharPos(self.to_uint() - rhs.to_uint())
93 /// Spans represent a region of code, used for error reporting. Positions in spans
94 /// are *absolute* positions from the beginning of the codemap, not positions
95 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
96 /// to the original source.
97 #[deriving(Clone, Copy, Show, Hash)]
101 /// Information about where the macro came from, if this piece of
102 /// code was created by a macro expansion.
106 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
108 #[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
109 pub struct Spanned<T> {
114 impl PartialEq for Span {
115 fn eq(&self, other: &Span) -> bool {
116 return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
118 fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
123 impl<S:Encoder<E>, E> Encodable<S, E> for Span {
124 /* Note #1972 -- spans are encoded but not decoded */
125 fn encode(&self, s: &mut S) -> Result<(), E> {
130 impl<D:Decoder<E>, E> Decodable<D, E> for Span {
131 fn decode(_d: &mut D) -> Result<Span, E> {
136 pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
137 respan(mk_sp(lo, hi), t)
140 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
141 Spanned {node: t, span: sp}
144 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
148 /* assuming that we're not in macro expansion */
149 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
150 Span {lo: lo, hi: hi, expn_id: NO_EXPANSION}
153 /// Return the span itself if it doesn't come from a macro expansion,
154 /// otherwise return the call site span up to the `enclosing_sp` by
155 /// following the `expn_info` chain.
156 pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span {
157 let call_site1 = cm.with_expn_info(sp.expn_id, |ei| ei.map(|ei| ei.call_site));
158 let call_site2 = cm.with_expn_info(enclosing_sp.expn_id, |ei| ei.map(|ei| ei.call_site));
159 match (call_site1, call_site2) {
161 (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
162 (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp),
166 /// A source code location used for error reporting
168 /// Information about the original source
169 pub file: Rc<FileMap>,
170 /// The (1-based) line number
172 /// The (0-based) column offset
176 /// A source code location used as the result of lookup_char_pos_adj
177 // Actually, *none* of the clients use the filename *or* file field;
178 // perhaps they should just be removed.
179 pub struct LocWithOpt {
180 pub filename: FileName,
183 pub file: Option<Rc<FileMap>>,
186 // used to be structural records. Better names, anyone?
187 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: uint }
188 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
190 /// The syntax with which a macro was invoked.
191 #[deriving(Clone, Copy, Hash, Show)]
192 pub enum MacroFormat {
193 /// e.g. #[deriving(...)] <item>
199 #[deriving(Clone, Hash, Show)]
200 pub struct NameAndSpan {
201 /// The name of the macro that was invoked to create the thing
204 /// The format with which the macro was invoked.
205 pub format: MacroFormat,
206 /// The span of the macro definition itself. The macro may not
207 /// have a sensible definition span (e.g. something defined
208 /// completely inside libsyntax) in which case this is None.
209 pub span: Option<Span>
212 /// Extra information for tracking macro expansion of spans
213 #[deriving(Hash, Show)]
214 pub struct ExpnInfo {
215 /// The location of the actual macro invocation, e.g. `let x =
218 /// This may recursively refer to other macro invocations, e.g. if
219 /// `foo!()` invoked `bar!()` internally, and there was an
220 /// expression inside `bar!`; the call_site of the expression in
221 /// the expansion would point to the `bar!` invocation; that
222 /// call_site span would have its own ExpnInfo, with the call_site
223 /// pointing to the `foo!` invocation.
225 /// Information about the macro and its definition.
227 /// The `callee` of the inner expression in the `call_site`
228 /// example would point to the `macro_rules! bar { ... }` and that
229 /// of the `bar!()` invocation would point to the `macro_rules!
231 pub callee: NameAndSpan
234 #[deriving(PartialEq, Eq, Clone, Show, Hash, RustcEncodable, RustcDecodable, Copy)]
235 pub struct ExpnId(u32);
237 pub const NO_EXPANSION: ExpnId = ExpnId(-1);
240 pub fn from_llvm_cookie(cookie: c_uint) -> ExpnId {
241 ExpnId(cookie as u32)
244 pub fn to_llvm_cookie(self) -> i32 {
245 let ExpnId(cookie) = self;
250 pub type FileName = String;
252 pub struct FileLines {
253 pub file: Rc<FileMap>,
257 /// Identifies an offset of a multi-byte character in a FileMap
259 pub struct MultiByteChar {
260 /// The absolute offset of the character in the CodeMap
262 /// The number of bytes, >=2
266 /// A single source in the CodeMap
268 /// The name of the file that the source came from, source that doesn't
269 /// originate from files has names between angle brackets by convention,
272 /// The complete source code
274 /// The start position of this source in the CodeMap
275 pub start_pos: BytePos,
276 /// Locations of lines beginnings in the source code
277 pub lines: RefCell<Vec<BytePos> >,
278 /// Locations of multi-byte characters in the source code
279 pub multibyte_chars: RefCell<Vec<MultiByteChar> >,
283 /// EFFECT: register a start-of-line offset in the
284 /// table of line-beginnings.
285 /// UNCHECKED INVARIANT: these offsets must be added in the right
286 /// order and must be in the right places; there is shared knowledge
287 /// about what ends a line between this file and parse.rs
288 /// WARNING: pos param here is the offset relative to start of CodeMap,
289 /// and CodeMap will append a newline when adding a filemap without a newline at the end,
290 /// so the safe way to call this is with value calculated as
291 /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
292 pub fn next_line(&self, pos: BytePos) {
293 // the new charpos must be > the last one (or it's the first one).
294 let mut lines = self.lines.borrow_mut();
295 let line_len = lines.len();
296 assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
300 /// get a line from the list of pre-computed line-beginnings
302 pub fn get_line(&self, line_number: uint) -> Option<String> {
303 let lines = self.lines.borrow();
304 lines.get(line_number).map(|&line| {
305 let begin: BytePos = line - self.start_pos;
306 let begin = begin.to_uint();
307 let slice = self.src[begin..];
308 match slice.find('\n') {
309 Some(e) => slice[0..e],
315 pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) {
316 assert!(bytes >=2 && bytes <= 4);
317 let mbc = MultiByteChar {
321 self.multibyte_chars.borrow_mut().push(mbc);
324 pub fn is_real_file(&self) -> bool {
325 !(self.name.starts_with("<") &&
326 self.name.ends_with(">"))
331 pub files: RefCell<Vec<Rc<FileMap>>>,
332 expansions: RefCell<Vec<ExpnInfo>>
336 pub fn new() -> CodeMap {
338 files: RefCell::new(Vec::new()),
339 expansions: RefCell::new(Vec::new()),
343 pub fn new_filemap(&self, filename: FileName, src: String) -> Rc<FileMap> {
344 let mut files = self.files.borrow_mut();
345 let start_pos = match files.last() {
347 Some(last) => last.start_pos.to_uint() + last.src.len(),
350 // Remove utf-8 BOM if any.
351 // FIXME #12884: no efficient/safe way to remove from the start of a string
352 // and reuse the allocation.
353 let mut src = if src.starts_with("\u{feff}") {
354 String::from_str(src[3..])
356 String::from_str(src[])
359 // Append '\n' in case it's not already there.
360 // This is a workaround to prevent CodeMap.lookup_filemap_idx from accidentally
361 // overflowing into the next filemap in case the last byte of span is also the last
362 // byte of filemap, which leads to incorrect results from CodeMap.span_to_*.
363 if src.len() > 0 && !src.ends_with("\n") {
367 let filemap = Rc::new(FileMap {
369 src: src.to_string(),
370 start_pos: Pos::from_uint(start_pos),
371 lines: RefCell::new(Vec::new()),
372 multibyte_chars: RefCell::new(Vec::new()),
375 files.push(filemap.clone());
380 pub fn mk_substr_filename(&self, sp: Span) -> String {
381 let pos = self.lookup_char_pos(sp.lo);
382 (format!("<{}:{}:{}>",
385 pos.col.to_uint() + 1)).to_string()
388 /// Lookup source information about a BytePos
389 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
393 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
394 let loc = self.lookup_char_pos(pos);
396 filename: loc.file.name.to_string(),
403 pub fn span_to_string(&self, sp: Span) -> String {
404 if self.files.borrow().len() == 0 && sp == DUMMY_SP {
405 return "no-location".to_string();
408 let lo = self.lookup_char_pos_adj(sp.lo);
409 let hi = self.lookup_char_pos_adj(sp.hi);
410 return (format!("{}:{}:{}: {}:{}",
413 lo.col.to_uint() + 1,
415 hi.col.to_uint() + 1)).to_string()
418 pub fn span_to_filename(&self, sp: Span) -> FileName {
419 self.lookup_char_pos(sp.lo).file.name.to_string()
422 pub fn span_to_lines(&self, sp: Span) -> FileLines {
423 let lo = self.lookup_char_pos(sp.lo);
424 let hi = self.lookup_char_pos(sp.hi);
425 let mut lines = Vec::new();
426 for i in range(lo.line - 1u, hi.line as uint) {
429 FileLines {file: lo.file, lines: lines}
432 pub fn span_to_snippet(&self, sp: Span) -> Option<String> {
433 let begin = self.lookup_byte_offset(sp.lo);
434 let end = self.lookup_byte_offset(sp.hi);
436 // FIXME #8256: this used to be an assert but whatever precondition
437 // it's testing isn't true for all spans in the AST, so to allow the
438 // caller to not have to panic (and it can't catch it since the CodeMap
439 // isn't sendable), return None
440 if begin.fm.start_pos != end.fm.start_pos {
443 Some(begin.fm.src[begin.pos.to_uint()..
444 end.pos.to_uint()].to_string())
448 pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> {
449 for fm in self.files.borrow().iter() {
450 if filename == fm.name {
454 panic!("asking for {} which we don't know about", filename);
457 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
458 let idx = self.lookup_filemap_idx(bpos);
459 let fm = (*self.files.borrow())[idx].clone();
460 let offset = bpos - fm.start_pos;
461 FileMapAndBytePos {fm: fm, pos: offset}
464 /// Converts an absolute BytePos to a CharPos relative to the filemap and above.
465 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
466 let idx = self.lookup_filemap_idx(bpos);
467 let files = self.files.borrow();
468 let map = &(*files)[idx];
470 // The number of extra bytes due to multibyte chars in the FileMap
471 let mut total_extra_bytes = 0;
473 for mbc in map.multibyte_chars.borrow().iter() {
474 debug!("{}-byte char at {}", mbc.bytes, mbc.pos);
476 // every character is at least one byte, so we only
477 // count the actual extra bytes.
478 total_extra_bytes += mbc.bytes - 1;
479 // We should never see a byte position in the middle of a
481 assert!(bpos.to_uint() >= mbc.pos.to_uint() + mbc.bytes);
487 assert!(map.start_pos.to_uint() + total_extra_bytes <= bpos.to_uint());
488 CharPos(bpos.to_uint() - map.start_pos.to_uint() - total_extra_bytes)
491 fn lookup_filemap_idx(&self, pos: BytePos) -> uint {
492 let files = self.files.borrow();
494 let len = files.len();
498 let m = (a + b) / 2u;
499 if files[m].start_pos > pos {
505 // There can be filemaps with length 0. These have the same start_pos as
506 // the previous filemap, but are not the filemaps we want (because they
507 // are length 0, they cannot contain what we are looking for). So,
508 // rewind until we find a useful filemap.
510 let lines = files[a].lines.borrow();
516 panic!("position {} does not resolve to a source location",
522 panic!("position {} does not resolve to a source location",
529 fn lookup_line(&self, pos: BytePos) -> FileMapAndLine {
530 let idx = self.lookup_filemap_idx(pos);
532 let files = self.files.borrow();
533 let f = (*files)[idx].clone();
536 let lines = f.lines.borrow();
537 let mut b = lines.len();
539 let m = (a + b) / 2u;
540 if (*lines)[m] > pos { b = m; } else { a = m; }
543 FileMapAndLine {fm: f, line: a}
546 fn lookup_pos(&self, pos: BytePos) -> Loc {
547 let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos);
548 let line = a + 1u; // Line numbers start at 1
549 let chpos = self.bytepos_to_file_charpos(pos);
550 let linebpos = (*f.lines.borrow())[a];
551 let linechpos = self.bytepos_to_file_charpos(linebpos);
552 debug!("byte pos {} is on the line at byte pos {}",
554 debug!("char pos {} is on the line at char pos {}",
556 debug!("byte is on line: {}", line);
557 assert!(chpos >= linechpos);
561 col: chpos - linechpos
565 pub fn record_expansion(&self, expn_info: ExpnInfo) -> ExpnId {
566 let mut expansions = self.expansions.borrow_mut();
567 expansions.push(expn_info);
568 ExpnId(expansions.len().to_u32().expect("too many ExpnInfo's!") - 1)
571 pub fn with_expn_info<T, F>(&self, id: ExpnId, f: F) -> T where
572 F: FnOnce(Option<&ExpnInfo>) -> T,
575 NO_EXPANSION => f(None),
576 ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as uint]))
580 /// Check if a span is "internal" to a macro. This means that it is entirely generated by a
581 /// macro expansion and contains no code that was passed in as an argument.
582 pub fn span_is_internal(&self, span: Span) -> bool {
583 // first, check if the given expression was generated by a macro or not
584 // we need to go back the expn_info tree to check only the arguments
585 // of the initial macro call, not the nested ones.
586 let mut is_internal = false;
587 let mut expnid = span.expn_id;
588 while self.with_expn_info(expnid, |expninfo| {
591 // save the parent expn_id for next loop iteration
592 expnid = info.call_site.expn_id;
593 if info.callee.span.is_none() {
594 // it's a compiler built-in, we *really* don't want to mess with it
595 // so we skip it, unless it was called by a regular macro, in which case
596 // we will handle the caller macro next turn
598 true // continue looping
600 // was this expression from the current macro arguments ?
601 is_internal = !( span.lo > info.call_site.lo &&
602 span.hi < info.call_site.hi );
603 true // continue looping
606 _ => false // stop looping
608 }) { /* empty while loop body */ }
619 let cm = CodeMap::new();
620 let fm = cm.new_filemap("blork.rs".to_string(),
621 "first line.\nsecond line".to_string());
622 fm.next_line(BytePos(0));
623 assert_eq!(fm.get_line(0), Some("first line.".to_string()));
624 // TESTING BROKEN BEHAVIOR:
625 fm.next_line(BytePos(10));
626 assert_eq!(fm.get_line(1), Some(".".to_string()));
632 let cm = CodeMap::new();
633 let fm = cm.new_filemap("blork.rs".to_string(),
634 "first line.\nsecond line".to_string());
635 // TESTING *REALLY* BROKEN BEHAVIOR:
636 fm.next_line(BytePos(0));
637 fm.next_line(BytePos(10));
638 fm.next_line(BytePos(2));
641 fn init_code_map() -> CodeMap {
642 let cm = CodeMap::new();
643 let fm1 = cm.new_filemap("blork.rs".to_string(),
644 "first line.\nsecond line".to_string());
645 let fm2 = cm.new_filemap("empty.rs".to_string(),
647 let fm3 = cm.new_filemap("blork2.rs".to_string(),
648 "first line.\nsecond line".to_string());
650 fm1.next_line(BytePos(0));
651 fm1.next_line(BytePos(12));
652 fm2.next_line(BytePos(24));
653 fm3.next_line(BytePos(24));
654 fm3.next_line(BytePos(34));
661 // Test lookup_byte_offset
662 let cm = init_code_map();
664 let fmabp1 = cm.lookup_byte_offset(BytePos(22));
665 assert_eq!(fmabp1.fm.name, "blork.rs");
666 assert_eq!(fmabp1.pos, BytePos(22));
668 let fmabp2 = cm.lookup_byte_offset(BytePos(24));
669 assert_eq!(fmabp2.fm.name, "blork2.rs");
670 assert_eq!(fmabp2.pos, BytePos(0));
675 // Test bytepos_to_file_charpos
676 let cm = init_code_map();
678 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
679 assert_eq!(cp1, CharPos(22));
681 let cp2 = cm.bytepos_to_file_charpos(BytePos(24));
682 assert_eq!(cp2, CharPos(0));
687 // Test zero-length filemaps.
688 let cm = init_code_map();
690 let loc1 = cm.lookup_char_pos(BytePos(22));
691 assert_eq!(loc1.file.name, "blork.rs");
692 assert_eq!(loc1.line, 2);
693 assert_eq!(loc1.col, CharPos(10));
695 let loc2 = cm.lookup_char_pos(BytePos(24));
696 assert_eq!(loc2.file.name, "blork2.rs");
697 assert_eq!(loc2.line, 1);
698 assert_eq!(loc2.col, CharPos(0));
701 fn init_code_map_mbc() -> CodeMap {
702 let cm = CodeMap::new();
703 // € is a three byte utf8 char.
705 cm.new_filemap("blork.rs".to_string(),
706 "fir€st €€€€ line.\nsecond line".to_string());
707 let fm2 = cm.new_filemap("blork2.rs".to_string(),
708 "first line€€.\n€ second line".to_string());
710 fm1.next_line(BytePos(0));
711 fm1.next_line(BytePos(22));
712 fm2.next_line(BytePos(40));
713 fm2.next_line(BytePos(58));
715 fm1.record_multibyte_char(BytePos(3), 3);
716 fm1.record_multibyte_char(BytePos(9), 3);
717 fm1.record_multibyte_char(BytePos(12), 3);
718 fm1.record_multibyte_char(BytePos(15), 3);
719 fm1.record_multibyte_char(BytePos(18), 3);
720 fm2.record_multibyte_char(BytePos(50), 3);
721 fm2.record_multibyte_char(BytePos(53), 3);
722 fm2.record_multibyte_char(BytePos(58), 3);
729 // Test bytepos_to_file_charpos in the presence of multi-byte chars
730 let cm = init_code_map_mbc();
732 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
733 assert_eq!(cp1, CharPos(3));
735 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
736 assert_eq!(cp2, CharPos(4));
738 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
739 assert_eq!(cp3, CharPos(12));
741 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
742 assert_eq!(cp4, CharPos(15));
747 // Test span_to_lines for a span ending at the end of filemap
748 let cm = init_code_map();
749 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
750 let file_lines = cm.span_to_lines(span);
752 assert_eq!(file_lines.file.name, "blork.rs");
753 assert_eq!(file_lines.lines.len(), 1);
754 assert_eq!(file_lines.lines[0], 1u);
759 // Test span_to_snippet for a span ending at the end of filemap
760 let cm = init_code_map();
761 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
762 let snippet = cm.span_to_snippet(span);
764 assert_eq!(snippet, Some("second line".to_string()));
769 // Test span_to_str for a span ending at the end of filemap
770 let cm = init_code_map();
771 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
772 let sstr = cm.span_to_string(span);
774 assert_eq!(sstr, "blork.rs:2:1: 2:12");