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