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