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