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