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