]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/lib.rs
Specify output filenames for compatibility with Windows
[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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19       html_root_url = "https://doc.rust-lang.org/nightly/")]
20 #![deny(warnings)]
21
22 #![feature(const_fn)]
23 #![feature(custom_attribute)]
24 #![feature(i128_type)]
25 #![feature(optin_builtin_traits)]
26 #![allow(unused_attributes)]
27 #![feature(specialization)]
28
29 use std::borrow::Cow;
30 use std::cell::{Cell, RefCell};
31 use std::cmp::{self, Ordering};
32 use std::fmt;
33 use std::hash::{Hasher, Hash};
34 use std::ops::{Add, Sub};
35 use std::path::PathBuf;
36 use std::rc::Rc;
37
38 use rustc_data_structures::stable_hasher::StableHasher;
39
40 extern crate rustc_data_structures;
41
42 use serialize::{Encodable, Decodable, Encoder, Decoder};
43
44 extern crate serialize;
45 extern crate serialize as rustc_serialize; // used by deriving
46
47 extern crate unicode_width;
48
49 pub mod hygiene;
50 pub use hygiene::{SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan, CompilerDesugaringKind};
51
52 mod span_encoding;
53 pub use span_encoding::{Span, DUMMY_SP};
54
55 pub mod symbol;
56
57 /// Differentiates between real files and common virtual files
58 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
59 pub enum FileName {
60     Real(PathBuf),
61     /// e.g. "std" macros
62     Macros(String),
63     /// call to `quote!`
64     QuoteExpansion,
65     /// Command line
66     Anon,
67     /// Hack in src/libsyntax/parse.rs
68     /// FIXME(jseyfried)
69     MacroExpansion,
70     ProcMacroSourceCode,
71     /// Strings provided as --cfg [cfgspec] stored in a crate_cfg
72     CfgSpec,
73     /// Custom sources for explicit parser calls from plugins and drivers
74     Custom(String),
75 }
76
77 impl std::fmt::Display for FileName {
78     fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
79         use self::FileName::*;
80         match *self {
81             Real(ref path) => write!(fmt, "{}", path.display()),
82             Macros(ref name) => write!(fmt, "<{} macros>", name),
83             QuoteExpansion => write!(fmt, "<quote expansion>"),
84             MacroExpansion => write!(fmt, "<macro expansion>"),
85             Anon => write!(fmt, "<anon>"),
86             ProcMacroSourceCode => write!(fmt, "<proc-macro source code>"),
87             CfgSpec => write!(fmt, "cfgspec"),
88             Custom(ref s) => write!(fmt, "<{}>", s),
89         }
90     }
91 }
92
93 impl From<PathBuf> for FileName {
94     fn from(p: PathBuf) -> Self {
95         assert!(!p.to_string_lossy().ends_with('>'));
96         FileName::Real(p)
97     }
98 }
99
100 impl FileName {
101     pub fn is_real(&self) -> bool {
102         use self::FileName::*;
103         match *self {
104             Real(_) => true,
105             Macros(_) |
106             Anon |
107             MacroExpansion |
108             ProcMacroSourceCode |
109             CfgSpec |
110             Custom(_) |
111             QuoteExpansion => false,
112         }
113     }
114
115     pub fn is_macros(&self) -> bool {
116         use self::FileName::*;
117         match *self {
118             Real(_) |
119             Anon |
120             MacroExpansion |
121             ProcMacroSourceCode |
122             CfgSpec |
123             Custom(_) |
124             QuoteExpansion => false,
125             Macros(_) => true,
126         }
127     }
128 }
129
130 /// Spans represent a region of code, used for error reporting. Positions in spans
131 /// are *absolute* positions from the beginning of the codemap, not positions
132 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
133 /// to the original source.
134 /// You must be careful if the span crosses more than one file - you will not be
135 /// able to use many of the functions on spans in codemap and you cannot assume
136 /// that the length of the span = hi - lo; there may be space in the BytePos
137 /// range between files.
138 ///
139 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
140 /// sent to other threads, but some pieces of performance infra run in a separate thread.
141 /// Using `Span` is generally preferred.
142 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
143 pub struct SpanData {
144     pub lo: BytePos,
145     pub hi: BytePos,
146     /// Information about where the macro came from, if this piece of
147     /// code was created by a macro expansion.
148     pub ctxt: SyntaxContext,
149 }
150
151 impl SpanData {
152     #[inline]
153     pub fn with_lo(&self, lo: BytePos) -> Span {
154         Span::new(lo, self.hi, self.ctxt)
155     }
156     #[inline]
157     pub fn with_hi(&self, hi: BytePos) -> Span {
158         Span::new(self.lo, hi, self.ctxt)
159     }
160     #[inline]
161     pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
162         Span::new(self.lo, self.hi, ctxt)
163     }
164 }
165
166 // The interner in thread-local, so `Span` shouldn't move between threads.
167 impl !Send for Span {}
168 impl !Sync for Span {}
169
170 impl PartialOrd for Span {
171     fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
172         PartialOrd::partial_cmp(&self.data(), &rhs.data())
173     }
174 }
175 impl Ord for Span {
176     fn cmp(&self, rhs: &Self) -> Ordering {
177         Ord::cmp(&self.data(), &rhs.data())
178     }
179 }
180
181 /// A collection of spans. Spans have two orthogonal attributes:
182 ///
183 /// - they can be *primary spans*. In this case they are the locus of
184 ///   the error, and would be rendered with `^^^`.
185 /// - they can have a *label*. In this case, the label is written next
186 ///   to the mark in the snippet when we render.
187 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
188 pub struct MultiSpan {
189     primary_spans: Vec<Span>,
190     span_labels: Vec<(Span, String)>,
191 }
192
193 impl Span {
194     #[inline]
195     pub fn lo(self) -> BytePos {
196         self.data().lo
197     }
198     #[inline]
199     pub fn with_lo(self, lo: BytePos) -> Span {
200         self.data().with_lo(lo)
201     }
202     #[inline]
203     pub fn hi(self) -> BytePos {
204         self.data().hi
205     }
206     #[inline]
207     pub fn with_hi(self, hi: BytePos) -> Span {
208         self.data().with_hi(hi)
209     }
210     #[inline]
211     pub fn ctxt(self) -> SyntaxContext {
212         self.data().ctxt
213     }
214     #[inline]
215     pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
216         self.data().with_ctxt(ctxt)
217     }
218
219     /// Returns a new span representing just the end-point of this span
220     pub fn end_point(self) -> Span {
221         let span = self.data();
222         let lo = cmp::max(span.hi.0 - 1, span.lo.0);
223         span.with_lo(BytePos(lo))
224     }
225
226     /// Returns a new span representing the next character after the end-point of this span
227     pub fn next_point(self) -> Span {
228         let span = self.data();
229         let lo = cmp::max(span.hi.0, span.lo.0 + 1);
230         Span::new(BytePos(lo), BytePos(lo), span.ctxt)
231     }
232
233     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
234     pub fn substitute_dummy(self, other: Span) -> Span {
235         if self.source_equal(&DUMMY_SP) { other } else { self }
236     }
237
238     /// Return true if `self` fully encloses `other`.
239     pub fn contains(self, other: Span) -> bool {
240         let span = self.data();
241         let other = other.data();
242         span.lo <= other.lo && other.hi <= span.hi
243     }
244
245     /// Return true if the spans are equal with regards to the source text.
246     ///
247     /// Use this instead of `==` when either span could be generated code,
248     /// and you only care that they point to the same bytes of source text.
249     pub fn source_equal(&self, other: &Span) -> bool {
250         let span = self.data();
251         let other = other.data();
252         span.lo == other.lo && span.hi == other.hi
253     }
254
255     /// Returns `Some(span)`, where the start is trimmed by the end of `other`
256     pub fn trim_start(self, other: Span) -> Option<Span> {
257         let span = self.data();
258         let other = other.data();
259         if span.hi > other.hi {
260             Some(span.with_lo(cmp::max(span.lo, other.hi)))
261         } else {
262             None
263         }
264     }
265
266     /// Return the source span - this is either the supplied span, or the span for
267     /// the macro callsite that expanded to it.
268     pub fn source_callsite(self) -> Span {
269         self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
270     }
271
272     /// Return the source callee.
273     ///
274     /// Returns None if the supplied span has no expansion trace,
275     /// else returns the NameAndSpan for the macro definition
276     /// corresponding to the source callsite.
277     pub fn source_callee(self) -> Option<NameAndSpan> {
278         fn source_callee(info: ExpnInfo) -> NameAndSpan {
279             match info.call_site.ctxt().outer().expn_info() {
280                 Some(info) => source_callee(info),
281                 None => info.callee,
282             }
283         }
284         self.ctxt().outer().expn_info().map(source_callee)
285     }
286
287     /// Check if a span is "internal" to a macro in which #[unstable]
288     /// items can be used (that is, a macro marked with
289     /// `#[allow_internal_unstable]`).
290     pub fn allows_unstable(&self) -> bool {
291         match self.ctxt().outer().expn_info() {
292             Some(info) => info.callee.allow_internal_unstable,
293             None => false,
294         }
295     }
296
297     /// Check if this span arises from a compiler desugaring of kind `kind`.
298     pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
299         match self.ctxt().outer().expn_info() {
300             Some(info) => match info.callee.format {
301                 ExpnFormat::CompilerDesugaring(k) => k == kind,
302                 _ => false,
303             },
304             None => false,
305         }
306     }
307
308     /// Return the compiler desugaring that created this span, or None
309     /// if this span is not from a desugaring.
310     pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
311         match self.ctxt().outer().expn_info() {
312             Some(info) => match info.callee.format {
313                 ExpnFormat::CompilerDesugaring(k) => Some(k),
314                 _ => None
315             },
316             None => None
317         }
318     }
319
320     /// Check if a span is "internal" to a macro in which `unsafe`
321     /// can be used without triggering the `unsafe_code` lint
322     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
323     pub fn allows_unsafe(&self) -> bool {
324         match self.ctxt().outer().expn_info() {
325             Some(info) => info.callee.allow_internal_unsafe,
326             None => false,
327         }
328     }
329
330     pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
331         let mut prev_span = DUMMY_SP;
332         let mut result = vec![];
333         loop {
334             let info = match self.ctxt().outer().expn_info() {
335                 Some(info) => info,
336                 None => break,
337             };
338
339             let (pre, post) = match info.callee.format {
340                 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
341                 ExpnFormat::MacroBang(..) => ("", "!"),
342                 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
343             };
344             let macro_decl_name = format!("{}{}{}", pre, info.callee.name(), post);
345             let def_site_span = info.callee.span;
346
347             // Don't print recursive invocations
348             if !info.call_site.source_equal(&prev_span) {
349                 result.push(MacroBacktrace {
350                     call_site: info.call_site,
351                     macro_decl_name,
352                     def_site_span,
353                 });
354             }
355
356             prev_span = self;
357             self = info.call_site;
358         }
359         result
360     }
361
362     /// Return a `Span` that would enclose both `self` and `end`.
363     pub fn to(self, end: Span) -> Span {
364         let span = self.data();
365         let end = end.data();
366         Span::new(
367             cmp::min(span.lo, end.lo),
368             cmp::max(span.hi, end.hi),
369             // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
370             if span.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
371         )
372     }
373
374     /// Return a `Span` between the end of `self` to the beginning of `end`.
375     pub fn between(self, end: Span) -> Span {
376         let span = self.data();
377         let end = end.data();
378         Span::new(
379             span.hi,
380             end.lo,
381             if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
382         )
383     }
384
385     /// Return a `Span` between the beginning of `self` to the beginning of `end`.
386     pub fn until(self, end: Span) -> Span {
387         let span = self.data();
388         let end = end.data();
389         Span::new(
390             span.lo,
391             end.lo,
392             if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
393         )
394     }
395 }
396
397 #[derive(Clone, Debug)]
398 pub struct SpanLabel {
399     /// The span we are going to include in the final snippet.
400     pub span: Span,
401
402     /// Is this a primary span? This is the "locus" of the message,
403     /// and is indicated with a `^^^^` underline, versus `----`.
404     pub is_primary: bool,
405
406     /// What label should we attach to this span (if any)?
407     pub label: Option<String>,
408 }
409
410 impl Default for Span {
411     fn default() -> Self {
412         DUMMY_SP
413     }
414 }
415
416 impl serialize::UseSpecializedEncodable for Span {
417     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
418         let span = self.data();
419         s.emit_struct("Span", 2, |s| {
420             s.emit_struct_field("lo", 0, |s| {
421                 span.lo.encode(s)
422             })?;
423
424             s.emit_struct_field("hi", 1, |s| {
425                 span.hi.encode(s)
426             })
427         })
428     }
429 }
430
431 impl serialize::UseSpecializedDecodable for Span {
432     fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
433         d.read_struct("Span", 2, |d| {
434             let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
435             let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
436             Ok(Span::new(lo, hi, NO_EXPANSION))
437         })
438     }
439 }
440
441 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
442     f.debug_struct("Span")
443         .field("lo", &span.lo())
444         .field("hi", &span.hi())
445         .field("ctxt", &span.ctxt())
446         .finish()
447 }
448
449 impl fmt::Debug for Span {
450     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
451         SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
452     }
453 }
454
455 impl fmt::Debug for SpanData {
456     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
457         SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
458     }
459 }
460
461 impl MultiSpan {
462     pub fn new() -> MultiSpan {
463         MultiSpan {
464             primary_spans: vec![],
465             span_labels: vec![]
466         }
467     }
468
469     pub fn from_span(primary_span: Span) -> MultiSpan {
470         MultiSpan {
471             primary_spans: vec![primary_span],
472             span_labels: vec![]
473         }
474     }
475
476     pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
477         MultiSpan {
478             primary_spans: vec,
479             span_labels: vec![]
480         }
481     }
482
483     pub fn push_span_label(&mut self, span: Span, label: String) {
484         self.span_labels.push((span, label));
485     }
486
487     /// Selects the first primary span (if any)
488     pub fn primary_span(&self) -> Option<Span> {
489         self.primary_spans.first().cloned()
490     }
491
492     /// Returns all primary spans.
493     pub fn primary_spans(&self) -> &[Span] {
494         &self.primary_spans
495     }
496
497     /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't
498     /// display well (like std macros). Returns true if replacements occurred.
499     pub fn replace(&mut self, before: Span, after: Span) -> bool {
500         let mut replacements_occurred = false;
501         for primary_span in &mut self.primary_spans {
502             if *primary_span == before {
503                 *primary_span = after;
504                 replacements_occurred = true;
505             }
506         }
507         for span_label in &mut self.span_labels {
508             if span_label.0 == before {
509                 span_label.0 = after;
510                 replacements_occurred = true;
511             }
512         }
513         replacements_occurred
514     }
515
516     /// Returns the strings to highlight. We always ensure that there
517     /// is an entry for each of the primary spans -- for each primary
518     /// span P, if there is at least one label with span P, we return
519     /// those labels (marked as primary). But otherwise we return
520     /// `SpanLabel` instances with empty labels.
521     pub fn span_labels(&self) -> Vec<SpanLabel> {
522         let is_primary = |span| self.primary_spans.contains(&span);
523         let mut span_labels = vec![];
524
525         for &(span, ref label) in &self.span_labels {
526             span_labels.push(SpanLabel {
527                 span,
528                 is_primary: is_primary(span),
529                 label: Some(label.clone())
530             });
531         }
532
533         for &span in &self.primary_spans {
534             if !span_labels.iter().any(|sl| sl.span == span) {
535                 span_labels.push(SpanLabel {
536                     span,
537                     is_primary: true,
538                     label: None
539                 });
540             }
541         }
542
543         span_labels
544     }
545 }
546
547 impl From<Span> for MultiSpan {
548     fn from(span: Span) -> MultiSpan {
549         MultiSpan::from_span(span)
550     }
551 }
552
553 impl From<Vec<Span>> for MultiSpan {
554     fn from(spans: Vec<Span>) -> MultiSpan {
555         MultiSpan::from_spans(spans)
556     }
557 }
558
559 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
560
561 /// Identifies an offset of a multi-byte character in a FileMap
562 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
563 pub struct MultiByteChar {
564     /// The absolute offset of the character in the CodeMap
565     pub pos: BytePos,
566     /// The number of bytes, >=2
567     pub bytes: usize,
568 }
569
570 /// Identifies an offset of a non-narrow character in a FileMap
571 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
572 pub enum NonNarrowChar {
573     /// Represents a zero-width character
574     ZeroWidth(BytePos),
575     /// Represents a wide (fullwidth) character
576     Wide(BytePos),
577     /// Represents a tab character, represented visually with a width of 4 characters
578     Tab(BytePos),
579 }
580
581 impl NonNarrowChar {
582     fn new(pos: BytePos, width: usize) -> Self {
583         match width {
584             0 => NonNarrowChar::ZeroWidth(pos),
585             2 => NonNarrowChar::Wide(pos),
586             4 => NonNarrowChar::Tab(pos),
587             _ => panic!("width {} given for non-narrow character", width),
588         }
589     }
590
591     /// Returns the absolute offset of the character in the CodeMap
592     pub fn pos(&self) -> BytePos {
593         match *self {
594             NonNarrowChar::ZeroWidth(p) |
595             NonNarrowChar::Wide(p) |
596             NonNarrowChar::Tab(p) => p,
597         }
598     }
599
600     /// Returns the width of the character, 0 (zero-width) or 2 (wide)
601     pub fn width(&self) -> usize {
602         match *self {
603             NonNarrowChar::ZeroWidth(_) => 0,
604             NonNarrowChar::Wide(_) => 2,
605             NonNarrowChar::Tab(_) => 4,
606         }
607     }
608 }
609
610 impl Add<BytePos> for NonNarrowChar {
611     type Output = Self;
612
613     fn add(self, rhs: BytePos) -> Self {
614         match self {
615             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
616             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
617             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
618         }
619     }
620 }
621
622 impl Sub<BytePos> for NonNarrowChar {
623     type Output = Self;
624
625     fn sub(self, rhs: BytePos) -> Self {
626         match self {
627             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
628             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
629             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
630         }
631     }
632 }
633
634 /// The state of the lazy external source loading mechanism of a FileMap.
635 #[derive(PartialEq, Eq, Clone)]
636 pub enum ExternalSource {
637     /// The external source has been loaded already.
638     Present(String),
639     /// No attempt has been made to load the external source.
640     AbsentOk,
641     /// A failed attempt has been made to load the external source.
642     AbsentErr,
643     /// No external source has to be loaded, since the FileMap represents a local crate.
644     Unneeded,
645 }
646
647 impl ExternalSource {
648     pub fn is_absent(&self) -> bool {
649         match *self {
650             ExternalSource::Present(_) => false,
651             _ => true,
652         }
653     }
654
655     pub fn get_source(&self) -> Option<&str> {
656         match *self {
657             ExternalSource::Present(ref src) => Some(src),
658             _ => None,
659         }
660     }
661 }
662
663 /// A single source in the CodeMap.
664 #[derive(Clone)]
665 pub struct FileMap {
666     /// The name of the file that the source came from, source that doesn't
667     /// originate from files has names between angle brackets by convention,
668     /// e.g. `<anon>`
669     pub name: FileName,
670     /// True if the `name` field above has been modified by -Zremap-path-prefix
671     pub name_was_remapped: bool,
672     /// The unmapped path of the file that the source came from.
673     /// Set to `None` if the FileMap was imported from an external crate.
674     pub unmapped_path: Option<FileName>,
675     /// Indicates which crate this FileMap was imported from.
676     pub crate_of_origin: u32,
677     /// The complete source code
678     pub src: Option<Rc<String>>,
679     /// The source code's hash
680     pub src_hash: u128,
681     /// The external source code (used for external crates, which will have a `None`
682     /// value as `self.src`.
683     pub external_src: RefCell<ExternalSource>,
684     /// The start position of this source in the CodeMap
685     pub start_pos: BytePos,
686     /// The end position of this source in the CodeMap
687     pub end_pos: BytePos,
688     /// Locations of lines beginnings in the source code
689     pub lines: RefCell<Vec<BytePos>>,
690     /// Locations of multi-byte characters in the source code
691     pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
692     /// Width of characters that are not narrow in the source code
693     pub non_narrow_chars: RefCell<Vec<NonNarrowChar>>,
694     /// A hash of the filename, used for speeding up the incr. comp. hashing.
695     pub name_hash: u128,
696 }
697
698 impl Encodable for FileMap {
699     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
700         s.emit_struct("FileMap", 8, |s| {
701             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
702             s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
703             s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
704             s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
705             s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
706             s.emit_struct_field("lines", 6, |s| {
707                 let lines = self.lines.borrow();
708                 // store the length
709                 s.emit_u32(lines.len() as u32)?;
710
711                 if !lines.is_empty() {
712                     // In order to preserve some space, we exploit the fact that
713                     // the lines list is sorted and individual lines are
714                     // probably not that long. Because of that we can store lines
715                     // as a difference list, using as little space as possible
716                     // for the differences.
717                     let max_line_length = if lines.len() == 1 {
718                         0
719                     } else {
720                         lines.windows(2)
721                              .map(|w| w[1] - w[0])
722                              .map(|bp| bp.to_usize())
723                              .max()
724                              .unwrap()
725                     };
726
727                     let bytes_per_diff: u8 = match max_line_length {
728                         0 ... 0xFF => 1,
729                         0x100 ... 0xFFFF => 2,
730                         _ => 4
731                     };
732
733                     // Encode the number of bytes used per diff.
734                     bytes_per_diff.encode(s)?;
735
736                     // Encode the first element.
737                     lines[0].encode(s)?;
738
739                     let diff_iter = (&lines[..]).windows(2)
740                                                 .map(|w| (w[1] - w[0]));
741
742                     match bytes_per_diff {
743                         1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
744                         2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
745                         4 => for diff in diff_iter { diff.0.encode(s)? },
746                         _ => unreachable!()
747                     }
748                 }
749
750                 Ok(())
751             })?;
752             s.emit_struct_field("multibyte_chars", 7, |s| {
753                 (*self.multibyte_chars.borrow()).encode(s)
754             })?;
755             s.emit_struct_field("non_narrow_chars", 8, |s| {
756                 (*self.non_narrow_chars.borrow()).encode(s)
757             })?;
758             s.emit_struct_field("name_hash", 9, |s| {
759                 self.name_hash.encode(s)
760             })
761         })
762     }
763 }
764
765 impl Decodable for FileMap {
766     fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
767
768         d.read_struct("FileMap", 8, |d| {
769             let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
770             let name_was_remapped: bool =
771                 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
772             let src_hash: u128 =
773                 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
774             let start_pos: BytePos =
775                 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
776             let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
777             let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
778                 let num_lines: u32 = Decodable::decode(d)?;
779                 let mut lines = Vec::with_capacity(num_lines as usize);
780
781                 if num_lines > 0 {
782                     // Read the number of bytes used per diff.
783                     let bytes_per_diff: u8 = Decodable::decode(d)?;
784
785                     // Read the first element.
786                     let mut line_start: BytePos = Decodable::decode(d)?;
787                     lines.push(line_start);
788
789                     for _ in 1..num_lines {
790                         let diff = match bytes_per_diff {
791                             1 => d.read_u8()? as u32,
792                             2 => d.read_u16()? as u32,
793                             4 => d.read_u32()?,
794                             _ => unreachable!()
795                         };
796
797                         line_start = line_start + BytePos(diff);
798
799                         lines.push(line_start);
800                     }
801                 }
802
803                 Ok(lines)
804             })?;
805             let multibyte_chars: Vec<MultiByteChar> =
806                 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
807             let non_narrow_chars: Vec<NonNarrowChar> =
808                 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
809             let name_hash: u128 =
810                 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
811             Ok(FileMap {
812                 name,
813                 name_was_remapped,
814                 unmapped_path: None,
815                 // `crate_of_origin` has to be set by the importer.
816                 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
817                 // That constant is not available here unfortunately :(
818                 crate_of_origin: ::std::u32::MAX - 1,
819                 start_pos,
820                 end_pos,
821                 src: None,
822                 src_hash,
823                 external_src: RefCell::new(ExternalSource::AbsentOk),
824                 lines: RefCell::new(lines),
825                 multibyte_chars: RefCell::new(multibyte_chars),
826                 non_narrow_chars: RefCell::new(non_narrow_chars),
827                 name_hash,
828             })
829         })
830     }
831 }
832
833 impl fmt::Debug for FileMap {
834     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
835         write!(fmt, "FileMap({})", self.name)
836     }
837 }
838
839 impl FileMap {
840     pub fn new(name: FileName,
841                name_was_remapped: bool,
842                unmapped_path: FileName,
843                mut src: String,
844                start_pos: BytePos) -> FileMap {
845         remove_bom(&mut src);
846
847         let src_hash = {
848             let mut hasher: StableHasher<u128> = StableHasher::new();
849             hasher.write(src.as_bytes());
850             hasher.finish()
851         };
852         let name_hash = {
853             let mut hasher: StableHasher<u128> = StableHasher::new();
854             name.hash(&mut hasher);
855             hasher.finish()
856         };
857         let end_pos = start_pos.to_usize() + src.len();
858
859         FileMap {
860             name,
861             name_was_remapped,
862             unmapped_path: Some(unmapped_path),
863             crate_of_origin: 0,
864             src: Some(Rc::new(src)),
865             src_hash,
866             external_src: RefCell::new(ExternalSource::Unneeded),
867             start_pos,
868             end_pos: Pos::from_usize(end_pos),
869             lines: RefCell::new(Vec::new()),
870             multibyte_chars: RefCell::new(Vec::new()),
871             non_narrow_chars: RefCell::new(Vec::new()),
872             name_hash,
873         }
874     }
875
876     /// EFFECT: register a start-of-line offset in the
877     /// table of line-beginnings.
878     /// UNCHECKED INVARIANT: these offsets must be added in the right
879     /// order and must be in the right places; there is shared knowledge
880     /// about what ends a line between this file and parse.rs
881     /// WARNING: pos param here is the offset relative to start of CodeMap,
882     /// and CodeMap will append a newline when adding a filemap without a newline at the end,
883     /// so the safe way to call this is with value calculated as
884     /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
885     pub fn next_line(&self, pos: BytePos) {
886         // the new charpos must be > the last one (or it's the first one).
887         let mut lines = self.lines.borrow_mut();
888         let line_len = lines.len();
889         assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
890         lines.push(pos);
891     }
892
893     /// Add externally loaded source.
894     /// If the hash of the input doesn't match or no input is supplied via None,
895     /// it is interpreted as an error and the corresponding enum variant is set.
896     /// The return value signifies whether some kind of source is present.
897     pub fn add_external_src<F>(&self, get_src: F) -> bool
898         where F: FnOnce() -> Option<String>
899     {
900         if *self.external_src.borrow() == ExternalSource::AbsentOk {
901             let src = get_src();
902             let mut external_src = self.external_src.borrow_mut();
903             if let Some(src) = src {
904                 let mut hasher: StableHasher<u128> = StableHasher::new();
905                 hasher.write(src.as_bytes());
906
907                 if hasher.finish() == self.src_hash {
908                     *external_src = ExternalSource::Present(src);
909                     return true;
910                 }
911             } else {
912                 *external_src = ExternalSource::AbsentErr;
913             }
914
915             false
916         } else {
917             self.src.is_some() || self.external_src.borrow().get_source().is_some()
918         }
919     }
920
921     /// Get a line from the list of pre-computed line-beginnings.
922     /// The line number here is 0-based.
923     pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
924         fn get_until_newline(src: &str, begin: usize) -> &str {
925             // We can't use `lines.get(line_number+1)` because we might
926             // be parsing when we call this function and thus the current
927             // line is the last one we have line info for.
928             let slice = &src[begin..];
929             match slice.find('\n') {
930                 Some(e) => &slice[..e],
931                 None => slice
932             }
933         }
934
935         let lines = self.lines.borrow();
936         let line = if let Some(line) = lines.get(line_number) {
937             line
938         } else {
939             return None;
940         };
941         let begin: BytePos = *line - self.start_pos;
942         let begin = begin.to_usize();
943
944         if let Some(ref src) = self.src {
945             Some(Cow::from(get_until_newline(src, begin)))
946         } else if let Some(src) = self.external_src.borrow().get_source() {
947             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
948         } else {
949             None
950         }
951     }
952
953     pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
954         assert!(bytes >=2 && bytes <= 4);
955         let mbc = MultiByteChar {
956             pos,
957             bytes,
958         };
959         self.multibyte_chars.borrow_mut().push(mbc);
960     }
961
962     pub fn record_width(&self, pos: BytePos, ch: char) {
963         let width = match ch {
964             '\t' =>
965                 // Tabs will consume 4 columns.
966                 4,
967             '\n' =>
968                 // Make newlines take one column so that displayed spans can point them.
969                 1,
970             ch =>
971                 // Assume control characters are zero width.
972                 // FIXME: How can we decide between `width` and `width_cjk`?
973                 unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0),
974         };
975         // Only record non-narrow characters.
976         if width != 1 {
977             self.non_narrow_chars.borrow_mut().push(NonNarrowChar::new(pos, width));
978         }
979     }
980
981     pub fn is_real_file(&self) -> bool {
982         self.name.is_real()
983     }
984
985     pub fn is_imported(&self) -> bool {
986         self.src.is_none()
987     }
988
989     pub fn byte_length(&self) -> u32 {
990         self.end_pos.0 - self.start_pos.0
991     }
992     pub fn count_lines(&self) -> usize {
993         self.lines.borrow().len()
994     }
995
996     /// Find the line containing the given position. The return value is the
997     /// index into the `lines` array of this FileMap, not the 1-based line
998     /// number. If the filemap is empty or the position is located before the
999     /// first line, None is returned.
1000     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1001         let lines = self.lines.borrow();
1002         if lines.len() == 0 {
1003             return None;
1004         }
1005
1006         let line_index = lookup_line(&lines[..], pos);
1007         assert!(line_index < lines.len() as isize);
1008         if line_index >= 0 {
1009             Some(line_index as usize)
1010         } else {
1011             None
1012         }
1013     }
1014
1015     pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1016         if self.start_pos == self.end_pos {
1017             return (self.start_pos, self.end_pos);
1018         }
1019
1020         let lines = self.lines.borrow();
1021         assert!(line_index < lines.len());
1022         if line_index == (lines.len() - 1) {
1023             (lines[line_index], self.end_pos)
1024         } else {
1025             (lines[line_index], lines[line_index + 1])
1026         }
1027     }
1028
1029     #[inline]
1030     pub fn contains(&self, byte_pos: BytePos) -> bool {
1031         byte_pos >= self.start_pos && byte_pos <= self.end_pos
1032     }
1033 }
1034
1035 /// Remove utf-8 BOM if any.
1036 fn remove_bom(src: &mut String) {
1037     if src.starts_with("\u{feff}") {
1038         src.drain(..3);
1039     }
1040 }
1041
1042 // _____________________________________________________________________________
1043 // Pos, BytePos, CharPos
1044 //
1045
1046 pub trait Pos {
1047     fn from_usize(n: usize) -> Self;
1048     fn to_usize(&self) -> usize;
1049 }
1050
1051 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1052 /// a lot of them.
1053 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1054 pub struct BytePos(pub u32);
1055
1056 /// A character offset. Because of multibyte utf8 characters, a byte offset
1057 /// is not equivalent to a character offset. The CodeMap will convert BytePos
1058 /// values to CharPos values as necessary.
1059 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1060 pub struct CharPos(pub usize);
1061
1062 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
1063 // have been unsuccessful
1064
1065 impl Pos for BytePos {
1066     fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1067     fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
1068 }
1069
1070 impl Add for BytePos {
1071     type Output = BytePos;
1072
1073     fn add(self, rhs: BytePos) -> BytePos {
1074         BytePos((self.to_usize() + rhs.to_usize()) as u32)
1075     }
1076 }
1077
1078 impl Sub for BytePos {
1079     type Output = BytePos;
1080
1081     fn sub(self, rhs: BytePos) -> BytePos {
1082         BytePos((self.to_usize() - rhs.to_usize()) as u32)
1083     }
1084 }
1085
1086 impl Encodable for BytePos {
1087     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1088         s.emit_u32(self.0)
1089     }
1090 }
1091
1092 impl Decodable for BytePos {
1093     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1094         Ok(BytePos(d.read_u32()?))
1095     }
1096 }
1097
1098 impl Pos for CharPos {
1099     fn from_usize(n: usize) -> CharPos { CharPos(n) }
1100     fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
1101 }
1102
1103 impl Add for CharPos {
1104     type Output = CharPos;
1105
1106     fn add(self, rhs: CharPos) -> CharPos {
1107         CharPos(self.to_usize() + rhs.to_usize())
1108     }
1109 }
1110
1111 impl Sub for CharPos {
1112     type Output = CharPos;
1113
1114     fn sub(self, rhs: CharPos) -> CharPos {
1115         CharPos(self.to_usize() - rhs.to_usize())
1116     }
1117 }
1118
1119 // _____________________________________________________________________________
1120 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
1121 //
1122
1123 /// A source code location used for error reporting
1124 #[derive(Debug, Clone)]
1125 pub struct Loc {
1126     /// Information about the original source
1127     pub file: Rc<FileMap>,
1128     /// The (1-based) line number
1129     pub line: usize,
1130     /// The (0-based) column offset
1131     pub col: CharPos,
1132     /// The (0-based) column offset when displayed
1133     pub col_display: usize,
1134 }
1135
1136 /// A source code location used as the result of lookup_char_pos_adj
1137 // Actually, *none* of the clients use the filename *or* file field;
1138 // perhaps they should just be removed.
1139 #[derive(Debug)]
1140 pub struct LocWithOpt {
1141     pub filename: FileName,
1142     pub line: usize,
1143     pub col: CharPos,
1144     pub file: Option<Rc<FileMap>>,
1145 }
1146
1147 // used to be structural records. Better names, anyone?
1148 #[derive(Debug)]
1149 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
1150 #[derive(Debug)]
1151 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
1152
1153 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1154 pub struct LineInfo {
1155     /// Index of line, starting from 0.
1156     pub line_index: usize,
1157
1158     /// Column in line where span begins, starting from 0.
1159     pub start_col: CharPos,
1160
1161     /// Column in line where span ends, starting from 0, exclusive.
1162     pub end_col: CharPos,
1163 }
1164
1165 pub struct FileLines {
1166     pub file: Rc<FileMap>,
1167     pub lines: Vec<LineInfo>
1168 }
1169
1170 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
1171                 Cell::new(default_span_debug));
1172
1173 #[derive(Debug)]
1174 pub struct MacroBacktrace {
1175     /// span where macro was applied to generate this code
1176     pub call_site: Span,
1177
1178     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1179     pub macro_decl_name: String,
1180
1181     /// span where macro was defined (if known)
1182     pub def_site_span: Option<Span>,
1183 }
1184
1185 // _____________________________________________________________________________
1186 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
1187 //
1188
1189 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1190
1191 #[derive(Clone, PartialEq, Eq, Debug)]
1192 pub enum SpanLinesError {
1193     IllFormedSpan(Span),
1194     DistinctSources(DistinctSources),
1195 }
1196
1197 #[derive(Clone, PartialEq, Eq, Debug)]
1198 pub enum SpanSnippetError {
1199     IllFormedSpan(Span),
1200     DistinctSources(DistinctSources),
1201     MalformedForCodemap(MalformedCodemapPositions),
1202     SourceNotAvailable { filename: FileName }
1203 }
1204
1205 #[derive(Clone, PartialEq, Eq, Debug)]
1206 pub struct DistinctSources {
1207     pub begin: (FileName, BytePos),
1208     pub end: (FileName, BytePos)
1209 }
1210
1211 #[derive(Clone, PartialEq, Eq, Debug)]
1212 pub struct MalformedCodemapPositions {
1213     pub name: FileName,
1214     pub source_len: usize,
1215     pub begin_pos: BytePos,
1216     pub end_pos: BytePos
1217 }
1218
1219 // Given a slice of line start positions and a position, returns the index of
1220 // the line the position is on. Returns -1 if the position is located before
1221 // the first line.
1222 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1223     match lines.binary_search(&pos) {
1224         Ok(line) => line as isize,
1225         Err(line) => line as isize - 1
1226     }
1227 }
1228
1229 #[cfg(test)]
1230 mod tests {
1231     use super::{lookup_line, BytePos};
1232
1233     #[test]
1234     fn test_lookup_line() {
1235
1236         let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1237
1238         assert_eq!(lookup_line(lines, BytePos(0)), -1);
1239         assert_eq!(lookup_line(lines, BytePos(3)),  0);
1240         assert_eq!(lookup_line(lines, BytePos(4)),  0);
1241
1242         assert_eq!(lookup_line(lines, BytePos(16)), 0);
1243         assert_eq!(lookup_line(lines, BytePos(17)), 1);
1244         assert_eq!(lookup_line(lines, BytePos(18)), 1);
1245
1246         assert_eq!(lookup_line(lines, BytePos(28)), 2);
1247         assert_eq!(lookup_line(lines, BytePos(29)), 2);
1248     }
1249 }