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