1 //! The source positions and related helper functions.
5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
8 #![feature(crate_visibility_modifier)]
10 #![feature(optin_builtin_traits)]
11 #![feature(rustc_attrs)]
12 #![feature(specialization)]
13 #![feature(step_trait)]
15 use rustc_data_structures::AtomicRef;
16 use rustc_macros::HashStable_Generic;
17 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
19 mod caching_source_map_view;
21 pub use self::caching_source_map_view::CachingSourceMapView;
26 use hygiene::Transparency;
27 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, MacroKind, SyntaxContext};
30 pub use span_encoding::{Span, DUMMY_SP};
33 pub use symbol::{sym, Symbol};
35 mod analyze_source_file;
38 use rustc_data_structures::fingerprint::Fingerprint;
39 use rustc_data_structures::fx::FxHashMap;
40 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
41 use rustc_data_structures::sync::{Lock, Lrc};
44 use std::cell::RefCell;
45 use std::cmp::{self, Ordering};
47 use std::hash::{Hash, Hasher};
48 use std::ops::{Add, Sub};
49 use std::path::PathBuf;
55 symbol_interner: Lock<symbol::Interner>,
56 span_interner: Lock<span_encoding::SpanInterner>,
57 hygiene_data: Lock<hygiene::HygieneData>,
61 pub fn new(edition: Edition) -> Globals {
63 symbol_interner: Lock::new(symbol::Interner::fresh()),
64 span_interner: Lock::new(span_encoding::SpanInterner::default()),
65 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
70 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
72 /// Differentiates between real files and common virtual files.
87 /// A macro. This includes the full name of the macro, so that there are no clashes.
93 /// Hack in `src/libsyntax/parse.rs`.
96 ProcMacroSourceCode(u64),
97 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
99 /// Strings provided as crate attributes in the CLI.
101 /// Custom sources for explicit parser calls from plugins and drivers.
103 DocTest(PathBuf, isize),
106 impl std::fmt::Display for FileName {
107 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 Real(ref path) => write!(fmt, "{}", path.display()),
111 Macros(ref name) => write!(fmt, "<{} macros>", name),
112 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
113 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
114 Anon(_) => write!(fmt, "<anon>"),
115 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
116 CfgSpec(_) => write!(fmt, "<cfgspec>"),
117 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
118 Custom(ref s) => write!(fmt, "<{}>", s),
119 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
124 impl From<PathBuf> for FileName {
125 fn from(p: PathBuf) -> Self {
126 assert!(!p.to_string_lossy().ends_with('>'));
132 pub fn is_real(&self) -> bool {
139 | ProcMacroSourceCode(_)
144 | DocTest(_, _) => false,
148 pub fn is_macros(&self) -> bool {
154 | ProcMacroSourceCode(_)
159 | DocTest(_, _) => false,
164 pub fn quote_expansion_source_code(src: &str) -> FileName {
165 let mut hasher = StableHasher::new();
166 src.hash(&mut hasher);
167 FileName::QuoteExpansion(hasher.finish())
170 pub fn macro_expansion_source_code(src: &str) -> FileName {
171 let mut hasher = StableHasher::new();
172 src.hash(&mut hasher);
173 FileName::MacroExpansion(hasher.finish())
176 pub fn anon_source_code(src: &str) -> FileName {
177 let mut hasher = StableHasher::new();
178 src.hash(&mut hasher);
179 FileName::Anon(hasher.finish())
182 pub fn proc_macro_source_code(src: &str) -> FileName {
183 let mut hasher = StableHasher::new();
184 src.hash(&mut hasher);
185 FileName::ProcMacroSourceCode(hasher.finish())
188 pub fn cfg_spec_source_code(src: &str) -> FileName {
189 let mut hasher = StableHasher::new();
190 src.hash(&mut hasher);
191 FileName::QuoteExpansion(hasher.finish())
194 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
195 let mut hasher = StableHasher::new();
196 src.hash(&mut hasher);
197 FileName::CliCrateAttr(hasher.finish())
200 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
201 FileName::DocTest(path, line)
205 /// Spans represent a region of code, used for error reporting. Positions in spans
206 /// are *absolute* positions from the beginning of the source_map, not positions
207 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
208 /// to the original source.
209 /// You must be careful if the span crosses more than one file - you will not be
210 /// able to use many of the functions on spans in source_map and you cannot assume
211 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
212 /// range between files.
214 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
215 /// sent to other threads, but some pieces of performance infra run in a separate thread.
216 /// Using `Span` is generally preferred.
217 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
218 pub struct SpanData {
221 /// Information about where the macro came from, if this piece of
222 /// code was created by a macro expansion.
223 pub ctxt: SyntaxContext,
228 pub fn with_lo(&self, lo: BytePos) -> Span {
229 Span::new(lo, self.hi, self.ctxt)
232 pub fn with_hi(&self, hi: BytePos) -> Span {
233 Span::new(self.lo, hi, self.ctxt)
236 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
237 Span::new(self.lo, self.hi, ctxt)
241 // The interner is pointed to by a thread local value which is only set on the main thread
242 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
243 // to avoid panics and other errors, even though it would be memory safe to do so.
244 #[cfg(not(parallel_compiler))]
245 impl !Send for Span {}
246 #[cfg(not(parallel_compiler))]
247 impl !Sync for Span {}
249 impl PartialOrd for Span {
250 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
251 PartialOrd::partial_cmp(&self.data(), &rhs.data())
255 fn cmp(&self, rhs: &Self) -> Ordering {
256 Ord::cmp(&self.data(), &rhs.data())
260 /// A collection of spans. Spans have two orthogonal attributes:
262 /// - They can be *primary spans*. In this case they are the locus of
263 /// the error, and would be rendered with `^^^`.
264 /// - They can have a *label*. In this case, the label is written next
265 /// to the mark in the snippet when we render.
266 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
267 pub struct MultiSpan {
268 primary_spans: Vec<Span>,
269 span_labels: Vec<(Span, String)>,
274 pub fn lo(self) -> BytePos {
278 pub fn with_lo(self, lo: BytePos) -> Span {
279 self.data().with_lo(lo)
282 pub fn hi(self) -> BytePos {
286 pub fn with_hi(self, hi: BytePos) -> Span {
287 self.data().with_hi(hi)
290 pub fn ctxt(self) -> SyntaxContext {
294 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
295 self.data().with_ctxt(ctxt)
298 /// Returns `true` if this is a dummy span with any hygienic context.
300 pub fn is_dummy(self) -> bool {
301 let span = self.data();
302 span.lo.0 == 0 && span.hi.0 == 0
305 /// Returns `true` if this span comes from a macro or desugaring.
307 pub fn from_expansion(self) -> bool {
308 self.ctxt() != SyntaxContext::root()
311 /// Returns `true` if `span` originates in a derive-macro's expansion.
312 pub fn in_derive_expansion(self) -> bool {
313 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
317 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
318 Span::new(lo, hi, SyntaxContext::root())
321 /// Returns a new span representing an empty span at the beginning of this span
323 pub fn shrink_to_lo(self) -> Span {
324 let span = self.data();
325 span.with_hi(span.lo)
327 /// Returns a new span representing an empty span at the end of this span.
329 pub fn shrink_to_hi(self) -> Span {
330 let span = self.data();
331 span.with_lo(span.hi)
334 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
335 pub fn substitute_dummy(self, other: Span) -> Span {
336 if self.is_dummy() { other } else { self }
339 /// Returns `true` if `self` fully encloses `other`.
340 pub fn contains(self, other: Span) -> bool {
341 let span = self.data();
342 let other = other.data();
343 span.lo <= other.lo && other.hi <= span.hi
346 /// Returns `true` if `self` touches `other`.
347 pub fn overlaps(self, other: Span) -> bool {
348 let span = self.data();
349 let other = other.data();
350 span.lo < other.hi && other.lo < span.hi
353 /// Returns `true` if the spans are equal with regards to the source text.
355 /// Use this instead of `==` when either span could be generated code,
356 /// and you only care that they point to the same bytes of source text.
357 pub fn source_equal(&self, other: &Span) -> bool {
358 let span = self.data();
359 let other = other.data();
360 span.lo == other.lo && span.hi == other.hi
363 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
364 pub fn trim_start(self, other: Span) -> Option<Span> {
365 let span = self.data();
366 let other = other.data();
367 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
370 /// Returns the source span -- this is either the supplied span, or the span for
371 /// the macro callsite that expanded to it.
372 pub fn source_callsite(self) -> Span {
373 let expn_data = self.ctxt().outer_expn_data();
374 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
377 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
379 pub fn parent(self) -> Option<Span> {
380 let expn_data = self.ctxt().outer_expn_data();
381 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
384 /// Edition of the crate from which this span came.
385 pub fn edition(self) -> edition::Edition {
386 self.ctxt().outer_expn_data().edition
390 pub fn rust_2015(&self) -> bool {
391 self.edition() == edition::Edition::Edition2015
395 pub fn rust_2018(&self) -> bool {
396 self.edition() >= edition::Edition::Edition2018
399 /// Returns the source callee.
401 /// Returns `None` if the supplied span has no expansion trace,
402 /// else returns the `ExpnData` for the macro definition
403 /// corresponding to the source callsite.
404 pub fn source_callee(self) -> Option<ExpnData> {
405 fn source_callee(expn_data: ExpnData) -> ExpnData {
406 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
407 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
409 let expn_data = self.ctxt().outer_expn_data();
410 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
413 /// Checks if a span is "internal" to a macro in which `#[unstable]`
414 /// items can be used (that is, a macro marked with
415 /// `#[allow_internal_unstable]`).
416 pub fn allows_unstable(&self, feature: Symbol) -> bool {
417 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
420 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
424 /// Checks if this span arises from a compiler desugaring of kind `kind`.
425 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
426 match self.ctxt().outer_expn_data().kind {
427 ExpnKind::Desugaring(k) => k == kind,
432 /// Returns the compiler desugaring that created this span, or `None`
433 /// if this span is not from a desugaring.
434 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
435 match self.ctxt().outer_expn_data().kind {
436 ExpnKind::Desugaring(k) => Some(k),
441 /// Checks if a span is "internal" to a macro in which `unsafe`
442 /// can be used without triggering the `unsafe_code` lint
443 // (that is, a macro marked with `#[allow_internal_unsafe]`).
444 pub fn allows_unsafe(&self) -> bool {
445 self.ctxt().outer_expn_data().allow_internal_unsafe
448 pub fn macro_backtrace(mut self) -> Vec<ExpnData> {
449 let mut prev_span = DUMMY_SP;
450 let mut result = vec![];
452 let expn_data = self.ctxt().outer_expn_data();
453 if expn_data.is_root() {
456 // Don't print recursive invocations.
457 if !expn_data.call_site.source_equal(&prev_span) {
458 result.push(expn_data.clone());
462 self = expn_data.call_site;
467 /// Returns a `Span` that would enclose both `self` and `end`.
468 pub fn to(self, end: Span) -> Span {
469 let span_data = self.data();
470 let end_data = end.data();
471 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
472 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
473 // have an incomplete span than a completely nonsensical one.
474 if span_data.ctxt != end_data.ctxt {
475 if span_data.ctxt == SyntaxContext::root() {
477 } else if end_data.ctxt == SyntaxContext::root() {
480 // Both spans fall within a macro.
481 // FIXME(estebank): check if it is the *same* macro.
484 cmp::min(span_data.lo, end_data.lo),
485 cmp::max(span_data.hi, end_data.hi),
486 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
490 /// Returns a `Span` between the end of `self` to the beginning of `end`.
491 pub fn between(self, end: Span) -> Span {
492 let span = self.data();
493 let end = end.data();
497 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
501 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
502 pub fn until(self, end: Span) -> Span {
503 let span = self.data();
504 let end = end.data();
508 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
512 pub fn from_inner(self, inner: InnerSpan) -> Span {
513 let span = self.data();
515 span.lo + BytePos::from_usize(inner.start),
516 span.lo + BytePos::from_usize(inner.end),
521 /// Equivalent of `Span::def_site` from the proc macro API,
522 /// except that the location is taken from the `self` span.
523 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
524 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
527 /// Equivalent of `Span::call_site` from the proc macro API,
528 /// except that the location is taken from the `self` span.
529 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
530 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
533 /// Equivalent of `Span::mixed_site` from the proc macro API,
534 /// except that the location is taken from the `self` span.
535 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
536 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
539 /// Produces a span with the same location as `self` and context produced by a macro with the
540 /// given ID and transparency, assuming that macro was defined directly and not produced by
541 /// some other macro (which is the case for built-in and procedural macros).
542 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
543 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
547 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
548 let span = self.data();
549 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
553 pub fn remove_mark(&mut self) -> ExpnId {
554 let mut span = self.data();
555 let mark = span.ctxt.remove_mark();
556 *self = Span::new(span.lo, span.hi, span.ctxt);
561 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
562 let mut span = self.data();
563 let mark = span.ctxt.adjust(expn_id);
564 *self = Span::new(span.lo, span.hi, span.ctxt);
569 pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
570 let mut span = self.data();
571 let mark = span.ctxt.modernize_and_adjust(expn_id);
572 *self = Span::new(span.lo, span.hi, span.ctxt);
577 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
578 let mut span = self.data();
579 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
580 *self = Span::new(span.lo, span.hi, span.ctxt);
585 pub fn reverse_glob_adjust(
589 ) -> Option<Option<ExpnId>> {
590 let mut span = self.data();
591 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
592 *self = Span::new(span.lo, span.hi, span.ctxt);
597 pub fn modern(self) -> Span {
598 let span = self.data();
599 span.with_ctxt(span.ctxt.modern())
603 pub fn modern_and_legacy(self) -> Span {
604 let span = self.data();
605 span.with_ctxt(span.ctxt.modern_and_legacy())
609 #[derive(Clone, Debug)]
610 pub struct SpanLabel {
611 /// The span we are going to include in the final snippet.
614 /// Is this a primary span? This is the "locus" of the message,
615 /// and is indicated with a `^^^^` underline, versus `----`.
616 pub is_primary: bool,
618 /// What label should we attach to this span (if any)?
619 pub label: Option<String>,
622 impl Default for Span {
623 fn default() -> Self {
628 impl rustc_serialize::UseSpecializedEncodable for Span {
629 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
630 let span = self.data();
631 s.emit_struct("Span", 2, |s| {
632 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
634 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
639 impl rustc_serialize::UseSpecializedDecodable for Span {
640 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
641 d.read_struct("Span", 2, |d| {
642 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
643 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
644 Ok(Span::with_root_ctxt(lo, hi))
649 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
650 f.debug_struct("Span")
651 .field("lo", &span.lo())
652 .field("hi", &span.hi())
653 .field("ctxt", &span.ctxt())
657 impl fmt::Debug for Span {
658 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659 (*SPAN_DEBUG)(*self, f)
663 impl fmt::Debug for SpanData {
664 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
671 pub fn new() -> MultiSpan {
672 MultiSpan { primary_spans: vec![], span_labels: vec![] }
675 pub fn from_span(primary_span: Span) -> MultiSpan {
676 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
679 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
680 MultiSpan { primary_spans: vec, span_labels: vec![] }
683 pub fn push_span_label(&mut self, span: Span, label: String) {
684 self.span_labels.push((span, label));
687 /// Selects the first primary span (if any).
688 pub fn primary_span(&self) -> Option<Span> {
689 self.primary_spans.first().cloned()
692 /// Returns all primary spans.
693 pub fn primary_spans(&self) -> &[Span] {
697 /// Returns `true` if any of the primary spans are displayable.
698 pub fn has_primary_spans(&self) -> bool {
699 self.primary_spans.iter().any(|sp| !sp.is_dummy())
702 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
703 pub fn is_dummy(&self) -> bool {
704 let mut is_dummy = true;
705 for span in &self.primary_spans {
706 if !span.is_dummy() {
713 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
714 /// display well (like std macros). Returns whether replacements occurred.
715 pub fn replace(&mut self, before: Span, after: Span) -> bool {
716 let mut replacements_occurred = false;
717 for primary_span in &mut self.primary_spans {
718 if *primary_span == before {
719 *primary_span = after;
720 replacements_occurred = true;
723 for span_label in &mut self.span_labels {
724 if span_label.0 == before {
725 span_label.0 = after;
726 replacements_occurred = true;
729 replacements_occurred
732 /// Returns the strings to highlight. We always ensure that there
733 /// is an entry for each of the primary spans -- for each primary
734 /// span `P`, if there is at least one label with span `P`, we return
735 /// those labels (marked as primary). But otherwise we return
736 /// `SpanLabel` instances with empty labels.
737 pub fn span_labels(&self) -> Vec<SpanLabel> {
738 let is_primary = |span| self.primary_spans.contains(&span);
740 let mut span_labels = self
743 .map(|&(span, ref label)| SpanLabel {
745 is_primary: is_primary(span),
746 label: Some(label.clone()),
748 .collect::<Vec<_>>();
750 for &span in &self.primary_spans {
751 if !span_labels.iter().any(|sl| sl.span == span) {
752 span_labels.push(SpanLabel { span, is_primary: true, label: None });
759 /// Returns `true` if any of the span labels is displayable.
760 pub fn has_span_labels(&self) -> bool {
761 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
765 impl From<Span> for MultiSpan {
766 fn from(span: Span) -> MultiSpan {
767 MultiSpan::from_span(span)
771 impl From<Vec<Span>> for MultiSpan {
772 fn from(spans: Vec<Span>) -> MultiSpan {
773 MultiSpan::from_spans(spans)
777 /// Identifies an offset of a multi-byte character in a `SourceFile`.
778 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
779 pub struct MultiByteChar {
780 /// The absolute offset of the character in the `SourceMap`.
782 /// The number of bytes, `>= 2`.
786 /// Identifies an offset of a non-narrow character in a `SourceFile`.
787 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
788 pub enum NonNarrowChar {
789 /// Represents a zero-width character.
791 /// Represents a wide (full-width) character.
793 /// Represents a tab character, represented visually with a width of 4 characters.
798 fn new(pos: BytePos, width: usize) -> Self {
800 0 => NonNarrowChar::ZeroWidth(pos),
801 2 => NonNarrowChar::Wide(pos),
802 4 => NonNarrowChar::Tab(pos),
803 _ => panic!("width {} given for non-narrow character", width),
807 /// Returns the absolute offset of the character in the `SourceMap`.
808 pub fn pos(&self) -> BytePos {
810 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
814 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
815 pub fn width(&self) -> usize {
817 NonNarrowChar::ZeroWidth(_) => 0,
818 NonNarrowChar::Wide(_) => 2,
819 NonNarrowChar::Tab(_) => 4,
824 impl Add<BytePos> for NonNarrowChar {
827 fn add(self, rhs: BytePos) -> Self {
829 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
830 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
831 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
836 impl Sub<BytePos> for NonNarrowChar {
839 fn sub(self, rhs: BytePos) -> Self {
841 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
842 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
843 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
848 /// Identifies an offset of a character that was normalized away from `SourceFile`.
849 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
850 pub struct NormalizedPos {
851 /// The absolute offset of the character in the `SourceMap`.
853 /// The difference between original and normalized string at position.
857 /// The state of the lazy external source loading mechanism of a `SourceFile`.
858 #[derive(PartialEq, Eq, Clone)]
859 pub enum ExternalSource {
860 /// The external source has been loaded already.
862 /// No attempt has been made to load the external source.
864 /// A failed attempt has been made to load the external source.
866 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
870 impl ExternalSource {
871 pub fn is_absent(&self) -> bool {
873 ExternalSource::Present(_) => false,
878 pub fn get_source(&self) -> Option<&str> {
880 ExternalSource::Present(ref src) => Some(src),
887 pub struct OffsetOverflowError;
889 /// A single source in the `SourceMap`.
891 pub struct SourceFile {
892 /// The name of the file that the source came from. Source that doesn't
893 /// originate from files has names between angle brackets by convention
894 /// (e.g., `<anon>`).
896 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
897 pub name_was_remapped: bool,
898 /// The unmapped path of the file that the source came from.
899 /// Set to `None` if the `SourceFile` was imported from an external crate.
900 pub unmapped_path: Option<FileName>,
901 /// Indicates which crate this `SourceFile` was imported from.
902 pub crate_of_origin: u32,
903 /// The complete source code.
904 pub src: Option<Lrc<String>>,
905 /// The source code's hash.
907 /// The external source code (used for external crates, which will have a `None`
908 /// value as `self.src`.
909 pub external_src: Lock<ExternalSource>,
910 /// The start position of this source in the `SourceMap`.
911 pub start_pos: BytePos,
912 /// The end position of this source in the `SourceMap`.
913 pub end_pos: BytePos,
914 /// Locations of lines beginnings in the source code.
915 pub lines: Vec<BytePos>,
916 /// Locations of multi-byte characters in the source code.
917 pub multibyte_chars: Vec<MultiByteChar>,
918 /// Width of characters that are not narrow in the source code.
919 pub non_narrow_chars: Vec<NonNarrowChar>,
920 /// Locations of characters removed during normalization.
921 pub normalized_pos: Vec<NormalizedPos>,
922 /// A hash of the filename, used for speeding up hashing in incremental compilation.
926 impl Encodable for SourceFile {
927 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
928 s.emit_struct("SourceFile", 8, |s| {
929 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
930 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
931 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
932 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
933 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
934 s.emit_struct_field("lines", 5, |s| {
935 let lines = &self.lines[..];
937 s.emit_u32(lines.len() as u32)?;
939 if !lines.is_empty() {
940 // In order to preserve some space, we exploit the fact that
941 // the lines list is sorted and individual lines are
942 // probably not that long. Because of that we can store lines
943 // as a difference list, using as little space as possible
944 // for the differences.
945 let max_line_length = if lines.len() == 1 {
948 lines.windows(2).map(|w| w[1] - w[0]).map(|bp| bp.to_usize()).max().unwrap()
951 let bytes_per_diff: u8 = match max_line_length {
957 // Encode the number of bytes used per diff.
958 bytes_per_diff.encode(s)?;
960 // Encode the first element.
963 let diff_iter = (&lines[..]).windows(2).map(|w| (w[1] - w[0]));
965 match bytes_per_diff {
967 for diff in diff_iter {
968 (diff.0 as u8).encode(s)?
972 for diff in diff_iter {
973 (diff.0 as u16).encode(s)?
977 for diff in diff_iter {
987 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
988 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
989 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
990 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))
995 impl Decodable for SourceFile {
996 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
997 d.read_struct("SourceFile", 8, |d| {
998 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
999 let name_was_remapped: bool =
1000 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1001 let src_hash: u128 = d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1002 let start_pos: BytePos =
1003 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1004 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1005 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1006 let num_lines: u32 = Decodable::decode(d)?;
1007 let mut lines = Vec::with_capacity(num_lines as usize);
1010 // Read the number of bytes used per diff.
1011 let bytes_per_diff: u8 = Decodable::decode(d)?;
1013 // Read the first element.
1014 let mut line_start: BytePos = Decodable::decode(d)?;
1015 lines.push(line_start);
1017 for _ in 1..num_lines {
1018 let diff = match bytes_per_diff {
1019 1 => d.read_u8()? as u32,
1020 2 => d.read_u16()? as u32,
1022 _ => unreachable!(),
1025 line_start = line_start + BytePos(diff);
1027 lines.push(line_start);
1033 let multibyte_chars: Vec<MultiByteChar> =
1034 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1035 let non_narrow_chars: Vec<NonNarrowChar> =
1036 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1037 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1038 let normalized_pos: Vec<NormalizedPos> =
1039 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1043 unmapped_path: None,
1044 // `crate_of_origin` has to be set by the importer.
1045 // This value matches up with `rustc_hir::def_id::INVALID_CRATE`.
1046 // That constant is not available here, unfortunately.
1047 crate_of_origin: std::u32::MAX - 1,
1052 external_src: Lock::new(ExternalSource::AbsentOk),
1063 impl fmt::Debug for SourceFile {
1064 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1065 write!(fmt, "SourceFile({})", self.name)
1072 name_was_remapped: bool,
1073 unmapped_path: FileName,
1076 ) -> Result<SourceFile, OffsetOverflowError> {
1077 let normalized_pos = normalize_src(&mut src, start_pos);
1080 let mut hasher: StableHasher = StableHasher::new();
1081 hasher.write(src.as_bytes());
1082 hasher.finish::<u128>()
1085 let mut hasher: StableHasher = StableHasher::new();
1086 name.hash(&mut hasher);
1087 hasher.finish::<u128>()
1089 let end_pos = start_pos.to_usize() + src.len();
1090 if end_pos > u32::max_value() as usize {
1091 return Err(OffsetOverflowError);
1094 let (lines, multibyte_chars, non_narrow_chars) =
1095 analyze_source_file::analyze_source_file(&src[..], start_pos);
1100 unmapped_path: Some(unmapped_path),
1102 src: Some(Lrc::new(src)),
1104 external_src: Lock::new(ExternalSource::Unneeded),
1106 end_pos: Pos::from_usize(end_pos),
1115 /// Returns the `BytePos` of the beginning of the current line.
1116 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1117 let line_index = self.lookup_line(pos).unwrap();
1118 self.lines[line_index]
1121 /// Add externally loaded source.
1122 /// If the hash of the input doesn't match or no input is supplied via None,
1123 /// it is interpreted as an error and the corresponding enum variant is set.
1124 /// The return value signifies whether some kind of source is present.
1125 pub fn add_external_src<F>(&self, get_src: F) -> bool
1127 F: FnOnce() -> Option<String>,
1129 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1130 let src = get_src();
1131 let mut external_src = self.external_src.borrow_mut();
1132 // Check that no-one else have provided the source while we were getting it
1133 if *external_src == ExternalSource::AbsentOk {
1134 if let Some(src) = src {
1135 let mut hasher: StableHasher = StableHasher::new();
1136 hasher.write(src.as_bytes());
1138 if hasher.finish::<u128>() == self.src_hash {
1139 *external_src = ExternalSource::Present(src);
1143 *external_src = ExternalSource::AbsentErr;
1148 self.src.is_some() || external_src.get_source().is_some()
1151 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1155 /// Gets a line from the list of pre-computed line-beginnings.
1156 /// The line number here is 0-based.
1157 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1158 fn get_until_newline(src: &str, begin: usize) -> &str {
1159 // We can't use `lines.get(line_number+1)` because we might
1160 // be parsing when we call this function and thus the current
1161 // line is the last one we have line info for.
1162 let slice = &src[begin..];
1163 match slice.find('\n') {
1164 Some(e) => &slice[..e],
1170 let line = if let Some(line) = self.lines.get(line_number) {
1175 let begin: BytePos = *line - self.start_pos;
1179 if let Some(ref src) = self.src {
1180 Some(Cow::from(get_until_newline(src, begin)))
1181 } else if let Some(src) = self.external_src.borrow().get_source() {
1182 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1188 pub fn is_real_file(&self) -> bool {
1192 pub fn is_imported(&self) -> bool {
1196 pub fn byte_length(&self) -> u32 {
1197 self.end_pos.0 - self.start_pos.0
1199 pub fn count_lines(&self) -> usize {
1203 /// Finds the line containing the given position. The return value is the
1204 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1205 /// number. If the source_file is empty or the position is located before the
1206 /// first line, `None` is returned.
1207 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1208 if self.lines.len() == 0 {
1212 let line_index = lookup_line(&self.lines[..], pos);
1213 assert!(line_index < self.lines.len() as isize);
1214 if line_index >= 0 { Some(line_index as usize) } else { None }
1217 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1218 if self.start_pos == self.end_pos {
1219 return (self.start_pos, self.end_pos);
1222 assert!(line_index < self.lines.len());
1223 if line_index == (self.lines.len() - 1) {
1224 (self.lines[line_index], self.end_pos)
1226 (self.lines[line_index], self.lines[line_index + 1])
1231 pub fn contains(&self, byte_pos: BytePos) -> bool {
1232 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1235 /// Calculates the original byte position relative to the start of the file
1236 /// based on the given byte position.
1237 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1238 // Diff before any records is 0. Otherwise use the previously recorded
1239 // diff as that applies to the following characters until a new diff
1241 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1242 Ok(i) => self.normalized_pos[i].diff,
1243 Err(i) if i == 0 => 0,
1244 Err(i) => self.normalized_pos[i - 1].diff,
1247 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1251 /// Normalizes the source code and records the normalizations.
1252 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1253 let mut normalized_pos = vec![];
1254 remove_bom(src, &mut normalized_pos);
1255 normalize_newlines(src, &mut normalized_pos);
1257 // Offset all the positions by start_pos to match the final file positions.
1258 for np in &mut normalized_pos {
1259 np.pos.0 += start_pos.0;
1265 /// Removes UTF-8 BOM, if any.
1266 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1267 if src.starts_with("\u{feff}") {
1269 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1273 /// Replaces `\r\n` with `\n` in-place in `src`.
1275 /// Returns error if there's a lone `\r` in the string
1276 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1277 if !src.as_bytes().contains(&b'\r') {
1281 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1282 // While we *can* call `as_mut_vec` and do surgery on the live string
1283 // directly, let's rather steal the contents of `src`. This makes the code
1284 // safe even if a panic occurs.
1286 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1287 let mut gap_len = 0;
1288 let mut tail = buf.as_mut_slice();
1290 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1292 let idx = match find_crlf(&tail[gap_len..]) {
1294 Some(idx) => idx + gap_len,
1296 tail.copy_within(gap_len..idx, 0);
1297 tail = &mut tail[idx - gap_len..];
1298 if tail.len() == gap_len {
1301 cursor += idx - gap_len;
1303 normalized_pos.push(NormalizedPos {
1304 pos: BytePos::from_usize(cursor + 1),
1305 diff: original_gap + gap_len as u32,
1309 // Account for removed `\r`.
1310 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1311 let new_len = buf.len() - gap_len;
1313 buf.set_len(new_len);
1314 *src = String::from_utf8_unchecked(buf);
1317 fn find_crlf(src: &[u8]) -> Option<usize> {
1318 let mut search_idx = 0;
1319 while let Some(idx) = find_cr(&src[search_idx..]) {
1320 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1321 search_idx += idx + 1;
1324 return Some(search_idx + idx);
1329 fn find_cr(src: &[u8]) -> Option<usize> {
1330 src.iter().position(|&b| b == b'\r')
1334 // _____________________________________________________________________________
1335 // Pos, BytePos, CharPos
1339 fn from_usize(n: usize) -> Self;
1340 fn to_usize(&self) -> usize;
1341 fn from_u32(n: u32) -> Self;
1342 fn to_u32(&self) -> u32;
1345 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1347 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1348 pub struct BytePos(pub u32);
1350 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1351 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1352 /// values to `CharPos` values as necessary.
1353 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1354 pub struct CharPos(pub usize);
1356 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1357 // have been unsuccessful.
1359 impl Pos for BytePos {
1361 fn from_usize(n: usize) -> BytePos {
1366 fn to_usize(&self) -> usize {
1371 fn from_u32(n: u32) -> BytePos {
1376 fn to_u32(&self) -> u32 {
1381 impl Add for BytePos {
1382 type Output = BytePos;
1385 fn add(self, rhs: BytePos) -> BytePos {
1386 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1390 impl Sub for BytePos {
1391 type Output = BytePos;
1394 fn sub(self, rhs: BytePos) -> BytePos {
1395 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1399 impl Encodable for BytePos {
1400 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1405 impl Decodable for BytePos {
1406 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1407 Ok(BytePos(d.read_u32()?))
1411 impl Pos for CharPos {
1413 fn from_usize(n: usize) -> CharPos {
1418 fn to_usize(&self) -> usize {
1423 fn from_u32(n: u32) -> CharPos {
1428 fn to_u32(&self) -> u32 {
1433 impl Add for CharPos {
1434 type Output = CharPos;
1437 fn add(self, rhs: CharPos) -> CharPos {
1438 CharPos(self.to_usize() + rhs.to_usize())
1442 impl Sub for CharPos {
1443 type Output = CharPos;
1446 fn sub(self, rhs: CharPos) -> CharPos {
1447 CharPos(self.to_usize() - rhs.to_usize())
1451 // _____________________________________________________________________________
1452 // Loc, SourceFileAndLine, SourceFileAndBytePos
1455 /// A source code location used for error reporting.
1456 #[derive(Debug, Clone)]
1458 /// Information about the original source.
1459 pub file: Lrc<SourceFile>,
1460 /// The (1-based) line number.
1462 /// The (0-based) column offset.
1464 /// The (0-based) column offset when displayed.
1465 pub col_display: usize,
1468 // Used to be structural records.
1470 pub struct SourceFileAndLine {
1471 pub sf: Lrc<SourceFile>,
1475 pub struct SourceFileAndBytePos {
1476 pub sf: Lrc<SourceFile>,
1480 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1481 pub struct LineInfo {
1482 /// Index of line, starting from 0.
1483 pub line_index: usize,
1485 /// Column in line where span begins, starting from 0.
1486 pub start_col: CharPos,
1488 /// Column in line where span ends, starting from 0, exclusive.
1489 pub end_col: CharPos,
1492 pub struct FileLines {
1493 pub file: Lrc<SourceFile>,
1494 pub lines: Vec<LineInfo>,
1497 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1498 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1500 // _____________________________________________________________________________
1501 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1504 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1506 #[derive(Clone, PartialEq, Eq, Debug)]
1507 pub enum SpanLinesError {
1508 DistinctSources(DistinctSources),
1511 #[derive(Clone, PartialEq, Eq, Debug)]
1512 pub enum SpanSnippetError {
1513 IllFormedSpan(Span),
1514 DistinctSources(DistinctSources),
1515 MalformedForSourcemap(MalformedSourceMapPositions),
1516 SourceNotAvailable { filename: FileName },
1519 #[derive(Clone, PartialEq, Eq, Debug)]
1520 pub struct DistinctSources {
1521 pub begin: (FileName, BytePos),
1522 pub end: (FileName, BytePos),
1525 #[derive(Clone, PartialEq, Eq, Debug)]
1526 pub struct MalformedSourceMapPositions {
1528 pub source_len: usize,
1529 pub begin_pos: BytePos,
1530 pub end_pos: BytePos,
1533 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1534 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1535 pub struct InnerSpan {
1541 pub fn new(start: usize, end: usize) -> InnerSpan {
1542 InnerSpan { start, end }
1546 // Given a slice of line start positions and a position, returns the index of
1547 // the line the position is on. Returns -1 if the position is located before
1549 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1550 match lines.binary_search(&pos) {
1551 Ok(line) => line as isize,
1552 Err(line) => line as isize - 1,
1556 /// Requirements for a `StableHashingContext` to be used in this crate.
1557 /// This is a hack to allow using the `HashStable_Generic` derive macro
1558 /// instead of implementing everything in librustc.
1559 pub trait HashStableContext {
1560 fn hash_spans(&self) -> bool;
1561 fn byte_pos_to_line_and_col(
1564 ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1567 impl<CTX> HashStable<CTX> for Span
1569 CTX: HashStableContext,
1571 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1572 /// fields (that would be similar to hashing pointers, since those are just
1573 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1574 /// triple, which stays the same even if the containing `SourceFile` has moved
1575 /// within the `SourceMap`.
1576 /// Also note that we are hashing byte offsets for the column, not unicode
1577 /// codepoint offsets. For the purpose of the hash that's sufficient.
1578 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1579 /// span starts and ends in the same file, which is almost always the case.
1580 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1581 const TAG_VALID_SPAN: u8 = 0;
1582 const TAG_INVALID_SPAN: u8 = 1;
1583 const TAG_EXPANSION: u8 = 0;
1584 const TAG_NO_EXPANSION: u8 = 1;
1586 if !ctx.hash_spans() {
1590 if *self == DUMMY_SP {
1591 return std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1594 // If this is not an empty or invalid span, we want to hash the last
1595 // position that belongs to it, as opposed to hashing the first
1596 // position past it.
1597 let span = self.data();
1598 let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1601 return std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1605 if !file_lo.contains(span.hi) {
1606 return std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1609 std::hash::Hash::hash(&TAG_VALID_SPAN, hasher);
1610 // We truncate the stable ID hash and line and column numbers. The chances
1611 // of causing a collision this way should be minimal.
1612 std::hash::Hash::hash(&(file_lo.name_hash as u64), hasher);
1614 let col = (col_lo.0 as u64) & 0xFF;
1615 let line = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1616 let len = ((span.hi - span.lo).0 as u64) << 32;
1617 let line_col_len = col | line | len;
1618 std::hash::Hash::hash(&line_col_len, hasher);
1620 if span.ctxt == SyntaxContext::root() {
1621 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1623 TAG_EXPANSION.hash_stable(ctx, hasher);
1625 // Since the same expansion context is usually referenced many
1626 // times, we cache a stable hash of it and hash that instead of
1627 // recursing every time.
1629 static CACHE: RefCell<FxHashMap<hygiene::ExpnId, u64>> = Default::default();
1632 let sub_hash: u64 = CACHE.with(|cache| {
1633 let expn_id = span.ctxt.outer_expn();
1635 if let Some(&sub_hash) = cache.borrow().get(&expn_id) {
1639 let mut hasher = StableHasher::new();
1640 expn_id.expn_data().hash_stable(ctx, &mut hasher);
1641 let sub_hash: Fingerprint = hasher.finish();
1642 let sub_hash = sub_hash.to_smaller_hash();
1643 cache.borrow_mut().insert(expn_id, sub_hash);
1647 sub_hash.hash_stable(ctx, hasher);