]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/codemap.rs
doc: remove incomplete sentence
[rust.git] / src / libsyntax / codemap.rs
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.
4 //
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.
10 //
11 // ignore-lexer-test FIXME #15679
12
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.
21
22 pub use self::MacroFormat::*;
23
24 use std::cell::RefCell;
25 use std::num::ToPrimitive;
26 use std::ops::{Add, Sub};
27 use std::rc::Rc;
28
29 use libc::c_uint;
30 use serialize::{Encodable, Decodable, Encoder, Decoder};
31
32 pub trait Pos {
33     fn from_uint(n: uint) -> Self;
34     fn to_uint(&self) -> uint;
35 }
36
37 /// A byte offset. Keep this small (currently 32-bits), as AST contains
38 /// a lot of them.
39 #[deriving(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Show)]
40 pub struct BytePos(pub u32);
41
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);
47
48 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
49 // have been unsuccessful
50
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 }
54 }
55
56 impl Add for BytePos {
57     type Output = BytePos;
58
59     fn add(self, rhs: BytePos) -> BytePos {
60         BytePos((self.to_uint() + rhs.to_uint()) as u32)
61     }
62 }
63
64 impl Sub for BytePos {
65     type Output = BytePos;
66
67     fn sub(self, rhs: BytePos) -> BytePos {
68         BytePos((self.to_uint() - rhs.to_uint()) as u32)
69     }
70 }
71
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 }
75 }
76
77 impl Add for CharPos {
78     type Output = CharPos;
79
80     fn add(self, rhs: CharPos) -> CharPos {
81         CharPos(self.to_uint() + rhs.to_uint())
82     }
83 }
84
85 impl Sub for CharPos {
86     type Output = CharPos;
87
88     fn sub(self, rhs: CharPos) -> CharPos {
89         CharPos(self.to_uint() - rhs.to_uint())
90     }
91 }
92
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)]
98 pub struct Span {
99     pub lo: BytePos,
100     pub hi: BytePos,
101     /// Information about where the macro came from, if this piece of
102     /// code was created by a macro expansion.
103     pub expn_id: ExpnId
104 }
105
106 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
107
108 #[deriving(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show, Copy)]
109 pub struct Spanned<T> {
110     pub node: T,
111     pub span: Span,
112 }
113
114 impl PartialEq for Span {
115     fn eq(&self, other: &Span) -> bool {
116         return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
117     }
118     fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
119 }
120
121 impl Eq for Span {}
122
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> {
126         s.emit_nil()
127     }
128 }
129
130 impl<D:Decoder<E>, E> Decodable<D, E> for Span {
131     fn decode(_d: &mut D) -> Result<Span, E> {
132         Ok(DUMMY_SP)
133     }
134 }
135
136 pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
137     respan(mk_sp(lo, hi), t)
138 }
139
140 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
141     Spanned {node: t, span: sp}
142 }
143
144 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
145     respan(DUMMY_SP, t)
146 }
147
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}
151 }
152
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) {
160         (None, _) => sp,
161         (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
162         (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp),
163     }
164 }
165
166 /// A source code location used for error reporting
167 pub struct Loc {
168     /// Information about the original source
169     pub file: Rc<FileMap>,
170     /// The (1-based) line number
171     pub line: uint,
172     /// The (0-based) column offset
173     pub col: CharPos
174 }
175
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,
181     pub line: uint,
182     pub col: CharPos,
183     pub file: Option<Rc<FileMap>>,
184 }
185
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 }
189
190 /// The syntax with which a macro was invoked.
191 #[deriving(Clone, Copy, Hash, Show)]
192 pub enum MacroFormat {
193     /// e.g. #[deriving(...)] <item>
194     MacroAttribute,
195     /// e.g. `format!()`
196     MacroBang
197 }
198
199 #[deriving(Clone, Hash, Show)]
200 pub struct NameAndSpan {
201     /// The name of the macro that was invoked to create the thing
202     /// with this Span.
203     pub name: String,
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>
210 }
211
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 =
216     /// foo!();`
217     ///
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.
224     pub call_site: Span,
225     /// Information about the macro and its definition.
226     ///
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!
230     /// foo { ... }`.
231     pub callee: NameAndSpan
232 }
233
234 #[deriving(PartialEq, Eq, Clone, Show, Hash, RustcEncodable, RustcDecodable, Copy)]
235 pub struct ExpnId(u32);
236
237 pub const NO_EXPANSION: ExpnId = ExpnId(-1);
238
239 impl ExpnId {
240     pub fn from_llvm_cookie(cookie: c_uint) -> ExpnId {
241         ExpnId(cookie as u32)
242     }
243
244     pub fn to_llvm_cookie(self) -> i32 {
245         let ExpnId(cookie) = self;
246         cookie as i32
247     }
248 }
249
250 pub type FileName = String;
251
252 pub struct FileLines {
253     pub file: Rc<FileMap>,
254     pub lines: Vec<uint>
255 }
256
257 /// Identifies an offset of a multi-byte character in a FileMap
258 #[deriving(Copy)]
259 pub struct MultiByteChar {
260     /// The absolute offset of the character in the CodeMap
261     pub pos: BytePos,
262     /// The number of bytes, >=2
263     pub bytes: uint,
264 }
265
266 /// A single source in the CodeMap
267 pub struct FileMap {
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,
270     /// e.g. `<anon>`
271     pub name: FileName,
272     /// The complete source code
273     pub src: String,
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> >,
280 }
281
282 impl FileMap {
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));
297         lines.push(pos);
298     }
299
300     /// get a line from the list of pre-computed line-beginnings
301     ///
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],
310                 None => slice
311             }.to_string()
312         })
313     }
314
315     pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) {
316         assert!(bytes >=2 && bytes <= 4);
317         let mbc = MultiByteChar {
318             pos: pos,
319             bytes: bytes,
320         };
321         self.multibyte_chars.borrow_mut().push(mbc);
322     }
323
324     pub fn is_real_file(&self) -> bool {
325         !(self.name.starts_with("<") &&
326           self.name.ends_with(">"))
327     }
328 }
329
330 pub struct CodeMap {
331     pub files: RefCell<Vec<Rc<FileMap>>>,
332     expansions: RefCell<Vec<ExpnInfo>>
333 }
334
335 impl CodeMap {
336     pub fn new() -> CodeMap {
337         CodeMap {
338             files: RefCell::new(Vec::new()),
339             expansions: RefCell::new(Vec::new()),
340         }
341     }
342
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() {
346             None => 0,
347             Some(last) => last.start_pos.to_uint() + last.src.len(),
348         };
349
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..])
355         } else {
356             String::from_str(src[])
357         };
358
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") {
364             src.push('\n');
365         }
366
367         let filemap = Rc::new(FileMap {
368             name: filename,
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()),
373         });
374
375         files.push(filemap.clone());
376
377         filemap
378     }
379
380     pub fn mk_substr_filename(&self, sp: Span) -> String {
381         let pos = self.lookup_char_pos(sp.lo);
382         (format!("<{}:{}:{}>",
383                  pos.file.name,
384                  pos.line,
385                  pos.col.to_uint() + 1)).to_string()
386     }
387
388     /// Lookup source information about a BytePos
389     pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
390         self.lookup_pos(pos)
391     }
392
393     pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
394         let loc = self.lookup_char_pos(pos);
395         LocWithOpt {
396             filename: loc.file.name.to_string(),
397             line: loc.line,
398             col: loc.col,
399             file: Some(loc.file)
400         }
401     }
402
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();
406         }
407
408         let lo = self.lookup_char_pos_adj(sp.lo);
409         let hi = self.lookup_char_pos_adj(sp.hi);
410         return (format!("{}:{}:{}: {}:{}",
411                         lo.filename,
412                         lo.line,
413                         lo.col.to_uint() + 1,
414                         hi.line,
415                         hi.col.to_uint() + 1)).to_string()
416     }
417
418     pub fn span_to_filename(&self, sp: Span) -> FileName {
419         self.lookup_char_pos(sp.lo).file.name.to_string()
420     }
421
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) {
427             lines.push(i);
428         };
429         FileLines {file: lo.file, lines: lines}
430     }
431
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);
435
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 {
441             None
442         } else {
443             Some(begin.fm.src[begin.pos.to_uint()..
444                               end.pos.to_uint()].to_string())
445         }
446     }
447
448     pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> {
449         for fm in self.files.borrow().iter() {
450             if filename == fm.name {
451                 return fm.clone();
452             }
453         }
454         panic!("asking for {} which we don't know about", filename);
455     }
456
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}
462     }
463
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];
469
470         // The number of extra bytes due to multibyte chars in the FileMap
471         let mut total_extra_bytes = 0;
472
473         for mbc in map.multibyte_chars.borrow().iter() {
474             debug!("{}-byte char at {}", mbc.bytes, mbc.pos);
475             if mbc.pos < bpos {
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
480                 // character
481                 assert!(bpos.to_uint() >= mbc.pos.to_uint() + mbc.bytes);
482             } else {
483                 break;
484             }
485         }
486
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)
489     }
490
491     fn lookup_filemap_idx(&self, pos: BytePos) -> uint {
492         let files = self.files.borrow();
493         let files = &*files;
494         let len = files.len();
495         let mut a = 0u;
496         let mut b = len;
497         while b - a > 1u {
498             let m = (a + b) / 2u;
499             if files[m].start_pos > pos {
500                 b = m;
501             } else {
502                 a = m;
503             }
504         }
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.
509         loop {
510             let lines = files[a].lines.borrow();
511             let lines = lines;
512             if lines.len() > 0 {
513                 break;
514             }
515             if a == 0 {
516                 panic!("position {} does not resolve to a source location",
517                       pos.to_uint());
518             }
519             a -= 1;
520         }
521         if a >= len {
522             panic!("position {} does not resolve to a source location",
523                   pos.to_uint())
524         }
525
526         return a;
527     }
528
529     fn lookup_line(&self, pos: BytePos) -> FileMapAndLine {
530         let idx = self.lookup_filemap_idx(pos);
531
532         let files = self.files.borrow();
533         let f = (*files)[idx].clone();
534         let mut a = 0u;
535         {
536             let lines = f.lines.borrow();
537             let mut b = lines.len();
538             while b - a > 1u {
539                 let m = (a + b) / 2u;
540                 if (*lines)[m] > pos { b = m; } else { a = m; }
541             }
542         }
543         FileMapAndLine {fm: f, line: a}
544     }
545
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 {}",
553                pos, linebpos);
554         debug!("char pos {} is on the line at char pos {}",
555                chpos, linechpos);
556         debug!("byte is on line: {}", line);
557         assert!(chpos >= linechpos);
558         Loc {
559             file: f,
560             line: line,
561             col: chpos - linechpos
562         }
563     }
564
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)
569     }
570
571     pub fn with_expn_info<T, F>(&self, id: ExpnId, f: F) -> T where
572         F: FnOnce(Option<&ExpnInfo>) -> T,
573     {
574         match id {
575             NO_EXPANSION => f(None),
576             ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as uint]))
577         }
578     }
579
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| {
589             match expninfo {
590                 Some(ref info) => {
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
597                         is_internal = true;
598                         true // continue looping
599                     } else {
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
604                     }
605                 },
606                 _ => false // stop looping
607             }
608         }) { /* empty while loop body */ }
609         return is_internal;
610     }
611 }
612
613 #[cfg(test)]
614 mod test {
615     use super::*;
616
617     #[test]
618     fn t1 () {
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()));
627     }
628
629     #[test]
630     #[should_fail]
631     fn t2 () {
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));
639     }
640
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(),
646                                  "".to_string());
647         let fm3 = cm.new_filemap("blork2.rs".to_string(),
648                                  "first line.\nsecond line".to_string());
649
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));
655
656         cm
657     }
658
659     #[test]
660     fn t3() {
661         // Test lookup_byte_offset
662         let cm = init_code_map();
663
664         let fmabp1 = cm.lookup_byte_offset(BytePos(22));
665         assert_eq!(fmabp1.fm.name, "blork.rs");
666         assert_eq!(fmabp1.pos, BytePos(22));
667
668         let fmabp2 = cm.lookup_byte_offset(BytePos(24));
669         assert_eq!(fmabp2.fm.name, "blork2.rs");
670         assert_eq!(fmabp2.pos, BytePos(0));
671     }
672
673     #[test]
674     fn t4() {
675         // Test bytepos_to_file_charpos
676         let cm = init_code_map();
677
678         let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
679         assert_eq!(cp1, CharPos(22));
680
681         let cp2 = cm.bytepos_to_file_charpos(BytePos(24));
682         assert_eq!(cp2, CharPos(0));
683     }
684
685     #[test]
686     fn t5() {
687         // Test zero-length filemaps.
688         let cm = init_code_map();
689
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));
694
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));
699     }
700
701     fn init_code_map_mbc() -> CodeMap {
702         let cm = CodeMap::new();
703         // € is a three byte utf8 char.
704         let fm1 =
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());
709
710         fm1.next_line(BytePos(0));
711         fm1.next_line(BytePos(22));
712         fm2.next_line(BytePos(40));
713         fm2.next_line(BytePos(58));
714
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);
723
724         cm
725     }
726
727     #[test]
728     fn t6() {
729         // Test bytepos_to_file_charpos in the presence of multi-byte chars
730         let cm = init_code_map_mbc();
731
732         let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
733         assert_eq!(cp1, CharPos(3));
734
735         let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
736         assert_eq!(cp2, CharPos(4));
737
738         let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
739         assert_eq!(cp3, CharPos(12));
740
741         let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
742         assert_eq!(cp4, CharPos(15));
743     }
744
745     #[test]
746     fn t7() {
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);
751
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);
755     }
756
757     #[test]
758     fn t8() {
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);
763
764         assert_eq!(snippet, Some("second line".to_string()));
765     }
766
767     #[test]
768     fn t9() {
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);
773
774         assert_eq!(sstr, "blork.rs:2:1: 2:12");
775     }
776 }