]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/lib.rs
Auto merge of #78068 - RalfJung:union-safe-assign, r=nikomatsakis
[rust.git] / compiler / rustc_span / src / 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/nightly-rustc/")]
8 #![feature(array_windows)]
9 #![feature(crate_visibility_modifier)]
10 #![feature(const_fn)]
11 #![feature(const_panic)]
12 #![feature(negative_impls)]
13 #![feature(nll)]
14 #![feature(min_specialization)]
15 #![feature(option_expect_none)]
16
17 #[macro_use]
18 extern crate rustc_macros;
19
20 use rustc_data_structures::AtomicRef;
21 use rustc_macros::HashStable_Generic;
22 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
23
24 mod caching_source_map_view;
25 pub mod source_map;
26 pub use self::caching_source_map_view::CachingSourceMapView;
27 use source_map::SourceMap;
28
29 pub mod edition;
30 use edition::Edition;
31 pub mod hygiene;
32 pub use hygiene::SyntaxContext;
33 use hygiene::Transparency;
34 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, ForLoopLoc, MacroKind};
35 pub mod def_id;
36 use def_id::{CrateNum, DefId, LOCAL_CRATE};
37 pub mod lev_distance;
38 mod span_encoding;
39 pub use span_encoding::{Span, DUMMY_SP};
40
41 pub mod symbol;
42 pub use symbol::{sym, Symbol};
43
44 mod analyze_source_file;
45 pub mod fatal_error;
46
47 use rustc_data_structures::fingerprint::Fingerprint;
48 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
49 use rustc_data_structures::sync::{Lock, Lrc};
50
51 use std::borrow::Cow;
52 use std::cell::RefCell;
53 use std::cmp::{self, Ordering};
54 use std::fmt;
55 use std::hash::Hash;
56 use std::ops::{Add, Range, Sub};
57 use std::path::{Path, PathBuf};
58 use std::str::FromStr;
59
60 use md5::Md5;
61 use sha1::Digest;
62 use sha1::Sha1;
63 use sha2::Sha256;
64
65 use tracing::debug;
66
67 #[cfg(test)]
68 mod tests;
69
70 // Per-session global variables: this struct is stored in thread-local storage
71 // in such a way that it is accessible without any kind of handle to all
72 // threads within the compilation session, but is not accessible outside the
73 // session.
74 pub struct SessionGlobals {
75     symbol_interner: Lock<symbol::Interner>,
76     span_interner: Lock<span_encoding::SpanInterner>,
77     hygiene_data: Lock<hygiene::HygieneData>,
78     source_map: Lock<Option<Lrc<SourceMap>>>,
79 }
80
81 impl SessionGlobals {
82     pub fn new(edition: Edition) -> SessionGlobals {
83         SessionGlobals {
84             symbol_interner: Lock::new(symbol::Interner::fresh()),
85             span_interner: Lock::new(span_encoding::SpanInterner::default()),
86             hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
87             source_map: Lock::new(None),
88         }
89     }
90 }
91
92 pub fn with_session_globals<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
93     let session_globals = SessionGlobals::new(edition);
94     SESSION_GLOBALS.set(&session_globals, f)
95 }
96
97 pub fn with_default_session_globals<R>(f: impl FnOnce() -> R) -> R {
98     with_session_globals(edition::DEFAULT_EDITION, f)
99 }
100
101 // If this ever becomes non thread-local, `decode_syntax_context`
102 // and `decode_expn_id` will need to be updated to handle concurrent
103 // deserialization.
104 scoped_tls::scoped_thread_local!(pub static SESSION_GLOBALS: SessionGlobals);
105
106 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
107 //
108 // FIXME: We should use this enum or something like it to get rid of the
109 // use of magic `/rust/1.x/...` paths across the board.
110 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
111 #[derive(HashStable_Generic, Decodable, Encodable)]
112 pub enum RealFileName {
113     Named(PathBuf),
114     /// For de-virtualized paths (namely paths into libstd that have been mapped
115     /// to the appropriate spot on the local host's file system),
116     Devirtualized {
117         /// `local_path` is the (host-dependent) local path to the file.
118         local_path: PathBuf,
119         /// `virtual_name` is the stable path rustc will store internally within
120         /// build artifacts.
121         virtual_name: PathBuf,
122     },
123 }
124
125 impl RealFileName {
126     /// Returns the path suitable for reading from the file system on the local host.
127     /// Avoid embedding this in build artifacts; see `stable_name` for that.
128     pub fn local_path(&self) -> &Path {
129         match self {
130             RealFileName::Named(p)
131             | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => &p,
132         }
133     }
134
135     /// Returns the path suitable for reading from the file system on the local host.
136     /// Avoid embedding this in build artifacts; see `stable_name` for that.
137     pub fn into_local_path(self) -> PathBuf {
138         match self {
139             RealFileName::Named(p)
140             | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => p,
141         }
142     }
143
144     /// Returns the path suitable for embedding into build artifacts. Note that
145     /// a virtualized path will not correspond to a valid file system path; see
146     /// `local_path` for something that is more likely to return paths into the
147     /// local host file system.
148     pub fn stable_name(&self) -> &Path {
149         match self {
150             RealFileName::Named(p)
151             | RealFileName::Devirtualized { local_path: _, virtual_name: p } => &p,
152         }
153     }
154 }
155
156 /// Differentiates between real files and common virtual files.
157 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
158 #[derive(HashStable_Generic, Decodable, Encodable)]
159 pub enum FileName {
160     Real(RealFileName),
161     /// Call to `quote!`.
162     QuoteExpansion(u64),
163     /// Command line.
164     Anon(u64),
165     /// Hack in `src/librustc_ast/parse.rs`.
166     // FIXME(jseyfried)
167     MacroExpansion(u64),
168     ProcMacroSourceCode(u64),
169     /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
170     CfgSpec(u64),
171     /// Strings provided as crate attributes in the CLI.
172     CliCrateAttr(u64),
173     /// Custom sources for explicit parser calls from plugins and drivers.
174     Custom(String),
175     DocTest(PathBuf, isize),
176     /// Post-substitution inline assembly from LLVM
177     InlineAsm(u64),
178 }
179
180 impl std::fmt::Display for FileName {
181     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182         use FileName::*;
183         match *self {
184             Real(RealFileName::Named(ref path)) => write!(fmt, "{}", path.display()),
185             // FIXME: might be nice to display both compoments of Devirtualized.
186             // But for now (to backport fix for issue #70924), best to not
187             // perturb diagnostics so its obvious test suite still works.
188             Real(RealFileName::Devirtualized { ref local_path, virtual_name: _ }) => {
189                 write!(fmt, "{}", local_path.display())
190             }
191             QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
192             MacroExpansion(_) => write!(fmt, "<macro expansion>"),
193             Anon(_) => write!(fmt, "<anon>"),
194             ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
195             CfgSpec(_) => write!(fmt, "<cfgspec>"),
196             CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
197             Custom(ref s) => write!(fmt, "<{}>", s),
198             DocTest(ref path, _) => write!(fmt, "{}", path.display()),
199             InlineAsm(_) => write!(fmt, "<inline asm>"),
200         }
201     }
202 }
203
204 impl From<PathBuf> for FileName {
205     fn from(p: PathBuf) -> Self {
206         assert!(!p.to_string_lossy().ends_with('>'));
207         FileName::Real(RealFileName::Named(p))
208     }
209 }
210
211 impl FileName {
212     pub fn is_real(&self) -> bool {
213         use FileName::*;
214         match *self {
215             Real(_) => true,
216             Anon(_)
217             | MacroExpansion(_)
218             | ProcMacroSourceCode(_)
219             | CfgSpec(_)
220             | CliCrateAttr(_)
221             | Custom(_)
222             | QuoteExpansion(_)
223             | DocTest(_, _)
224             | InlineAsm(_) => false,
225         }
226     }
227
228     pub fn macro_expansion_source_code(src: &str) -> FileName {
229         let mut hasher = StableHasher::new();
230         src.hash(&mut hasher);
231         FileName::MacroExpansion(hasher.finish())
232     }
233
234     pub fn anon_source_code(src: &str) -> FileName {
235         let mut hasher = StableHasher::new();
236         src.hash(&mut hasher);
237         FileName::Anon(hasher.finish())
238     }
239
240     pub fn proc_macro_source_code(src: &str) -> FileName {
241         let mut hasher = StableHasher::new();
242         src.hash(&mut hasher);
243         FileName::ProcMacroSourceCode(hasher.finish())
244     }
245
246     pub fn cfg_spec_source_code(src: &str) -> FileName {
247         let mut hasher = StableHasher::new();
248         src.hash(&mut hasher);
249         FileName::QuoteExpansion(hasher.finish())
250     }
251
252     pub fn cli_crate_attr_source_code(src: &str) -> FileName {
253         let mut hasher = StableHasher::new();
254         src.hash(&mut hasher);
255         FileName::CliCrateAttr(hasher.finish())
256     }
257
258     pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
259         FileName::DocTest(path, line)
260     }
261
262     pub fn inline_asm_source_code(src: &str) -> FileName {
263         let mut hasher = StableHasher::new();
264         src.hash(&mut hasher);
265         FileName::InlineAsm(hasher.finish())
266     }
267 }
268
269 /// Spans represent a region of code, used for error reporting. Positions in spans
270 /// are *absolute* positions from the beginning of the source_map, not positions
271 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
272 /// to the original source.
273 /// You must be careful if the span crosses more than one file - you will not be
274 /// able to use many of the functions on spans in source_map and you cannot assume
275 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
276 /// range between files.
277 ///
278 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
279 /// sent to other threads, but some pieces of performance infra run in a separate thread.
280 /// Using `Span` is generally preferred.
281 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
282 pub struct SpanData {
283     pub lo: BytePos,
284     pub hi: BytePos,
285     /// Information about where the macro came from, if this piece of
286     /// code was created by a macro expansion.
287     pub ctxt: SyntaxContext,
288 }
289
290 impl SpanData {
291     #[inline]
292     pub fn with_lo(&self, lo: BytePos) -> Span {
293         Span::new(lo, self.hi, self.ctxt)
294     }
295     #[inline]
296     pub fn with_hi(&self, hi: BytePos) -> Span {
297         Span::new(self.lo, hi, self.ctxt)
298     }
299     #[inline]
300     pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
301         Span::new(self.lo, self.hi, ctxt)
302     }
303 }
304
305 // The interner is pointed to by a thread local value which is only set on the main thread
306 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
307 // to avoid panics and other errors, even though it would be memory safe to do so.
308 #[cfg(not(parallel_compiler))]
309 impl !Send for Span {}
310 #[cfg(not(parallel_compiler))]
311 impl !Sync for Span {}
312
313 impl PartialOrd for Span {
314     fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
315         PartialOrd::partial_cmp(&self.data(), &rhs.data())
316     }
317 }
318 impl Ord for Span {
319     fn cmp(&self, rhs: &Self) -> Ordering {
320         Ord::cmp(&self.data(), &rhs.data())
321     }
322 }
323
324 /// A collection of `Span`s.
325 ///
326 /// Spans have two orthogonal attributes:
327 ///
328 /// - They can be *primary spans*. In this case they are the locus of
329 ///   the error, and would be rendered with `^^^`.
330 /// - They can have a *label*. In this case, the label is written next
331 ///   to the mark in the snippet when we render.
332 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
333 pub struct MultiSpan {
334     primary_spans: Vec<Span>,
335     span_labels: Vec<(Span, String)>,
336 }
337
338 impl Span {
339     #[inline]
340     pub fn lo(self) -> BytePos {
341         self.data().lo
342     }
343     #[inline]
344     pub fn with_lo(self, lo: BytePos) -> Span {
345         self.data().with_lo(lo)
346     }
347     #[inline]
348     pub fn hi(self) -> BytePos {
349         self.data().hi
350     }
351     #[inline]
352     pub fn with_hi(self, hi: BytePos) -> Span {
353         self.data().with_hi(hi)
354     }
355     #[inline]
356     pub fn ctxt(self) -> SyntaxContext {
357         self.data().ctxt
358     }
359     #[inline]
360     pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
361         self.data().with_ctxt(ctxt)
362     }
363
364     /// Returns `true` if this is a dummy span with any hygienic context.
365     #[inline]
366     pub fn is_dummy(self) -> bool {
367         let span = self.data();
368         span.lo.0 == 0 && span.hi.0 == 0
369     }
370
371     /// Returns `true` if this span comes from a macro or desugaring.
372     #[inline]
373     pub fn from_expansion(self) -> bool {
374         self.ctxt() != SyntaxContext::root()
375     }
376
377     /// Returns `true` if `span` originates in a derive-macro's expansion.
378     pub fn in_derive_expansion(self) -> bool {
379         matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
380     }
381
382     #[inline]
383     pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
384         Span::new(lo, hi, SyntaxContext::root())
385     }
386
387     /// Returns a new span representing an empty span at the beginning of this span
388     #[inline]
389     pub fn shrink_to_lo(self) -> Span {
390         let span = self.data();
391         span.with_hi(span.lo)
392     }
393     /// Returns a new span representing an empty span at the end of this span.
394     #[inline]
395     pub fn shrink_to_hi(self) -> Span {
396         let span = self.data();
397         span.with_lo(span.hi)
398     }
399
400     #[inline]
401     /// Returns true if hi == lo
402     pub fn is_empty(&self) -> bool {
403         let span = self.data();
404         span.hi == span.lo
405     }
406
407     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
408     pub fn substitute_dummy(self, other: Span) -> Span {
409         if self.is_dummy() { other } else { self }
410     }
411
412     /// Returns `true` if `self` fully encloses `other`.
413     pub fn contains(self, other: Span) -> bool {
414         let span = self.data();
415         let other = other.data();
416         span.lo <= other.lo && other.hi <= span.hi
417     }
418
419     /// Returns `true` if `self` touches `other`.
420     pub fn overlaps(self, other: Span) -> bool {
421         let span = self.data();
422         let other = other.data();
423         span.lo < other.hi && other.lo < span.hi
424     }
425
426     /// Returns `true` if the spans are equal with regards to the source text.
427     ///
428     /// Use this instead of `==` when either span could be generated code,
429     /// and you only care that they point to the same bytes of source text.
430     pub fn source_equal(&self, other: &Span) -> bool {
431         let span = self.data();
432         let other = other.data();
433         span.lo == other.lo && span.hi == other.hi
434     }
435
436     /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
437     pub fn trim_start(self, other: Span) -> Option<Span> {
438         let span = self.data();
439         let other = other.data();
440         if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
441     }
442
443     /// Returns the source span -- this is either the supplied span, or the span for
444     /// the macro callsite that expanded to it.
445     pub fn source_callsite(self) -> Span {
446         let expn_data = self.ctxt().outer_expn_data();
447         if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
448     }
449
450     /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
451     /// if any.
452     pub fn parent(self) -> Option<Span> {
453         let expn_data = self.ctxt().outer_expn_data();
454         if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
455     }
456
457     /// Edition of the crate from which this span came.
458     pub fn edition(self) -> edition::Edition {
459         self.ctxt().outer_expn_data().edition
460     }
461
462     #[inline]
463     pub fn rust_2015(&self) -> bool {
464         self.edition() == edition::Edition::Edition2015
465     }
466
467     #[inline]
468     pub fn rust_2018(&self) -> bool {
469         self.edition() >= edition::Edition::Edition2018
470     }
471
472     /// Returns the source callee.
473     ///
474     /// Returns `None` if the supplied span has no expansion trace,
475     /// else returns the `ExpnData` for the macro definition
476     /// corresponding to the source callsite.
477     pub fn source_callee(self) -> Option<ExpnData> {
478         fn source_callee(expn_data: ExpnData) -> ExpnData {
479             let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
480             if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
481         }
482         let expn_data = self.ctxt().outer_expn_data();
483         if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
484     }
485
486     /// Checks if a span is "internal" to a macro in which `#[unstable]`
487     /// items can be used (that is, a macro marked with
488     /// `#[allow_internal_unstable]`).
489     pub fn allows_unstable(&self, feature: Symbol) -> bool {
490         self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
491             features
492                 .iter()
493                 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
494         })
495     }
496
497     /// Checks if this span arises from a compiler desugaring of kind `kind`.
498     pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
499         match self.ctxt().outer_expn_data().kind {
500             ExpnKind::Desugaring(k) => k == kind,
501             _ => false,
502         }
503     }
504
505     /// Returns the compiler desugaring that created this span, or `None`
506     /// if this span is not from a desugaring.
507     pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
508         match self.ctxt().outer_expn_data().kind {
509             ExpnKind::Desugaring(k) => Some(k),
510             _ => None,
511         }
512     }
513
514     /// Checks if a span is "internal" to a macro in which `unsafe`
515     /// can be used without triggering the `unsafe_code` lint
516     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
517     pub fn allows_unsafe(&self) -> bool {
518         self.ctxt().outer_expn_data().allow_internal_unsafe
519     }
520
521     pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
522         let mut prev_span = DUMMY_SP;
523         std::iter::from_fn(move || {
524             loop {
525                 let expn_data = self.ctxt().outer_expn_data();
526                 if expn_data.is_root() {
527                     return None;
528                 }
529
530                 let is_recursive = expn_data.call_site.source_equal(&prev_span);
531
532                 prev_span = self;
533                 self = expn_data.call_site;
534
535                 // Don't print recursive invocations.
536                 if !is_recursive {
537                     return Some(expn_data);
538                 }
539             }
540         })
541     }
542
543     /// Returns a `Span` that would enclose both `self` and `end`.
544     ///
545     /// ```text
546     ///     ____             ___
547     ///     self lorem ipsum end
548     ///     ^^^^^^^^^^^^^^^^^^^^
549     /// ```
550     pub fn to(self, end: Span) -> Span {
551         let span_data = self.data();
552         let end_data = end.data();
553         // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
554         // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
555         // have an incomplete span than a completely nonsensical one.
556         if span_data.ctxt != end_data.ctxt {
557             if span_data.ctxt == SyntaxContext::root() {
558                 return end;
559             } else if end_data.ctxt == SyntaxContext::root() {
560                 return self;
561             }
562             // Both spans fall within a macro.
563             // FIXME(estebank): check if it is the *same* macro.
564         }
565         Span::new(
566             cmp::min(span_data.lo, end_data.lo),
567             cmp::max(span_data.hi, end_data.hi),
568             if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
569         )
570     }
571
572     /// Returns a `Span` between the end of `self` to the beginning of `end`.
573     ///
574     /// ```text
575     ///     ____             ___
576     ///     self lorem ipsum end
577     ///         ^^^^^^^^^^^^^
578     /// ```
579     pub fn between(self, end: Span) -> Span {
580         let span = self.data();
581         let end = end.data();
582         Span::new(
583             span.hi,
584             end.lo,
585             if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
586         )
587     }
588
589     /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
590     ///
591     /// ```text
592     ///     ____             ___
593     ///     self lorem ipsum end
594     ///     ^^^^^^^^^^^^^^^^^
595     /// ```
596     pub fn until(self, end: Span) -> Span {
597         let span = self.data();
598         let end = end.data();
599         Span::new(
600             span.lo,
601             end.lo,
602             if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
603         )
604     }
605
606     pub fn from_inner(self, inner: InnerSpan) -> Span {
607         let span = self.data();
608         Span::new(
609             span.lo + BytePos::from_usize(inner.start),
610             span.lo + BytePos::from_usize(inner.end),
611             span.ctxt,
612         )
613     }
614
615     /// Equivalent of `Span::def_site` from the proc macro API,
616     /// except that the location is taken from the `self` span.
617     pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
618         self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
619     }
620
621     /// Equivalent of `Span::call_site` from the proc macro API,
622     /// except that the location is taken from the `self` span.
623     pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
624         self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
625     }
626
627     /// Equivalent of `Span::mixed_site` from the proc macro API,
628     /// except that the location is taken from the `self` span.
629     pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
630         self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
631     }
632
633     /// Produces a span with the same location as `self` and context produced by a macro with the
634     /// given ID and transparency, assuming that macro was defined directly and not produced by
635     /// some other macro (which is the case for built-in and procedural macros).
636     pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
637         self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
638     }
639
640     #[inline]
641     pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
642         let span = self.data();
643         span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
644     }
645
646     #[inline]
647     pub fn remove_mark(&mut self) -> ExpnId {
648         let mut span = self.data();
649         let mark = span.ctxt.remove_mark();
650         *self = Span::new(span.lo, span.hi, span.ctxt);
651         mark
652     }
653
654     #[inline]
655     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
656         let mut span = self.data();
657         let mark = span.ctxt.adjust(expn_id);
658         *self = Span::new(span.lo, span.hi, span.ctxt);
659         mark
660     }
661
662     #[inline]
663     pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
664         let mut span = self.data();
665         let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
666         *self = Span::new(span.lo, span.hi, span.ctxt);
667         mark
668     }
669
670     #[inline]
671     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
672         let mut span = self.data();
673         let mark = span.ctxt.glob_adjust(expn_id, glob_span);
674         *self = Span::new(span.lo, span.hi, span.ctxt);
675         mark
676     }
677
678     #[inline]
679     pub fn reverse_glob_adjust(
680         &mut self,
681         expn_id: ExpnId,
682         glob_span: Span,
683     ) -> Option<Option<ExpnId>> {
684         let mut span = self.data();
685         let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
686         *self = Span::new(span.lo, span.hi, span.ctxt);
687         mark
688     }
689
690     #[inline]
691     pub fn normalize_to_macros_2_0(self) -> Span {
692         let span = self.data();
693         span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
694     }
695
696     #[inline]
697     pub fn normalize_to_macro_rules(self) -> Span {
698         let span = self.data();
699         span.with_ctxt(span.ctxt.normalize_to_macro_rules())
700     }
701 }
702
703 #[derive(Clone, Debug)]
704 pub struct SpanLabel {
705     /// The span we are going to include in the final snippet.
706     pub span: Span,
707
708     /// Is this a primary span? This is the "locus" of the message,
709     /// and is indicated with a `^^^^` underline, versus `----`.
710     pub is_primary: bool,
711
712     /// What label should we attach to this span (if any)?
713     pub label: Option<String>,
714 }
715
716 impl Default for Span {
717     fn default() -> Self {
718         DUMMY_SP
719     }
720 }
721
722 impl<E: Encoder> Encodable<E> for Span {
723     default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
724         let span = self.data();
725         s.emit_struct("Span", 2, |s| {
726             s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
727             s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
728         })
729     }
730 }
731 impl<D: Decoder> Decodable<D> for Span {
732     default fn decode(s: &mut D) -> Result<Span, D::Error> {
733         s.read_struct("Span", 2, |d| {
734             let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
735             let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
736
737             Ok(Span::new(lo, hi, SyntaxContext::root()))
738         })
739     }
740 }
741
742 /// Calls the provided closure, using the provided `SourceMap` to format
743 /// any spans that are debug-printed during the closure's execution.
744 ///
745 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
746 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
747 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
748 /// a `TyCtxt` is available. In this case, we fall back to
749 /// the `SourceMap` provided to this function. If that is not available,
750 /// we fall back to printing the raw `Span` field values.
751 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
752     SESSION_GLOBALS.with(|session_globals| {
753         *session_globals.source_map.borrow_mut() = Some(source_map);
754     });
755     struct ClearSourceMap;
756     impl Drop for ClearSourceMap {
757         fn drop(&mut self) {
758             SESSION_GLOBALS.with(|session_globals| {
759                 session_globals.source_map.borrow_mut().take();
760             });
761         }
762     }
763
764     let _guard = ClearSourceMap;
765     f()
766 }
767
768 pub fn debug_with_source_map(
769     span: Span,
770     f: &mut fmt::Formatter<'_>,
771     source_map: &SourceMap,
772 ) -> fmt::Result {
773     write!(f, "{} ({:?})", source_map.span_to_string(span), span.ctxt())
774 }
775
776 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
777     SESSION_GLOBALS.with(|session_globals| {
778         if let Some(source_map) = &*session_globals.source_map.borrow() {
779             debug_with_source_map(span, f, source_map)
780         } else {
781             f.debug_struct("Span")
782                 .field("lo", &span.lo())
783                 .field("hi", &span.hi())
784                 .field("ctxt", &span.ctxt())
785                 .finish()
786         }
787     })
788 }
789
790 impl fmt::Debug for Span {
791     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
792         (*SPAN_DEBUG)(*self, f)
793     }
794 }
795
796 impl fmt::Debug for SpanData {
797     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
798         (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
799     }
800 }
801
802 impl MultiSpan {
803     #[inline]
804     pub fn new() -> MultiSpan {
805         MultiSpan { primary_spans: vec![], span_labels: vec![] }
806     }
807
808     pub fn from_span(primary_span: Span) -> MultiSpan {
809         MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
810     }
811
812     pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
813         vec.sort();
814         MultiSpan { primary_spans: vec, span_labels: vec![] }
815     }
816
817     pub fn push_span_label(&mut self, span: Span, label: String) {
818         self.span_labels.push((span, label));
819     }
820
821     /// Selects the first primary span (if any).
822     pub fn primary_span(&self) -> Option<Span> {
823         self.primary_spans.first().cloned()
824     }
825
826     /// Returns all primary spans.
827     pub fn primary_spans(&self) -> &[Span] {
828         &self.primary_spans
829     }
830
831     /// Returns `true` if any of the primary spans are displayable.
832     pub fn has_primary_spans(&self) -> bool {
833         self.primary_spans.iter().any(|sp| !sp.is_dummy())
834     }
835
836     /// Returns `true` if this contains only a dummy primary span with any hygienic context.
837     pub fn is_dummy(&self) -> bool {
838         let mut is_dummy = true;
839         for span in &self.primary_spans {
840             if !span.is_dummy() {
841                 is_dummy = false;
842             }
843         }
844         is_dummy
845     }
846
847     /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
848     /// display well (like std macros). Returns whether replacements occurred.
849     pub fn replace(&mut self, before: Span, after: Span) -> bool {
850         let mut replacements_occurred = false;
851         for primary_span in &mut self.primary_spans {
852             if *primary_span == before {
853                 *primary_span = after;
854                 replacements_occurred = true;
855             }
856         }
857         for span_label in &mut self.span_labels {
858             if span_label.0 == before {
859                 span_label.0 = after;
860                 replacements_occurred = true;
861             }
862         }
863         replacements_occurred
864     }
865
866     /// Returns the strings to highlight. We always ensure that there
867     /// is an entry for each of the primary spans -- for each primary
868     /// span `P`, if there is at least one label with span `P`, we return
869     /// those labels (marked as primary). But otherwise we return
870     /// `SpanLabel` instances with empty labels.
871     pub fn span_labels(&self) -> Vec<SpanLabel> {
872         let is_primary = |span| self.primary_spans.contains(&span);
873
874         let mut span_labels = self
875             .span_labels
876             .iter()
877             .map(|&(span, ref label)| SpanLabel {
878                 span,
879                 is_primary: is_primary(span),
880                 label: Some(label.clone()),
881             })
882             .collect::<Vec<_>>();
883
884         for &span in &self.primary_spans {
885             if !span_labels.iter().any(|sl| sl.span == span) {
886                 span_labels.push(SpanLabel { span, is_primary: true, label: None });
887             }
888         }
889
890         span_labels
891     }
892
893     /// Returns `true` if any of the span labels is displayable.
894     pub fn has_span_labels(&self) -> bool {
895         self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
896     }
897 }
898
899 impl From<Span> for MultiSpan {
900     fn from(span: Span) -> MultiSpan {
901         MultiSpan::from_span(span)
902     }
903 }
904
905 impl From<Vec<Span>> for MultiSpan {
906     fn from(spans: Vec<Span>) -> MultiSpan {
907         MultiSpan::from_spans(spans)
908     }
909 }
910
911 /// Identifies an offset of a multi-byte character in a `SourceFile`.
912 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
913 pub struct MultiByteChar {
914     /// The absolute offset of the character in the `SourceMap`.
915     pub pos: BytePos,
916     /// The number of bytes, `>= 2`.
917     pub bytes: u8,
918 }
919
920 /// Identifies an offset of a non-narrow character in a `SourceFile`.
921 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
922 pub enum NonNarrowChar {
923     /// Represents a zero-width character.
924     ZeroWidth(BytePos),
925     /// Represents a wide (full-width) character.
926     Wide(BytePos),
927     /// Represents a tab character, represented visually with a width of 4 characters.
928     Tab(BytePos),
929 }
930
931 impl NonNarrowChar {
932     fn new(pos: BytePos, width: usize) -> Self {
933         match width {
934             0 => NonNarrowChar::ZeroWidth(pos),
935             2 => NonNarrowChar::Wide(pos),
936             4 => NonNarrowChar::Tab(pos),
937             _ => panic!("width {} given for non-narrow character", width),
938         }
939     }
940
941     /// Returns the absolute offset of the character in the `SourceMap`.
942     pub fn pos(&self) -> BytePos {
943         match *self {
944             NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
945         }
946     }
947
948     /// Returns the width of the character, 0 (zero-width) or 2 (wide).
949     pub fn width(&self) -> usize {
950         match *self {
951             NonNarrowChar::ZeroWidth(_) => 0,
952             NonNarrowChar::Wide(_) => 2,
953             NonNarrowChar::Tab(_) => 4,
954         }
955     }
956 }
957
958 impl Add<BytePos> for NonNarrowChar {
959     type Output = Self;
960
961     fn add(self, rhs: BytePos) -> Self {
962         match self {
963             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
964             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
965             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
966         }
967     }
968 }
969
970 impl Sub<BytePos> for NonNarrowChar {
971     type Output = Self;
972
973     fn sub(self, rhs: BytePos) -> Self {
974         match self {
975             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
976             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
977             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
978         }
979     }
980 }
981
982 /// Identifies an offset of a character that was normalized away from `SourceFile`.
983 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
984 pub struct NormalizedPos {
985     /// The absolute offset of the character in the `SourceMap`.
986     pub pos: BytePos,
987     /// The difference between original and normalized string at position.
988     pub diff: u32,
989 }
990
991 #[derive(PartialEq, Eq, Clone, Debug)]
992 pub enum ExternalSource {
993     /// No external source has to be loaded, since the `SourceFile` represents a local crate.
994     Unneeded,
995     Foreign {
996         kind: ExternalSourceKind,
997         /// This SourceFile's byte-offset within the source_map of its original crate
998         original_start_pos: BytePos,
999         /// The end of this SourceFile within the source_map of its original crate
1000         original_end_pos: BytePos,
1001     },
1002 }
1003
1004 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1005 #[derive(PartialEq, Eq, Clone, Debug)]
1006 pub enum ExternalSourceKind {
1007     /// The external source has been loaded already.
1008     Present(Lrc<String>),
1009     /// No attempt has been made to load the external source.
1010     AbsentOk,
1011     /// A failed attempt has been made to load the external source.
1012     AbsentErr,
1013     Unneeded,
1014 }
1015
1016 impl ExternalSource {
1017     pub fn is_absent(&self) -> bool {
1018         !matches!(self, ExternalSource::Foreign { kind: ExternalSourceKind::Present(_), .. })
1019     }
1020
1021     pub fn get_source(&self) -> Option<&Lrc<String>> {
1022         match self {
1023             ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1024             _ => None,
1025         }
1026     }
1027 }
1028
1029 #[derive(Debug)]
1030 pub struct OffsetOverflowError;
1031
1032 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1033 pub enum SourceFileHashAlgorithm {
1034     Md5,
1035     Sha1,
1036     Sha256,
1037 }
1038
1039 impl FromStr for SourceFileHashAlgorithm {
1040     type Err = ();
1041
1042     fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1043         match s {
1044             "md5" => Ok(SourceFileHashAlgorithm::Md5),
1045             "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1046             "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1047             _ => Err(()),
1048         }
1049     }
1050 }
1051
1052 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1053
1054 /// The hash of the on-disk source file used for debug info.
1055 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1056 #[derive(HashStable_Generic, Encodable, Decodable)]
1057 pub struct SourceFileHash {
1058     pub kind: SourceFileHashAlgorithm,
1059     value: [u8; 32],
1060 }
1061
1062 impl SourceFileHash {
1063     pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1064         let mut hash = SourceFileHash { kind, value: Default::default() };
1065         let len = hash.hash_len();
1066         let value = &mut hash.value[..len];
1067         let data = src.as_bytes();
1068         match kind {
1069             SourceFileHashAlgorithm::Md5 => {
1070                 value.copy_from_slice(&Md5::digest(data));
1071             }
1072             SourceFileHashAlgorithm::Sha1 => {
1073                 value.copy_from_slice(&Sha1::digest(data));
1074             }
1075             SourceFileHashAlgorithm::Sha256 => {
1076                 value.copy_from_slice(&Sha256::digest(data));
1077             }
1078         }
1079         hash
1080     }
1081
1082     /// Check if the stored hash matches the hash of the string.
1083     pub fn matches(&self, src: &str) -> bool {
1084         Self::new(self.kind, src) == *self
1085     }
1086
1087     /// The bytes of the hash.
1088     pub fn hash_bytes(&self) -> &[u8] {
1089         let len = self.hash_len();
1090         &self.value[..len]
1091     }
1092
1093     fn hash_len(&self) -> usize {
1094         match self.kind {
1095             SourceFileHashAlgorithm::Md5 => 16,
1096             SourceFileHashAlgorithm::Sha1 => 20,
1097             SourceFileHashAlgorithm::Sha256 => 32,
1098         }
1099     }
1100 }
1101
1102 /// A single source in the `SourceMap`.
1103 #[derive(Clone)]
1104 pub struct SourceFile {
1105     /// The name of the file that the source came from. Source that doesn't
1106     /// originate from files has names between angle brackets by convention
1107     /// (e.g., `<anon>`).
1108     pub name: FileName,
1109     /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1110     pub name_was_remapped: bool,
1111     /// The unmapped path of the file that the source came from.
1112     /// Set to `None` if the `SourceFile` was imported from an external crate.
1113     pub unmapped_path: Option<FileName>,
1114     /// The complete source code.
1115     pub src: Option<Lrc<String>>,
1116     /// The source code's hash.
1117     pub src_hash: SourceFileHash,
1118     /// The external source code (used for external crates, which will have a `None`
1119     /// value as `self.src`.
1120     pub external_src: Lock<ExternalSource>,
1121     /// The start position of this source in the `SourceMap`.
1122     pub start_pos: BytePos,
1123     /// The end position of this source in the `SourceMap`.
1124     pub end_pos: BytePos,
1125     /// Locations of lines beginnings in the source code.
1126     pub lines: Vec<BytePos>,
1127     /// Locations of multi-byte characters in the source code.
1128     pub multibyte_chars: Vec<MultiByteChar>,
1129     /// Width of characters that are not narrow in the source code.
1130     pub non_narrow_chars: Vec<NonNarrowChar>,
1131     /// Locations of characters removed during normalization.
1132     pub normalized_pos: Vec<NormalizedPos>,
1133     /// A hash of the filename, used for speeding up hashing in incremental compilation.
1134     pub name_hash: u128,
1135     /// Indicates which crate this `SourceFile` was imported from.
1136     pub cnum: CrateNum,
1137 }
1138
1139 impl<S: Encoder> Encodable<S> for SourceFile {
1140     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1141         s.emit_struct("SourceFile", 8, |s| {
1142             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1143             s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1144             s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1145             s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1146             s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1147             s.emit_struct_field("lines", 5, |s| {
1148                 let lines = &self.lines[..];
1149                 // Store the length.
1150                 s.emit_u32(lines.len() as u32)?;
1151
1152                 if !lines.is_empty() {
1153                     // In order to preserve some space, we exploit the fact that
1154                     // the lines list is sorted and individual lines are
1155                     // probably not that long. Because of that we can store lines
1156                     // as a difference list, using as little space as possible
1157                     // for the differences.
1158                     let max_line_length = if lines.len() == 1 {
1159                         0
1160                     } else {
1161                         lines
1162                             .array_windows()
1163                             .map(|&[fst, snd]| snd - fst)
1164                             .map(|bp| bp.to_usize())
1165                             .max()
1166                             .unwrap()
1167                     };
1168
1169                     let bytes_per_diff: u8 = match max_line_length {
1170                         0..=0xFF => 1,
1171                         0x100..=0xFFFF => 2,
1172                         _ => 4,
1173                     };
1174
1175                     // Encode the number of bytes used per diff.
1176                     bytes_per_diff.encode(s)?;
1177
1178                     // Encode the first element.
1179                     lines[0].encode(s)?;
1180
1181                     let diff_iter = lines[..].array_windows().map(|&[fst, snd]| snd - fst);
1182
1183                     match bytes_per_diff {
1184                         1 => {
1185                             for diff in diff_iter {
1186                                 (diff.0 as u8).encode(s)?
1187                             }
1188                         }
1189                         2 => {
1190                             for diff in diff_iter {
1191                                 (diff.0 as u16).encode(s)?
1192                             }
1193                         }
1194                         4 => {
1195                             for diff in diff_iter {
1196                                 diff.0.encode(s)?
1197                             }
1198                         }
1199                         _ => unreachable!(),
1200                     }
1201                 }
1202
1203                 Ok(())
1204             })?;
1205             s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1206             s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1207             s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1208             s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1209             s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1210         })
1211     }
1212 }
1213
1214 impl<D: Decoder> Decodable<D> for SourceFile {
1215     fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1216         d.read_struct("SourceFile", 8, |d| {
1217             let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1218             let name_was_remapped: bool =
1219                 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1220             let src_hash: SourceFileHash =
1221                 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1222             let start_pos: BytePos =
1223                 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1224             let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1225             let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1226                 let num_lines: u32 = Decodable::decode(d)?;
1227                 let mut lines = Vec::with_capacity(num_lines as usize);
1228
1229                 if num_lines > 0 {
1230                     // Read the number of bytes used per diff.
1231                     let bytes_per_diff: u8 = Decodable::decode(d)?;
1232
1233                     // Read the first element.
1234                     let mut line_start: BytePos = Decodable::decode(d)?;
1235                     lines.push(line_start);
1236
1237                     for _ in 1..num_lines {
1238                         let diff = match bytes_per_diff {
1239                             1 => d.read_u8()? as u32,
1240                             2 => d.read_u16()? as u32,
1241                             4 => d.read_u32()?,
1242                             _ => unreachable!(),
1243                         };
1244
1245                         line_start = line_start + BytePos(diff);
1246
1247                         lines.push(line_start);
1248                     }
1249                 }
1250
1251                 Ok(lines)
1252             })?;
1253             let multibyte_chars: Vec<MultiByteChar> =
1254                 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1255             let non_narrow_chars: Vec<NonNarrowChar> =
1256                 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1257             let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1258             let normalized_pos: Vec<NormalizedPos> =
1259                 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1260             let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1261             Ok(SourceFile {
1262                 name,
1263                 name_was_remapped,
1264                 unmapped_path: None,
1265                 start_pos,
1266                 end_pos,
1267                 src: None,
1268                 src_hash,
1269                 // Unused - the metadata decoder will construct
1270                 // a new SourceFile, filling in `external_src` properly
1271                 external_src: Lock::new(ExternalSource::Unneeded),
1272                 lines,
1273                 multibyte_chars,
1274                 non_narrow_chars,
1275                 normalized_pos,
1276                 name_hash,
1277                 cnum,
1278             })
1279         })
1280     }
1281 }
1282
1283 impl fmt::Debug for SourceFile {
1284     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1285         write!(fmt, "SourceFile({})", self.name)
1286     }
1287 }
1288
1289 impl SourceFile {
1290     pub fn new(
1291         name: FileName,
1292         name_was_remapped: bool,
1293         unmapped_path: FileName,
1294         mut src: String,
1295         start_pos: BytePos,
1296         hash_kind: SourceFileHashAlgorithm,
1297     ) -> Self {
1298         // Compute the file hash before any normalization.
1299         let src_hash = SourceFileHash::new(hash_kind, &src);
1300         let normalized_pos = normalize_src(&mut src, start_pos);
1301
1302         let name_hash = {
1303             let mut hasher: StableHasher = StableHasher::new();
1304             name.hash(&mut hasher);
1305             hasher.finish::<u128>()
1306         };
1307         let end_pos = start_pos.to_usize() + src.len();
1308         assert!(end_pos <= u32::MAX as usize);
1309
1310         let (lines, multibyte_chars, non_narrow_chars) =
1311             analyze_source_file::analyze_source_file(&src[..], start_pos);
1312
1313         SourceFile {
1314             name,
1315             name_was_remapped,
1316             unmapped_path: Some(unmapped_path),
1317             src: Some(Lrc::new(src)),
1318             src_hash,
1319             external_src: Lock::new(ExternalSource::Unneeded),
1320             start_pos,
1321             end_pos: Pos::from_usize(end_pos),
1322             lines,
1323             multibyte_chars,
1324             non_narrow_chars,
1325             normalized_pos,
1326             name_hash,
1327             cnum: LOCAL_CRATE,
1328         }
1329     }
1330
1331     /// Returns the `BytePos` of the beginning of the current line.
1332     pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1333         let line_index = self.lookup_line(pos).unwrap();
1334         self.lines[line_index]
1335     }
1336
1337     /// Add externally loaded source.
1338     /// If the hash of the input doesn't match or no input is supplied via None,
1339     /// it is interpreted as an error and the corresponding enum variant is set.
1340     /// The return value signifies whether some kind of source is present.
1341     pub fn add_external_src<F>(&self, get_src: F) -> bool
1342     where
1343         F: FnOnce() -> Option<String>,
1344     {
1345         if matches!(
1346             *self.external_src.borrow(),
1347             ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1348         ) {
1349             let src = get_src();
1350             let mut external_src = self.external_src.borrow_mut();
1351             // Check that no-one else have provided the source while we were getting it
1352             if let ExternalSource::Foreign {
1353                 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1354             } = &mut *external_src
1355             {
1356                 if let Some(mut src) = src {
1357                     // The src_hash needs to be computed on the pre-normalized src.
1358                     if self.src_hash.matches(&src) {
1359                         normalize_src(&mut src, BytePos::from_usize(0));
1360                         *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1361                         return true;
1362                     }
1363                 } else {
1364                     *src_kind = ExternalSourceKind::AbsentErr;
1365                 }
1366
1367                 false
1368             } else {
1369                 self.src.is_some() || external_src.get_source().is_some()
1370             }
1371         } else {
1372             self.src.is_some() || self.external_src.borrow().get_source().is_some()
1373         }
1374     }
1375
1376     /// Gets a line from the list of pre-computed line-beginnings.
1377     /// The line number here is 0-based.
1378     pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1379         fn get_until_newline(src: &str, begin: usize) -> &str {
1380             // We can't use `lines.get(line_number+1)` because we might
1381             // be parsing when we call this function and thus the current
1382             // line is the last one we have line info for.
1383             let slice = &src[begin..];
1384             match slice.find('\n') {
1385                 Some(e) => &slice[..e],
1386                 None => slice,
1387             }
1388         }
1389
1390         let begin = {
1391             let line = self.lines.get(line_number)?;
1392             let begin: BytePos = *line - self.start_pos;
1393             begin.to_usize()
1394         };
1395
1396         if let Some(ref src) = self.src {
1397             Some(Cow::from(get_until_newline(src, begin)))
1398         } else if let Some(src) = self.external_src.borrow().get_source() {
1399             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1400         } else {
1401             None
1402         }
1403     }
1404
1405     pub fn is_real_file(&self) -> bool {
1406         self.name.is_real()
1407     }
1408
1409     pub fn is_imported(&self) -> bool {
1410         self.src.is_none()
1411     }
1412
1413     pub fn byte_length(&self) -> u32 {
1414         self.end_pos.0 - self.start_pos.0
1415     }
1416     pub fn count_lines(&self) -> usize {
1417         self.lines.len()
1418     }
1419
1420     /// Finds the line containing the given position. The return value is the
1421     /// index into the `lines` array of this `SourceFile`, not the 1-based line
1422     /// number. If the source_file is empty or the position is located before the
1423     /// first line, `None` is returned.
1424     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1425         if self.lines.is_empty() {
1426             return None;
1427         }
1428
1429         let line_index = lookup_line(&self.lines[..], pos);
1430         assert!(line_index < self.lines.len() as isize);
1431         if line_index >= 0 { Some(line_index as usize) } else { None }
1432     }
1433
1434     pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1435         if self.is_empty() {
1436             return self.start_pos..self.end_pos;
1437         }
1438
1439         assert!(line_index < self.lines.len());
1440         if line_index == (self.lines.len() - 1) {
1441             self.lines[line_index]..self.end_pos
1442         } else {
1443             self.lines[line_index]..self.lines[line_index + 1]
1444         }
1445     }
1446
1447     /// Returns whether or not the file contains the given `SourceMap` byte
1448     /// position. The position one past the end of the file is considered to be
1449     /// contained by the file. This implies that files for which `is_empty`
1450     /// returns true still contain one byte position according to this function.
1451     #[inline]
1452     pub fn contains(&self, byte_pos: BytePos) -> bool {
1453         byte_pos >= self.start_pos && byte_pos <= self.end_pos
1454     }
1455
1456     #[inline]
1457     pub fn is_empty(&self) -> bool {
1458         self.start_pos == self.end_pos
1459     }
1460
1461     /// Calculates the original byte position relative to the start of the file
1462     /// based on the given byte position.
1463     pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1464         // Diff before any records is 0. Otherwise use the previously recorded
1465         // diff as that applies to the following characters until a new diff
1466         // is recorded.
1467         let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1468             Ok(i) => self.normalized_pos[i].diff,
1469             Err(i) if i == 0 => 0,
1470             Err(i) => self.normalized_pos[i - 1].diff,
1471         };
1472
1473         BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1474     }
1475
1476     /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1477     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1478         // The number of extra bytes due to multibyte chars in the `SourceFile`.
1479         let mut total_extra_bytes = 0;
1480
1481         for mbc in self.multibyte_chars.iter() {
1482             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1483             if mbc.pos < bpos {
1484                 // Every character is at least one byte, so we only
1485                 // count the actual extra bytes.
1486                 total_extra_bytes += mbc.bytes as u32 - 1;
1487                 // We should never see a byte position in the middle of a
1488                 // character.
1489                 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1490             } else {
1491                 break;
1492             }
1493         }
1494
1495         assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1496         CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1497     }
1498
1499     /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1500     /// given `BytePos`.
1501     pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1502         let chpos = self.bytepos_to_file_charpos(pos);
1503         match self.lookup_line(pos) {
1504             Some(a) => {
1505                 let line = a + 1; // Line numbers start at 1
1506                 let linebpos = self.lines[a];
1507                 let linechpos = self.bytepos_to_file_charpos(linebpos);
1508                 let col = chpos - linechpos;
1509                 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1510                 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1511                 debug!("byte is on line: {}", line);
1512                 assert!(chpos >= linechpos);
1513                 (line, col)
1514             }
1515             None => (0, chpos),
1516         }
1517     }
1518
1519     /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1520     /// column offset when displayed, for a given `BytePos`.
1521     pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1522         let (line, col_or_chpos) = self.lookup_file_pos(pos);
1523         if line > 0 {
1524             let col = col_or_chpos;
1525             let linebpos = self.lines[line - 1];
1526             let col_display = {
1527                 let start_width_idx = self
1528                     .non_narrow_chars
1529                     .binary_search_by_key(&linebpos, |x| x.pos())
1530                     .unwrap_or_else(|x| x);
1531                 let end_width_idx = self
1532                     .non_narrow_chars
1533                     .binary_search_by_key(&pos, |x| x.pos())
1534                     .unwrap_or_else(|x| x);
1535                 let special_chars = end_width_idx - start_width_idx;
1536                 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1537                     .iter()
1538                     .map(|x| x.width())
1539                     .sum();
1540                 col.0 - special_chars + non_narrow
1541             };
1542             (line, col, col_display)
1543         } else {
1544             let chpos = col_or_chpos;
1545             let col_display = {
1546                 let end_width_idx = self
1547                     .non_narrow_chars
1548                     .binary_search_by_key(&pos, |x| x.pos())
1549                     .unwrap_or_else(|x| x);
1550                 let non_narrow: usize =
1551                     self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1552                 chpos.0 - end_width_idx + non_narrow
1553             };
1554             (0, chpos, col_display)
1555         }
1556     }
1557 }
1558
1559 /// Normalizes the source code and records the normalizations.
1560 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1561     let mut normalized_pos = vec![];
1562     remove_bom(src, &mut normalized_pos);
1563     normalize_newlines(src, &mut normalized_pos);
1564
1565     // Offset all the positions by start_pos to match the final file positions.
1566     for np in &mut normalized_pos {
1567         np.pos.0 += start_pos.0;
1568     }
1569
1570     normalized_pos
1571 }
1572
1573 /// Removes UTF-8 BOM, if any.
1574 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1575     if src.starts_with('\u{feff}') {
1576         src.drain(..3);
1577         normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1578     }
1579 }
1580
1581 /// Replaces `\r\n` with `\n` in-place in `src`.
1582 ///
1583 /// Returns error if there's a lone `\r` in the string
1584 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1585     if !src.as_bytes().contains(&b'\r') {
1586         return;
1587     }
1588
1589     // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1590     // While we *can* call `as_mut_vec` and do surgery on the live string
1591     // directly, let's rather steal the contents of `src`. This makes the code
1592     // safe even if a panic occurs.
1593
1594     let mut buf = std::mem::replace(src, String::new()).into_bytes();
1595     let mut gap_len = 0;
1596     let mut tail = buf.as_mut_slice();
1597     let mut cursor = 0;
1598     let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1599     loop {
1600         let idx = match find_crlf(&tail[gap_len..]) {
1601             None => tail.len(),
1602             Some(idx) => idx + gap_len,
1603         };
1604         tail.copy_within(gap_len..idx, 0);
1605         tail = &mut tail[idx - gap_len..];
1606         if tail.len() == gap_len {
1607             break;
1608         }
1609         cursor += idx - gap_len;
1610         gap_len += 1;
1611         normalized_pos.push(NormalizedPos {
1612             pos: BytePos::from_usize(cursor + 1),
1613             diff: original_gap + gap_len as u32,
1614         });
1615     }
1616
1617     // Account for removed `\r`.
1618     // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1619     let new_len = buf.len() - gap_len;
1620     unsafe {
1621         buf.set_len(new_len);
1622         *src = String::from_utf8_unchecked(buf);
1623     }
1624
1625     fn find_crlf(src: &[u8]) -> Option<usize> {
1626         let mut search_idx = 0;
1627         while let Some(idx) = find_cr(&src[search_idx..]) {
1628             if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1629                 search_idx += idx + 1;
1630                 continue;
1631             }
1632             return Some(search_idx + idx);
1633         }
1634         None
1635     }
1636
1637     fn find_cr(src: &[u8]) -> Option<usize> {
1638         src.iter().position(|&b| b == b'\r')
1639     }
1640 }
1641
1642 // _____________________________________________________________________________
1643 // Pos, BytePos, CharPos
1644 //
1645
1646 pub trait Pos {
1647     fn from_usize(n: usize) -> Self;
1648     fn to_usize(&self) -> usize;
1649     fn from_u32(n: u32) -> Self;
1650     fn to_u32(&self) -> u32;
1651 }
1652
1653 macro_rules! impl_pos {
1654     (
1655         $(
1656             $(#[$attr:meta])*
1657             $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1658         )*
1659     ) => {
1660         $(
1661             $(#[$attr])*
1662             $vis struct $ident($inner_vis $inner_ty);
1663
1664             impl Pos for $ident {
1665                 #[inline(always)]
1666                 fn from_usize(n: usize) -> $ident {
1667                     $ident(n as $inner_ty)
1668                 }
1669
1670                 #[inline(always)]
1671                 fn to_usize(&self) -> usize {
1672                     self.0 as usize
1673                 }
1674
1675                 #[inline(always)]
1676                 fn from_u32(n: u32) -> $ident {
1677                     $ident(n as $inner_ty)
1678                 }
1679
1680                 #[inline(always)]
1681                 fn to_u32(&self) -> u32 {
1682                     self.0 as u32
1683                 }
1684             }
1685
1686             impl Add for $ident {
1687                 type Output = $ident;
1688
1689                 #[inline(always)]
1690                 fn add(self, rhs: $ident) -> $ident {
1691                     $ident(self.0 + rhs.0)
1692                 }
1693             }
1694
1695             impl Sub for $ident {
1696                 type Output = $ident;
1697
1698                 #[inline(always)]
1699                 fn sub(self, rhs: $ident) -> $ident {
1700                     $ident(self.0 - rhs.0)
1701                 }
1702             }
1703         )*
1704     };
1705 }
1706
1707 impl_pos! {
1708     /// A byte offset. Keep this small (currently 32-bits), as AST contains
1709     /// a lot of them.
1710     #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1711     pub struct BytePos(pub u32);
1712
1713     /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1714     /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1715     /// values to `CharPos` values as necessary.
1716     #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1717     pub struct CharPos(pub usize);
1718 }
1719
1720 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1721     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1722         s.emit_u32(self.0)
1723     }
1724 }
1725
1726 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1727     fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1728         Ok(BytePos(d.read_u32()?))
1729     }
1730 }
1731
1732 // _____________________________________________________________________________
1733 // Loc, SourceFileAndLine, SourceFileAndBytePos
1734 //
1735
1736 /// A source code location used for error reporting.
1737 #[derive(Debug, Clone)]
1738 pub struct Loc {
1739     /// Information about the original source.
1740     pub file: Lrc<SourceFile>,
1741     /// The (1-based) line number.
1742     pub line: usize,
1743     /// The (0-based) column offset.
1744     pub col: CharPos,
1745     /// The (0-based) column offset when displayed.
1746     pub col_display: usize,
1747 }
1748
1749 // Used to be structural records.
1750 #[derive(Debug)]
1751 pub struct SourceFileAndLine {
1752     pub sf: Lrc<SourceFile>,
1753     pub line: usize,
1754 }
1755 #[derive(Debug)]
1756 pub struct SourceFileAndBytePos {
1757     pub sf: Lrc<SourceFile>,
1758     pub pos: BytePos,
1759 }
1760
1761 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1762 pub struct LineInfo {
1763     /// Index of line, starting from 0.
1764     pub line_index: usize,
1765
1766     /// Column in line where span begins, starting from 0.
1767     pub start_col: CharPos,
1768
1769     /// Column in line where span ends, starting from 0, exclusive.
1770     pub end_col: CharPos,
1771 }
1772
1773 pub struct FileLines {
1774     pub file: Lrc<SourceFile>,
1775     pub lines: Vec<LineInfo>,
1776 }
1777
1778 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1779     AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1780
1781 // _____________________________________________________________________________
1782 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1783 //
1784
1785 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1786
1787 #[derive(Clone, PartialEq, Eq, Debug)]
1788 pub enum SpanLinesError {
1789     DistinctSources(DistinctSources),
1790 }
1791
1792 #[derive(Clone, PartialEq, Eq, Debug)]
1793 pub enum SpanSnippetError {
1794     IllFormedSpan(Span),
1795     DistinctSources(DistinctSources),
1796     MalformedForSourcemap(MalformedSourceMapPositions),
1797     SourceNotAvailable { filename: FileName },
1798 }
1799
1800 #[derive(Clone, PartialEq, Eq, Debug)]
1801 pub struct DistinctSources {
1802     pub begin: (FileName, BytePos),
1803     pub end: (FileName, BytePos),
1804 }
1805
1806 #[derive(Clone, PartialEq, Eq, Debug)]
1807 pub struct MalformedSourceMapPositions {
1808     pub name: FileName,
1809     pub source_len: usize,
1810     pub begin_pos: BytePos,
1811     pub end_pos: BytePos,
1812 }
1813
1814 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1815 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1816 pub struct InnerSpan {
1817     pub start: usize,
1818     pub end: usize,
1819 }
1820
1821 impl InnerSpan {
1822     pub fn new(start: usize, end: usize) -> InnerSpan {
1823         InnerSpan { start, end }
1824     }
1825 }
1826
1827 // Given a slice of line start positions and a position, returns the index of
1828 // the line the position is on. Returns -1 if the position is located before
1829 // the first line.
1830 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1831     match lines.binary_search(&pos) {
1832         Ok(line) => line as isize,
1833         Err(line) => line as isize - 1,
1834     }
1835 }
1836
1837 /// Requirements for a `StableHashingContext` to be used in this crate.
1838 /// This is a hack to allow using the `HashStable_Generic` derive macro
1839 /// instead of implementing everything in librustc_middle.
1840 pub trait HashStableContext {
1841     fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1842     fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1843     fn hash_spans(&self) -> bool;
1844     fn byte_pos_to_line_and_col(
1845         &mut self,
1846         byte: BytePos,
1847     ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1848 }
1849
1850 impl<CTX> HashStable<CTX> for Span
1851 where
1852     CTX: HashStableContext,
1853 {
1854     /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1855     /// fields (that would be similar to hashing pointers, since those are just
1856     /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1857     /// triple, which stays the same even if the containing `SourceFile` has moved
1858     /// within the `SourceMap`.
1859     /// Also note that we are hashing byte offsets for the column, not unicode
1860     /// codepoint offsets. For the purpose of the hash that's sufficient.
1861     /// Also, hashing filenames is expensive so we avoid doing it twice when the
1862     /// span starts and ends in the same file, which is almost always the case.
1863     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1864         const TAG_VALID_SPAN: u8 = 0;
1865         const TAG_INVALID_SPAN: u8 = 1;
1866
1867         if !ctx.hash_spans() {
1868             return;
1869         }
1870
1871         if *self == DUMMY_SP {
1872             Hash::hash(&TAG_INVALID_SPAN, hasher);
1873             return;
1874         }
1875
1876         // If this is not an empty or invalid span, we want to hash the last
1877         // position that belongs to it, as opposed to hashing the first
1878         // position past it.
1879         let span = self.data();
1880         let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1881             Some(pos) => pos,
1882             None => {
1883                 Hash::hash(&TAG_INVALID_SPAN, hasher);
1884                 span.ctxt.hash_stable(ctx, hasher);
1885                 return;
1886             }
1887         };
1888
1889         if !file_lo.contains(span.hi) {
1890             Hash::hash(&TAG_INVALID_SPAN, hasher);
1891             span.ctxt.hash_stable(ctx, hasher);
1892             return;
1893         }
1894
1895         let (_, line_hi, col_hi) = match ctx.byte_pos_to_line_and_col(span.hi) {
1896             Some(pos) => pos,
1897             None => {
1898                 Hash::hash(&TAG_INVALID_SPAN, hasher);
1899                 span.ctxt.hash_stable(ctx, hasher);
1900                 return;
1901             }
1902         };
1903
1904         Hash::hash(&TAG_VALID_SPAN, hasher);
1905         // We truncate the stable ID hash and line and column numbers. The chances
1906         // of causing a collision this way should be minimal.
1907         Hash::hash(&(file_lo.name_hash as u64), hasher);
1908
1909         // Hash both the length and the end location (line/column) of a span. If we
1910         // hash only the length, for example, then two otherwise equal spans with
1911         // different end locations will have the same hash. This can cause a problem
1912         // during incremental compilation wherein a previous result for a query that
1913         // depends on the end location of a span will be incorrectly reused when the
1914         // end location of the span it depends on has changed (see issue #74890). A
1915         // similar analysis applies if some query depends specifically on the length
1916         // of the span, but we only hash the end location. So hash both.
1917
1918         let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
1919         let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1920         let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
1921         let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
1922         let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
1923         let len = (span.hi - span.lo).0;
1924         Hash::hash(&col_line, hasher);
1925         Hash::hash(&len, hasher);
1926         span.ctxt.hash_stable(ctx, hasher);
1927     }
1928 }
1929
1930 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1931     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1932         const TAG_EXPANSION: u8 = 0;
1933         const TAG_NO_EXPANSION: u8 = 1;
1934
1935         if *self == SyntaxContext::root() {
1936             TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1937         } else {
1938             TAG_EXPANSION.hash_stable(ctx, hasher);
1939             let (expn_id, transparency) = self.outer_mark();
1940             expn_id.hash_stable(ctx, hasher);
1941             transparency.hash_stable(ctx, hasher);
1942         }
1943     }
1944 }
1945
1946 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1947     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1948         // Since the same expansion context is usually referenced many
1949         // times, we cache a stable hash of it and hash that instead of
1950         // recursing every time.
1951         thread_local! {
1952             static CACHE: RefCell<Vec<Option<Fingerprint>>> = Default::default();
1953         }
1954
1955         const TAG_ROOT: u8 = 0;
1956         const TAG_NOT_ROOT: u8 = 1;
1957
1958         if *self == ExpnId::root() {
1959             TAG_ROOT.hash_stable(ctx, hasher);
1960             return;
1961         }
1962
1963         let index = self.as_u32() as usize;
1964         let res = CACHE.with(|cache| cache.borrow().get(index).copied().flatten());
1965
1966         if let Some(res) = res {
1967             res.hash_stable(ctx, hasher);
1968         } else {
1969             let new_len = index + 1;
1970
1971             let mut sub_hasher = StableHasher::new();
1972             TAG_NOT_ROOT.hash_stable(ctx, &mut sub_hasher);
1973             self.expn_data().hash_stable(ctx, &mut sub_hasher);
1974             let sub_hash: Fingerprint = sub_hasher.finish();
1975
1976             CACHE.with(|cache| {
1977                 let mut cache = cache.borrow_mut();
1978                 if cache.len() < new_len {
1979                     cache.resize(new_len, None);
1980                 }
1981                 cache[index].replace(sub_hash).expect_none("Cache slot was filled");
1982             });
1983             sub_hash.hash_stable(ctx, hasher);
1984         }
1985     }
1986 }