]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/lib.rs
Auto merge of #79338 - Aaron1011:fix/token-reparse-cache, r=petrochenkov
[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         match self {
1019             ExternalSource::Foreign { kind: ExternalSourceKind::Present(_), .. } => false,
1020             _ => true,
1021         }
1022     }
1023
1024     pub fn get_source(&self) -> Option<&Lrc<String>> {
1025         match self {
1026             ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1027             _ => None,
1028         }
1029     }
1030 }
1031
1032 #[derive(Debug)]
1033 pub struct OffsetOverflowError;
1034
1035 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1036 pub enum SourceFileHashAlgorithm {
1037     Md5,
1038     Sha1,
1039     Sha256,
1040 }
1041
1042 impl FromStr for SourceFileHashAlgorithm {
1043     type Err = ();
1044
1045     fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1046         match s {
1047             "md5" => Ok(SourceFileHashAlgorithm::Md5),
1048             "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1049             "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1050             _ => Err(()),
1051         }
1052     }
1053 }
1054
1055 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1056
1057 /// The hash of the on-disk source file used for debug info.
1058 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1059 #[derive(HashStable_Generic, Encodable, Decodable)]
1060 pub struct SourceFileHash {
1061     pub kind: SourceFileHashAlgorithm,
1062     value: [u8; 32],
1063 }
1064
1065 impl SourceFileHash {
1066     pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1067         let mut hash = SourceFileHash { kind, value: Default::default() };
1068         let len = hash.hash_len();
1069         let value = &mut hash.value[..len];
1070         let data = src.as_bytes();
1071         match kind {
1072             SourceFileHashAlgorithm::Md5 => {
1073                 value.copy_from_slice(&Md5::digest(data));
1074             }
1075             SourceFileHashAlgorithm::Sha1 => {
1076                 value.copy_from_slice(&Sha1::digest(data));
1077             }
1078             SourceFileHashAlgorithm::Sha256 => {
1079                 value.copy_from_slice(&Sha256::digest(data));
1080             }
1081         }
1082         hash
1083     }
1084
1085     /// Check if the stored hash matches the hash of the string.
1086     pub fn matches(&self, src: &str) -> bool {
1087         Self::new(self.kind, src) == *self
1088     }
1089
1090     /// The bytes of the hash.
1091     pub fn hash_bytes(&self) -> &[u8] {
1092         let len = self.hash_len();
1093         &self.value[..len]
1094     }
1095
1096     fn hash_len(&self) -> usize {
1097         match self.kind {
1098             SourceFileHashAlgorithm::Md5 => 16,
1099             SourceFileHashAlgorithm::Sha1 => 20,
1100             SourceFileHashAlgorithm::Sha256 => 32,
1101         }
1102     }
1103 }
1104
1105 /// A single source in the `SourceMap`.
1106 #[derive(Clone)]
1107 pub struct SourceFile {
1108     /// The name of the file that the source came from. Source that doesn't
1109     /// originate from files has names between angle brackets by convention
1110     /// (e.g., `<anon>`).
1111     pub name: FileName,
1112     /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1113     pub name_was_remapped: bool,
1114     /// The unmapped path of the file that the source came from.
1115     /// Set to `None` if the `SourceFile` was imported from an external crate.
1116     pub unmapped_path: Option<FileName>,
1117     /// The complete source code.
1118     pub src: Option<Lrc<String>>,
1119     /// The source code's hash.
1120     pub src_hash: SourceFileHash,
1121     /// The external source code (used for external crates, which will have a `None`
1122     /// value as `self.src`.
1123     pub external_src: Lock<ExternalSource>,
1124     /// The start position of this source in the `SourceMap`.
1125     pub start_pos: BytePos,
1126     /// The end position of this source in the `SourceMap`.
1127     pub end_pos: BytePos,
1128     /// Locations of lines beginnings in the source code.
1129     pub lines: Vec<BytePos>,
1130     /// Locations of multi-byte characters in the source code.
1131     pub multibyte_chars: Vec<MultiByteChar>,
1132     /// Width of characters that are not narrow in the source code.
1133     pub non_narrow_chars: Vec<NonNarrowChar>,
1134     /// Locations of characters removed during normalization.
1135     pub normalized_pos: Vec<NormalizedPos>,
1136     /// A hash of the filename, used for speeding up hashing in incremental compilation.
1137     pub name_hash: u128,
1138     /// Indicates which crate this `SourceFile` was imported from.
1139     pub cnum: CrateNum,
1140 }
1141
1142 impl<S: Encoder> Encodable<S> for SourceFile {
1143     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1144         s.emit_struct("SourceFile", 8, |s| {
1145             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1146             s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1147             s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1148             s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1149             s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1150             s.emit_struct_field("lines", 5, |s| {
1151                 let lines = &self.lines[..];
1152                 // Store the length.
1153                 s.emit_u32(lines.len() as u32)?;
1154
1155                 if !lines.is_empty() {
1156                     // In order to preserve some space, we exploit the fact that
1157                     // the lines list is sorted and individual lines are
1158                     // probably not that long. Because of that we can store lines
1159                     // as a difference list, using as little space as possible
1160                     // for the differences.
1161                     let max_line_length = if lines.len() == 1 {
1162                         0
1163                     } else {
1164                         lines
1165                             .array_windows()
1166                             .map(|&[fst, snd]| snd - fst)
1167                             .map(|bp| bp.to_usize())
1168                             .max()
1169                             .unwrap()
1170                     };
1171
1172                     let bytes_per_diff: u8 = match max_line_length {
1173                         0..=0xFF => 1,
1174                         0x100..=0xFFFF => 2,
1175                         _ => 4,
1176                     };
1177
1178                     // Encode the number of bytes used per diff.
1179                     bytes_per_diff.encode(s)?;
1180
1181                     // Encode the first element.
1182                     lines[0].encode(s)?;
1183
1184                     let diff_iter = lines[..].array_windows().map(|&[fst, snd]| snd - fst);
1185
1186                     match bytes_per_diff {
1187                         1 => {
1188                             for diff in diff_iter {
1189                                 (diff.0 as u8).encode(s)?
1190                             }
1191                         }
1192                         2 => {
1193                             for diff in diff_iter {
1194                                 (diff.0 as u16).encode(s)?
1195                             }
1196                         }
1197                         4 => {
1198                             for diff in diff_iter {
1199                                 diff.0.encode(s)?
1200                             }
1201                         }
1202                         _ => unreachable!(),
1203                     }
1204                 }
1205
1206                 Ok(())
1207             })?;
1208             s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1209             s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1210             s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1211             s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1212             s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1213         })
1214     }
1215 }
1216
1217 impl<D: Decoder> Decodable<D> for SourceFile {
1218     fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1219         d.read_struct("SourceFile", 8, |d| {
1220             let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1221             let name_was_remapped: bool =
1222                 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1223             let src_hash: SourceFileHash =
1224                 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1225             let start_pos: BytePos =
1226                 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1227             let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1228             let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1229                 let num_lines: u32 = Decodable::decode(d)?;
1230                 let mut lines = Vec::with_capacity(num_lines as usize);
1231
1232                 if num_lines > 0 {
1233                     // Read the number of bytes used per diff.
1234                     let bytes_per_diff: u8 = Decodable::decode(d)?;
1235
1236                     // Read the first element.
1237                     let mut line_start: BytePos = Decodable::decode(d)?;
1238                     lines.push(line_start);
1239
1240                     for _ in 1..num_lines {
1241                         let diff = match bytes_per_diff {
1242                             1 => d.read_u8()? as u32,
1243                             2 => d.read_u16()? as u32,
1244                             4 => d.read_u32()?,
1245                             _ => unreachable!(),
1246                         };
1247
1248                         line_start = line_start + BytePos(diff);
1249
1250                         lines.push(line_start);
1251                     }
1252                 }
1253
1254                 Ok(lines)
1255             })?;
1256             let multibyte_chars: Vec<MultiByteChar> =
1257                 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1258             let non_narrow_chars: Vec<NonNarrowChar> =
1259                 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1260             let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1261             let normalized_pos: Vec<NormalizedPos> =
1262                 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1263             let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1264             Ok(SourceFile {
1265                 name,
1266                 name_was_remapped,
1267                 unmapped_path: None,
1268                 start_pos,
1269                 end_pos,
1270                 src: None,
1271                 src_hash,
1272                 // Unused - the metadata decoder will construct
1273                 // a new SourceFile, filling in `external_src` properly
1274                 external_src: Lock::new(ExternalSource::Unneeded),
1275                 lines,
1276                 multibyte_chars,
1277                 non_narrow_chars,
1278                 normalized_pos,
1279                 name_hash,
1280                 cnum,
1281             })
1282         })
1283     }
1284 }
1285
1286 impl fmt::Debug for SourceFile {
1287     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1288         write!(fmt, "SourceFile({})", self.name)
1289     }
1290 }
1291
1292 impl SourceFile {
1293     pub fn new(
1294         name: FileName,
1295         name_was_remapped: bool,
1296         unmapped_path: FileName,
1297         mut src: String,
1298         start_pos: BytePos,
1299         hash_kind: SourceFileHashAlgorithm,
1300     ) -> Self {
1301         // Compute the file hash before any normalization.
1302         let src_hash = SourceFileHash::new(hash_kind, &src);
1303         let normalized_pos = normalize_src(&mut src, start_pos);
1304
1305         let name_hash = {
1306             let mut hasher: StableHasher = StableHasher::new();
1307             name.hash(&mut hasher);
1308             hasher.finish::<u128>()
1309         };
1310         let end_pos = start_pos.to_usize() + src.len();
1311         assert!(end_pos <= u32::MAX as usize);
1312
1313         let (lines, multibyte_chars, non_narrow_chars) =
1314             analyze_source_file::analyze_source_file(&src[..], start_pos);
1315
1316         SourceFile {
1317             name,
1318             name_was_remapped,
1319             unmapped_path: Some(unmapped_path),
1320             src: Some(Lrc::new(src)),
1321             src_hash,
1322             external_src: Lock::new(ExternalSource::Unneeded),
1323             start_pos,
1324             end_pos: Pos::from_usize(end_pos),
1325             lines,
1326             multibyte_chars,
1327             non_narrow_chars,
1328             normalized_pos,
1329             name_hash,
1330             cnum: LOCAL_CRATE,
1331         }
1332     }
1333
1334     /// Returns the `BytePos` of the beginning of the current line.
1335     pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1336         let line_index = self.lookup_line(pos).unwrap();
1337         self.lines[line_index]
1338     }
1339
1340     /// Add externally loaded source.
1341     /// If the hash of the input doesn't match or no input is supplied via None,
1342     /// it is interpreted as an error and the corresponding enum variant is set.
1343     /// The return value signifies whether some kind of source is present.
1344     pub fn add_external_src<F>(&self, get_src: F) -> bool
1345     where
1346         F: FnOnce() -> Option<String>,
1347     {
1348         if matches!(
1349             *self.external_src.borrow(),
1350             ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1351         ) {
1352             let src = get_src();
1353             let mut external_src = self.external_src.borrow_mut();
1354             // Check that no-one else have provided the source while we were getting it
1355             if let ExternalSource::Foreign {
1356                 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1357             } = &mut *external_src
1358             {
1359                 if let Some(mut src) = src {
1360                     // The src_hash needs to be computed on the pre-normalized src.
1361                     if self.src_hash.matches(&src) {
1362                         normalize_src(&mut src, BytePos::from_usize(0));
1363                         *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1364                         return true;
1365                     }
1366                 } else {
1367                     *src_kind = ExternalSourceKind::AbsentErr;
1368                 }
1369
1370                 false
1371             } else {
1372                 self.src.is_some() || external_src.get_source().is_some()
1373             }
1374         } else {
1375             self.src.is_some() || self.external_src.borrow().get_source().is_some()
1376         }
1377     }
1378
1379     /// Gets a line from the list of pre-computed line-beginnings.
1380     /// The line number here is 0-based.
1381     pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1382         fn get_until_newline(src: &str, begin: usize) -> &str {
1383             // We can't use `lines.get(line_number+1)` because we might
1384             // be parsing when we call this function and thus the current
1385             // line is the last one we have line info for.
1386             let slice = &src[begin..];
1387             match slice.find('\n') {
1388                 Some(e) => &slice[..e],
1389                 None => slice,
1390             }
1391         }
1392
1393         let begin = {
1394             let line = self.lines.get(line_number)?;
1395             let begin: BytePos = *line - self.start_pos;
1396             begin.to_usize()
1397         };
1398
1399         if let Some(ref src) = self.src {
1400             Some(Cow::from(get_until_newline(src, begin)))
1401         } else if let Some(src) = self.external_src.borrow().get_source() {
1402             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1403         } else {
1404             None
1405         }
1406     }
1407
1408     pub fn is_real_file(&self) -> bool {
1409         self.name.is_real()
1410     }
1411
1412     pub fn is_imported(&self) -> bool {
1413         self.src.is_none()
1414     }
1415
1416     pub fn byte_length(&self) -> u32 {
1417         self.end_pos.0 - self.start_pos.0
1418     }
1419     pub fn count_lines(&self) -> usize {
1420         self.lines.len()
1421     }
1422
1423     /// Finds the line containing the given position. The return value is the
1424     /// index into the `lines` array of this `SourceFile`, not the 1-based line
1425     /// number. If the source_file is empty or the position is located before the
1426     /// first line, `None` is returned.
1427     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1428         if self.lines.is_empty() {
1429             return None;
1430         }
1431
1432         let line_index = lookup_line(&self.lines[..], pos);
1433         assert!(line_index < self.lines.len() as isize);
1434         if line_index >= 0 { Some(line_index as usize) } else { None }
1435     }
1436
1437     pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1438         if self.is_empty() {
1439             return self.start_pos..self.end_pos;
1440         }
1441
1442         assert!(line_index < self.lines.len());
1443         if line_index == (self.lines.len() - 1) {
1444             self.lines[line_index]..self.end_pos
1445         } else {
1446             self.lines[line_index]..self.lines[line_index + 1]
1447         }
1448     }
1449
1450     /// Returns whether or not the file contains the given `SourceMap` byte
1451     /// position. The position one past the end of the file is considered to be
1452     /// contained by the file. This implies that files for which `is_empty`
1453     /// returns true still contain one byte position according to this function.
1454     #[inline]
1455     pub fn contains(&self, byte_pos: BytePos) -> bool {
1456         byte_pos >= self.start_pos && byte_pos <= self.end_pos
1457     }
1458
1459     #[inline]
1460     pub fn is_empty(&self) -> bool {
1461         self.start_pos == self.end_pos
1462     }
1463
1464     /// Calculates the original byte position relative to the start of the file
1465     /// based on the given byte position.
1466     pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1467         // Diff before any records is 0. Otherwise use the previously recorded
1468         // diff as that applies to the following characters until a new diff
1469         // is recorded.
1470         let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1471             Ok(i) => self.normalized_pos[i].diff,
1472             Err(i) if i == 0 => 0,
1473             Err(i) => self.normalized_pos[i - 1].diff,
1474         };
1475
1476         BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1477     }
1478
1479     /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1480     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1481         // The number of extra bytes due to multibyte chars in the `SourceFile`.
1482         let mut total_extra_bytes = 0;
1483
1484         for mbc in self.multibyte_chars.iter() {
1485             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1486             if mbc.pos < bpos {
1487                 // Every character is at least one byte, so we only
1488                 // count the actual extra bytes.
1489                 total_extra_bytes += mbc.bytes as u32 - 1;
1490                 // We should never see a byte position in the middle of a
1491                 // character.
1492                 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1493             } else {
1494                 break;
1495             }
1496         }
1497
1498         assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1499         CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1500     }
1501
1502     /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1503     /// given `BytePos`.
1504     pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1505         let chpos = self.bytepos_to_file_charpos(pos);
1506         match self.lookup_line(pos) {
1507             Some(a) => {
1508                 let line = a + 1; // Line numbers start at 1
1509                 let linebpos = self.lines[a];
1510                 let linechpos = self.bytepos_to_file_charpos(linebpos);
1511                 let col = chpos - linechpos;
1512                 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1513                 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1514                 debug!("byte is on line: {}", line);
1515                 assert!(chpos >= linechpos);
1516                 (line, col)
1517             }
1518             None => (0, chpos),
1519         }
1520     }
1521
1522     /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1523     /// column offset when displayed, for a given `BytePos`.
1524     pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1525         let (line, col_or_chpos) = self.lookup_file_pos(pos);
1526         if line > 0 {
1527             let col = col_or_chpos;
1528             let linebpos = self.lines[line - 1];
1529             let col_display = {
1530                 let start_width_idx = self
1531                     .non_narrow_chars
1532                     .binary_search_by_key(&linebpos, |x| x.pos())
1533                     .unwrap_or_else(|x| x);
1534                 let end_width_idx = self
1535                     .non_narrow_chars
1536                     .binary_search_by_key(&pos, |x| x.pos())
1537                     .unwrap_or_else(|x| x);
1538                 let special_chars = end_width_idx - start_width_idx;
1539                 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1540                     .iter()
1541                     .map(|x| x.width())
1542                     .sum();
1543                 col.0 - special_chars + non_narrow
1544             };
1545             (line, col, col_display)
1546         } else {
1547             let chpos = col_or_chpos;
1548             let col_display = {
1549                 let end_width_idx = self
1550                     .non_narrow_chars
1551                     .binary_search_by_key(&pos, |x| x.pos())
1552                     .unwrap_or_else(|x| x);
1553                 let non_narrow: usize =
1554                     self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1555                 chpos.0 - end_width_idx + non_narrow
1556             };
1557             (0, chpos, col_display)
1558         }
1559     }
1560 }
1561
1562 /// Normalizes the source code and records the normalizations.
1563 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1564     let mut normalized_pos = vec![];
1565     remove_bom(src, &mut normalized_pos);
1566     normalize_newlines(src, &mut normalized_pos);
1567
1568     // Offset all the positions by start_pos to match the final file positions.
1569     for np in &mut normalized_pos {
1570         np.pos.0 += start_pos.0;
1571     }
1572
1573     normalized_pos
1574 }
1575
1576 /// Removes UTF-8 BOM, if any.
1577 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1578     if src.starts_with('\u{feff}') {
1579         src.drain(..3);
1580         normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1581     }
1582 }
1583
1584 /// Replaces `\r\n` with `\n` in-place in `src`.
1585 ///
1586 /// Returns error if there's a lone `\r` in the string
1587 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1588     if !src.as_bytes().contains(&b'\r') {
1589         return;
1590     }
1591
1592     // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1593     // While we *can* call `as_mut_vec` and do surgery on the live string
1594     // directly, let's rather steal the contents of `src`. This makes the code
1595     // safe even if a panic occurs.
1596
1597     let mut buf = std::mem::replace(src, String::new()).into_bytes();
1598     let mut gap_len = 0;
1599     let mut tail = buf.as_mut_slice();
1600     let mut cursor = 0;
1601     let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1602     loop {
1603         let idx = match find_crlf(&tail[gap_len..]) {
1604             None => tail.len(),
1605             Some(idx) => idx + gap_len,
1606         };
1607         tail.copy_within(gap_len..idx, 0);
1608         tail = &mut tail[idx - gap_len..];
1609         if tail.len() == gap_len {
1610             break;
1611         }
1612         cursor += idx - gap_len;
1613         gap_len += 1;
1614         normalized_pos.push(NormalizedPos {
1615             pos: BytePos::from_usize(cursor + 1),
1616             diff: original_gap + gap_len as u32,
1617         });
1618     }
1619
1620     // Account for removed `\r`.
1621     // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1622     let new_len = buf.len() - gap_len;
1623     unsafe {
1624         buf.set_len(new_len);
1625         *src = String::from_utf8_unchecked(buf);
1626     }
1627
1628     fn find_crlf(src: &[u8]) -> Option<usize> {
1629         let mut search_idx = 0;
1630         while let Some(idx) = find_cr(&src[search_idx..]) {
1631             if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1632                 search_idx += idx + 1;
1633                 continue;
1634             }
1635             return Some(search_idx + idx);
1636         }
1637         None
1638     }
1639
1640     fn find_cr(src: &[u8]) -> Option<usize> {
1641         src.iter().position(|&b| b == b'\r')
1642     }
1643 }
1644
1645 // _____________________________________________________________________________
1646 // Pos, BytePos, CharPos
1647 //
1648
1649 pub trait Pos {
1650     fn from_usize(n: usize) -> Self;
1651     fn to_usize(&self) -> usize;
1652     fn from_u32(n: u32) -> Self;
1653     fn to_u32(&self) -> u32;
1654 }
1655
1656 macro_rules! impl_pos {
1657     (
1658         $(
1659             $(#[$attr:meta])*
1660             $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1661         )*
1662     ) => {
1663         $(
1664             $(#[$attr])*
1665             $vis struct $ident($inner_vis $inner_ty);
1666
1667             impl Pos for $ident {
1668                 #[inline(always)]
1669                 fn from_usize(n: usize) -> $ident {
1670                     $ident(n as $inner_ty)
1671                 }
1672
1673                 #[inline(always)]
1674                 fn to_usize(&self) -> usize {
1675                     self.0 as usize
1676                 }
1677
1678                 #[inline(always)]
1679                 fn from_u32(n: u32) -> $ident {
1680                     $ident(n as $inner_ty)
1681                 }
1682
1683                 #[inline(always)]
1684                 fn to_u32(&self) -> u32 {
1685                     self.0 as u32
1686                 }
1687             }
1688
1689             impl Add for $ident {
1690                 type Output = $ident;
1691
1692                 #[inline(always)]
1693                 fn add(self, rhs: $ident) -> $ident {
1694                     $ident(self.0 + rhs.0)
1695                 }
1696             }
1697
1698             impl Sub for $ident {
1699                 type Output = $ident;
1700
1701                 #[inline(always)]
1702                 fn sub(self, rhs: $ident) -> $ident {
1703                     $ident(self.0 - rhs.0)
1704                 }
1705             }
1706         )*
1707     };
1708 }
1709
1710 impl_pos! {
1711     /// A byte offset. Keep this small (currently 32-bits), as AST contains
1712     /// a lot of them.
1713     #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1714     pub struct BytePos(pub u32);
1715
1716     /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1717     /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1718     /// values to `CharPos` values as necessary.
1719     #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1720     pub struct CharPos(pub usize);
1721 }
1722
1723 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1724     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1725         s.emit_u32(self.0)
1726     }
1727 }
1728
1729 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1730     fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1731         Ok(BytePos(d.read_u32()?))
1732     }
1733 }
1734
1735 // _____________________________________________________________________________
1736 // Loc, SourceFileAndLine, SourceFileAndBytePos
1737 //
1738
1739 /// A source code location used for error reporting.
1740 #[derive(Debug, Clone)]
1741 pub struct Loc {
1742     /// Information about the original source.
1743     pub file: Lrc<SourceFile>,
1744     /// The (1-based) line number.
1745     pub line: usize,
1746     /// The (0-based) column offset.
1747     pub col: CharPos,
1748     /// The (0-based) column offset when displayed.
1749     pub col_display: usize,
1750 }
1751
1752 // Used to be structural records.
1753 #[derive(Debug)]
1754 pub struct SourceFileAndLine {
1755     pub sf: Lrc<SourceFile>,
1756     pub line: usize,
1757 }
1758 #[derive(Debug)]
1759 pub struct SourceFileAndBytePos {
1760     pub sf: Lrc<SourceFile>,
1761     pub pos: BytePos,
1762 }
1763
1764 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1765 pub struct LineInfo {
1766     /// Index of line, starting from 0.
1767     pub line_index: usize,
1768
1769     /// Column in line where span begins, starting from 0.
1770     pub start_col: CharPos,
1771
1772     /// Column in line where span ends, starting from 0, exclusive.
1773     pub end_col: CharPos,
1774 }
1775
1776 pub struct FileLines {
1777     pub file: Lrc<SourceFile>,
1778     pub lines: Vec<LineInfo>,
1779 }
1780
1781 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1782     AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1783
1784 // _____________________________________________________________________________
1785 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1786 //
1787
1788 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1789
1790 #[derive(Clone, PartialEq, Eq, Debug)]
1791 pub enum SpanLinesError {
1792     DistinctSources(DistinctSources),
1793 }
1794
1795 #[derive(Clone, PartialEq, Eq, Debug)]
1796 pub enum SpanSnippetError {
1797     IllFormedSpan(Span),
1798     DistinctSources(DistinctSources),
1799     MalformedForSourcemap(MalformedSourceMapPositions),
1800     SourceNotAvailable { filename: FileName },
1801 }
1802
1803 #[derive(Clone, PartialEq, Eq, Debug)]
1804 pub struct DistinctSources {
1805     pub begin: (FileName, BytePos),
1806     pub end: (FileName, BytePos),
1807 }
1808
1809 #[derive(Clone, PartialEq, Eq, Debug)]
1810 pub struct MalformedSourceMapPositions {
1811     pub name: FileName,
1812     pub source_len: usize,
1813     pub begin_pos: BytePos,
1814     pub end_pos: BytePos,
1815 }
1816
1817 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1818 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1819 pub struct InnerSpan {
1820     pub start: usize,
1821     pub end: usize,
1822 }
1823
1824 impl InnerSpan {
1825     pub fn new(start: usize, end: usize) -> InnerSpan {
1826         InnerSpan { start, end }
1827     }
1828 }
1829
1830 // Given a slice of line start positions and a position, returns the index of
1831 // the line the position is on. Returns -1 if the position is located before
1832 // the first line.
1833 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1834     match lines.binary_search(&pos) {
1835         Ok(line) => line as isize,
1836         Err(line) => line as isize - 1,
1837     }
1838 }
1839
1840 /// Requirements for a `StableHashingContext` to be used in this crate.
1841 /// This is a hack to allow using the `HashStable_Generic` derive macro
1842 /// instead of implementing everything in librustc_middle.
1843 pub trait HashStableContext {
1844     fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1845     fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1846     fn hash_spans(&self) -> bool;
1847     fn byte_pos_to_line_and_col(
1848         &mut self,
1849         byte: BytePos,
1850     ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1851 }
1852
1853 impl<CTX> HashStable<CTX> for Span
1854 where
1855     CTX: HashStableContext,
1856 {
1857     /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1858     /// fields (that would be similar to hashing pointers, since those are just
1859     /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1860     /// triple, which stays the same even if the containing `SourceFile` has moved
1861     /// within the `SourceMap`.
1862     /// Also note that we are hashing byte offsets for the column, not unicode
1863     /// codepoint offsets. For the purpose of the hash that's sufficient.
1864     /// Also, hashing filenames is expensive so we avoid doing it twice when the
1865     /// span starts and ends in the same file, which is almost always the case.
1866     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1867         const TAG_VALID_SPAN: u8 = 0;
1868         const TAG_INVALID_SPAN: u8 = 1;
1869
1870         if !ctx.hash_spans() {
1871             return;
1872         }
1873
1874         if *self == DUMMY_SP {
1875             Hash::hash(&TAG_INVALID_SPAN, hasher);
1876             return;
1877         }
1878
1879         // If this is not an empty or invalid span, we want to hash the last
1880         // position that belongs to it, as opposed to hashing the first
1881         // position past it.
1882         let span = self.data();
1883         let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1884             Some(pos) => pos,
1885             None => {
1886                 Hash::hash(&TAG_INVALID_SPAN, hasher);
1887                 span.ctxt.hash_stable(ctx, hasher);
1888                 return;
1889             }
1890         };
1891
1892         if !file_lo.contains(span.hi) {
1893             Hash::hash(&TAG_INVALID_SPAN, hasher);
1894             span.ctxt.hash_stable(ctx, hasher);
1895             return;
1896         }
1897
1898         let (_, line_hi, col_hi) = match ctx.byte_pos_to_line_and_col(span.hi) {
1899             Some(pos) => pos,
1900             None => {
1901                 Hash::hash(&TAG_INVALID_SPAN, hasher);
1902                 span.ctxt.hash_stable(ctx, hasher);
1903                 return;
1904             }
1905         };
1906
1907         Hash::hash(&TAG_VALID_SPAN, hasher);
1908         // We truncate the stable ID hash and line and column numbers. The chances
1909         // of causing a collision this way should be minimal.
1910         Hash::hash(&(file_lo.name_hash as u64), hasher);
1911
1912         // Hash both the length and the end location (line/column) of a span. If we
1913         // hash only the length, for example, then two otherwise equal spans with
1914         // different end locations will have the same hash. This can cause a problem
1915         // during incremental compilation wherein a previous result for a query that
1916         // depends on the end location of a span will be incorrectly reused when the
1917         // end location of the span it depends on has changed (see issue #74890). A
1918         // similar analysis applies if some query depends specifically on the length
1919         // of the span, but we only hash the end location. So hash both.
1920
1921         let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
1922         let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1923         let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
1924         let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
1925         let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
1926         let len = (span.hi - span.lo).0;
1927         Hash::hash(&col_line, hasher);
1928         Hash::hash(&len, hasher);
1929         span.ctxt.hash_stable(ctx, hasher);
1930     }
1931 }
1932
1933 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1934     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1935         const TAG_EXPANSION: u8 = 0;
1936         const TAG_NO_EXPANSION: u8 = 1;
1937
1938         if *self == SyntaxContext::root() {
1939             TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1940         } else {
1941             TAG_EXPANSION.hash_stable(ctx, hasher);
1942             let (expn_id, transparency) = self.outer_mark();
1943             expn_id.hash_stable(ctx, hasher);
1944             transparency.hash_stable(ctx, hasher);
1945         }
1946     }
1947 }
1948
1949 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1950     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1951         // Since the same expansion context is usually referenced many
1952         // times, we cache a stable hash of it and hash that instead of
1953         // recursing every time.
1954         thread_local! {
1955             static CACHE: RefCell<Vec<Option<Fingerprint>>> = Default::default();
1956         }
1957
1958         const TAG_ROOT: u8 = 0;
1959         const TAG_NOT_ROOT: u8 = 1;
1960
1961         if *self == ExpnId::root() {
1962             TAG_ROOT.hash_stable(ctx, hasher);
1963             return;
1964         }
1965
1966         let index = self.as_u32() as usize;
1967         let res = CACHE.with(|cache| cache.borrow().get(index).copied().flatten());
1968
1969         if let Some(res) = res {
1970             res.hash_stable(ctx, hasher);
1971         } else {
1972             let new_len = index + 1;
1973
1974             let mut sub_hasher = StableHasher::new();
1975             TAG_NOT_ROOT.hash_stable(ctx, &mut sub_hasher);
1976             self.expn_data().hash_stable(ctx, &mut sub_hasher);
1977             let sub_hash: Fingerprint = sub_hasher.finish();
1978
1979             CACHE.with(|cache| {
1980                 let mut cache = cache.borrow_mut();
1981                 if cache.len() < new_len {
1982                     cache.resize(new_len, None);
1983                 }
1984                 cache[index].replace(sub_hash).expect_none("Cache slot was filled");
1985             });
1986             sub_hash.hash_stable(ctx, hasher);
1987         }
1988     }
1989 }