]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/codemap.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[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 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.
19
20 pub use self::MacroFormat::*;
21
22 use serialize::{Encodable, Decodable, Encoder, Decoder};
23 use std::cell::RefCell;
24 use std::rc::Rc;
25 use libc::c_uint;
26
27 pub trait Pos {
28     fn from_uint(n: uint) -> Self;
29     fn to_uint(&self) -> uint;
30 }
31
32 /// A byte offset. Keep this small (currently 32-bits), as AST contains
33 /// a lot of them.
34 #[deriving(Clone, PartialEq, Eq, Hash, PartialOrd, Show)]
35 pub struct BytePos(pub u32);
36
37 impl Copy for BytePos {}
38
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);
44
45 impl Copy for CharPos {}
46
47 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
48 // have been unsuccessful
49
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 }
53 }
54
55 impl Add<BytePos, BytePos> for BytePos {
56     fn add(&self, rhs: &BytePos) -> BytePos {
57         BytePos((self.to_uint() + rhs.to_uint()) as u32)
58     }
59 }
60
61 impl Sub<BytePos, BytePos> for BytePos {
62     fn sub(&self, rhs: &BytePos) -> BytePos {
63         BytePos((self.to_uint() - rhs.to_uint()) as u32)
64     }
65 }
66
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 }
70 }
71
72 impl Add<CharPos,CharPos> for CharPos {
73     fn add(&self, rhs: &CharPos) -> CharPos {
74         CharPos(self.to_uint() + rhs.to_uint())
75     }
76 }
77
78 impl Sub<CharPos,CharPos> for CharPos {
79     fn sub(&self, rhs: &CharPos) -> CharPos {
80         CharPos(self.to_uint() - rhs.to_uint())
81     }
82 }
83
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)]
89 pub struct Span {
90     pub lo: BytePos,
91     pub hi: BytePos,
92     /// Information about where the macro came from, if this piece of
93     /// code was created by a macro expansion.
94     pub expn_id: ExpnId
95 }
96
97 impl Copy for Span {}
98
99 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
100
101 #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Show)]
102 pub struct Spanned<T> {
103     pub node: T,
104     pub span: Span,
105 }
106
107 impl<T:Copy> Copy for Spanned<T> {}
108
109 impl PartialEq for Span {
110     fn eq(&self, other: &Span) -> bool {
111         return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
112     }
113     fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
114 }
115
116 impl Eq for Span {}
117
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> {
121         s.emit_nil()
122     }
123 }
124
125 impl<D:Decoder<E>, E> Decodable<D, E> for Span {
126     fn decode(_d: &mut D) -> Result<Span, E> {
127         Ok(DUMMY_SP)
128     }
129 }
130
131 pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
132     respan(mk_sp(lo, hi), t)
133 }
134
135 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
136     Spanned {node: t, span: sp}
137 }
138
139 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
140     respan(DUMMY_SP, t)
141 }
142
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}
146 }
147
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) {
155         (None, _) => sp,
156         (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
157         (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp),
158     }
159 }
160
161 /// A source code location used for error reporting
162 pub struct Loc {
163     /// Information about the original source
164     pub file: Rc<FileMap>,
165     /// The (1-based) line number
166     pub line: uint,
167     /// The (0-based) column offset
168     pub col: CharPos
169 }
170
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,
176     pub line: uint,
177     pub col: CharPos,
178     pub file: Option<Rc<FileMap>>,
179 }
180
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 }
184
185 /// The syntax with which a macro was invoked.
186 #[deriving(Clone, Hash, Show)]
187 pub enum MacroFormat {
188     /// e.g. #[deriving(...)] <item>
189     MacroAttribute,
190     /// e.g. `format!()`
191     MacroBang
192 }
193
194 impl Copy for MacroFormat {}
195
196 #[deriving(Clone, Hash, Show)]
197 pub struct NameAndSpan {
198     /// The name of the macro that was invoked to create the thing
199     /// with this Span.
200     pub name: String,
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>
207 }
208
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 =
213     /// foo!();`
214     ///
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.
221     pub call_site: Span,
222     /// Information about the macro and its definition.
223     ///
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!
227     /// foo { ... }`.
228     pub callee: NameAndSpan
229 }
230
231 #[deriving(PartialEq, Eq, Clone, Show, Hash, Encodable, Decodable)]
232 pub struct ExpnId(u32);
233
234 impl Copy for ExpnId {}
235
236 pub const NO_EXPANSION: ExpnId = ExpnId(-1);
237
238 impl ExpnId {
239     pub fn from_llvm_cookie(cookie: c_uint) -> ExpnId {
240         ExpnId(cookie as u32)
241     }
242
243     pub fn to_llvm_cookie(self) -> i32 {
244         let ExpnId(cookie) = self;
245         cookie as i32
246     }
247 }
248
249 pub type FileName = String;
250
251 pub struct FileLines {
252     pub file: Rc<FileMap>,
253     pub lines: Vec<uint>
254 }
255
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
259     pub pos: BytePos,
260     /// The number of bytes, >=2
261     pub bytes: uint,
262 }
263
264 impl Copy for MultiByteChar {}
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.slice_from(begin);
308             match slice.find('\n') {
309                 Some(e) => slice.slice_to(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("\ufeff") {
354             String::from_str(src.slice_from(3))
355         } else {
356             String::from_str(src.as_slice())
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.slice(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>(&self, id: ExpnId, f: |Option<&ExpnInfo>| -> T) -> T {
572         match id {
573             NO_EXPANSION => f(None),
574             ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as uint]))
575         }
576     }
577 }
578
579 #[cfg(test)]
580 mod test {
581     use super::*;
582
583     #[test]
584     fn t1 () {
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()));
593     }
594
595     #[test]
596     #[should_fail]
597     fn t2 () {
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));
605     }
606
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(),
612                                  "".to_string());
613         let fm3 = cm.new_filemap("blork2.rs".to_string(),
614                                  "first line.\nsecond line".to_string());
615
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));
621
622         cm
623     }
624
625     #[test]
626     fn t3() {
627         // Test lookup_byte_offset
628         let cm = init_code_map();
629
630         let fmabp1 = cm.lookup_byte_offset(BytePos(22));
631         assert_eq!(fmabp1.fm.name, "blork.rs");
632         assert_eq!(fmabp1.pos, BytePos(22));
633
634         let fmabp2 = cm.lookup_byte_offset(BytePos(24));
635         assert_eq!(fmabp2.fm.name, "blork2.rs");
636         assert_eq!(fmabp2.pos, BytePos(0));
637     }
638
639     #[test]
640     fn t4() {
641         // Test bytepos_to_file_charpos
642         let cm = init_code_map();
643
644         let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
645         assert_eq!(cp1, CharPos(22));
646
647         let cp2 = cm.bytepos_to_file_charpos(BytePos(24));
648         assert_eq!(cp2, CharPos(0));
649     }
650
651     #[test]
652     fn t5() {
653         // Test zero-length filemaps.
654         let cm = init_code_map();
655
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));
660
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));
665     }
666
667     fn init_code_map_mbc() -> CodeMap {
668         let cm = CodeMap::new();
669         // € is a three byte utf8 char.
670         let fm1 =
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());
675
676         fm1.next_line(BytePos(0));
677         fm1.next_line(BytePos(22));
678         fm2.next_line(BytePos(40));
679         fm2.next_line(BytePos(58));
680
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);
689
690         cm
691     }
692
693     #[test]
694     fn t6() {
695         // Test bytepos_to_file_charpos in the presence of multi-byte chars
696         let cm = init_code_map_mbc();
697
698         let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
699         assert_eq!(cp1, CharPos(3));
700
701         let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
702         assert_eq!(cp2, CharPos(4));
703
704         let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
705         assert_eq!(cp3, CharPos(12));
706
707         let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
708         assert_eq!(cp4, CharPos(15));
709     }
710
711     #[test]
712     fn t7() {
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);
717
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);
721     }
722
723     #[test]
724     fn t8() {
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);
729
730         assert_eq!(snippet, Some("second line".to_string()));
731     }
732
733     #[test]
734     fn t9() {
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);
739
740         assert_eq!(sstr, "blork.rs:2:1: 2:12");
741     }
742 }