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 from integer byte
14 //! positions to the original source code location. Each bit of source parsed during crate parsing
15 //! (typically files, in-memory strings, or various bits of macro expansion) cover a continuous
16 //! range of bytes in the CodeMap and are represented by FileMaps. Byte positions are stored in
17 //! `spans` and used pervasively in the compiler. They are absolute positions within the CodeMap,
18 //! which upon request can be converted to line and column information, source code snippets, etc.
20 pub use self::MacroFormat::*;
22 use serialize::{Encodable, Decodable, Encoder, Decoder};
23 use std::cell::RefCell;
28 fn from_uint(n: uint) -> Self;
29 fn to_uint(&self) -> uint;
32 /// A byte offset. Keep this small (currently 32-bits), as AST contains
34 #[deriving(Clone, PartialEq, Eq, Hash, PartialOrd, Show)]
35 pub struct BytePos(pub u32);
37 impl Copy for BytePos {}
39 /// A character offset. Because of multibyte utf8 characters, a byte offset
40 /// is not equivalent to a character offset. The CodeMap will convert BytePos
41 /// values to CharPos values as necessary.
42 #[deriving(PartialEq, Hash, PartialOrd, Show)]
43 pub struct CharPos(pub uint);
45 impl Copy for CharPos {}
47 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
48 // have been unsuccessful
50 impl Pos for BytePos {
51 fn from_uint(n: uint) -> BytePos { BytePos(n as u32) }
52 fn to_uint(&self) -> uint { let BytePos(n) = *self; n as uint }
55 impl Add<BytePos, BytePos> for BytePos {
56 fn add(&self, rhs: &BytePos) -> BytePos {
57 BytePos((self.to_uint() + rhs.to_uint()) as u32)
61 impl Sub<BytePos, BytePos> for BytePos {
62 fn sub(&self, rhs: &BytePos) -> BytePos {
63 BytePos((self.to_uint() - rhs.to_uint()) as u32)
67 impl Pos for CharPos {
68 fn from_uint(n: uint) -> CharPos { CharPos(n) }
69 fn to_uint(&self) -> uint { let CharPos(n) = *self; n }
72 impl Add<CharPos,CharPos> for CharPos {
73 fn add(&self, rhs: &CharPos) -> CharPos {
74 CharPos(self.to_uint() + rhs.to_uint())
78 impl Sub<CharPos,CharPos> for CharPos {
79 fn sub(&self, rhs: &CharPos) -> CharPos {
80 CharPos(self.to_uint() - rhs.to_uint())
84 /// Spans represent a region of code, used for error reporting. Positions in spans
85 /// are *absolute* positions from the beginning of the codemap, not positions
86 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
87 /// to the original source.
88 #[deriving(Clone, Show, Hash)]
92 /// Information about where the macro came from, if this piece of
93 /// code was created by a macro expansion.
99 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
101 #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)]
102 pub struct Spanned<T> {
107 impl<T:Copy> Copy for Spanned<T> {}
109 impl PartialEq for Span {
110 fn eq(&self, other: &Span) -> bool {
111 return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
113 fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
118 impl<S:Encoder<E>, E> Encodable<S, E> for Span {
119 /* Note #1972 -- spans are encoded but not decoded */
120 fn encode(&self, s: &mut S) -> Result<(), E> {
125 impl<D:Decoder<E>, E> Decodable<D, E> for Span {
126 fn decode(_d: &mut D) -> Result<Span, E> {
131 pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
132 respan(mk_sp(lo, hi), t)
135 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
136 Spanned {node: t, span: sp}
139 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
143 /* assuming that we're not in macro expansion */
144 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
145 Span {lo: lo, hi: hi, expn_id: NO_EXPANSION}
148 /// Return the span itself if it doesn't come from a macro expansion,
149 /// otherwise return the call site span up to the `enclosing_sp` by
150 /// following the `expn_info` chain.
151 pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span {
152 let call_site1 = cm.with_expn_info(sp.expn_id, |ei| ei.map(|ei| ei.call_site));
153 let call_site2 = cm.with_expn_info(enclosing_sp.expn_id, |ei| ei.map(|ei| ei.call_site));
154 match (call_site1, call_site2) {
156 (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
157 (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp),
161 /// A source code location used for error reporting
163 /// Information about the original source
164 pub file: Rc<FileMap>,
165 /// The (1-based) line number
167 /// The (0-based) column offset
171 /// A source code location used as the result of lookup_char_pos_adj
172 // Actually, *none* of the clients use the filename *or* file field;
173 // perhaps they should just be removed.
174 pub struct LocWithOpt {
175 pub filename: FileName,
178 pub file: Option<Rc<FileMap>>,
181 // used to be structural records. Better names, anyone?
182 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: uint }
183 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
185 /// The syntax with which a macro was invoked.
186 #[deriving(Clone, Hash, Show)]
187 pub enum MacroFormat {
188 /// e.g. #[deriving(...)] <item>
194 impl Copy for MacroFormat {}
196 #[deriving(Clone, Hash, Show)]
197 pub struct NameAndSpan {
198 /// The name of the macro that was invoked to create the thing
201 /// The format with which the macro was invoked.
202 pub format: MacroFormat,
203 /// The span of the macro definition itself. The macro may not
204 /// have a sensible definition span (e.g. something defined
205 /// completely inside libsyntax) in which case this is None.
206 pub span: Option<Span>
209 /// Extra information for tracking macro expansion of spans
210 #[deriving(Hash, Show)]
211 pub struct ExpnInfo {
212 /// The location of the actual macro invocation, e.g. `let x =
215 /// This may recursively refer to other macro invocations, e.g. if
216 /// `foo!()` invoked `bar!()` internally, and there was an
217 /// expression inside `bar!`; the call_site of the expression in
218 /// the expansion would point to the `bar!` invocation; that
219 /// call_site span would have its own ExpnInfo, with the call_site
220 /// pointing to the `foo!` invocation.
222 /// Information about the macro and its definition.
224 /// The `callee` of the inner expression in the `call_site`
225 /// example would point to the `macro_rules! bar { ... }` and that
226 /// of the `bar!()` invocation would point to the `macro_rules!
228 pub callee: NameAndSpan
231 #[deriving(PartialEq, Eq, Clone, Show, Hash, Encodable, Decodable)]
232 pub struct ExpnId(u32);
234 impl Copy for ExpnId {}
236 pub const NO_EXPANSION: ExpnId = ExpnId(-1);
239 pub fn from_llvm_cookie(cookie: c_uint) -> ExpnId {
240 ExpnId(cookie as u32)
243 pub fn to_llvm_cookie(self) -> i32 {
244 let ExpnId(cookie) = self;
249 pub type FileName = String;
251 pub struct FileLines {
252 pub file: Rc<FileMap>,
256 /// Identifies an offset of a multi-byte character in a FileMap
257 pub struct MultiByteChar {
258 /// The absolute offset of the character in the CodeMap
260 /// The number of bytes, >=2
264 impl Copy for MultiByteChar {}
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.slice_from(begin);
308 match slice.find('\n') {
309 Some(e) => slice.slice_to(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("\ufeff") {
354 String::from_str(src.slice_from(3))
356 String::from_str(src.as_slice())
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.slice(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>(&self, id: ExpnId, f: |Option<&ExpnInfo>| -> T) -> T {
573 NO_EXPANSION => f(None),
574 ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as uint]))
585 let cm = CodeMap::new();
586 let fm = cm.new_filemap("blork.rs".to_string(),
587 "first line.\nsecond line".to_string());
588 fm.next_line(BytePos(0));
589 assert_eq!(fm.get_line(0), Some("first line.".to_string()));
590 // TESTING BROKEN BEHAVIOR:
591 fm.next_line(BytePos(10));
592 assert_eq!(fm.get_line(1), Some(".".to_string()));
598 let cm = CodeMap::new();
599 let fm = cm.new_filemap("blork.rs".to_string(),
600 "first line.\nsecond line".to_string());
601 // TESTING *REALLY* BROKEN BEHAVIOR:
602 fm.next_line(BytePos(0));
603 fm.next_line(BytePos(10));
604 fm.next_line(BytePos(2));
607 fn init_code_map() -> CodeMap {
608 let cm = CodeMap::new();
609 let fm1 = cm.new_filemap("blork.rs".to_string(),
610 "first line.\nsecond line".to_string());
611 let fm2 = cm.new_filemap("empty.rs".to_string(),
613 let fm3 = cm.new_filemap("blork2.rs".to_string(),
614 "first line.\nsecond line".to_string());
616 fm1.next_line(BytePos(0));
617 fm1.next_line(BytePos(12));
618 fm2.next_line(BytePos(24));
619 fm3.next_line(BytePos(24));
620 fm3.next_line(BytePos(34));
627 // Test lookup_byte_offset
628 let cm = init_code_map();
630 let fmabp1 = cm.lookup_byte_offset(BytePos(22));
631 assert_eq!(fmabp1.fm.name, "blork.rs");
632 assert_eq!(fmabp1.pos, BytePos(22));
634 let fmabp2 = cm.lookup_byte_offset(BytePos(24));
635 assert_eq!(fmabp2.fm.name, "blork2.rs");
636 assert_eq!(fmabp2.pos, BytePos(0));
641 // Test bytepos_to_file_charpos
642 let cm = init_code_map();
644 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
645 assert_eq!(cp1, CharPos(22));
647 let cp2 = cm.bytepos_to_file_charpos(BytePos(24));
648 assert_eq!(cp2, CharPos(0));
653 // Test zero-length filemaps.
654 let cm = init_code_map();
656 let loc1 = cm.lookup_char_pos(BytePos(22));
657 assert_eq!(loc1.file.name, "blork.rs");
658 assert_eq!(loc1.line, 2);
659 assert_eq!(loc1.col, CharPos(10));
661 let loc2 = cm.lookup_char_pos(BytePos(24));
662 assert_eq!(loc2.file.name, "blork2.rs");
663 assert_eq!(loc2.line, 1);
664 assert_eq!(loc2.col, CharPos(0));
667 fn init_code_map_mbc() -> CodeMap {
668 let cm = CodeMap::new();
669 // € is a three byte utf8 char.
671 cm.new_filemap("blork.rs".to_string(),
672 "fir€st €€€€ line.\nsecond line".to_string());
673 let fm2 = cm.new_filemap("blork2.rs".to_string(),
674 "first line€€.\n€ second line".to_string());
676 fm1.next_line(BytePos(0));
677 fm1.next_line(BytePos(22));
678 fm2.next_line(BytePos(40));
679 fm2.next_line(BytePos(58));
681 fm1.record_multibyte_char(BytePos(3), 3);
682 fm1.record_multibyte_char(BytePos(9), 3);
683 fm1.record_multibyte_char(BytePos(12), 3);
684 fm1.record_multibyte_char(BytePos(15), 3);
685 fm1.record_multibyte_char(BytePos(18), 3);
686 fm2.record_multibyte_char(BytePos(50), 3);
687 fm2.record_multibyte_char(BytePos(53), 3);
688 fm2.record_multibyte_char(BytePos(58), 3);
695 // Test bytepos_to_file_charpos in the presence of multi-byte chars
696 let cm = init_code_map_mbc();
698 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
699 assert_eq!(cp1, CharPos(3));
701 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
702 assert_eq!(cp2, CharPos(4));
704 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
705 assert_eq!(cp3, CharPos(12));
707 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
708 assert_eq!(cp4, CharPos(15));
713 // Test span_to_lines for a span ending at the end of filemap
714 let cm = init_code_map();
715 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
716 let file_lines = cm.span_to_lines(span);
718 assert_eq!(file_lines.file.name, "blork.rs");
719 assert_eq!(file_lines.lines.len(), 1);
720 assert_eq!(file_lines.lines[0], 1u);
725 // Test span_to_snippet for a span ending at the end of filemap
726 let cm = init_code_map();
727 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
728 let snippet = cm.span_to_snippet(span);
730 assert_eq!(snippet, Some("second line".to_string()));
735 // Test span_to_str for a span ending at the end of filemap
736 let cm = init_code_map();
737 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
738 let sstr = cm.span_to_string(span);
740 assert_eq!(sstr, "blork.rs:2:1: 2:12");