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(specialization)]
13 use rustc_data_structures::AtomicRef;
14 use rustc_macros::HashStable_Generic;
15 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
17 mod caching_source_map_view;
19 pub use self::caching_source_map_view::CachingSourceMapView;
24 use hygiene::Transparency;
25 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, MacroKind, SyntaxContext};
29 pub use span_encoding::{Span, DUMMY_SP};
32 pub use symbol::{sym, Symbol};
34 mod analyze_source_file;
37 use rustc_data_structures::fingerprint::Fingerprint;
38 use rustc_data_structures::fx::FxHashMap;
39 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
40 use rustc_data_structures::sync::{Lock, Lrc};
43 use std::cell::RefCell;
44 use std::cmp::{self, Ordering};
46 use std::hash::{Hash, Hasher};
47 use std::ops::{Add, Sub};
48 use std::path::PathBuf;
54 symbol_interner: Lock<symbol::Interner>,
55 span_interner: Lock<span_encoding::SpanInterner>,
56 hygiene_data: Lock<hygiene::HygieneData>,
60 pub fn new(edition: Edition) -> Globals {
62 symbol_interner: Lock::new(symbol::Interner::fresh()),
63 span_interner: Lock::new(span_encoding::SpanInterner::default()),
64 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
69 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
71 /// Differentiates between real files and common virtual files.
86 /// A macro. This includes the full name of the macro, so that there are no clashes.
92 /// Hack in `src/libsyntax/parse.rs`.
95 ProcMacroSourceCode(u64),
96 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
98 /// Strings provided as crate attributes in the CLI.
100 /// Custom sources for explicit parser calls from plugins and drivers.
102 DocTest(PathBuf, isize),
105 impl std::fmt::Display for FileName {
106 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 Real(ref path) => write!(fmt, "{}", path.display()),
110 Macros(ref name) => write!(fmt, "<{} macros>", name),
111 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
112 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
113 Anon(_) => write!(fmt, "<anon>"),
114 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
115 CfgSpec(_) => write!(fmt, "<cfgspec>"),
116 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
117 Custom(ref s) => write!(fmt, "<{}>", s),
118 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
123 impl From<PathBuf> for FileName {
124 fn from(p: PathBuf) -> Self {
125 assert!(!p.to_string_lossy().ends_with('>'));
131 pub fn is_real(&self) -> bool {
138 | ProcMacroSourceCode(_)
143 | DocTest(_, _) => false,
147 pub fn is_macros(&self) -> bool {
153 | ProcMacroSourceCode(_)
158 | DocTest(_, _) => false,
163 pub fn quote_expansion_source_code(src: &str) -> FileName {
164 let mut hasher = StableHasher::new();
165 src.hash(&mut hasher);
166 FileName::QuoteExpansion(hasher.finish())
169 pub fn macro_expansion_source_code(src: &str) -> FileName {
170 let mut hasher = StableHasher::new();
171 src.hash(&mut hasher);
172 FileName::MacroExpansion(hasher.finish())
175 pub fn anon_source_code(src: &str) -> FileName {
176 let mut hasher = StableHasher::new();
177 src.hash(&mut hasher);
178 FileName::Anon(hasher.finish())
181 pub fn proc_macro_source_code(src: &str) -> FileName {
182 let mut hasher = StableHasher::new();
183 src.hash(&mut hasher);
184 FileName::ProcMacroSourceCode(hasher.finish())
187 pub fn cfg_spec_source_code(src: &str) -> FileName {
188 let mut hasher = StableHasher::new();
189 src.hash(&mut hasher);
190 FileName::QuoteExpansion(hasher.finish())
193 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
194 let mut hasher = StableHasher::new();
195 src.hash(&mut hasher);
196 FileName::CliCrateAttr(hasher.finish())
199 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
200 FileName::DocTest(path, line)
204 /// Spans represent a region of code, used for error reporting. Positions in spans
205 /// are *absolute* positions from the beginning of the source_map, not positions
206 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
207 /// to the original source.
208 /// You must be careful if the span crosses more than one file - you will not be
209 /// able to use many of the functions on spans in source_map and you cannot assume
210 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
211 /// range between files.
213 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
214 /// sent to other threads, but some pieces of performance infra run in a separate thread.
215 /// Using `Span` is generally preferred.
216 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
217 pub struct SpanData {
220 /// Information about where the macro came from, if this piece of
221 /// code was created by a macro expansion.
222 pub ctxt: SyntaxContext,
227 pub fn with_lo(&self, lo: BytePos) -> Span {
228 Span::new(lo, self.hi, self.ctxt)
231 pub fn with_hi(&self, hi: BytePos) -> Span {
232 Span::new(self.lo, hi, self.ctxt)
235 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
236 Span::new(self.lo, self.hi, ctxt)
240 // The interner is pointed to by a thread local value which is only set on the main thread
241 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
242 // to avoid panics and other errors, even though it would be memory safe to do so.
243 #[cfg(not(parallel_compiler))]
244 impl !Send for Span {}
245 #[cfg(not(parallel_compiler))]
246 impl !Sync for Span {}
248 impl PartialOrd for Span {
249 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
250 PartialOrd::partial_cmp(&self.data(), &rhs.data())
254 fn cmp(&self, rhs: &Self) -> Ordering {
255 Ord::cmp(&self.data(), &rhs.data())
259 /// A collection of spans. Spans have two orthogonal attributes:
261 /// - They can be *primary spans*. In this case they are the locus of
262 /// the error, and would be rendered with `^^^`.
263 /// - They can have a *label*. In this case, the label is written next
264 /// to the mark in the snippet when we render.
265 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
266 pub struct MultiSpan {
267 primary_spans: Vec<Span>,
268 span_labels: Vec<(Span, String)>,
273 pub fn lo(self) -> BytePos {
277 pub fn with_lo(self, lo: BytePos) -> Span {
278 self.data().with_lo(lo)
281 pub fn hi(self) -> BytePos {
285 pub fn with_hi(self, hi: BytePos) -> Span {
286 self.data().with_hi(hi)
289 pub fn ctxt(self) -> SyntaxContext {
293 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
294 self.data().with_ctxt(ctxt)
297 /// Returns `true` if this is a dummy span with any hygienic context.
299 pub fn is_dummy(self) -> bool {
300 let span = self.data();
301 span.lo.0 == 0 && span.hi.0 == 0
304 /// Returns `true` if this span comes from a macro or desugaring.
306 pub fn from_expansion(self) -> bool {
307 self.ctxt() != SyntaxContext::root()
310 /// Returns `true` if `span` originates in a derive-macro's expansion.
311 pub fn in_derive_expansion(self) -> bool {
312 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
316 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
317 Span::new(lo, hi, SyntaxContext::root())
320 /// Returns a new span representing an empty span at the beginning of this span
322 pub fn shrink_to_lo(self) -> Span {
323 let span = self.data();
324 span.with_hi(span.lo)
326 /// Returns a new span representing an empty span at the end of this span.
328 pub fn shrink_to_hi(self) -> Span {
329 let span = self.data();
330 span.with_lo(span.hi)
333 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
334 pub fn substitute_dummy(self, other: Span) -> Span {
335 if self.is_dummy() { other } else { self }
338 /// Returns `true` if `self` fully encloses `other`.
339 pub fn contains(self, other: Span) -> bool {
340 let span = self.data();
341 let other = other.data();
342 span.lo <= other.lo && other.hi <= span.hi
345 /// Returns `true` if `self` touches `other`.
346 pub fn overlaps(self, other: Span) -> bool {
347 let span = self.data();
348 let other = other.data();
349 span.lo < other.hi && other.lo < span.hi
352 /// Returns `true` if the spans are equal with regards to the source text.
354 /// Use this instead of `==` when either span could be generated code,
355 /// and you only care that they point to the same bytes of source text.
356 pub fn source_equal(&self, other: &Span) -> bool {
357 let span = self.data();
358 let other = other.data();
359 span.lo == other.lo && span.hi == other.hi
362 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
363 pub fn trim_start(self, other: Span) -> Option<Span> {
364 let span = self.data();
365 let other = other.data();
366 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
369 /// Returns the source span -- this is either the supplied span, or the span for
370 /// the macro callsite that expanded to it.
371 pub fn source_callsite(self) -> Span {
372 let expn_data = self.ctxt().outer_expn_data();
373 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
376 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
378 pub fn parent(self) -> Option<Span> {
379 let expn_data = self.ctxt().outer_expn_data();
380 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
383 /// Edition of the crate from which this span came.
384 pub fn edition(self) -> edition::Edition {
385 self.ctxt().outer_expn_data().edition
389 pub fn rust_2015(&self) -> bool {
390 self.edition() == edition::Edition::Edition2015
394 pub fn rust_2018(&self) -> bool {
395 self.edition() >= edition::Edition::Edition2018
398 /// Returns the source callee.
400 /// Returns `None` if the supplied span has no expansion trace,
401 /// else returns the `ExpnData` for the macro definition
402 /// corresponding to the source callsite.
403 pub fn source_callee(self) -> Option<ExpnData> {
404 fn source_callee(expn_data: ExpnData) -> ExpnData {
405 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
406 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
408 let expn_data = self.ctxt().outer_expn_data();
409 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
412 /// Checks if a span is "internal" to a macro in which `#[unstable]`
413 /// items can be used (that is, a macro marked with
414 /// `#[allow_internal_unstable]`).
415 pub fn allows_unstable(&self, feature: Symbol) -> bool {
416 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
419 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
423 /// Checks if this span arises from a compiler desugaring of kind `kind`.
424 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
425 match self.ctxt().outer_expn_data().kind {
426 ExpnKind::Desugaring(k) => k == kind,
431 /// Returns the compiler desugaring that created this span, or `None`
432 /// if this span is not from a desugaring.
433 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
434 match self.ctxt().outer_expn_data().kind {
435 ExpnKind::Desugaring(k) => Some(k),
440 /// Checks if a span is "internal" to a macro in which `unsafe`
441 /// can be used without triggering the `unsafe_code` lint
442 // (that is, a macro marked with `#[allow_internal_unsafe]`).
443 pub fn allows_unsafe(&self) -> bool {
444 self.ctxt().outer_expn_data().allow_internal_unsafe
447 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
448 let mut prev_span = DUMMY_SP;
449 std::iter::from_fn(move || {
451 let expn_data = self.ctxt().outer_expn_data();
452 if expn_data.is_root() {
456 let is_recursive = expn_data.call_site.source_equal(&prev_span);
459 self = expn_data.call_site;
461 // Don't print recursive invocations.
463 return Some(expn_data);
469 /// Returns a `Span` that would enclose both `self` and `end`.
470 pub fn to(self, end: Span) -> Span {
471 let span_data = self.data();
472 let end_data = end.data();
473 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
474 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
475 // have an incomplete span than a completely nonsensical one.
476 if span_data.ctxt != end_data.ctxt {
477 if span_data.ctxt == SyntaxContext::root() {
479 } else if end_data.ctxt == SyntaxContext::root() {
482 // Both spans fall within a macro.
483 // FIXME(estebank): check if it is the *same* macro.
486 cmp::min(span_data.lo, end_data.lo),
487 cmp::max(span_data.hi, end_data.hi),
488 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
492 /// Returns a `Span` between the end of `self` to the beginning of `end`.
493 pub fn between(self, end: Span) -> Span {
494 let span = self.data();
495 let end = end.data();
499 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
503 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
504 pub fn until(self, end: Span) -> Span {
505 let span = self.data();
506 let end = end.data();
510 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
514 pub fn from_inner(self, inner: InnerSpan) -> Span {
515 let span = self.data();
517 span.lo + BytePos::from_usize(inner.start),
518 span.lo + BytePos::from_usize(inner.end),
523 /// Equivalent of `Span::def_site` from the proc macro API,
524 /// except that the location is taken from the `self` span.
525 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
526 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
529 /// Equivalent of `Span::call_site` from the proc macro API,
530 /// except that the location is taken from the `self` span.
531 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
532 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
535 /// Equivalent of `Span::mixed_site` from the proc macro API,
536 /// except that the location is taken from the `self` span.
537 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
538 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
541 /// Produces a span with the same location as `self` and context produced by a macro with the
542 /// given ID and transparency, assuming that macro was defined directly and not produced by
543 /// some other macro (which is the case for built-in and procedural macros).
544 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
545 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
549 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
550 let span = self.data();
551 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
555 pub fn remove_mark(&mut self) -> ExpnId {
556 let mut span = self.data();
557 let mark = span.ctxt.remove_mark();
558 *self = Span::new(span.lo, span.hi, span.ctxt);
563 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
564 let mut span = self.data();
565 let mark = span.ctxt.adjust(expn_id);
566 *self = Span::new(span.lo, span.hi, span.ctxt);
571 pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
572 let mut span = self.data();
573 let mark = span.ctxt.modernize_and_adjust(expn_id);
574 *self = Span::new(span.lo, span.hi, span.ctxt);
579 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
580 let mut span = self.data();
581 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
582 *self = Span::new(span.lo, span.hi, span.ctxt);
587 pub fn reverse_glob_adjust(
591 ) -> Option<Option<ExpnId>> {
592 let mut span = self.data();
593 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
594 *self = Span::new(span.lo, span.hi, span.ctxt);
599 pub fn modern(self) -> Span {
600 let span = self.data();
601 span.with_ctxt(span.ctxt.modern())
605 pub fn modern_and_legacy(self) -> Span {
606 let span = self.data();
607 span.with_ctxt(span.ctxt.modern_and_legacy())
611 #[derive(Clone, Debug)]
612 pub struct SpanLabel {
613 /// The span we are going to include in the final snippet.
616 /// Is this a primary span? This is the "locus" of the message,
617 /// and is indicated with a `^^^^` underline, versus `----`.
618 pub is_primary: bool,
620 /// What label should we attach to this span (if any)?
621 pub label: Option<String>,
624 impl Default for Span {
625 fn default() -> Self {
630 impl rustc_serialize::UseSpecializedEncodable for Span {
631 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
632 let span = self.data();
633 s.emit_struct("Span", 2, |s| {
634 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
636 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
641 impl rustc_serialize::UseSpecializedDecodable for Span {
642 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
643 d.read_struct("Span", 2, |d| {
644 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
645 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
646 Ok(Span::with_root_ctxt(lo, hi))
651 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652 f.debug_struct("Span")
653 .field("lo", &span.lo())
654 .field("hi", &span.hi())
655 .field("ctxt", &span.ctxt())
659 impl fmt::Debug for Span {
660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 (*SPAN_DEBUG)(*self, f)
665 impl fmt::Debug for SpanData {
666 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
667 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
673 pub fn new() -> MultiSpan {
674 MultiSpan { primary_spans: vec![], span_labels: vec![] }
677 pub fn from_span(primary_span: Span) -> MultiSpan {
678 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
681 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
682 MultiSpan { primary_spans: vec, span_labels: vec![] }
685 pub fn push_span_label(&mut self, span: Span, label: String) {
686 self.span_labels.push((span, label));
689 /// Selects the first primary span (if any).
690 pub fn primary_span(&self) -> Option<Span> {
691 self.primary_spans.first().cloned()
694 /// Returns all primary spans.
695 pub fn primary_spans(&self) -> &[Span] {
699 /// Returns `true` if any of the primary spans are displayable.
700 pub fn has_primary_spans(&self) -> bool {
701 self.primary_spans.iter().any(|sp| !sp.is_dummy())
704 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
705 pub fn is_dummy(&self) -> bool {
706 let mut is_dummy = true;
707 for span in &self.primary_spans {
708 if !span.is_dummy() {
715 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
716 /// display well (like std macros). Returns whether replacements occurred.
717 pub fn replace(&mut self, before: Span, after: Span) -> bool {
718 let mut replacements_occurred = false;
719 for primary_span in &mut self.primary_spans {
720 if *primary_span == before {
721 *primary_span = after;
722 replacements_occurred = true;
725 for span_label in &mut self.span_labels {
726 if span_label.0 == before {
727 span_label.0 = after;
728 replacements_occurred = true;
731 replacements_occurred
734 /// Returns the strings to highlight. We always ensure that there
735 /// is an entry for each of the primary spans -- for each primary
736 /// span `P`, if there is at least one label with span `P`, we return
737 /// those labels (marked as primary). But otherwise we return
738 /// `SpanLabel` instances with empty labels.
739 pub fn span_labels(&self) -> Vec<SpanLabel> {
740 let is_primary = |span| self.primary_spans.contains(&span);
742 let mut span_labels = self
745 .map(|&(span, ref label)| SpanLabel {
747 is_primary: is_primary(span),
748 label: Some(label.clone()),
750 .collect::<Vec<_>>();
752 for &span in &self.primary_spans {
753 if !span_labels.iter().any(|sl| sl.span == span) {
754 span_labels.push(SpanLabel { span, is_primary: true, label: None });
761 /// Returns `true` if any of the span labels is displayable.
762 pub fn has_span_labels(&self) -> bool {
763 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
767 impl From<Span> for MultiSpan {
768 fn from(span: Span) -> MultiSpan {
769 MultiSpan::from_span(span)
773 impl From<Vec<Span>> for MultiSpan {
774 fn from(spans: Vec<Span>) -> MultiSpan {
775 MultiSpan::from_spans(spans)
779 /// Identifies an offset of a multi-byte character in a `SourceFile`.
780 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
781 pub struct MultiByteChar {
782 /// The absolute offset of the character in the `SourceMap`.
784 /// The number of bytes, `>= 2`.
788 /// Identifies an offset of a non-narrow character in a `SourceFile`.
789 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
790 pub enum NonNarrowChar {
791 /// Represents a zero-width character.
793 /// Represents a wide (full-width) character.
795 /// Represents a tab character, represented visually with a width of 4 characters.
800 fn new(pos: BytePos, width: usize) -> Self {
802 0 => NonNarrowChar::ZeroWidth(pos),
803 2 => NonNarrowChar::Wide(pos),
804 4 => NonNarrowChar::Tab(pos),
805 _ => panic!("width {} given for non-narrow character", width),
809 /// Returns the absolute offset of the character in the `SourceMap`.
810 pub fn pos(&self) -> BytePos {
812 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
816 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
817 pub fn width(&self) -> usize {
819 NonNarrowChar::ZeroWidth(_) => 0,
820 NonNarrowChar::Wide(_) => 2,
821 NonNarrowChar::Tab(_) => 4,
826 impl Add<BytePos> for NonNarrowChar {
829 fn add(self, rhs: BytePos) -> Self {
831 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
832 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
833 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
838 impl Sub<BytePos> for NonNarrowChar {
841 fn sub(self, rhs: BytePos) -> Self {
843 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
844 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
845 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
850 /// Identifies an offset of a character that was normalized away from `SourceFile`.
851 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
852 pub struct NormalizedPos {
853 /// The absolute offset of the character in the `SourceMap`.
855 /// The difference between original and normalized string at position.
859 /// The state of the lazy external source loading mechanism of a `SourceFile`.
860 #[derive(PartialEq, Eq, Clone)]
861 pub enum ExternalSource {
862 /// The external source has been loaded already.
864 /// No attempt has been made to load the external source.
866 /// A failed attempt has been made to load the external source.
868 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
872 impl ExternalSource {
873 pub fn is_absent(&self) -> bool {
875 ExternalSource::Present(_) => false,
880 pub fn get_source(&self) -> Option<&str> {
882 ExternalSource::Present(ref src) => Some(src),
889 pub struct OffsetOverflowError;
891 /// A single source in the `SourceMap`.
893 pub struct SourceFile {
894 /// The name of the file that the source came from. Source that doesn't
895 /// originate from files has names between angle brackets by convention
896 /// (e.g., `<anon>`).
898 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
899 pub name_was_remapped: bool,
900 /// The unmapped path of the file that the source came from.
901 /// Set to `None` if the `SourceFile` was imported from an external crate.
902 pub unmapped_path: Option<FileName>,
903 /// Indicates which crate this `SourceFile` was imported from.
904 pub crate_of_origin: u32,
905 /// The complete source code.
906 pub src: Option<Lrc<String>>,
907 /// The source code's hash.
909 /// The external source code (used for external crates, which will have a `None`
910 /// value as `self.src`.
911 pub external_src: Lock<ExternalSource>,
912 /// The start position of this source in the `SourceMap`.
913 pub start_pos: BytePos,
914 /// The end position of this source in the `SourceMap`.
915 pub end_pos: BytePos,
916 /// Locations of lines beginnings in the source code.
917 pub lines: Vec<BytePos>,
918 /// Locations of multi-byte characters in the source code.
919 pub multibyte_chars: Vec<MultiByteChar>,
920 /// Width of characters that are not narrow in the source code.
921 pub non_narrow_chars: Vec<NonNarrowChar>,
922 /// Locations of characters removed during normalization.
923 pub normalized_pos: Vec<NormalizedPos>,
924 /// A hash of the filename, used for speeding up hashing in incremental compilation.
928 impl Encodable for SourceFile {
929 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
930 s.emit_struct("SourceFile", 8, |s| {
931 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
932 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
933 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
934 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
935 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
936 s.emit_struct_field("lines", 5, |s| {
937 let lines = &self.lines[..];
939 s.emit_u32(lines.len() as u32)?;
941 if !lines.is_empty() {
942 // In order to preserve some space, we exploit the fact that
943 // the lines list is sorted and individual lines are
944 // probably not that long. Because of that we can store lines
945 // as a difference list, using as little space as possible
946 // for the differences.
947 let max_line_length = if lines.len() == 1 {
950 lines.windows(2).map(|w| w[1] - w[0]).map(|bp| bp.to_usize()).max().unwrap()
953 let bytes_per_diff: u8 = match max_line_length {
959 // Encode the number of bytes used per diff.
960 bytes_per_diff.encode(s)?;
962 // Encode the first element.
965 let diff_iter = (&lines[..]).windows(2).map(|w| (w[1] - w[0]));
967 match bytes_per_diff {
969 for diff in diff_iter {
970 (diff.0 as u8).encode(s)?
974 for diff in diff_iter {
975 (diff.0 as u16).encode(s)?
979 for diff in diff_iter {
989 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
990 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
991 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
992 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))
997 impl Decodable for SourceFile {
998 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
999 d.read_struct("SourceFile", 8, |d| {
1000 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1001 let name_was_remapped: bool =
1002 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1003 let src_hash: u128 = d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1004 let start_pos: BytePos =
1005 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1006 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1007 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1008 let num_lines: u32 = Decodable::decode(d)?;
1009 let mut lines = Vec::with_capacity(num_lines as usize);
1012 // Read the number of bytes used per diff.
1013 let bytes_per_diff: u8 = Decodable::decode(d)?;
1015 // Read the first element.
1016 let mut line_start: BytePos = Decodable::decode(d)?;
1017 lines.push(line_start);
1019 for _ in 1..num_lines {
1020 let diff = match bytes_per_diff {
1021 1 => d.read_u8()? as u32,
1022 2 => d.read_u16()? as u32,
1024 _ => unreachable!(),
1027 line_start = line_start + BytePos(diff);
1029 lines.push(line_start);
1035 let multibyte_chars: Vec<MultiByteChar> =
1036 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1037 let non_narrow_chars: Vec<NonNarrowChar> =
1038 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1039 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1040 let normalized_pos: Vec<NormalizedPos> =
1041 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1045 unmapped_path: None,
1046 // `crate_of_origin` has to be set by the importer.
1047 // This value matches up with `rustc_hir::def_id::INVALID_CRATE`.
1048 // That constant is not available here, unfortunately.
1049 crate_of_origin: std::u32::MAX - 1,
1054 external_src: Lock::new(ExternalSource::AbsentOk),
1065 impl fmt::Debug for SourceFile {
1066 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1067 write!(fmt, "SourceFile({})", self.name)
1074 name_was_remapped: bool,
1075 unmapped_path: FileName,
1079 let normalized_pos = normalize_src(&mut src, start_pos);
1082 let mut hasher: StableHasher = StableHasher::new();
1083 hasher.write(src.as_bytes());
1084 hasher.finish::<u128>()
1087 let mut hasher: StableHasher = StableHasher::new();
1088 name.hash(&mut hasher);
1089 hasher.finish::<u128>()
1091 let end_pos = start_pos.to_usize() + src.len();
1092 assert!(end_pos <= u32::max_value() as usize);
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 hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1562 fn byte_pos_to_line_and_col(
1565 ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1568 impl<CTX> HashStable<CTX> for Span
1570 CTX: HashStableContext,
1572 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1573 /// fields (that would be similar to hashing pointers, since those are just
1574 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1575 /// triple, which stays the same even if the containing `SourceFile` has moved
1576 /// within the `SourceMap`.
1577 /// Also note that we are hashing byte offsets for the column, not unicode
1578 /// codepoint offsets. For the purpose of the hash that's sufficient.
1579 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1580 /// span starts and ends in the same file, which is almost always the case.
1581 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1582 const TAG_VALID_SPAN: u8 = 0;
1583 const TAG_INVALID_SPAN: u8 = 1;
1584 const TAG_EXPANSION: u8 = 0;
1585 const TAG_NO_EXPANSION: u8 = 1;
1587 if !ctx.hash_spans() {
1591 if *self == DUMMY_SP {
1592 return std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1595 // If this is not an empty or invalid span, we want to hash the last
1596 // position that belongs to it, as opposed to hashing the first
1597 // position past it.
1598 let span = self.data();
1599 let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1602 return std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1606 if !file_lo.contains(span.hi) {
1607 return std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1610 std::hash::Hash::hash(&TAG_VALID_SPAN, hasher);
1611 // We truncate the stable ID hash and line and column numbers. The chances
1612 // of causing a collision this way should be minimal.
1613 std::hash::Hash::hash(&(file_lo.name_hash as u64), hasher);
1615 let col = (col_lo.0 as u64) & 0xFF;
1616 let line = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1617 let len = ((span.hi - span.lo).0 as u64) << 32;
1618 let line_col_len = col | line | len;
1619 std::hash::Hash::hash(&line_col_len, hasher);
1621 if span.ctxt == SyntaxContext::root() {
1622 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1624 TAG_EXPANSION.hash_stable(ctx, hasher);
1626 // Since the same expansion context is usually referenced many
1627 // times, we cache a stable hash of it and hash that instead of
1628 // recursing every time.
1630 static CACHE: RefCell<FxHashMap<hygiene::ExpnId, u64>> = Default::default();
1633 let sub_hash: u64 = CACHE.with(|cache| {
1634 let expn_id = span.ctxt.outer_expn();
1636 if let Some(&sub_hash) = cache.borrow().get(&expn_id) {
1640 let mut hasher = StableHasher::new();
1641 expn_id.expn_data().hash_stable(ctx, &mut hasher);
1642 let sub_hash: Fingerprint = hasher.finish();
1643 let sub_hash = sub_hash.to_smaller_hash();
1644 cache.borrow_mut().insert(expn_id, sub_hash);
1648 sub_hash.hash_stable(ctx, hasher);