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