]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/lib.rs
Rollup merge of #43374 - stjepang:fix-sort-randomization-comment, r=alexcrichton
[rust.git] / src / libsyntax_pos / lib.rs
1 // Copyright 2012-2013 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 //! The source positions and related helper functions
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![crate_name = "syntax_pos"]
18 #![crate_type = "dylib"]
19 #![crate_type = "rlib"]
20 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
21       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
22       html_root_url = "https://doc.rust-lang.org/nightly/")]
23 #![deny(warnings)]
24
25 #![feature(const_fn)]
26 #![feature(custom_attribute)]
27 #![feature(i128_type)]
28 #![feature(optin_builtin_traits)]
29 #![allow(unused_attributes)]
30 #![feature(specialization)]
31
32 use std::borrow::Cow;
33 use std::cell::{Cell, RefCell};
34 use std::cmp;
35 use std::fmt;
36 use std::hash::Hasher;
37 use std::ops::{Add, Sub};
38 use std::rc::Rc;
39
40 use rustc_data_structures::stable_hasher::StableHasher;
41
42 extern crate rustc_data_structures;
43
44 use serialize::{Encodable, Decodable, Encoder, Decoder};
45
46 extern crate serialize;
47 extern crate serialize as rustc_serialize; // used by deriving
48
49 pub mod hygiene;
50 pub use hygiene::{SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan};
51
52 pub mod symbol;
53
54 pub type FileName = String;
55
56 /// Spans represent a region of code, used for error reporting. Positions in spans
57 /// are *absolute* positions from the beginning of the codemap, not positions
58 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
59 /// to the original source.
60 /// You must be careful if the span crosses more than one file - you will not be
61 /// able to use many of the functions on spans in codemap and you cannot assume
62 /// that the length of the span = hi - lo; there may be space in the BytePos
63 /// range between files.
64 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
65 pub struct Span {
66     pub lo: BytePos,
67     pub hi: BytePos,
68     /// Information about where the macro came from, if this piece of
69     /// code was created by a macro expansion.
70     pub ctxt: SyntaxContext,
71 }
72
73 /// A collection of spans. Spans have two orthogonal attributes:
74 ///
75 /// - they can be *primary spans*. In this case they are the locus of
76 ///   the error, and would be rendered with `^^^`.
77 /// - they can have a *label*. In this case, the label is written next
78 ///   to the mark in the snippet when we render.
79 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
80 pub struct MultiSpan {
81     primary_spans: Vec<Span>,
82     span_labels: Vec<(Span, String)>,
83 }
84
85 impl Span {
86     /// Returns a new span representing just the end-point of this span
87     pub fn end_point(self) -> Span {
88         let lo = cmp::max(self.hi.0 - 1, self.lo.0);
89         Span { lo: BytePos(lo), ..self }
90     }
91
92     /// Returns a new span representing the next character after the end-point of this span
93     pub fn next_point(self) -> Span {
94         let lo = cmp::max(self.hi.0, self.lo.0 + 1);
95         Span { lo: BytePos(lo), hi: BytePos(lo), ..self }
96     }
97
98     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
99     pub fn substitute_dummy(self, other: Span) -> Span {
100         if self.source_equal(&DUMMY_SP) { other } else { self }
101     }
102
103     /// Return true if `self` fully encloses `other`.
104     pub fn contains(self, other: Span) -> bool {
105         self.lo <= other.lo && other.hi <= self.hi
106     }
107
108     /// Return true if the spans are equal with regards to the source text.
109     ///
110     /// Use this instead of `==` when either span could be generated code,
111     /// and you only care that they point to the same bytes of source text.
112     pub fn source_equal(&self, other: &Span) -> bool {
113         self.lo == other.lo && self.hi == other.hi
114     }
115
116     /// Returns `Some(span)`, where the start is trimmed by the end of `other`
117     pub fn trim_start(self, other: Span) -> Option<Span> {
118         if self.hi > other.hi {
119             Some(Span { lo: cmp::max(self.lo, other.hi), .. self })
120         } else {
121             None
122         }
123     }
124
125     /// Return the source span - this is either the supplied span, or the span for
126     /// the macro callsite that expanded to it.
127     pub fn source_callsite(self) -> Span {
128         self.ctxt.outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
129     }
130
131     /// Return the source callee.
132     ///
133     /// Returns None if the supplied span has no expansion trace,
134     /// else returns the NameAndSpan for the macro definition
135     /// corresponding to the source callsite.
136     pub fn source_callee(self) -> Option<NameAndSpan> {
137         fn source_callee(info: ExpnInfo) -> NameAndSpan {
138             match info.call_site.ctxt.outer().expn_info() {
139                 Some(info) => source_callee(info),
140                 None => info.callee,
141             }
142         }
143         self.ctxt.outer().expn_info().map(source_callee)
144     }
145
146     /// Check if a span is "internal" to a macro in which #[unstable]
147     /// items can be used (that is, a macro marked with
148     /// `#[allow_internal_unstable]`).
149     pub fn allows_unstable(&self) -> bool {
150         match self.ctxt.outer().expn_info() {
151             Some(info) => info.callee.allow_internal_unstable,
152             None => false,
153         }
154     }
155
156     pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
157         let mut prev_span = DUMMY_SP;
158         let mut result = vec![];
159         loop {
160             let info = match self.ctxt.outer().expn_info() {
161                 Some(info) => info,
162                 None => break,
163             };
164
165             let (pre, post) = match info.callee.format {
166                 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
167                 ExpnFormat::MacroBang(..) => ("", "!"),
168                 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
169             };
170             let macro_decl_name = format!("{}{}{}", pre, info.callee.name(), post);
171             let def_site_span = info.callee.span;
172
173             // Don't print recursive invocations
174             if !info.call_site.source_equal(&prev_span) {
175                 result.push(MacroBacktrace {
176                     call_site: info.call_site,
177                     macro_decl_name: macro_decl_name,
178                     def_site_span: def_site_span,
179                 });
180             }
181
182             prev_span = self;
183             self = info.call_site;
184         }
185         result
186     }
187
188     /// Return a `Span` that would enclose both `self` and `end`.
189     pub fn to(self, end: Span) -> Span {
190         Span {
191             lo: cmp::min(self.lo, end.lo),
192             hi: cmp::max(self.hi, end.hi),
193             // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
194             ctxt: if self.ctxt == SyntaxContext::empty() {
195                 end.ctxt
196             } else {
197                 self.ctxt
198             },
199         }
200     }
201
202     /// Return a `Span` between the end of `self` to the beginning of `end`.
203     pub fn between(self, end: Span) -> Span {
204         Span {
205             lo: self.hi,
206             hi: end.lo,
207             ctxt: if end.ctxt == SyntaxContext::empty() {
208                 end.ctxt
209             } else {
210                 self.ctxt
211             }
212         }
213     }
214
215     /// Return a `Span` between the beginning of `self` to the beginning of `end`.
216     pub fn until(self, end: Span) -> Span {
217         Span {
218             lo: self.lo,
219             hi: end.lo,
220             ctxt: if end.ctxt == SyntaxContext::empty() {
221                 end.ctxt
222             } else {
223                 self.ctxt
224             }
225         }
226     }
227 }
228
229 #[derive(Clone, Debug)]
230 pub struct SpanLabel {
231     /// The span we are going to include in the final snippet.
232     pub span: Span,
233
234     /// Is this a primary span? This is the "locus" of the message,
235     /// and is indicated with a `^^^^` underline, versus `----`.
236     pub is_primary: bool,
237
238     /// What label should we attach to this span (if any)?
239     pub label: Option<String>,
240 }
241
242 impl serialize::UseSpecializedEncodable for Span {
243     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
244         s.emit_struct("Span", 2, |s| {
245             s.emit_struct_field("lo", 0, |s| {
246                 self.lo.encode(s)
247             })?;
248
249             s.emit_struct_field("hi", 1, |s| {
250                 self.hi.encode(s)
251             })
252         })
253     }
254 }
255
256 impl serialize::UseSpecializedDecodable for Span {
257     fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
258         d.read_struct("Span", 2, |d| {
259             let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
260             let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
261             Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION })
262         })
263     }
264 }
265
266 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
267     write!(f, "Span {{ lo: {:?}, hi: {:?}, ctxt: {:?} }}",
268            span.lo, span.hi, span.ctxt)
269 }
270
271 impl fmt::Debug for Span {
272     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
273         SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
274     }
275 }
276
277 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), ctxt: NO_EXPANSION };
278
279 impl MultiSpan {
280     pub fn new() -> MultiSpan {
281         MultiSpan {
282             primary_spans: vec![],
283             span_labels: vec![]
284         }
285     }
286
287     pub fn from_span(primary_span: Span) -> MultiSpan {
288         MultiSpan {
289             primary_spans: vec![primary_span],
290             span_labels: vec![]
291         }
292     }
293
294     pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
295         MultiSpan {
296             primary_spans: vec,
297             span_labels: vec![]
298         }
299     }
300
301     pub fn push_span_label(&mut self, span: Span, label: String) {
302         self.span_labels.push((span, label));
303     }
304
305     /// Selects the first primary span (if any)
306     pub fn primary_span(&self) -> Option<Span> {
307         self.primary_spans.first().cloned()
308     }
309
310     /// Returns all primary spans.
311     pub fn primary_spans(&self) -> &[Span] {
312         &self.primary_spans
313     }
314
315     /// Replaces all occurances of one Span with another. Used to move Spans in areas that don't
316     /// display well (like std macros). Returns true if replacements occurred.
317     pub fn replace(&mut self, before: Span, after: Span) -> bool {
318         let mut replacements_occurred = false;
319         for primary_span in &mut self.primary_spans {
320             if *primary_span == before {
321                 *primary_span = after;
322                 replacements_occurred = true;
323             }
324         }
325         for span_label in &mut self.span_labels {
326             if span_label.0 == before {
327                 span_label.0 = after;
328                 replacements_occurred = true;
329             }
330         }
331         replacements_occurred
332     }
333
334     /// Returns the strings to highlight. We always ensure that there
335     /// is an entry for each of the primary spans -- for each primary
336     /// span P, if there is at least one label with span P, we return
337     /// those labels (marked as primary). But otherwise we return
338     /// `SpanLabel` instances with empty labels.
339     pub fn span_labels(&self) -> Vec<SpanLabel> {
340         let is_primary = |span| self.primary_spans.contains(&span);
341         let mut span_labels = vec![];
342
343         for &(span, ref label) in &self.span_labels {
344             span_labels.push(SpanLabel {
345                 span: span,
346                 is_primary: is_primary(span),
347                 label: Some(label.clone())
348             });
349         }
350
351         for &span in &self.primary_spans {
352             if !span_labels.iter().any(|sl| sl.span == span) {
353                 span_labels.push(SpanLabel {
354                     span: span,
355                     is_primary: true,
356                     label: None
357                 });
358             }
359         }
360
361         span_labels
362     }
363 }
364
365 impl From<Span> for MultiSpan {
366     fn from(span: Span) -> MultiSpan {
367         MultiSpan::from_span(span)
368     }
369 }
370
371 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
372
373 /// Identifies an offset of a multi-byte character in a FileMap
374 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
375 pub struct MultiByteChar {
376     /// The absolute offset of the character in the CodeMap
377     pub pos: BytePos,
378     /// The number of bytes, >=2
379     pub bytes: usize,
380 }
381
382 /// The state of the lazy external source loading mechanism of a FileMap.
383 #[derive(PartialEq, Eq, Clone)]
384 pub enum ExternalSource {
385     /// The external source has been loaded already.
386     Present(String),
387     /// No attempt has been made to load the external source.
388     AbsentOk,
389     /// A failed attempt has been made to load the external source.
390     AbsentErr,
391     /// No external source has to be loaded, since the FileMap represents a local crate.
392     Unneeded,
393 }
394
395 impl ExternalSource {
396     pub fn is_absent(&self) -> bool {
397         match *self {
398             ExternalSource::Present(_) => false,
399             _ => true,
400         }
401     }
402
403     pub fn get_source(&self) -> Option<&str> {
404         match *self {
405             ExternalSource::Present(ref src) => Some(src),
406             _ => None,
407         }
408     }
409 }
410
411 /// A single source in the CodeMap.
412 #[derive(Clone)]
413 pub struct FileMap {
414     /// The name of the file that the source came from, source that doesn't
415     /// originate from files has names between angle brackets by convention,
416     /// e.g. `<anon>`
417     pub name: FileName,
418     /// True if the `name` field above has been modified by -Zremap-path-prefix
419     pub name_was_remapped: bool,
420     /// Indicates which crate this FileMap was imported from.
421     pub crate_of_origin: u32,
422     /// The complete source code
423     pub src: Option<Rc<String>>,
424     /// The source code's hash
425     pub src_hash: u128,
426     /// The external source code (used for external crates, which will have a `None`
427     /// value as `self.src`.
428     pub external_src: RefCell<ExternalSource>,
429     /// The start position of this source in the CodeMap
430     pub start_pos: BytePos,
431     /// The end position of this source in the CodeMap
432     pub end_pos: BytePos,
433     /// Locations of lines beginnings in the source code
434     pub lines: RefCell<Vec<BytePos>>,
435     /// Locations of multi-byte characters in the source code
436     pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
437 }
438
439 impl Encodable for FileMap {
440     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
441         s.emit_struct("FileMap", 7, |s| {
442             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
443             s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
444             s.emit_struct_field("src_hash", 6, |s| self.src_hash.encode(s))?;
445             s.emit_struct_field("start_pos", 2, |s| self.start_pos.encode(s))?;
446             s.emit_struct_field("end_pos", 3, |s| self.end_pos.encode(s))?;
447             s.emit_struct_field("lines", 4, |s| {
448                 let lines = self.lines.borrow();
449                 // store the length
450                 s.emit_u32(lines.len() as u32)?;
451
452                 if !lines.is_empty() {
453                     // In order to preserve some space, we exploit the fact that
454                     // the lines list is sorted and individual lines are
455                     // probably not that long. Because of that we can store lines
456                     // as a difference list, using as little space as possible
457                     // for the differences.
458                     let max_line_length = if lines.len() == 1 {
459                         0
460                     } else {
461                         lines.windows(2)
462                              .map(|w| w[1] - w[0])
463                              .map(|bp| bp.to_usize())
464                              .max()
465                              .unwrap()
466                     };
467
468                     let bytes_per_diff: u8 = match max_line_length {
469                         0 ... 0xFF => 1,
470                         0x100 ... 0xFFFF => 2,
471                         _ => 4
472                     };
473
474                     // Encode the number of bytes used per diff.
475                     bytes_per_diff.encode(s)?;
476
477                     // Encode the first element.
478                     lines[0].encode(s)?;
479
480                     let diff_iter = (&lines[..]).windows(2)
481                                                 .map(|w| (w[1] - w[0]));
482
483                     match bytes_per_diff {
484                         1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
485                         2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
486                         4 => for diff in diff_iter { diff.0.encode(s)? },
487                         _ => unreachable!()
488                     }
489                 }
490
491                 Ok(())
492             })?;
493             s.emit_struct_field("multibyte_chars", 5, |s| {
494                 (*self.multibyte_chars.borrow()).encode(s)
495             })
496         })
497     }
498 }
499
500 impl Decodable for FileMap {
501     fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
502
503         d.read_struct("FileMap", 6, |d| {
504             let name: String = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
505             let name_was_remapped: bool =
506                 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
507             let src_hash: u128 =
508                 d.read_struct_field("src_hash", 6, |d| Decodable::decode(d))?;
509             let start_pos: BytePos =
510                 d.read_struct_field("start_pos", 2, |d| Decodable::decode(d))?;
511             let end_pos: BytePos = d.read_struct_field("end_pos", 3, |d| Decodable::decode(d))?;
512             let lines: Vec<BytePos> = d.read_struct_field("lines", 4, |d| {
513                 let num_lines: u32 = Decodable::decode(d)?;
514                 let mut lines = Vec::with_capacity(num_lines as usize);
515
516                 if num_lines > 0 {
517                     // Read the number of bytes used per diff.
518                     let bytes_per_diff: u8 = Decodable::decode(d)?;
519
520                     // Read the first element.
521                     let mut line_start: BytePos = Decodable::decode(d)?;
522                     lines.push(line_start);
523
524                     for _ in 1..num_lines {
525                         let diff = match bytes_per_diff {
526                             1 => d.read_u8()? as u32,
527                             2 => d.read_u16()? as u32,
528                             4 => d.read_u32()?,
529                             _ => unreachable!()
530                         };
531
532                         line_start = line_start + BytePos(diff);
533
534                         lines.push(line_start);
535                     }
536                 }
537
538                 Ok(lines)
539             })?;
540             let multibyte_chars: Vec<MultiByteChar> =
541                 d.read_struct_field("multibyte_chars", 5, |d| Decodable::decode(d))?;
542             Ok(FileMap {
543                 name: name,
544                 name_was_remapped: name_was_remapped,
545                 // `crate_of_origin` has to be set by the importer.
546                 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
547                 // That constant is not available here unfortunately :(
548                 crate_of_origin: ::std::u32::MAX - 1,
549                 start_pos: start_pos,
550                 end_pos: end_pos,
551                 src: None,
552                 src_hash: src_hash,
553                 external_src: RefCell::new(ExternalSource::AbsentOk),
554                 lines: RefCell::new(lines),
555                 multibyte_chars: RefCell::new(multibyte_chars)
556             })
557         })
558     }
559 }
560
561 impl fmt::Debug for FileMap {
562     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
563         write!(fmt, "FileMap({})", self.name)
564     }
565 }
566
567 impl FileMap {
568     pub fn new(name: FileName,
569                name_was_remapped: bool,
570                mut src: String,
571                start_pos: BytePos) -> FileMap {
572         remove_bom(&mut src);
573
574         let mut hasher: StableHasher<u128> = StableHasher::new();
575         hasher.write(src.as_bytes());
576         let src_hash = hasher.finish();
577
578         let end_pos = start_pos.to_usize() + src.len();
579
580         FileMap {
581             name: name,
582             name_was_remapped: name_was_remapped,
583             crate_of_origin: 0,
584             src: Some(Rc::new(src)),
585             src_hash: src_hash,
586             external_src: RefCell::new(ExternalSource::Unneeded),
587             start_pos: start_pos,
588             end_pos: Pos::from_usize(end_pos),
589             lines: RefCell::new(Vec::new()),
590             multibyte_chars: RefCell::new(Vec::new()),
591         }
592     }
593
594     /// EFFECT: register a start-of-line offset in the
595     /// table of line-beginnings.
596     /// UNCHECKED INVARIANT: these offsets must be added in the right
597     /// order and must be in the right places; there is shared knowledge
598     /// about what ends a line between this file and parse.rs
599     /// WARNING: pos param here is the offset relative to start of CodeMap,
600     /// and CodeMap will append a newline when adding a filemap without a newline at the end,
601     /// so the safe way to call this is with value calculated as
602     /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
603     pub fn next_line(&self, pos: BytePos) {
604         // the new charpos must be > the last one (or it's the first one).
605         let mut lines = self.lines.borrow_mut();
606         let line_len = lines.len();
607         assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
608         lines.push(pos);
609     }
610
611     /// Add externally loaded source.
612     /// If the hash of the input doesn't match or no input is supplied via None,
613     /// it is interpreted as an error and the corresponding enum variant is set.
614     /// The return value signifies whether some kind of source is present.
615     pub fn add_external_src(&self, src: Option<String>) -> bool {
616         if *self.external_src.borrow() == ExternalSource::AbsentOk {
617             let mut external_src = self.external_src.borrow_mut();
618             if let Some(src) = src {
619                 let mut hasher: StableHasher<u128> = StableHasher::new();
620                 hasher.write(src.as_bytes());
621
622                 if hasher.finish() == self.src_hash {
623                     *external_src = ExternalSource::Present(src);
624                     return true;
625                 }
626             } else {
627                 *external_src = ExternalSource::AbsentErr;
628             }
629
630             false
631         } else {
632             self.src.is_some() || self.external_src.borrow().get_source().is_some()
633         }
634     }
635
636     /// Get a line from the list of pre-computed line-beginnings.
637     /// The line number here is 0-based.
638     pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
639         fn get_until_newline(src: &str, begin: usize) -> &str {
640             // We can't use `lines.get(line_number+1)` because we might
641             // be parsing when we call this function and thus the current
642             // line is the last one we have line info for.
643             let slice = &src[begin..];
644             match slice.find('\n') {
645                 Some(e) => &slice[..e],
646                 None => slice
647             }
648         }
649
650         let lines = self.lines.borrow();
651         let line = if let Some(line) = lines.get(line_number) {
652             line
653         } else {
654             return None;
655         };
656         let begin: BytePos = *line - self.start_pos;
657         let begin = begin.to_usize();
658
659         if let Some(ref src) = self.src {
660             Some(Cow::from(get_until_newline(src, begin)))
661         } else if let Some(src) = self.external_src.borrow().get_source() {
662             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
663         } else {
664             None
665         }
666     }
667
668     pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
669         assert!(bytes >=2 && bytes <= 4);
670         let mbc = MultiByteChar {
671             pos: pos,
672             bytes: bytes,
673         };
674         self.multibyte_chars.borrow_mut().push(mbc);
675     }
676
677     pub fn is_real_file(&self) -> bool {
678         !(self.name.starts_with("<") &&
679           self.name.ends_with(">"))
680     }
681
682     pub fn is_imported(&self) -> bool {
683         self.src.is_none()
684     }
685
686     pub fn byte_length(&self) -> u32 {
687         self.end_pos.0 - self.start_pos.0
688     }
689     pub fn count_lines(&self) -> usize {
690         self.lines.borrow().len()
691     }
692
693     /// Find the line containing the given position. The return value is the
694     /// index into the `lines` array of this FileMap, not the 1-based line
695     /// number. If the filemap is empty or the position is located before the
696     /// first line, None is returned.
697     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
698         let lines = self.lines.borrow();
699         if lines.len() == 0 {
700             return None;
701         }
702
703         let line_index = lookup_line(&lines[..], pos);
704         assert!(line_index < lines.len() as isize);
705         if line_index >= 0 {
706             Some(line_index as usize)
707         } else {
708             None
709         }
710     }
711
712     pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
713         if self.start_pos == self.end_pos {
714             return (self.start_pos, self.end_pos);
715         }
716
717         let lines = self.lines.borrow();
718         assert!(line_index < lines.len());
719         if line_index == (lines.len() - 1) {
720             (lines[line_index], self.end_pos)
721         } else {
722             (lines[line_index], lines[line_index + 1])
723         }
724     }
725 }
726
727 /// Remove utf-8 BOM if any.
728 fn remove_bom(src: &mut String) {
729     if src.starts_with("\u{feff}") {
730         src.drain(..3);
731     }
732 }
733
734 // _____________________________________________________________________________
735 // Pos, BytePos, CharPos
736 //
737
738 pub trait Pos {
739     fn from_usize(n: usize) -> Self;
740     fn to_usize(&self) -> usize;
741 }
742
743 /// A byte offset. Keep this small (currently 32-bits), as AST contains
744 /// a lot of them.
745 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
746 pub struct BytePos(pub u32);
747
748 /// A character offset. Because of multibyte utf8 characters, a byte offset
749 /// is not equivalent to a character offset. The CodeMap will convert BytePos
750 /// values to CharPos values as necessary.
751 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
752 pub struct CharPos(pub usize);
753
754 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
755 // have been unsuccessful
756
757 impl Pos for BytePos {
758     fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
759     fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
760 }
761
762 impl Add for BytePos {
763     type Output = BytePos;
764
765     fn add(self, rhs: BytePos) -> BytePos {
766         BytePos((self.to_usize() + rhs.to_usize()) as u32)
767     }
768 }
769
770 impl Sub for BytePos {
771     type Output = BytePos;
772
773     fn sub(self, rhs: BytePos) -> BytePos {
774         BytePos((self.to_usize() - rhs.to_usize()) as u32)
775     }
776 }
777
778 impl Encodable for BytePos {
779     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
780         s.emit_u32(self.0)
781     }
782 }
783
784 impl Decodable for BytePos {
785     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
786         Ok(BytePos(d.read_u32()?))
787     }
788 }
789
790 impl Pos for CharPos {
791     fn from_usize(n: usize) -> CharPos { CharPos(n) }
792     fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
793 }
794
795 impl Add for CharPos {
796     type Output = CharPos;
797
798     fn add(self, rhs: CharPos) -> CharPos {
799         CharPos(self.to_usize() + rhs.to_usize())
800     }
801 }
802
803 impl Sub for CharPos {
804     type Output = CharPos;
805
806     fn sub(self, rhs: CharPos) -> CharPos {
807         CharPos(self.to_usize() - rhs.to_usize())
808     }
809 }
810
811 // _____________________________________________________________________________
812 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
813 //
814
815 /// A source code location used for error reporting
816 #[derive(Debug, Clone)]
817 pub struct Loc {
818     /// Information about the original source
819     pub file: Rc<FileMap>,
820     /// The (1-based) line number
821     pub line: usize,
822     /// The (0-based) column offset
823     pub col: CharPos
824 }
825
826 /// A source code location used as the result of lookup_char_pos_adj
827 // Actually, *none* of the clients use the filename *or* file field;
828 // perhaps they should just be removed.
829 #[derive(Debug)]
830 pub struct LocWithOpt {
831     pub filename: FileName,
832     pub line: usize,
833     pub col: CharPos,
834     pub file: Option<Rc<FileMap>>,
835 }
836
837 // used to be structural records. Better names, anyone?
838 #[derive(Debug)]
839 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
840 #[derive(Debug)]
841 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
842
843 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
844 pub struct LineInfo {
845     /// Index of line, starting from 0.
846     pub line_index: usize,
847
848     /// Column in line where span begins, starting from 0.
849     pub start_col: CharPos,
850
851     /// Column in line where span ends, starting from 0, exclusive.
852     pub end_col: CharPos,
853 }
854
855 pub struct FileLines {
856     pub file: Rc<FileMap>,
857     pub lines: Vec<LineInfo>
858 }
859
860 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
861                 Cell::new(default_span_debug));
862
863 #[derive(Debug)]
864 pub struct MacroBacktrace {
865     /// span where macro was applied to generate this code
866     pub call_site: Span,
867
868     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
869     pub macro_decl_name: String,
870
871     /// span where macro was defined (if known)
872     pub def_site_span: Option<Span>,
873 }
874
875 // _____________________________________________________________________________
876 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
877 //
878
879 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
880
881 #[derive(Clone, PartialEq, Eq, Debug)]
882 pub enum SpanLinesError {
883     IllFormedSpan(Span),
884     DistinctSources(DistinctSources),
885 }
886
887 #[derive(Clone, PartialEq, Eq, Debug)]
888 pub enum SpanSnippetError {
889     IllFormedSpan(Span),
890     DistinctSources(DistinctSources),
891     MalformedForCodemap(MalformedCodemapPositions),
892     SourceNotAvailable { filename: String }
893 }
894
895 #[derive(Clone, PartialEq, Eq, Debug)]
896 pub struct DistinctSources {
897     pub begin: (String, BytePos),
898     pub end: (String, BytePos)
899 }
900
901 #[derive(Clone, PartialEq, Eq, Debug)]
902 pub struct MalformedCodemapPositions {
903     pub name: String,
904     pub source_len: usize,
905     pub begin_pos: BytePos,
906     pub end_pos: BytePos
907 }
908
909 // Given a slice of line start positions and a position, returns the index of
910 // the line the position is on. Returns -1 if the position is located before
911 // the first line.
912 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
913     match lines.binary_search(&pos) {
914         Ok(line) => line as isize,
915         Err(line) => line as isize - 1
916     }
917 }
918
919 #[cfg(test)]
920 mod tests {
921     use super::{lookup_line, BytePos};
922
923     #[test]
924     fn test_lookup_line() {
925
926         let lines = &[BytePos(3), BytePos(17), BytePos(28)];
927
928         assert_eq!(lookup_line(lines, BytePos(0)), -1);
929         assert_eq!(lookup_line(lines, BytePos(3)),  0);
930         assert_eq!(lookup_line(lines, BytePos(4)),  0);
931
932         assert_eq!(lookup_line(lines, BytePos(16)), 0);
933         assert_eq!(lookup_line(lines, BytePos(17)), 1);
934         assert_eq!(lookup_line(lines, BytePos(18)), 1);
935
936         assert_eq!(lookup_line(lines, BytePos(28)), 2);
937         assert_eq!(lookup_line(lines, BytePos(29)), 2);
938     }
939 }