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