]> git.proxmox.com Git - rustc.git/blob - src/libsyntax/codemap.rs
099f646294235d175dcdf47b59ac0daa419f7024
[rustc.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_usize(n: usize) -> Self;
34 fn to_usize(&self) -> usize;
35 }
36
37 /// A byte offset. Keep this small (currently 32-bits), as AST contains
38 /// a lot of them.
39 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Debug)]
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 #[derive(Copy, PartialEq, Hash, PartialOrd, Debug)]
46 pub struct CharPos(pub usize);
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_usize(n: usize) -> BytePos { BytePos(n as u32) }
53 fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
54 }
55
56 impl Add for BytePos {
57 type Output = BytePos;
58
59 fn add(self, rhs: BytePos) -> BytePos {
60 BytePos((self.to_usize() + rhs.to_usize()) 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_usize() - rhs.to_usize()) as u32)
69 }
70 }
71
72 impl Pos for CharPos {
73 fn from_usize(n: usize) -> CharPos { CharPos(n) }
74 fn to_usize(&self) -> usize { 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_usize() + rhs.to_usize())
82 }
83 }
84
85 impl Sub for CharPos {
86 type Output = CharPos;
87
88 fn sub(self, rhs: CharPos) -> CharPos {
89 CharPos(self.to_usize() - rhs.to_usize())
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 #[derive(Clone, Copy, Debug, 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 // Generic span to be used for code originating from the command line
109 pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0),
110 hi: BytePos(0),
111 expn_id: COMMAND_LINE_EXPN };
112
113 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
114 pub struct Spanned<T> {
115 pub node: T,
116 pub span: Span,
117 }
118
119 impl PartialEq for Span {
120 fn eq(&self, other: &Span) -> bool {
121 return (*self).lo == (*other).lo && (*self).hi == (*other).hi;
122 }
123 fn ne(&self, other: &Span) -> bool { !(*self).eq(other) }
124 }
125
126 impl Eq for Span {}
127
128 impl Encodable for Span {
129 /* Note #1972 -- spans are encoded but not decoded */
130 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
131 s.emit_nil()
132 }
133 }
134
135 impl Decodable for Span {
136 fn decode<D: Decoder>(_d: &mut D) -> Result<Span, D::Error> {
137 Ok(DUMMY_SP)
138 }
139 }
140
141 pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
142 respan(mk_sp(lo, hi), t)
143 }
144
145 pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
146 Spanned {node: t, span: sp}
147 }
148
149 pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
150 respan(DUMMY_SP, t)
151 }
152
153 /* assuming that we're not in macro expansion */
154 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
155 Span {lo: lo, hi: hi, expn_id: NO_EXPANSION}
156 }
157
158 /// Return the span itself if it doesn't come from a macro expansion,
159 /// otherwise return the call site span up to the `enclosing_sp` by
160 /// following the `expn_info` chain.
161 pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span {
162 let call_site1 = cm.with_expn_info(sp.expn_id, |ei| ei.map(|ei| ei.call_site));
163 let call_site2 = cm.with_expn_info(enclosing_sp.expn_id, |ei| ei.map(|ei| ei.call_site));
164 match (call_site1, call_site2) {
165 (None, _) => sp,
166 (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
167 (Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp),
168 }
169 }
170
171 /// A source code location used for error reporting
172 pub struct Loc {
173 /// Information about the original source
174 pub file: Rc<FileMap>,
175 /// The (1-based) line number
176 pub line: usize,
177 /// The (0-based) column offset
178 pub col: CharPos
179 }
180
181 /// A source code location used as the result of lookup_char_pos_adj
182 // Actually, *none* of the clients use the filename *or* file field;
183 // perhaps they should just be removed.
184 pub struct LocWithOpt {
185 pub filename: FileName,
186 pub line: usize,
187 pub col: CharPos,
188 pub file: Option<Rc<FileMap>>,
189 }
190
191 // used to be structural records. Better names, anyone?
192 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
193 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
194
195 /// The syntax with which a macro was invoked.
196 #[derive(Clone, Copy, Hash, Debug)]
197 pub enum MacroFormat {
198 /// e.g. #[derive(...)] <item>
199 MacroAttribute,
200 /// e.g. `format!()`
201 MacroBang
202 }
203
204 #[derive(Clone, Hash, Debug)]
205 pub struct NameAndSpan {
206 /// The name of the macro that was invoked to create the thing
207 /// with this Span.
208 pub name: String,
209 /// The format with which the macro was invoked.
210 pub format: MacroFormat,
211 /// The span of the macro definition itself. The macro may not
212 /// have a sensible definition span (e.g. something defined
213 /// completely inside libsyntax) in which case this is None.
214 pub span: Option<Span>
215 }
216
217 /// Extra information for tracking macro expansion of spans
218 #[derive(Hash, Debug)]
219 pub struct ExpnInfo {
220 /// The location of the actual macro invocation, e.g. `let x =
221 /// foo!();`
222 ///
223 /// This may recursively refer to other macro invocations, e.g. if
224 /// `foo!()` invoked `bar!()` internally, and there was an
225 /// expression inside `bar!`; the call_site of the expression in
226 /// the expansion would point to the `bar!` invocation; that
227 /// call_site span would have its own ExpnInfo, with the call_site
228 /// pointing to the `foo!` invocation.
229 pub call_site: Span,
230 /// Information about the macro and its definition.
231 ///
232 /// The `callee` of the inner expression in the `call_site`
233 /// example would point to the `macro_rules! bar { ... }` and that
234 /// of the `bar!()` invocation would point to the `macro_rules!
235 /// foo { ... }`.
236 pub callee: NameAndSpan
237 }
238
239 #[derive(PartialEq, Eq, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Copy)]
240 pub struct ExpnId(u32);
241
242 pub const NO_EXPANSION: ExpnId = ExpnId(-1);
243 // For code appearing from the command line
244 pub const COMMAND_LINE_EXPN: ExpnId = ExpnId(-2);
245
246 impl ExpnId {
247 pub fn from_llvm_cookie(cookie: c_uint) -> ExpnId {
248 ExpnId(cookie as u32)
249 }
250
251 pub fn to_llvm_cookie(self) -> i32 {
252 let ExpnId(cookie) = self;
253 cookie as i32
254 }
255 }
256
257 pub type FileName = String;
258
259 pub struct FileLines {
260 pub file: Rc<FileMap>,
261 pub lines: Vec<usize>
262 }
263
264 /// Identifies an offset of a multi-byte character in a FileMap
265 #[derive(Copy)]
266 pub struct MultiByteChar {
267 /// The absolute offset of the character in the CodeMap
268 pub pos: BytePos,
269 /// The number of bytes, >=2
270 pub bytes: usize,
271 }
272
273 /// A single source in the CodeMap
274 pub struct FileMap {
275 /// The name of the file that the source came from, source that doesn't
276 /// originate from files has names between angle brackets by convention,
277 /// e.g. `<anon>`
278 pub name: FileName,
279 /// The complete source code
280 pub src: String,
281 /// The start position of this source in the CodeMap
282 pub start_pos: BytePos,
283 /// Locations of lines beginnings in the source code
284 pub lines: RefCell<Vec<BytePos> >,
285 /// Locations of multi-byte characters in the source code
286 pub multibyte_chars: RefCell<Vec<MultiByteChar> >,
287 }
288
289 impl FileMap {
290 /// EFFECT: register a start-of-line offset in the
291 /// table of line-beginnings.
292 /// UNCHECKED INVARIANT: these offsets must be added in the right
293 /// order and must be in the right places; there is shared knowledge
294 /// about what ends a line between this file and parse.rs
295 /// WARNING: pos param here is the offset relative to start of CodeMap,
296 /// and CodeMap will append a newline when adding a filemap without a newline at the end,
297 /// so the safe way to call this is with value calculated as
298 /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
299 pub fn next_line(&self, pos: BytePos) {
300 // the new charpos must be > the last one (or it's the first one).
301 let mut lines = self.lines.borrow_mut();
302 let line_len = lines.len();
303 assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
304 lines.push(pos);
305 }
306
307 /// get a line from the list of pre-computed line-beginnings
308 ///
309 pub fn get_line(&self, line_number: usize) -> Option<String> {
310 let lines = self.lines.borrow();
311 lines.get(line_number).map(|&line| {
312 let begin: BytePos = line - self.start_pos;
313 let begin = begin.to_usize();
314 let slice = &self.src[begin..];
315 match slice.find('\n') {
316 Some(e) => &slice[..e],
317 None => slice
318 }.to_string()
319 })
320 }
321
322 pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
323 assert!(bytes >=2 && bytes <= 4);
324 let mbc = MultiByteChar {
325 pos: pos,
326 bytes: bytes,
327 };
328 self.multibyte_chars.borrow_mut().push(mbc);
329 }
330
331 pub fn is_real_file(&self) -> bool {
332 !(self.name.starts_with("<") &&
333 self.name.ends_with(">"))
334 }
335 }
336
337 pub struct CodeMap {
338 pub files: RefCell<Vec<Rc<FileMap>>>,
339 expansions: RefCell<Vec<ExpnInfo>>
340 }
341
342 impl CodeMap {
343 pub fn new() -> CodeMap {
344 CodeMap {
345 files: RefCell::new(Vec::new()),
346 expansions: RefCell::new(Vec::new()),
347 }
348 }
349
350 pub fn new_filemap(&self, filename: FileName, src: String) -> Rc<FileMap> {
351 let mut files = self.files.borrow_mut();
352 let start_pos = match files.last() {
353 None => 0,
354 Some(last) => last.start_pos.to_usize() + last.src.len(),
355 };
356
357 // Remove utf-8 BOM if any.
358 // FIXME #12884: no efficient/safe way to remove from the start of a string
359 // and reuse the allocation.
360 let mut src = if src.starts_with("\u{feff}") {
361 String::from_str(&src[3..])
362 } else {
363 String::from_str(&src[..])
364 };
365
366 // Append '\n' in case it's not already there.
367 // This is a workaround to prevent CodeMap.lookup_filemap_idx from
368 // accidentally overflowing into the next filemap in case the last byte
369 // of span is also the last byte of filemap, which leads to incorrect
370 // results from CodeMap.span_to_*.
371 if src.len() > 0 && !src.ends_with("\n") {
372 src.push('\n');
373 }
374
375 let filemap = Rc::new(FileMap {
376 name: filename,
377 src: src.to_string(),
378 start_pos: Pos::from_usize(start_pos),
379 lines: RefCell::new(Vec::new()),
380 multibyte_chars: RefCell::new(Vec::new()),
381 });
382
383 files.push(filemap.clone());
384
385 filemap
386 }
387
388 pub fn mk_substr_filename(&self, sp: Span) -> String {
389 let pos = self.lookup_char_pos(sp.lo);
390 (format!("<{}:{}:{}>",
391 pos.file.name,
392 pos.line,
393 pos.col.to_usize() + 1)).to_string()
394 }
395
396 /// Lookup source information about a BytePos
397 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
398 self.lookup_pos(pos)
399 }
400
401 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
402 let loc = self.lookup_char_pos(pos);
403 LocWithOpt {
404 filename: loc.file.name.to_string(),
405 line: loc.line,
406 col: loc.col,
407 file: Some(loc.file)
408 }
409 }
410
411 pub fn span_to_string(&self, sp: Span) -> String {
412 if self.files.borrow().len() == 0 && sp == DUMMY_SP {
413 return "no-location".to_string();
414 }
415
416 let lo = self.lookup_char_pos_adj(sp.lo);
417 let hi = self.lookup_char_pos_adj(sp.hi);
418 return (format!("{}:{}:{}: {}:{}",
419 lo.filename,
420 lo.line,
421 lo.col.to_usize() + 1,
422 hi.line,
423 hi.col.to_usize() + 1)).to_string()
424 }
425
426 pub fn span_to_filename(&self, sp: Span) -> FileName {
427 self.lookup_char_pos(sp.lo).file.name.to_string()
428 }
429
430 pub fn span_to_lines(&self, sp: Span) -> FileLines {
431 let lo = self.lookup_char_pos(sp.lo);
432 let hi = self.lookup_char_pos(sp.hi);
433 let mut lines = Vec::new();
434 for i in lo.line - 1..hi.line as usize {
435 lines.push(i);
436 };
437 FileLines {file: lo.file, lines: lines}
438 }
439
440 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
441 if sp.lo > sp.hi {
442 return Err(SpanSnippetError::IllFormedSpan(sp));
443 }
444
445 let begin = self.lookup_byte_offset(sp.lo);
446 let end = self.lookup_byte_offset(sp.hi);
447
448 if begin.fm.start_pos != end.fm.start_pos {
449 return Err(SpanSnippetError::DistinctSources(DistinctSources {
450 begin: (begin.fm.name.clone(),
451 begin.fm.start_pos),
452 end: (end.fm.name.clone(),
453 end.fm.start_pos)
454 }));
455 } else {
456 let start = begin.pos.to_usize();
457 let limit = end.pos.to_usize();
458 if start > limit || limit > begin.fm.src.len() {
459 return Err(SpanSnippetError::MalformedForCodemap(
460 MalformedCodemapPositions {
461 name: begin.fm.name.clone(),
462 source_len: begin.fm.src.len(),
463 begin_pos: begin.pos,
464 end_pos: end.pos,
465 }));
466 }
467
468 return Ok((&begin.fm.src[start..limit]).to_string())
469 }
470 }
471
472 pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> {
473 for fm in &*self.files.borrow() {
474 if filename == fm.name {
475 return fm.clone();
476 }
477 }
478 panic!("asking for {} which we don't know about", filename);
479 }
480
481 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
482 let idx = self.lookup_filemap_idx(bpos);
483 let fm = (*self.files.borrow())[idx].clone();
484 let offset = bpos - fm.start_pos;
485 FileMapAndBytePos {fm: fm, pos: offset}
486 }
487
488 /// Converts an absolute BytePos to a CharPos relative to the filemap and above.
489 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
490 let idx = self.lookup_filemap_idx(bpos);
491 let files = self.files.borrow();
492 let map = &(*files)[idx];
493
494 // The number of extra bytes due to multibyte chars in the FileMap
495 let mut total_extra_bytes = 0;
496
497 for mbc in &*map.multibyte_chars.borrow() {
498 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
499 if mbc.pos < bpos {
500 // every character is at least one byte, so we only
501 // count the actual extra bytes.
502 total_extra_bytes += mbc.bytes - 1;
503 // We should never see a byte position in the middle of a
504 // character
505 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
506 } else {
507 break;
508 }
509 }
510
511 assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
512 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
513 }
514
515 fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
516 let files = self.files.borrow();
517 let files = &*files;
518 let len = files.len();
519 let mut a = 0;
520 let mut b = len;
521 while b - a > 1 {
522 let m = (a + b) / 2;
523 if files[m].start_pos > pos {
524 b = m;
525 } else {
526 a = m;
527 }
528 }
529 // There can be filemaps with length 0. These have the same start_pos as
530 // the previous filemap, but are not the filemaps we want (because they
531 // are length 0, they cannot contain what we are looking for). So,
532 // rewind until we find a useful filemap.
533 loop {
534 let lines = files[a].lines.borrow();
535 let lines = lines;
536 if lines.len() > 0 {
537 break;
538 }
539 if a == 0 {
540 panic!("position {} does not resolve to a source location",
541 pos.to_usize());
542 }
543 a -= 1;
544 }
545 if a >= len {
546 panic!("position {} does not resolve to a source location",
547 pos.to_usize())
548 }
549
550 return a;
551 }
552
553 fn lookup_line(&self, pos: BytePos) -> FileMapAndLine {
554 let idx = self.lookup_filemap_idx(pos);
555
556 let files = self.files.borrow();
557 let f = (*files)[idx].clone();
558 let mut a = 0;
559 {
560 let lines = f.lines.borrow();
561 let mut b = lines.len();
562 while b - a > 1 {
563 let m = (a + b) / 2;
564 if (*lines)[m] > pos { b = m; } else { a = m; }
565 }
566 }
567 FileMapAndLine {fm: f, line: a}
568 }
569
570 fn lookup_pos(&self, pos: BytePos) -> Loc {
571 let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos);
572 let line = a + 1; // Line numbers start at 1
573 let chpos = self.bytepos_to_file_charpos(pos);
574 let linebpos = (*f.lines.borrow())[a];
575 let linechpos = self.bytepos_to_file_charpos(linebpos);
576 debug!("byte pos {:?} is on the line at byte pos {:?}",
577 pos, linebpos);
578 debug!("char pos {:?} is on the line at char pos {:?}",
579 chpos, linechpos);
580 debug!("byte is on line: {}", line);
581 assert!(chpos >= linechpos);
582 Loc {
583 file: f,
584 line: line,
585 col: chpos - linechpos
586 }
587 }
588
589 pub fn record_expansion(&self, expn_info: ExpnInfo) -> ExpnId {
590 let mut expansions = self.expansions.borrow_mut();
591 expansions.push(expn_info);
592 ExpnId(expansions.len().to_u32().expect("too many ExpnInfo's!") - 1)
593 }
594
595 pub fn with_expn_info<T, F>(&self, id: ExpnId, f: F) -> T where
596 F: FnOnce(Option<&ExpnInfo>) -> T,
597 {
598 match id {
599 NO_EXPANSION => f(None),
600 ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as usize]))
601 }
602 }
603
604 /// Check if a span is "internal" to a macro. This means that it is entirely generated by a
605 /// macro expansion and contains no code that was passed in as an argument.
606 pub fn span_is_internal(&self, span: Span) -> bool {
607 // first, check if the given expression was generated by a macro or not
608 // we need to go back the expn_info tree to check only the arguments
609 // of the initial macro call, not the nested ones.
610 let mut is_internal = false;
611 let mut expnid = span.expn_id;
612 while self.with_expn_info(expnid, |expninfo| {
613 match expninfo {
614 Some(ref info) => {
615 // save the parent expn_id for next loop iteration
616 expnid = info.call_site.expn_id;
617 if info.callee.name == "format_args" {
618 // This is a hack because the format_args builtin calls unstable APIs.
619 // I spent like 6 hours trying to solve this more generally but am stupid.
620 is_internal = true;
621 false
622 } else if info.callee.span.is_none() {
623 // it's a compiler built-in, we *really* don't want to mess with it
624 // so we skip it, unless it was called by a regular macro, in which case
625 // we will handle the caller macro next turn
626 is_internal = true;
627 true // continue looping
628 } else {
629 // was this expression from the current macro arguments ?
630 is_internal = !( span.lo > info.call_site.lo &&
631 span.hi < info.call_site.hi );
632 true // continue looping
633 }
634 },
635 _ => false // stop looping
636 }
637 }) { /* empty while loop body */ }
638 return is_internal;
639 }
640 }
641
642 #[derive(Clone, PartialEq, Eq, Debug)]
643 pub enum SpanSnippetError {
644 IllFormedSpan(Span),
645 DistinctSources(DistinctSources),
646 MalformedForCodemap(MalformedCodemapPositions),
647 }
648
649 #[derive(Clone, PartialEq, Eq, Debug)]
650 pub struct DistinctSources {
651 begin: (String, BytePos),
652 end: (String, BytePos)
653 }
654
655 #[derive(Clone, PartialEq, Eq, Debug)]
656 pub struct MalformedCodemapPositions {
657 name: String,
658 source_len: usize,
659 begin_pos: BytePos,
660 end_pos: BytePos
661 }
662
663 #[cfg(test)]
664 mod test {
665 use super::*;
666
667 #[test]
668 fn t1 () {
669 let cm = CodeMap::new();
670 let fm = cm.new_filemap("blork.rs".to_string(),
671 "first line.\nsecond line".to_string());
672 fm.next_line(BytePos(0));
673 assert_eq!(fm.get_line(0), Some("first line.".to_string()));
674 // TESTING BROKEN BEHAVIOR:
675 fm.next_line(BytePos(10));
676 assert_eq!(fm.get_line(1), Some(".".to_string()));
677 }
678
679 #[test]
680 #[should_fail]
681 fn t2 () {
682 let cm = CodeMap::new();
683 let fm = cm.new_filemap("blork.rs".to_string(),
684 "first line.\nsecond line".to_string());
685 // TESTING *REALLY* BROKEN BEHAVIOR:
686 fm.next_line(BytePos(0));
687 fm.next_line(BytePos(10));
688 fm.next_line(BytePos(2));
689 }
690
691 fn init_code_map() -> CodeMap {
692 let cm = CodeMap::new();
693 let fm1 = cm.new_filemap("blork.rs".to_string(),
694 "first line.\nsecond line".to_string());
695 let fm2 = cm.new_filemap("empty.rs".to_string(),
696 "".to_string());
697 let fm3 = cm.new_filemap("blork2.rs".to_string(),
698 "first line.\nsecond line".to_string());
699
700 fm1.next_line(BytePos(0));
701 fm1.next_line(BytePos(12));
702 fm2.next_line(BytePos(24));
703 fm3.next_line(BytePos(24));
704 fm3.next_line(BytePos(34));
705
706 cm
707 }
708
709 #[test]
710 fn t3() {
711 // Test lookup_byte_offset
712 let cm = init_code_map();
713
714 let fmabp1 = cm.lookup_byte_offset(BytePos(22));
715 assert_eq!(fmabp1.fm.name, "blork.rs");
716 assert_eq!(fmabp1.pos, BytePos(22));
717
718 let fmabp2 = cm.lookup_byte_offset(BytePos(24));
719 assert_eq!(fmabp2.fm.name, "blork2.rs");
720 assert_eq!(fmabp2.pos, BytePos(0));
721 }
722
723 #[test]
724 fn t4() {
725 // Test bytepos_to_file_charpos
726 let cm = init_code_map();
727
728 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
729 assert_eq!(cp1, CharPos(22));
730
731 let cp2 = cm.bytepos_to_file_charpos(BytePos(24));
732 assert_eq!(cp2, CharPos(0));
733 }
734
735 #[test]
736 fn t5() {
737 // Test zero-length filemaps.
738 let cm = init_code_map();
739
740 let loc1 = cm.lookup_char_pos(BytePos(22));
741 assert_eq!(loc1.file.name, "blork.rs");
742 assert_eq!(loc1.line, 2);
743 assert_eq!(loc1.col, CharPos(10));
744
745 let loc2 = cm.lookup_char_pos(BytePos(24));
746 assert_eq!(loc2.file.name, "blork2.rs");
747 assert_eq!(loc2.line, 1);
748 assert_eq!(loc2.col, CharPos(0));
749 }
750
751 fn init_code_map_mbc() -> CodeMap {
752 let cm = CodeMap::new();
753 // € is a three byte utf8 char.
754 let fm1 =
755 cm.new_filemap("blork.rs".to_string(),
756 "fir€st €€€€ line.\nsecond line".to_string());
757 let fm2 = cm.new_filemap("blork2.rs".to_string(),
758 "first line€€.\n€ second line".to_string());
759
760 fm1.next_line(BytePos(0));
761 fm1.next_line(BytePos(22));
762 fm2.next_line(BytePos(40));
763 fm2.next_line(BytePos(58));
764
765 fm1.record_multibyte_char(BytePos(3), 3);
766 fm1.record_multibyte_char(BytePos(9), 3);
767 fm1.record_multibyte_char(BytePos(12), 3);
768 fm1.record_multibyte_char(BytePos(15), 3);
769 fm1.record_multibyte_char(BytePos(18), 3);
770 fm2.record_multibyte_char(BytePos(50), 3);
771 fm2.record_multibyte_char(BytePos(53), 3);
772 fm2.record_multibyte_char(BytePos(58), 3);
773
774 cm
775 }
776
777 #[test]
778 fn t6() {
779 // Test bytepos_to_file_charpos in the presence of multi-byte chars
780 let cm = init_code_map_mbc();
781
782 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
783 assert_eq!(cp1, CharPos(3));
784
785 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
786 assert_eq!(cp2, CharPos(4));
787
788 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
789 assert_eq!(cp3, CharPos(12));
790
791 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
792 assert_eq!(cp4, CharPos(15));
793 }
794
795 #[test]
796 fn t7() {
797 // Test span_to_lines for a span ending at the end of filemap
798 let cm = init_code_map();
799 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
800 let file_lines = cm.span_to_lines(span);
801
802 assert_eq!(file_lines.file.name, "blork.rs");
803 assert_eq!(file_lines.lines.len(), 1);
804 assert_eq!(file_lines.lines[0], 1);
805 }
806
807 #[test]
808 fn t8() {
809 // Test span_to_snippet for a span ending at the end of filemap
810 let cm = init_code_map();
811 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
812 let snippet = cm.span_to_snippet(span);
813
814 assert_eq!(snippet, Ok("second line".to_string()));
815 }
816
817 #[test]
818 fn t9() {
819 // Test span_to_str for a span ending at the end of filemap
820 let cm = init_code_map();
821 let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
822 let sstr = cm.span_to_string(span);
823
824 assert_eq!(sstr, "blork.rs:2:1: 2:12");
825 }
826 }