Skip to main content

rustc_span/
hygiene.rs

1//! Machinery for hygienic macros.
2//!
3//! Inspired by Matthew Flatt et al., “Macros That Work Together: Compile-Time Bindings, Partial
4//! Expansion, and Definition Contexts,” *Journal of Functional Programming* 22, no. 2
5//! (March 1, 2012): 181–216, <https://doi.org/10.1017/S0956796812000093>.
6
7// Hygiene data is stored in a global variable and accessed via TLS, which
8// means that accesses are somewhat expensive. (`HygieneData::with`
9// encapsulates a single access.) Therefore, on hot code paths it is worth
10// ensuring that multiple HygieneData accesses are combined into a single
11// `HygieneData::with`.
12//
13// This explains why `HygieneData`, `SyntaxContext` and `ExpnId` have interfaces
14// with a certain amount of redundancy in them. For example,
15// `SyntaxContext::outer_expn_data` combines `SyntaxContext::outer` and
16// `ExpnId::expn_data` so that two `HygieneData` accesses can be performed within
17// a single `HygieneData::with` call.
18//
19// It also explains why many functions appear in `HygieneData` and again in
20// `SyntaxContext` or `ExpnId`. For example, `HygieneData::outer` and
21// `SyntaxContext::outer` do the same thing, but the former is for use within a
22// `HygieneData::with` call while the latter is for use outside such a call.
23// When modifying this file it is important to understand this distinction,
24// because getting it wrong can lead to nested `HygieneData::with` calls that
25// trigger runtime aborts. (Fortunately these are obvious and easy to fix.)
26
27use std::cell::RefCell;
28use std::hash::Hash;
29use std::sync::Arc;
30use std::{fmt, iter, mem};
31
32use rustc_data_structures::fingerprint::Fingerprint;
33use rustc_data_structures::fx::{FxHashMap, FxHashSet};
34use rustc_data_structures::stable_hash::{
35    StableHash, StableHashCtxt, StableHasher, ToStableHashKey,
36};
37use rustc_data_structures::sync::Lock;
38use rustc_data_structures::unhash::UnhashMap;
39use rustc_hashes::Hash64;
40use rustc_index::IndexVec;
41use rustc_macros::{Decodable, Encodable, StableHash};
42use rustc_serialize::{Decodable, Decoder, Encodable};
43use tracing::{debug, trace};
44
45use crate::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, ModId, StableCrateId};
46use crate::edition::Edition;
47use crate::source_map::SourceMap;
48use crate::symbol::{Symbol, kw, sym};
49use crate::{DUMMY_SP, Span, SpanDecoder, SpanEncoder, with_session_globals};
50
51/// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
52///
53/// See <https://rustc-dev-guide.rust-lang.org/macro-expansion.html> for more explanation.
54#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SyntaxContext { }
#[automatically_derived]
impl ::core::clone::Clone for SyntaxContext {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SyntaxContext { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SyntaxContext { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SyntaxContext {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SyntaxContext {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u32>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for SyntaxContext {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
55pub struct SyntaxContext(u32);
56
57// To ensure correctness of incremental compilation,
58// `SyntaxContext` must not implement `Ord` or `PartialOrd`.
59// See https://github.com/rust-lang/rust/issues/90317.
60impl !Ord for SyntaxContext {}
61impl !PartialOrd for SyntaxContext {}
62
63/// If this part of two syntax contexts is equal, then the whole syntax contexts should be equal.
64/// The other fields are only for caching.
65pub type SyntaxContextKey = (SyntaxContext, ExpnId, Transparency);
66
67#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SyntaxContextData { }
#[automatically_derived]
impl ::core::clone::Clone for SyntaxContextData {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<ExpnId>;
        let _: ::core::clone::AssertParamIsClone<Transparency>;
        let _: ::core::clone::AssertParamIsClone<SyntaxContext>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SyntaxContextData { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for SyntaxContextData {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["outer_expn", "outer_transparency", "parent", "opaque",
                        "opaque_and_semiopaque", "dollar_crate_name"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.outer_expn, &self.outer_transparency, &self.parent,
                        &self.opaque, &self.opaque_and_semiopaque,
                        &&self.dollar_crate_name];
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "SyntaxContextData", names, values)
    }
}Debug)]
68struct SyntaxContextData {
69    /// The last macro expansion in the chain.
70    /// (Here we say the most deeply nested macro expansion is the "outermost" expansion.)
71    outer_expn: ExpnId,
72    /// Transparency of the last macro expansion
73    outer_transparency: Transparency,
74    parent: SyntaxContext,
75    /// This context, but with all transparent and semi-opaque expansions filtered away.
76    opaque: SyntaxContext,
77    /// This context, but with all transparent expansions filtered away.
78    opaque_and_semiopaque: SyntaxContext,
79    /// Name of the crate to which `$crate` with this context would resolve.
80    dollar_crate_name: Symbol,
81}
82
83impl SyntaxContextData {
84    fn root() -> SyntaxContextData {
85        SyntaxContextData {
86            outer_expn: ExpnId::root(),
87            outer_transparency: Transparency::Opaque,
88            parent: SyntaxContext::root(),
89            opaque: SyntaxContext::root(),
90            opaque_and_semiopaque: SyntaxContext::root(),
91            dollar_crate_name: kw::DollarCrate,
92        }
93    }
94
95    fn key(&self) -> SyntaxContextKey {
96        (self.parent, self.outer_expn, self.outer_transparency)
97    }
98}
99
100#[automatically_derived]
impl ::core::marker::Copy for ExpnIndex { }
impl ExpnIndex {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    pub const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    pub const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for ExpnIndex {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for ExpnIndex {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for ExpnIndex {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for ExpnIndex {
    #[inline]
    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
        <usize as
                ::std::iter::Step>::steps_between(&Self::index(*start),
            &Self::index(*end))
    }
    #[inline]
    fn forward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_add(u).map(Self::from_usize)
    }
    #[inline]
    fn backward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_sub(u).map(Self::from_usize)
    }
    #[inline]
    fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_add(u);
        (Self::from_usize(s), o)
    }
    #[inline]
    fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_sub(u);
        (Self::from_usize(s), o)
    }
}
impl ::std::cmp::Ord for ExpnIndex {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_u32().cmp(&other.as_u32())
    }
}
impl ::std::cmp::PartialOrd for ExpnIndex {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl From<ExpnIndex> for u32 {
    #[inline]
    fn from(v: ExpnIndex) -> u32 { v.as_u32() }
}
impl From<ExpnIndex> for usize {
    #[inline]
    fn from(v: ExpnIndex) -> usize { v.as_usize() }
}
impl From<usize> for ExpnIndex {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for ExpnIndex {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for ExpnIndex {}
impl ::std::cmp::PartialEq for ExpnIndex {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for ExpnIndex {}
impl ::std::hash::Hash for ExpnIndex {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for ExpnIndex {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
101    /// A unique ID associated with a macro invocation and expansion.
102    #[orderable]
103    pub struct ExpnIndex {}
104}
105
106/// A unique ID associated with a macro invocation and expansion.
107#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ExpnId { }
#[automatically_derived]
impl ::core::clone::Clone for ExpnId {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<CrateNum>;
        let _: ::core::clone::AssertParamIsClone<ExpnIndex>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ExpnId { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ExpnId { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ExpnId {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.krate == other.krate && self.local_id == other.local_id
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ExpnId {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<CrateNum>;
        let _: ::core::cmp::AssertParamIsEq<ExpnIndex>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ExpnId {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.krate, state);
        ::core::hash::Hash::hash(&self.local_id, state)
    }
}Hash)]
108pub struct ExpnId {
109    pub krate: CrateNum,
110    pub local_id: ExpnIndex,
111}
112
113impl fmt::Debug for ExpnId {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        // Generate crate_::{{expn_}}.
116        f.write_fmt(format_args!("{0:?}::{{{{expn{1}}}}}", self.krate,
        self.local_id.as_u32()))write!(f, "{:?}::{{{{expn{}}}}}", self.krate, self.local_id.as_u32())
117    }
118}
119
120#[automatically_derived]
impl ::core::marker::Copy for LocalExpnId { }
impl LocalExpnId {
    #[doc = r" Maximum value the index can take, as a `u32`."]
    pub const MAX_AS_U32: u32 = 0xFFFF_FF00;
    #[doc = r" Maximum value the index can take."]
    pub const MAX: Self = Self::from_u32(0xFFFF_FF00);
    #[doc = r" Zero value of the index."]
    pub const ZERO: Self = Self::from_u32(0);
    #[doc = r" Creates a new index from a given `usize`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_usize(value: usize) -> Self {
        if !(value <= (0xFFFF_FF00 as usize)) {
            ::core::panicking::panic("assertion failed: value <= (0xFFFF_FF00 as usize)")
        };
        unsafe { Self::from_u32_unchecked(value as u32) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u32(value: u32) -> Self {
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u16`."]
    #[doc = r""]
    #[doc = r" # Panics"]
    #[doc = r""]
    #[doc = r" Will panic if `value` exceeds `MAX`."]
    #[inline]
    pub const fn from_u16(value: u16) -> Self {
        let value = value as u32;
        if !(value <= 0xFFFF_FF00) {
            ::core::panicking::panic("assertion failed: value <= 0xFFFF_FF00")
        };
        unsafe { Self::from_u32_unchecked(value) }
    }
    #[doc = r" Creates a new index from a given `u32`."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc =
    r" The provided value must be less than or equal to the maximum value for the newtype."]
    #[doc =
    r" Providing a value outside this range is undefined due to layout restrictions."]
    #[doc = r""]
    #[doc = r" Prefer using `from_u32`."]
    #[inline]
    pub const unsafe fn from_u32_unchecked(value: u32) -> Self {
        Self {
            private_use_as_methods_instead: unsafe {
                std::mem::transmute(value)
            },
        }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn index(self) -> usize { self.as_usize() }
    #[doc = r" Extracts the value of this index as a `u32`."]
    #[inline]
    pub const fn as_u32(self) -> u32 {
        unsafe { std::mem::transmute(self.private_use_as_methods_instead) }
    }
    #[doc = r" Extracts the value of this index as a `usize`."]
    #[inline]
    pub const fn as_usize(self) -> usize { self.as_u32() as usize }
}
impl std::ops::Add<usize> for LocalExpnId {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for LocalExpnId {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for LocalExpnId {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl From<LocalExpnId> for u32 {
    #[inline]
    fn from(v: LocalExpnId) -> u32 { v.as_u32() }
}
impl From<LocalExpnId> for usize {
    #[inline]
    fn from(v: LocalExpnId) -> usize { v.as_usize() }
}
impl From<usize> for LocalExpnId {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for LocalExpnId {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for LocalExpnId {}
impl ::std::cmp::PartialEq for LocalExpnId {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for LocalExpnId {}
impl ::std::hash::Hash for LocalExpnId {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for LocalExpnId {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("expn{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
121    /// A unique ID associated with a macro invocation and expansion.
122    #[debug_format = "expn{}"]
123    pub struct LocalExpnId {}
124}
125
126// To ensure correctness of incremental compilation,
127// `LocalExpnId` must not implement `Ord` or `PartialOrd`.
128// See https://github.com/rust-lang/rust/issues/90317.
129impl !Ord for LocalExpnId {}
130impl !PartialOrd for LocalExpnId {}
131
132/// A unique hash value associated to an expansion.
133#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ExpnHash { }
#[automatically_derived]
impl ::core::clone::Clone for ExpnHash {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Fingerprint>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ExpnHash { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ExpnHash { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ExpnHash {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ExpnHash {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Fingerprint>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for ExpnHash {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for ExpnHash {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "ExpnHash",
            &&self.0)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for ExpnHash {
            fn encode(&self, __encoder: &mut __E) {
                let ExpnHash(ref __binding_0) = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for ExpnHash {
            fn decode(__decoder: &mut __D) -> Self {
                ExpnHash(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for ExpnHash {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ExpnHash(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
134pub struct ExpnHash(Fingerprint);
135
136impl ExpnHash {
137    /// Returns the [StableCrateId] identifying the crate this [ExpnHash]
138    /// originates from.
139    #[inline]
140    pub fn stable_crate_id(self) -> StableCrateId {
141        StableCrateId(self.0.split().0)
142    }
143
144    /// Returns the crate-local part of the [ExpnHash].
145    ///
146    /// Used for assertions.
147    #[inline]
148    pub fn local_hash(self) -> Hash64 {
149        self.0.split().1
150    }
151
152    #[inline]
153    pub fn is_root(self) -> bool {
154        self.0 == Fingerprint::ZERO
155    }
156
157    /// Builds a new [ExpnHash] with the given [StableCrateId] and
158    /// `local_hash`, where `local_hash` must be unique within its crate.
159    fn new(stable_crate_id: StableCrateId, local_hash: Hash64) -> ExpnHash {
160        ExpnHash(Fingerprint::new(stable_crate_id.0, local_hash))
161    }
162}
163
164/// A property of a macro expansion that determines how identifiers
165/// produced by that expansion are resolved.
166#[derive(#[automatically_derived]
impl ::core::marker::Copy for Transparency { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Transparency { }
#[automatically_derived]
impl ::core::clone::Clone for Transparency {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Transparency { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Transparency {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Transparency { }Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Transparency {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::cmp::PartialOrd::partial_cmp(&::core::intrinsics::discriminant_value(self),
            &::core::intrinsics::discriminant_value(other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::hash::Hash for Transparency {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for Transparency {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Transparency::Transparent => "Transparent",
                Transparency::SemiOpaque => "SemiOpaque",
                Transparency::Opaque => "Opaque",
            })
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Transparency {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        Transparency::Transparent => { 0usize }
                        Transparency::SemiOpaque => { 1usize }
                        Transparency::Opaque => { 2usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for Transparency {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { Transparency::Transparent }
                    1usize => { Transparency::SemiOpaque }
                    2usize => { Transparency::Opaque }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Transparency`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
167#[derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Transparency
            {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    Transparency::Transparent => {}
                    Transparency::SemiOpaque => {}
                    Transparency::Opaque => {}
                }
            }
        }
    };StableHash)]
168pub enum Transparency {
169    /// Identifier produced by a transparent expansion is always resolved at call-site.
170    /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
171    Transparent,
172    /// Identifier produced by a semi-opaque expansion may be resolved
173    /// either at call-site or at definition-site.
174    /// If it's a local variable, label or `$crate` then it's resolved at def-site.
175    /// Otherwise it's resolved at call-site.
176    /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
177    /// but that's an implementation detail.
178    SemiOpaque,
179    /// Identifier produced by an opaque expansion is always resolved at definition-site.
180    /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
181    Opaque,
182}
183
184impl Transparency {
185    pub fn fallback(macro_rules: bool) -> Self {
186        if macro_rules { Transparency::SemiOpaque } else { Transparency::Opaque }
187    }
188}
189
190impl LocalExpnId {
191    /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
192    pub const ROOT: LocalExpnId = LocalExpnId::ZERO;
193
194    #[inline]
195    fn from_raw(idx: ExpnIndex) -> LocalExpnId {
196        LocalExpnId::from_u32(idx.as_u32())
197    }
198
199    #[inline]
200    pub fn as_raw(self) -> ExpnIndex {
201        ExpnIndex::from_u32(self.as_u32())
202    }
203
204    pub fn fresh_empty() -> LocalExpnId {
205        HygieneData::with(|data| {
206            let expn_id = data.local_expn_data.push(None);
207            let _eid = data.local_expn_hashes.push(ExpnHash(Fingerprint::ZERO));
208            if true {
    {
        match (&expn_id, &_eid) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(expn_id, _eid);
209            expn_id
210        })
211    }
212
213    pub fn fresh(mut expn_data: ExpnData, hcx: impl StableHashCtxt) -> LocalExpnId {
214        if true {
    {
        match (&expn_data.parent.krate, &LOCAL_CRATE) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(expn_data.parent.krate, LOCAL_CRATE);
215        let expn_hash = update_disambiguator(&mut expn_data, hcx);
216        HygieneData::with(|data| {
217            let expn_id = data.local_expn_data.push(Some(expn_data));
218            let _eid = data.local_expn_hashes.push(expn_hash);
219            if true {
    {
        match (&expn_id, &_eid) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(expn_id, _eid);
220            let _old_id = data.expn_hash_to_expn_id.insert(expn_hash, expn_id.to_expn_id());
221            if true {
    if !_old_id.is_none() {
        ::core::panicking::panic("assertion failed: _old_id.is_none()")
    };
};debug_assert!(_old_id.is_none());
222            expn_id
223        })
224    }
225
226    #[inline]
227    pub fn expn_data(self) -> ExpnData {
228        HygieneData::with(|data| data.local_expn_data(self).clone())
229    }
230
231    #[inline]
232    pub fn to_expn_id(self) -> ExpnId {
233        ExpnId { krate: LOCAL_CRATE, local_id: self.as_raw() }
234    }
235
236    #[inline]
237    pub fn set_expn_data(self, mut expn_data: ExpnData, hcx: impl StableHashCtxt) {
238        if true {
    {
        match (&expn_data.parent.krate, &LOCAL_CRATE) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(expn_data.parent.krate, LOCAL_CRATE);
239        let expn_hash = update_disambiguator(&mut expn_data, hcx);
240        HygieneData::with(|data| {
241            let old_expn_data = &mut data.local_expn_data[self];
242            if !old_expn_data.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("expansion data is reset for an expansion ID"));
    }
};assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
243            *old_expn_data = Some(expn_data);
244            if true {
    {
        match (&data.local_expn_hashes[self].0, &Fingerprint::ZERO) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(data.local_expn_hashes[self].0, Fingerprint::ZERO);
245            data.local_expn_hashes[self] = expn_hash;
246            let _old_id = data.expn_hash_to_expn_id.insert(expn_hash, self.to_expn_id());
247            if true {
    if !_old_id.is_none() {
        ::core::panicking::panic("assertion failed: _old_id.is_none()")
    };
};debug_assert!(_old_id.is_none());
248        });
249    }
250
251    #[inline]
252    pub fn is_descendant_of(self, ancestor: LocalExpnId) -> bool {
253        self.to_expn_id().is_descendant_of(ancestor.to_expn_id())
254    }
255
256    /// Returns span for the macro which originally caused this expansion to happen.
257    ///
258    /// Stops backtracing at include! boundary.
259    #[inline]
260    pub fn expansion_cause(self) -> Option<Span> {
261        self.to_expn_id().expansion_cause()
262    }
263}
264
265impl ExpnId {
266    /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
267    /// Invariant: we do not create any ExpnId with local_id == 0 and krate != 0.
268    pub const fn root() -> ExpnId {
269        ExpnId { krate: LOCAL_CRATE, local_id: ExpnIndex::ZERO }
270    }
271
272    #[inline]
273    pub fn expn_hash(self) -> ExpnHash {
274        HygieneData::with(|data| data.expn_hash(self))
275    }
276
277    #[inline]
278    pub fn from_hash(hash: ExpnHash) -> Option<ExpnId> {
279        HygieneData::with(|data| data.expn_hash_to_expn_id.get(&hash).copied())
280    }
281
282    #[inline]
283    pub fn as_local(self) -> Option<LocalExpnId> {
284        if self.krate == LOCAL_CRATE { Some(LocalExpnId::from_raw(self.local_id)) } else { None }
285    }
286
287    #[inline]
288    #[track_caller]
289    pub fn expect_local(self) -> LocalExpnId {
290        self.as_local().unwrap()
291    }
292
293    #[inline]
294    pub fn expn_data(self) -> ExpnData {
295        HygieneData::with(|data| data.expn_data(self).clone())
296    }
297
298    #[inline]
299    pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
300        // a few "fast path" cases to avoid locking HygieneData
301        if ancestor == ExpnId::root() || ancestor == self {
302            return true;
303        }
304        if ancestor.krate != self.krate {
305            return false;
306        }
307        HygieneData::with(|data| data.is_descendant_of(self, ancestor))
308    }
309
310    /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
311    /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
312    #[inline]
313    pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
314        // fast path to avoid locking: everything is a descendant of the root context's
315        // outer expansion
316        if ctxt.is_root() {
317            return true;
318        }
319        HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
320    }
321
322    /// Returns span for the macro which originally caused this expansion to happen.
323    ///
324    /// Stops backtracing at include! boundary.
325    pub fn expansion_cause(mut self) -> Option<Span> {
326        let mut last_macro = None;
327        loop {
328            // Fast path to avoid locking.
329            if self == ExpnId::root() {
330                break;
331            }
332            let expn_data = self.expn_data();
333            // Stop going up the backtrace once include! is encountered
334            if expn_data.kind == ExpnKind::Macro(MacroKind::Bang, sym::include) {
335                break;
336            }
337            self = expn_data.call_site.ctxt().outer_expn();
338            last_macro = Some(expn_data.call_site);
339        }
340        last_macro
341    }
342}
343
344#[derive(#[automatically_derived]
impl ::core::fmt::Debug for HygieneData {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["local_expn_data", "local_expn_hashes", "foreign_expn_data",
                        "foreign_expn_hashes", "expn_hash_to_expn_id",
                        "syntax_context_data", "syntax_context_map",
                        "expn_data_disambiguators"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.local_expn_data, &self.local_expn_hashes,
                        &self.foreign_expn_data, &self.foreign_expn_hashes,
                        &self.expn_hash_to_expn_id, &self.syntax_context_data,
                        &self.syntax_context_map, &&self.expn_data_disambiguators];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "HygieneData",
            names, values)
    }
}Debug)]
345pub(crate) struct HygieneData {
346    /// Each expansion should have an associated expansion data, but sometimes there's a delay
347    /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
348    /// first and then resolved later), so we use an `Option` here.
349    local_expn_data: IndexVec<LocalExpnId, Option<ExpnData>>,
350    local_expn_hashes: IndexVec<LocalExpnId, ExpnHash>,
351    /// Data and hash information from external crates. We may eventually want to remove these
352    /// maps, and fetch the information directly from the other crate's metadata like DefIds do.
353    foreign_expn_data: FxHashMap<ExpnId, ExpnData>,
354    foreign_expn_hashes: FxHashMap<ExpnId, ExpnHash>,
355    expn_hash_to_expn_id: UnhashMap<ExpnHash, ExpnId>,
356    syntax_context_data: Vec<SyntaxContextData>,
357    syntax_context_map: FxHashMap<SyntaxContextKey, SyntaxContext>,
358    /// Maps the `local_hash` of an `ExpnData` to the next disambiguator value.
359    /// This is used by `update_disambiguator` to keep track of which `ExpnData`s
360    /// would have collisions without a disambiguator.
361    /// The keys of this map are always computed with `ExpnData.disambiguator`
362    /// set to 0.
363    expn_data_disambiguators: UnhashMap<Hash64, u32>,
364}
365
366impl HygieneData {
367    pub(crate) fn new(edition: Edition) -> Self {
368        let root_data = ExpnData::default(
369            ExpnKind::Root,
370            DUMMY_SP,
371            edition,
372            Some(CRATE_DEF_ID.to_def_id()),
373            None,
374        );
375
376        // Index 0 is the root context, and nothing but its `dollar_crate_name` is ever
377        // mutated afterwards. The lock-free root paths on `SyntaxContext` rely on that.
378        let root_ctxt_data = SyntaxContextData::root();
379        HygieneData {
380            local_expn_data: IndexVec::from_elem_n(Some(root_data), 1),
381            local_expn_hashes: IndexVec::from_elem_n(ExpnHash(Fingerprint::ZERO), 1),
382            foreign_expn_data: FxHashMap::default(),
383            foreign_expn_hashes: FxHashMap::default(),
384            expn_hash_to_expn_id: iter::once((ExpnHash(Fingerprint::ZERO), ExpnId::root()))
385                .collect(),
386            syntax_context_data: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [root_ctxt_data]))vec![root_ctxt_data],
387            syntax_context_map: iter::once((root_ctxt_data.key(), SyntaxContext(0))).collect(),
388            expn_data_disambiguators: UnhashMap::default(),
389        }
390    }
391
392    #[inline]
393    fn with<R>(f: impl FnOnce(&mut HygieneData) -> R) -> R {
394        with_session_globals(|session_globals| f(&mut session_globals.hygiene_data.borrow_mut()))
395    }
396
397    #[inline]
398    fn expn_hash(&self, expn_id: ExpnId) -> ExpnHash {
399        match expn_id.as_local() {
400            Some(expn_id) => self.local_expn_hashes[expn_id],
401            None => self.foreign_expn_hashes[&expn_id],
402        }
403    }
404
405    #[inline]
406    fn local_expn_data(&self, expn_id: LocalExpnId) -> &ExpnData {
407        self.local_expn_data[expn_id].as_ref().expect("no expansion data for an expansion ID")
408    }
409
410    fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
411        if let Some(expn_id) = expn_id.as_local() {
412            self.local_expn_data[expn_id].as_ref().expect("no expansion data for an expansion ID")
413        } else {
414            &self.foreign_expn_data[&expn_id]
415        }
416    }
417
418    fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
419        // a couple "fast path" cases to avoid traversing parents in the loop below
420        if ancestor == ExpnId::root() {
421            return true;
422        }
423        if expn_id.krate != ancestor.krate {
424            return false;
425        }
426        loop {
427            if expn_id == ancestor {
428                return true;
429            }
430            if expn_id == ExpnId::root() {
431                return false;
432            }
433            expn_id = self.expn_data(expn_id).parent;
434        }
435    }
436
437    #[inline]
438    fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
439        self.syntax_context_data[ctxt.0 as usize].opaque
440    }
441
442    #[inline]
443    fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
444        self.syntax_context_data[ctxt.0 as usize].opaque_and_semiopaque
445    }
446
447    /// See [`SyntaxContextData::outer_expn`]
448    #[inline]
449    fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
450        self.syntax_context_data[ctxt.0 as usize].outer_expn
451    }
452
453    /// The last macro expansion and its Transparency
454    #[inline]
455    fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
456        let data = &self.syntax_context_data[ctxt.0 as usize];
457        (data.outer_expn, data.outer_transparency)
458    }
459
460    #[inline]
461    fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
462        self.syntax_context_data[ctxt.0 as usize].parent
463    }
464
465    fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
466        let outer_mark = self.outer_mark(*ctxt);
467        *ctxt = self.parent_ctxt(*ctxt);
468        outer_mark
469    }
470
471    fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
472        let mut marks = Vec::new();
473        while !ctxt.is_root() {
474            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:474",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(474u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("marks: getting parent of {0:?}",
                                                    ctxt) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("marks: getting parent of {:?}", ctxt);
475            marks.push(self.outer_mark(ctxt));
476            ctxt = self.parent_ctxt(ctxt);
477        }
478        marks.reverse();
479        marks
480    }
481
482    fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
483        let orig_span = span;
484        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:484",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(484u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain({0:?}, {1:?})",
                                                    span, to) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain({:?}, {:?})", span, to);
485        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:485",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(485u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain: span ctxt = {0:?}",
                                                    span.ctxt()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain: span ctxt = {:?}", span.ctxt());
486        while span.ctxt() != to && span.from_expansion() {
487            let outer_expn = self.outer_expn(span.ctxt());
488            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:488",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(488u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain({0:?}): outer_expn={1:?}",
                                                    span, outer_expn) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn);
489            let expn_data = self.expn_data(outer_expn);
490            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:490",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(490u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain({0:?}): expn_data={1:?}",
                                                    span, expn_data) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain({:?}): expn_data={:?}", span, expn_data);
491            span = expn_data.call_site;
492        }
493        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:493",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(493u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain: for span {0:?} >>> return span = {1:?}",
                                                    orig_span, span) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain: for span {:?} >>> return span = {:?}", orig_span, span);
494        span
495    }
496
497    fn walk_chain_collapsed(&self, mut span: Span, to: Span) -> Span {
498        let orig_span = span;
499        let mut ret_span = span;
500        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:500",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(500u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain_collapsed({0:?}, {1:?})",
                                                    span, to) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain_collapsed({:?}, {:?})", span, to);
501        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:501",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(501u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain_collapsed: span ctxt = {0:?}",
                                                    span.ctxt()) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain_collapsed: span ctxt = {:?}", span.ctxt());
502        while let ctxt = span.ctxt()
503            && !ctxt.is_root()
504            && ctxt != to.ctxt()
505        {
506            let outer_expn = self.outer_expn(ctxt);
507            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:507",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(507u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain_collapsed({0:?}): outer_expn={1:?}",
                                                    span, outer_expn) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain_collapsed({:?}): outer_expn={:?}", span, outer_expn);
508            let expn_data = self.expn_data(outer_expn);
509            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:509",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(509u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain_collapsed({0:?}): expn_data={1:?}",
                                                    span, expn_data) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain_collapsed({:?}): expn_data={:?}", span, expn_data);
510            span = expn_data.call_site;
511            if expn_data.collapse_debuginfo {
512                ret_span = span;
513            }
514        }
515        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:515",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(515u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("walk_chain_collapsed: for span {0:?} >>> return span = {1:?}",
                                                    orig_span, ret_span) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("walk_chain_collapsed: for span {:?} >>> return span = {:?}", orig_span, ret_span);
516        ret_span
517    }
518
519    fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
520        let mut scope = None;
521        while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
522            scope = Some(self.remove_mark(ctxt).0);
523        }
524        scope
525    }
526
527    fn apply_mark(
528        &mut self,
529        ctxt: SyntaxContext,
530        expn_id: ExpnId,
531        transparency: Transparency,
532    ) -> SyntaxContext {
533        {
    match (&expn_id, &ExpnId::root()) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_ne!(expn_id, ExpnId::root());
534        if transparency == Transparency::Opaque {
535            return self.alloc_ctxt(ctxt, expn_id, transparency);
536        }
537
538        let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
539        let mut call_site_ctxt = if transparency == Transparency::SemiOpaque {
540            self.normalize_to_macros_2_0(call_site_ctxt)
541        } else {
542            self.normalize_to_macro_rules(call_site_ctxt)
543        };
544
545        if call_site_ctxt.is_root() {
546            return self.alloc_ctxt(ctxt, expn_id, transparency);
547        }
548
549        // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
550        // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
551        //
552        // In this case, the tokens from the macros 1.0 definition inherit the hygiene
553        // at their invocation. That is, we pretend that the macros 1.0 definition
554        // was defined at its invocation (i.e., inside the macros 2.0 definition)
555        // so that the macros 2.0 definition remains hygienic.
556        //
557        // See the example at `test/ui/hygiene/legacy_interaction.rs`.
558        for (expn_id, transparency) in self.marks(ctxt) {
559            call_site_ctxt = self.alloc_ctxt(call_site_ctxt, expn_id, transparency);
560        }
561        self.alloc_ctxt(call_site_ctxt, expn_id, transparency)
562    }
563
564    /// Allocate a new context with the given key, or retrieve it from cache if the given key
565    /// already exists. The auxiliary fields are calculated from the key.
566    fn alloc_ctxt(
567        &mut self,
568        parent: SyntaxContext,
569        expn_id: ExpnId,
570        transparency: Transparency,
571    ) -> SyntaxContext {
572        // Look into the cache first.
573        let key = (parent, expn_id, transparency);
574        if let Some(ctxt) = self.syntax_context_map.get(&key) {
575            return *ctxt;
576        }
577
578        // Reserve a new syntax context.
579        // The inserted dummy data can only be potentially accessed by nested `alloc_ctxt` calls,
580        // the assert below ensures that it doesn't happen.
581        let ctxt = SyntaxContext::from_usize(self.syntax_context_data.len());
582        self.syntax_context_data
583            .push(SyntaxContextData { dollar_crate_name: sym::dummy, ..SyntaxContextData::root() });
584        self.syntax_context_map.insert(key, ctxt);
585
586        // Opaque and semi-opaque versions of the parent. Note that they may be equal to the
587        // parent itself. E.g. `parent_opaque` == `parent` if the expn chain contains only opaques,
588        // and `parent_opaque_and_semiopaque` == `parent` if the expn contains only (semi-)opaques.
589        let parent_data = &self.syntax_context_data[parent.0 as usize];
590        {
    match (&parent_data.dollar_crate_name, &sym::dummy) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_ne!(parent_data.dollar_crate_name, sym::dummy);
591        let parent_opaque = parent_data.opaque;
592        let parent_opaque_and_semiopaque = parent_data.opaque_and_semiopaque;
593
594        // Evaluate opaque and semi-opaque versions of the new syntax context.
595        let (opaque, opaque_and_semiopaque) = match transparency {
596            Transparency::Transparent => (parent_opaque, parent_opaque_and_semiopaque),
597            Transparency::SemiOpaque => (
598                parent_opaque,
599                // Will be the same as `ctxt` if the expn chain contains only (semi-)opaques.
600                self.alloc_ctxt(parent_opaque_and_semiopaque, expn_id, transparency),
601            ),
602            Transparency::Opaque => (
603                // Will be the same as `ctxt` if the expn chain contains only opaques.
604                self.alloc_ctxt(parent_opaque, expn_id, transparency),
605                // Will be the same as `ctxt` if the expn chain contains only (semi-)opaques.
606                self.alloc_ctxt(parent_opaque_and_semiopaque, expn_id, transparency),
607            ),
608        };
609
610        // Fill the full data, now that we have it.
611        self.syntax_context_data[ctxt.as_u32() as usize] = SyntaxContextData {
612            outer_expn: expn_id,
613            outer_transparency: transparency,
614            parent,
615            opaque,
616            opaque_and_semiopaque,
617            dollar_crate_name: kw::DollarCrate,
618        };
619        ctxt
620    }
621}
622
623pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
624    HygieneData::with(|data| data.walk_chain(span, to))
625}
626
627/// In order to have good line stepping behavior in debugger, for the given span we return its
628/// outermost macro call site that still has a `#[collapse_debuginfo(yes)]` property on it.
629/// We also stop walking call sites at the function body level because no line stepping can occur
630/// at the level above that.
631/// The returned span can then be used in emitted debuginfo.
632pub fn walk_chain_collapsed(span: Span, to: Span) -> Span {
633    HygieneData::with(|data| data.walk_chain_collapsed(span, to))
634}
635
636pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
637    // The new contexts that need updating are at the end of the list and have `$crate` as a name.
638    let mut to_update = ::alloc::vec::Vec::new()vec![];
639    HygieneData::with(|data| {
640        for (idx, scdata) in data.syntax_context_data.iter().enumerate().rev() {
641            if scdata.dollar_crate_name == kw::DollarCrate {
642                to_update.push((idx, kw::DollarCrate));
643            } else {
644                break;
645            }
646        }
647    });
648    // The callback must be called from outside of the `HygieneData` lock,
649    // since it will try to acquire it too.
650    for (idx, name) in &mut to_update {
651        *name = get_name(SyntaxContext::from_usize(*idx));
652    }
653    HygieneData::with(|data| {
654        for (idx, name) in to_update {
655            data.syntax_context_data[idx].dollar_crate_name = name;
656        }
657    })
658}
659
660pub fn debug_hygiene_data(verbose: bool) -> String {
661    HygieneData::with(|data| {
662        if verbose {
663            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:#?}", data))
    })format!("{data:#?}")
664        } else {
665            let mut s = String::from("Expansions:");
666            let mut debug_expn_data = |(id, expn_data): (&ExpnId, &ExpnData)| {
667                s.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0:?}: parent: {1:?}, call_site_ctxt: {2:?}, def_site_ctxt: {3:?}, kind: {4:?}",
                id, expn_data.parent, expn_data.call_site.ctxt(),
                expn_data.def_site.ctxt(), expn_data.kind))
    })format!(
668                    "\n{:?}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
669                    id,
670                    expn_data.parent,
671                    expn_data.call_site.ctxt(),
672                    expn_data.def_site.ctxt(),
673                    expn_data.kind,
674                ))
675            };
676            data.local_expn_data.iter_enumerated().for_each(|(id, expn_data)| {
677                let expn_data = expn_data.as_ref().expect("no expansion data for an expansion ID");
678                debug_expn_data((&id.to_expn_id(), expn_data))
679            });
680
681            // Sort the hash map for more reproducible output.
682            // Because of this, it is fine to rely on the unstable iteration order of the map.
683            #[allow(rustc::potential_query_instability)]
684            let mut foreign_expn_data: Vec<_> = data.foreign_expn_data.iter().collect();
685            foreign_expn_data.sort_by_key(|(id, _)| (id.krate, id.local_id));
686            foreign_expn_data.into_iter().for_each(debug_expn_data);
687            s.push_str("\n\nSyntaxContexts:");
688            data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
689                s.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n#{0}: parent: {1:?}, outer_mark: ({2:?}, {3:?})",
                id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency))
    })format!(
690                    "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
691                    id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
692                ));
693            });
694            s
695        }
696    })
697}
698
699impl SyntaxContext {
700    #[inline]
701    pub const fn root() -> Self {
702        SyntaxContext(0)
703    }
704
705    #[inline]
706    pub const fn is_root(self) -> bool {
707        self.0 == SyntaxContext::root().as_u32()
708    }
709
710    #[inline]
711    pub(crate) const fn as_u32(self) -> u32 {
712        self.0
713    }
714
715    #[inline]
716    pub(crate) const fn from_u32(raw: u32) -> SyntaxContext {
717        SyntaxContext(raw)
718    }
719
720    #[inline]
721    fn from_usize(raw: usize) -> SyntaxContext {
722        SyntaxContext(u32::try_from(raw).unwrap())
723    }
724
725    /// Extend a syntax context with a given expansion and transparency.
726    #[inline]
727    pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
728        HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
729    }
730
731    /// Pulls a single mark off of the syntax context. This effectively moves the
732    /// context up one macro definition level. That is, if we have a nested macro
733    /// definition as follows:
734    ///
735    /// ```ignore (illustrative)
736    /// macro_rules! f {
737    ///    macro_rules! g {
738    ///        ...
739    ///    }
740    /// }
741    /// ```
742    ///
743    /// and we have a SyntaxContext that is referring to something declared by an invocation
744    /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
745    /// invocation of f that created g1.
746    /// Returns the mark that was removed.
747    #[inline]
748    pub fn remove_mark(&mut self) -> ExpnId {
749        HygieneData::with(|data| data.remove_mark(self).0)
750    }
751
752    #[inline]
753    pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
754        HygieneData::with(|data| data.marks(self))
755    }
756
757    /// Adjust this context for resolution in a scope created by the given expansion.
758    /// For example, consider the following three resolutions of `f`:
759    ///
760    /// ```rust
761    /// #![feature(decl_macro)]
762    /// mod foo {
763    ///     pub fn f() {} // `f`'s `SyntaxContext` is empty.
764    /// }
765    /// m!(f);
766    /// macro m($f:ident) {
767    ///     mod bar {
768    ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
769    ///         pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
770    ///     }
771    ///     foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
772    ///     //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
773    ///     //| and it resolves to `::foo::f`.
774    ///     bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
775    ///     //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
776    ///     //| and it resolves to `::bar::f`.
777    ///     bar::$f(); // `f`'s `SyntaxContext` is empty.
778    ///     //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
779    ///     //| and it resolves to `::bar::$f`.
780    /// }
781    /// ```
782    /// This returns the expansion whose definition scope we use to privacy check the resolution,
783    /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
784    #[inline]
785    pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
786        HygieneData::with(|data| data.adjust(self, expn_id))
787    }
788
789    /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
790    #[inline]
791    pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
792        HygieneData::with(|data| {
793            *self = data.normalize_to_macros_2_0(*self);
794            data.adjust(self, expn_id)
795        })
796    }
797
798    /// Adjust this context for resolution in a scope created by the given expansion
799    /// via a glob import with the given `SyntaxContext`.
800    /// For example:
801    ///
802    /// ```compile_fail,E0425
803    /// #![feature(decl_macro)]
804    /// m!(f);
805    /// macro m($i:ident) {
806    ///     mod foo {
807    ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
808    ///         pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
809    ///     }
810    ///     n!(f);
811    ///     macro n($j:ident) {
812    ///         use foo::*;
813    ///         f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
814    ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
815    ///         $i(); // `$i`'s `SyntaxContext` has a mark from `n`
816    ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
817    ///         $j(); // `$j`'s `SyntaxContext` has a mark from `m`
818    ///         //^ This cannot be glob-adjusted, so this is a resolution error.
819    ///     }
820    /// }
821    /// ```
822    /// This returns `None` if the context cannot be glob-adjusted.
823    /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
824    pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
825        HygieneData::with(|data| {
826            let mut scope = None;
827            let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
828            while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
829                scope = Some(data.remove_mark(&mut glob_ctxt).0);
830                if data.remove_mark(self).0 != scope.unwrap() {
831                    return None;
832                }
833            }
834            if data.adjust(self, expn_id).is_some() {
835                return None;
836            }
837            Some(scope)
838        })
839    }
840
841    /// Undo `glob_adjust` if possible:
842    ///
843    /// ```ignore (illustrative)
844    /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
845    ///     assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
846    /// }
847    /// ```
848    pub fn reverse_glob_adjust(
849        &mut self,
850        expn_id: ExpnId,
851        glob_span: Span,
852    ) -> Option<Option<ExpnId>> {
853        HygieneData::with(|data| {
854            if data.adjust(self, expn_id).is_some() {
855                return None;
856            }
857
858            let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
859            let mut marks = Vec::new();
860            while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
861                marks.push(data.remove_mark(&mut glob_ctxt));
862            }
863
864            let scope = marks.last().map(|mark| mark.0);
865            while let Some((expn_id, transparency)) = marks.pop() {
866                *self = data.apply_mark(*self, expn_id, transparency);
867            }
868            Some(scope)
869        })
870    }
871
872    pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
873        HygieneData::with(|data| {
874            let mut self_normalized = data.normalize_to_macros_2_0(self);
875            data.adjust(&mut self_normalized, expn_id);
876            self_normalized == data.normalize_to_macros_2_0(other)
877        })
878    }
879
880    #[inline]
881    pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
882        // fast path to avoid locking: the root context normalizes to itself
883        if self.is_root() {
884            return self;
885        }
886        HygieneData::with(|data| data.normalize_to_macros_2_0(self))
887    }
888
889    #[inline]
890    pub fn normalize_to_macro_rules(self) -> SyntaxContext {
891        // fast path to avoid locking: the root context normalizes to itself
892        if self.is_root() {
893            return self;
894        }
895        HygieneData::with(|data| data.normalize_to_macro_rules(self))
896    }
897
898    /// See [`SyntaxContextData::outer_expn`]
899    #[inline]
900    pub fn outer_expn(self) -> ExpnId {
901        HygieneData::with(|data| data.outer_expn(self))
902    }
903
904    /// `ctxt.outer_expn_data()` is equivalent to but faster than
905    /// `ctxt.outer_expn().expn_data()`.
906    #[inline]
907    pub fn outer_expn_data(self) -> ExpnData {
908        HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
909    }
910
911    #[inline]
912    pub(crate) fn dollar_crate_name(self) -> Symbol {
913        HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
914    }
915
916    #[inline]
917    pub fn edition(self) -> Edition {
918        HygieneData::with(|data| data.expn_data(data.outer_expn(self)).edition)
919    }
920
921    /// Returns whether this context originates in a foreign crate's external macro.
922    ///
923    /// This is used to test whether a lint should not even begin to figure out whether it should
924    /// be reported on the current node.
925    pub fn in_external_macro(self, sm: &SourceMap) -> bool {
926        // fast path to avoid locking/expn-data read: the root context is not in a macro
927        if self.is_root() {
928            return false;
929        }
930        let expn_data = self.outer_expn_data();
931        match expn_data.kind {
932            ExpnKind::Root
933            | ExpnKind::Desugaring(
934                DesugaringKind::ForLoop
935                | DesugaringKind::WhileLoop
936                | DesugaringKind::OpaqueTy
937                | DesugaringKind::Async
938                | DesugaringKind::Await,
939            ) => false,
940            ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
941            ExpnKind::Macro(MacroKind::Bang, _) => {
942                // Dummy span for the `def_site` means it's an external macro.
943                expn_data.def_site.is_dummy() || sm.is_imported(expn_data.def_site)
944            }
945            ExpnKind::Macro { .. } => true, // definitely a plugin
946        }
947    }
948}
949
950impl fmt::Debug for SyntaxContext {
951    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
952        f.write_fmt(format_args!("#{0}", self.0))write!(f, "#{}", self.0)
953    }
954}
955
956impl Span {
957    /// Reuses the span but adds information like the kind of the desugaring and features that are
958    /// allowed inside this span.
959    pub fn mark_with_reason(
960        self,
961        allow_internal_unstable: Option<Arc<[Symbol]>>,
962        reason: DesugaringKind,
963        edition: Edition,
964        hcx: impl StableHashCtxt,
965    ) -> Span {
966        let expn_data = ExpnData {
967            allow_internal_unstable,
968            ..ExpnData::default(ExpnKind::Desugaring(reason), self, edition, None, None)
969        };
970        let expn_id = LocalExpnId::fresh(expn_data, hcx);
971        self.apply_mark(expn_id.to_expn_id(), Transparency::Transparent)
972    }
973}
974
975/// A subset of properties from both macro definition and macro call available through global data.
976/// Avoid using this if you have access to the original definition or call structures.
977#[derive(#[automatically_derived]
impl ::core::clone::Clone for ExpnData {
    #[inline]
    fn clone(&self) -> Self {
        ExpnData {
            kind: ::core::clone::Clone::clone(&self.kind),
            parent: ::core::clone::Clone::clone(&self.parent),
            call_site: ::core::clone::Clone::clone(&self.call_site),
            disambiguator: ::core::clone::Clone::clone(&self.disambiguator),
            def_site: ::core::clone::Clone::clone(&self.def_site),
            allow_internal_unstable: ::core::clone::Clone::clone(&self.allow_internal_unstable),
            edition: ::core::clone::Clone::clone(&self.edition),
            macro_def_id: ::core::clone::Clone::clone(&self.macro_def_id),
            parent_module: ::core::clone::Clone::clone(&self.parent_module),
            allow_internal_unsafe: ::core::clone::Clone::clone(&self.allow_internal_unsafe),
            local_inner_macros: ::core::clone::Clone::clone(&self.local_inner_macros),
            collapse_debuginfo: ::core::clone::Clone::clone(&self.collapse_debuginfo),
            diagnostic_opaque: ::core::clone::Clone::clone(&self.diagnostic_opaque),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ExpnData {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["kind", "parent", "call_site", "disambiguator", "def_site",
                        "allow_internal_unstable", "edition", "macro_def_id",
                        "parent_module", "allow_internal_unsafe",
                        "local_inner_macros", "collapse_debuginfo",
                        "diagnostic_opaque"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.kind, &self.parent, &self.call_site, &self.disambiguator,
                        &self.def_site, &self.allow_internal_unstable,
                        &self.edition, &self.macro_def_id, &self.parent_module,
                        &self.allow_internal_unsafe, &self.local_inner_macros,
                        &self.collapse_debuginfo, &&self.diagnostic_opaque];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "ExpnData",
            names, values)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for ExpnData {
            fn encode(&self, __encoder: &mut __E) {
                let ExpnData {
                        kind: ref __binding_0,
                        parent: ref __binding_1,
                        call_site: ref __binding_2,
                        disambiguator: ref __binding_3,
                        def_site: ref __binding_4,
                        allow_internal_unstable: ref __binding_5,
                        edition: ref __binding_6,
                        macro_def_id: ref __binding_7,
                        parent_module: ref __binding_8,
                        allow_internal_unsafe: ref __binding_9,
                        local_inner_macros: ref __binding_10,
                        collapse_debuginfo: ref __binding_11,
                        diagnostic_opaque: ref __binding_12 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_3,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_4,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_5,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_6,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_7,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_8,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_9,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_10,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_11,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_12,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for ExpnData {
            fn decode(__decoder: &mut __D) -> Self {
                ExpnData {
                    kind: ::rustc_serialize::Decodable::decode(__decoder),
                    parent: ::rustc_serialize::Decodable::decode(__decoder),
                    call_site: ::rustc_serialize::Decodable::decode(__decoder),
                    disambiguator: ::rustc_serialize::Decodable::decode(__decoder),
                    def_site: ::rustc_serialize::Decodable::decode(__decoder),
                    allow_internal_unstable: ::rustc_serialize::Decodable::decode(__decoder),
                    edition: ::rustc_serialize::Decodable::decode(__decoder),
                    macro_def_id: ::rustc_serialize::Decodable::decode(__decoder),
                    parent_module: ::rustc_serialize::Decodable::decode(__decoder),
                    allow_internal_unsafe: ::rustc_serialize::Decodable::decode(__decoder),
                    local_inner_macros: ::rustc_serialize::Decodable::decode(__decoder),
                    collapse_debuginfo: ::rustc_serialize::Decodable::decode(__decoder),
                    diagnostic_opaque: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for ExpnData {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    ExpnData {
                        kind: ref __binding_0,
                        parent: ref __binding_1,
                        call_site: ref __binding_2,
                        disambiguator: ref __binding_3,
                        def_site: ref __binding_4,
                        allow_internal_unstable: ref __binding_5,
                        edition: ref __binding_6,
                        macro_def_id: ref __binding_7,
                        parent_module: ref __binding_8,
                        allow_internal_unsafe: ref __binding_9,
                        local_inner_macros: ref __binding_10,
                        collapse_debuginfo: ref __binding_11,
                        diagnostic_opaque: ref __binding_12 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                        { __binding_4.stable_hash(__hcx, __hasher); }
                        { __binding_5.stable_hash(__hcx, __hasher); }
                        { __binding_6.stable_hash(__hcx, __hasher); }
                        { __binding_7.stable_hash(__hcx, __hasher); }
                        { __binding_8.stable_hash(__hcx, __hasher); }
                        { __binding_9.stable_hash(__hcx, __hasher); }
                        { __binding_10.stable_hash(__hcx, __hasher); }
                        { __binding_11.stable_hash(__hcx, __hasher); }
                        { __binding_12.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
978pub struct ExpnData {
979    // --- The part unique to each expansion.
980    pub kind: ExpnKind,
981    /// The expansion that contains the definition of the macro for this expansion.
982    pub parent: ExpnId,
983    /// The span of the macro call which produced this expansion.
984    ///
985    /// This span will typically have a different `ExpnData` and `call_site`.
986    /// This recursively traces back through any macro calls which expanded into further
987    /// macro calls, until the "source call-site" is reached at the root SyntaxContext.
988    /// For example, if `food!()` expands to `fruit!()` which then expands to `grape`,
989    /// then the call-site of `grape` is `fruit!()` and the call-site of `fruit!()`
990    /// is `food!()`.
991    ///
992    /// For a desugaring expansion, this is the span of the expression or node that was
993    /// desugared.
994    pub call_site: Span,
995    /// Used to force two `ExpnData`s to have different `Fingerprint`s.
996    /// Due to macro expansion, it's possible to end up with two `ExpnId`s
997    /// that have identical `ExpnData`s. This violates the contract of `StableHash`
998    /// - the two `ExpnId`s are not equal, but their `Fingerprint`s are equal
999    /// (since the numerical `ExpnId` value is not considered by the `StableHash`
1000    /// implementation).
1001    ///
1002    /// The `disambiguator` field is set by `update_disambiguator` when two distinct
1003    /// `ExpnId`s would end up with the same `Fingerprint`. Since `ExpnData` includes
1004    /// a `krate` field, this value only needs to be unique within a single crate.
1005    disambiguator: u32,
1006
1007    // --- The part specific to the macro/desugaring definition.
1008    // --- It may be reasonable to share this part between expansions with the same definition,
1009    // --- but such sharing is known to bring some minor inconveniences without also bringing
1010    // --- noticeable perf improvements (PR #62898).
1011    /// The span of the macro definition (possibly dummy).
1012    /// This span serves only informational purpose and is not used for resolution.
1013    pub def_site: Span,
1014    /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
1015    /// internally without forcing the whole crate to opt-in
1016    /// to them.
1017    pub allow_internal_unstable: Option<Arc<[Symbol]>>,
1018    /// Edition of the crate in which the macro is defined.
1019    pub edition: Edition,
1020    /// The `DefId` of the macro being invoked,
1021    /// if this `ExpnData` corresponds to a macro invocation
1022    pub macro_def_id: Option<DefId>,
1023    /// The normal module (`mod`) in which the expanded macro was defined.
1024    pub parent_module: Option<ModId>,
1025    /// Suppresses the `unsafe_code` lint for code produced by this macro.
1026    pub(crate) allow_internal_unsafe: bool,
1027    /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
1028    pub local_inner_macros: bool,
1029    /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other
1030    /// words, was the macro definition annotated with `#[collapse_debuginfo]`)?
1031    pub(crate) collapse_debuginfo: bool,
1032    /// When true, we prevent diagnostics pointing into this macro, if it is one, and we do not
1033    /// display the note telling people to use the `-Zmacro-backtrace` flag.
1034    pub diagnostic_opaque: bool,
1035}
1036
1037impl !PartialEq for ExpnData {}
1038impl !Hash for ExpnData {}
1039
1040impl ExpnData {
1041    pub fn new(
1042        kind: ExpnKind,
1043        parent: ExpnId,
1044        call_site: Span,
1045        def_site: Span,
1046        allow_internal_unstable: Option<Arc<[Symbol]>>,
1047        edition: Edition,
1048        macro_def_id: Option<DefId>,
1049        parent_module: Option<ModId>,
1050        allow_internal_unsafe: bool,
1051        local_inner_macros: bool,
1052        collapse_debuginfo: bool,
1053        diagnostic_opaque: bool,
1054    ) -> ExpnData {
1055        ExpnData {
1056            kind,
1057            parent,
1058            call_site,
1059            def_site,
1060            allow_internal_unstable,
1061            edition,
1062            macro_def_id,
1063            parent_module,
1064            disambiguator: 0,
1065            allow_internal_unsafe,
1066            local_inner_macros,
1067            collapse_debuginfo,
1068            diagnostic_opaque,
1069        }
1070    }
1071
1072    /// Constructs expansion data with default properties.
1073    pub fn default(
1074        kind: ExpnKind,
1075        call_site: Span,
1076        edition: Edition,
1077        macro_def_id: Option<DefId>,
1078        parent_module: Option<ModId>,
1079    ) -> ExpnData {
1080        ExpnData {
1081            kind,
1082            parent: ExpnId::root(),
1083            call_site,
1084            def_site: DUMMY_SP,
1085            allow_internal_unstable: None,
1086            edition,
1087            macro_def_id,
1088            parent_module,
1089            disambiguator: 0,
1090            allow_internal_unsafe: false,
1091            local_inner_macros: false,
1092            collapse_debuginfo: false,
1093            diagnostic_opaque: false,
1094        }
1095    }
1096
1097    pub fn allow_unstable(
1098        kind: ExpnKind,
1099        call_site: Span,
1100        edition: Edition,
1101        allow_internal_unstable: Arc<[Symbol]>,
1102        macro_def_id: Option<DefId>,
1103        parent_module: Option<ModId>,
1104    ) -> ExpnData {
1105        ExpnData {
1106            allow_internal_unstable: Some(allow_internal_unstable),
1107            ..ExpnData::default(kind, call_site, edition, macro_def_id, parent_module)
1108        }
1109    }
1110
1111    #[inline]
1112    pub fn is_root(&self) -> bool {
1113        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ExpnKind::Root => true,
    _ => false,
}matches!(self.kind, ExpnKind::Root)
1114    }
1115
1116    #[inline]
1117    fn hash_expn(&self, hcx: &mut impl StableHashCtxt) -> Hash64 {
1118        let mut hasher = StableHasher::new();
1119        self.stable_hash(hcx, &mut hasher);
1120        hasher.finish()
1121    }
1122}
1123
1124/// Expansion kind.
1125#[derive(#[automatically_derived]
impl ::core::clone::Clone for ExpnKind {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Root => ExpnKind::Root,
            Self::Macro(__self_0, __self_1) =>
                ExpnKind::Macro(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Self::AstPass(__self_0) =>
                ExpnKind::AstPass(::core::clone::Clone::clone(__self_0)),
            Self::Desugaring(__self_0) =>
                ExpnKind::Desugaring(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ExpnKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Root => ::core::fmt::Formatter::write_str(f, "Root"),
            Self::Macro(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Macro",
                    __self_0, &__self_1),
            Self::AstPass(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AstPass", &__self_0),
            Self::Desugaring(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Desugaring", &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for ExpnKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ExpnKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Macro(__self_0, __self_1),
                    Self::Macro(__arg1_0, __arg1_1)) =>
                    __self_0 == __arg1_0 && __self_1 == __arg1_1,
                (Self::AstPass(__self_0), Self::AstPass(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Desugaring(__self_0), Self::Desugaring(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for ExpnKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        ExpnKind::Root => { 0usize }
                        ExpnKind::Macro(ref __binding_0, ref __binding_1) => {
                            1usize
                        }
                        ExpnKind::AstPass(ref __binding_0) => { 2usize }
                        ExpnKind::Desugaring(ref __binding_0) => { 3usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    ExpnKind::Root => {}
                    ExpnKind::Macro(ref __binding_0, ref __binding_1) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    ExpnKind::AstPass(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    ExpnKind::Desugaring(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for ExpnKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { ExpnKind::Root }
                    1usize => {
                        ExpnKind::Macro(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    2usize => {
                        ExpnKind::AstPass(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    3usize => {
                        ExpnKind::Desugaring(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `ExpnKind`, expected 0..4, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for ExpnKind {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    ExpnKind::Root => {}
                    ExpnKind::Macro(ref __binding_0, ref __binding_1) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    ExpnKind::AstPass(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    ExpnKind::Desugaring(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
1126pub enum ExpnKind {
1127    /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
1128    Root,
1129    /// Expansion produced by a macro.
1130    Macro(MacroKind, Symbol),
1131    /// Transform done by the compiler on the AST.
1132    AstPass(AstPass),
1133    /// Desugaring done by the compiler during AST lowering.
1134    Desugaring(DesugaringKind),
1135}
1136
1137impl ExpnKind {
1138    pub fn descr(&self) -> String {
1139        match *self {
1140            ExpnKind::Root => kw::PathRoot.to_string(),
1141            ExpnKind::Macro(macro_kind, name) => match macro_kind {
1142                MacroKind::Bang => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}!", name))
    })format!("{name}!"),
1143                MacroKind::Attr => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[{0}]", name))
    })format!("#[{name}]"),
1144                MacroKind::Derive => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[derive({0})]", name))
    })format!("#[derive({name})]"),
1145            },
1146            ExpnKind::AstPass(kind) => kind.descr().to_string(),
1147            ExpnKind::Desugaring(kind) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("desugaring of {0}", kind.descr()))
    })format!("desugaring of {}", kind.descr()),
1148        }
1149    }
1150}
1151
1152/// The kind of macro invocation or definition.
1153#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MacroKind { }
#[automatically_derived]
impl ::core::clone::Clone for MacroKind {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MacroKind { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MacroKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MacroKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MacroKind { }Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for MacroKind {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MacroKind {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
            &::core::intrinsics::discriminant_value(other))
    }
}Ord, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for MacroKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        MacroKind::Bang => { 0usize }
                        MacroKind::Attr => { 1usize }
                        MacroKind::Derive => { 2usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for MacroKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { MacroKind::Bang }
                    1usize => { MacroKind::Attr }
                    2usize => { MacroKind::Derive }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `MacroKind`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable, #[automatically_derived]
impl ::core::hash::Hash for MacroKind {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for MacroKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                MacroKind::Bang => "Bang",
                MacroKind::Attr => "Attr",
                MacroKind::Derive => "Derive",
            })
    }
}Debug)]
1154#[derive(const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for MacroKind {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    MacroKind::Bang => {}
                    MacroKind::Attr => {}
                    MacroKind::Derive => {}
                }
            }
        }
    };StableHash)]
1155pub enum MacroKind {
1156    /// A bang macro `foo!()`.
1157    Bang,
1158    /// An attribute macro `#[foo]`.
1159    Attr,
1160    /// A derive macro `#[derive(Foo)]`
1161    Derive,
1162}
1163
1164impl MacroKind {
1165    pub fn descr(self) -> &'static str {
1166        match self {
1167            MacroKind::Bang => "macro",
1168            MacroKind::Attr => "attribute macro",
1169            MacroKind::Derive => "derive macro",
1170        }
1171    }
1172
1173    pub fn descr_expected(self) -> &'static str {
1174        match self {
1175            MacroKind::Attr => "attribute",
1176            _ => self.descr(),
1177        }
1178    }
1179
1180    pub fn article(self) -> &'static str {
1181        match self {
1182            MacroKind::Attr => "an",
1183            _ => "a",
1184        }
1185    }
1186}
1187
1188/// The kind of AST transform.
1189#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AstPass { }
#[automatically_derived]
impl ::core::clone::Clone for AstPass {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AstPass { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for AstPass {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AstPass::StdImports => "StdImports",
                AstPass::TestHarness => "TestHarness",
                AstPass::ProcMacroHarness => "ProcMacroHarness",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AstPass { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AstPass {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for AstPass {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        AstPass::StdImports => { 0usize }
                        AstPass::TestHarness => { 1usize }
                        AstPass::ProcMacroHarness => { 2usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for AstPass {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { AstPass::StdImports }
                    1usize => { AstPass::TestHarness }
                    2usize => { AstPass::ProcMacroHarness }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `AstPass`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for AstPass {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    AstPass::StdImports => {}
                    AstPass::TestHarness => {}
                    AstPass::ProcMacroHarness => {}
                }
            }
        }
    };StableHash)]
1190pub enum AstPass {
1191    StdImports,
1192    TestHarness,
1193    ProcMacroHarness,
1194}
1195
1196impl AstPass {
1197    pub fn descr(self) -> &'static str {
1198        match self {
1199            AstPass::StdImports => "standard library imports",
1200            AstPass::TestHarness => "test harness",
1201            AstPass::ProcMacroHarness => "proc macro harness",
1202        }
1203    }
1204}
1205
1206/// The kind of compiler desugaring.
1207#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DesugaringKind { }
#[automatically_derived]
impl ::core::clone::Clone for DesugaringKind {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DesugaringKind { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for DesugaringKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for DesugaringKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::FormatLiteral { source: __self_0 },
                    Self::FormatLiteral { source: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for DesugaringKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::QuestionMark =>
                ::core::fmt::Formatter::write_str(f, "QuestionMark"),
            Self::TryBlock =>
                ::core::fmt::Formatter::write_str(f, "TryBlock"),
            Self::YeetExpr =>
                ::core::fmt::Formatter::write_str(f, "YeetExpr"),
            Self::OpaqueTy =>
                ::core::fmt::Formatter::write_str(f, "OpaqueTy"),
            Self::Async => ::core::fmt::Formatter::write_str(f, "Async"),
            Self::Await => ::core::fmt::Formatter::write_str(f, "Await"),
            Self::ForLoop => ::core::fmt::Formatter::write_str(f, "ForLoop"),
            Self::WhileLoop =>
                ::core::fmt::Formatter::write_str(f, "WhileLoop"),
            Self::BoundModifier =>
                ::core::fmt::Formatter::write_str(f, "BoundModifier"),
            Self::Contract =>
                ::core::fmt::Formatter::write_str(f, "Contract"),
            Self::PatTyRange =>
                ::core::fmt::Formatter::write_str(f, "PatTyRange"),
            Self::FormatLiteral { source: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FormatLiteral", "source", &__self_0),
            Self::RangeExpr =>
                ::core::fmt::Formatter::write_str(f, "RangeExpr"),
        }
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DesugaringKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        DesugaringKind::QuestionMark => { 0usize }
                        DesugaringKind::TryBlock => { 1usize }
                        DesugaringKind::YeetExpr => { 2usize }
                        DesugaringKind::OpaqueTy => { 3usize }
                        DesugaringKind::Async => { 4usize }
                        DesugaringKind::Await => { 5usize }
                        DesugaringKind::ForLoop => { 6usize }
                        DesugaringKind::WhileLoop => { 7usize }
                        DesugaringKind::BoundModifier => { 8usize }
                        DesugaringKind::Contract => { 9usize }
                        DesugaringKind::PatTyRange => { 10usize }
                        DesugaringKind::FormatLiteral { source: ref __binding_0 } =>
                            {
                            11usize
                        }
                        DesugaringKind::RangeExpr => { 12usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    DesugaringKind::QuestionMark => {}
                    DesugaringKind::TryBlock => {}
                    DesugaringKind::YeetExpr => {}
                    DesugaringKind::OpaqueTy => {}
                    DesugaringKind::Async => {}
                    DesugaringKind::Await => {}
                    DesugaringKind::ForLoop => {}
                    DesugaringKind::WhileLoop => {}
                    DesugaringKind::BoundModifier => {}
                    DesugaringKind::Contract => {}
                    DesugaringKind::PatTyRange => {}
                    DesugaringKind::FormatLiteral { source: ref __binding_0 } =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    DesugaringKind::RangeExpr => {}
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for DesugaringKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { DesugaringKind::QuestionMark }
                    1usize => { DesugaringKind::TryBlock }
                    2usize => { DesugaringKind::YeetExpr }
                    3usize => { DesugaringKind::OpaqueTy }
                    4usize => { DesugaringKind::Async }
                    5usize => { DesugaringKind::Await }
                    6usize => { DesugaringKind::ForLoop }
                    7usize => { DesugaringKind::WhileLoop }
                    8usize => { DesugaringKind::BoundModifier }
                    9usize => { DesugaringKind::Contract }
                    10usize => { DesugaringKind::PatTyRange }
                    11usize => {
                        DesugaringKind::FormatLiteral {
                            source: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    12usize => { DesugaringKind::RangeExpr }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `DesugaringKind`, expected 0..13, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for
            DesugaringKind {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    DesugaringKind::QuestionMark => {}
                    DesugaringKind::TryBlock => {}
                    DesugaringKind::YeetExpr => {}
                    DesugaringKind::OpaqueTy => {}
                    DesugaringKind::Async => {}
                    DesugaringKind::Await => {}
                    DesugaringKind::ForLoop => {}
                    DesugaringKind::WhileLoop => {}
                    DesugaringKind::BoundModifier => {}
                    DesugaringKind::Contract => {}
                    DesugaringKind::PatTyRange => {}
                    DesugaringKind::FormatLiteral { source: ref __binding_0 } =>
                        {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    DesugaringKind::RangeExpr => {}
                }
            }
        }
    };StableHash)]
1208pub enum DesugaringKind {
1209    QuestionMark,
1210    TryBlock,
1211    YeetExpr,
1212    /// Desugaring of an `impl Trait` in return type position
1213    /// to an `type Foo = impl Trait;` and replacing the
1214    /// `impl Trait` with `Foo`.
1215    OpaqueTy,
1216    Async,
1217    Await,
1218    ForLoop,
1219    WhileLoop,
1220    /// `async Fn()` bound modifier
1221    BoundModifier,
1222    /// Calls to contract checks (`#[requires]` to precond, `#[ensures]` to postcond)
1223    Contract,
1224    /// A pattern type range start/end
1225    PatTyRange,
1226    /// A format literal.
1227    FormatLiteral {
1228        /// Was this format literal written in the source?
1229        /// - `format!("boo")` => Yes,
1230        /// - `format!(concat!("b", "o", "o"))` => No,
1231        /// - `format!(include_str!("boo.txt"))` => No,
1232        ///
1233        /// If it wasn't written in the source then we have to be careful with suggestions about
1234        /// rewriting it.
1235        source: bool,
1236    },
1237    RangeExpr,
1238}
1239
1240impl DesugaringKind {
1241    /// The description wording should combine well with "desugaring of {}".
1242    pub fn descr(self) -> &'static str {
1243        match self {
1244            DesugaringKind::Async => "`async` block or function",
1245            DesugaringKind::Await => "`await` expression",
1246            DesugaringKind::QuestionMark => "operator `?`",
1247            DesugaringKind::TryBlock => "`try` block",
1248            DesugaringKind::YeetExpr => "`do yeet` expression",
1249            DesugaringKind::OpaqueTy => "`impl Trait`",
1250            DesugaringKind::ForLoop => "`for` loop",
1251            DesugaringKind::WhileLoop => "`while` loop",
1252            DesugaringKind::BoundModifier => "trait bound modifier",
1253            DesugaringKind::Contract => "contract check",
1254            DesugaringKind::PatTyRange => "pattern type",
1255            DesugaringKind::FormatLiteral { source: true } => "format string literal",
1256            DesugaringKind::FormatLiteral { source: false } => {
1257                "expression that expanded into a format string literal"
1258            }
1259            DesugaringKind::RangeExpr => "range expression",
1260        }
1261    }
1262
1263    /// For use with `rustc_unimplemented` to support conditions
1264    /// like `from_desugaring = "QuestionMark"`
1265    pub fn matches(&self, value: &str) -> bool {
1266        match self {
1267            DesugaringKind::Async => value == "Async",
1268            DesugaringKind::Await => value == "Await",
1269            DesugaringKind::QuestionMark => value == "QuestionMark",
1270            DesugaringKind::TryBlock => value == "TryBlock",
1271            DesugaringKind::YeetExpr => value == "YeetExpr",
1272            DesugaringKind::OpaqueTy => value == "OpaqueTy",
1273            DesugaringKind::ForLoop => value == "ForLoop",
1274            DesugaringKind::WhileLoop => value == "WhileLoop",
1275            DesugaringKind::BoundModifier => value == "BoundModifier",
1276            DesugaringKind::Contract => value == "Contract",
1277            DesugaringKind::PatTyRange => value == "PatTyRange",
1278            DesugaringKind::FormatLiteral { .. } => value == "FormatLiteral",
1279            DesugaringKind::RangeExpr => value == "RangeExpr",
1280        }
1281    }
1282}
1283
1284pub struct HygieneEncodeContext {
1285    /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
1286    serialized_ctxts: FxHashSet<SyntaxContext>,
1287    /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
1288    /// in the most recent 'round' of serializing. Serializing `SyntaxContextData`
1289    /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
1290    /// until we reach a fixed point.
1291    latest_ctxts: Vec<(u32 /* Encoding index */, SyntaxContext)>,
1292
1293    serialized_expns: FxHashSet<ExpnId>,
1294    latest_expns: Vec<ExpnId>,
1295
1296    /// Maps every `SyntaxContext` into its encoding index.
1297    /// Earlier the `ctxt.0` was used when writing metadata, however,
1298    /// this results into non-deterministic metadata (see #129094).
1299    /// The non-determinism is encountered when decoding syntax contexts
1300    /// in `decode_syntax_context` function below. The syntax contexts from
1301    /// other crate metadata can be decoded in different order, which results
1302    /// into different ids assigned to decoded syntax contexts.
1303    /// First invocation:
1304    /// (ALLOC - syntax context id, ORIG - original id of decoded syntax context:
1305    /// `raw_id` in `decode_syntax_context`)
1306    /// ALLOC: #3, ORIG: 1
1307    /// ALLOC: #9, ORIG: 18769
1308    /// ALLOC: #10, ORIG: 25868
1309    /// ALLOC: #11, ORIG: 18822
1310    /// ALLOC: #12, ORIG: 23092
1311    ///
1312    /// Second invocation:
1313    /// ALLOC: #3, ORIG: 1
1314    /// ALLOC: #9, ORIG: 25868
1315    /// ALLOC: #10, ORIG: 18769
1316    /// ALLOC: #11, ORIG: 18822
1317    /// ALLOC: #12, ORIG: 23092
1318    ///
1319    /// We see that `18769` and `25868` assigned different syntax context ids,
1320    /// however, the order of encoding is deterministic, so we can remap allocated
1321    /// syntax context ids into encoding indices and use them, thus outputting
1322    /// same metadata.
1323    encoding_indices: FxHashMap<SyntaxContext, u32>,
1324}
1325
1326impl Default for HygieneEncodeContext {
1327    fn default() -> HygieneEncodeContext {
1328        HygieneEncodeContext {
1329            serialized_ctxts: Default::default(),
1330            latest_ctxts: Default::default(),
1331            serialized_expns: Default::default(),
1332            latest_expns: Default::default(),
1333            // Zero is taken by root syntax context.
1334            encoding_indices: FxHashMap::from_iter(iter::once((SyntaxContext::root(), 0))),
1335        }
1336    }
1337}
1338
1339impl HygieneEncodeContext {
1340    #[inline]
1341    fn get_encoding_index(&mut self, ctxt: SyntaxContext) -> u32 {
1342        let map = &mut self.encoding_indices;
1343        let len = map.len();
1344        *map.entry(ctxt).or_insert(len as u32)
1345    }
1346
1347    /// Record the fact that we need to serialize the corresponding `ExpnData`.
1348    #[inline]
1349    pub fn schedule_expn_data_for_encoding(&mut self, expn: ExpnId) {
1350        if self.serialized_expns.insert(expn) {
1351            self.latest_expns.push(expn);
1352        }
1353    }
1354
1355    pub fn encode<T>(
1356        h_ctxt: &RefCell<HygieneEncodeContext>,
1357        encoder: &mut T,
1358        mut encode_ctxt: impl FnMut(&mut T, u32, &SyntaxContextKey),
1359        mut encode_expn: impl FnMut(&mut T, ExpnId, Option<&ExpnData>, ExpnHash),
1360    ) {
1361        // When we serialize a `SyntaxContextData`, we may end up serializing
1362        // a `SyntaxContext` that we haven't seen before
1363        while {
1364            let h_ctxt = h_ctxt.borrow();
1365            !h_ctxt.latest_ctxts.is_empty() || !h_ctxt.latest_expns.is_empty()
1366        } {
1367            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:1367",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(1367u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("encode_hygiene: Serializing a round of {0:?} SyntaxContextData: {1:?}",
                                                    h_ctxt.borrow().latest_ctxts.len(),
                                                    h_ctxt.borrow().latest_ctxts) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1368                "encode_hygiene: Serializing a round of {:?} SyntaxContextData: {:?}",
1369                h_ctxt.borrow().latest_ctxts.len(),
1370                h_ctxt.borrow().latest_ctxts
1371            );
1372
1373            // Consume the current round of syntax contexts.
1374            // It's fine to iterate over a HashSet, because the serialization of the table
1375            // that we insert data into doesn't depend on insertion order.
1376            #[allow(rustc::potential_query_instability)]
1377            let latest_contexts = { mem::take(&mut h_ctxt.borrow_mut().latest_ctxts) }.into_iter();
1378
1379            for (idx, ctxt) in latest_contexts {
1380                let key = HygieneData::with(|data| data.syntax_context_data[ctxt.0 as usize].key());
1381                encode_ctxt(encoder, idx, &key);
1382            }
1383
1384            // Same as above, but for expansions instead of syntax contexts.
1385            #[allow(rustc::potential_query_instability)]
1386            let latest_expns = { mem::take(&mut h_ctxt.borrow_mut().latest_expns) }.into_iter();
1387
1388            for expn in latest_expns {
1389                let (data, hash) = HygieneData::with(|data| {
1390                    // We need `data` only for local expansions, so don't clone `data` for non-local
1391                    // expansions.
1392                    // FIXME: completely remove this clone
1393                    let expn_data = expn.as_local().map(|id| data.local_expn_data(id).clone());
1394                    (expn_data, data.expn_hash(expn))
1395                });
1396
1397                encode_expn(encoder, expn, data.as_ref(), hash);
1398            }
1399        }
1400
1401        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:1401",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(1401u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("encode_hygiene: Done serializing SyntaxContextData")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("encode_hygiene: Done serializing SyntaxContextData");
1402    }
1403
1404    #[inline]
1405    pub fn get_syntax_ctxt_encoding_index(&mut self, ctxt: SyntaxContext) -> u32 {
1406        let index = self.get_encoding_index(ctxt);
1407        if self.serialized_ctxts.insert(ctxt) {
1408            // If we created new encoding index then it is greater
1409            // than any previous index, so this vector is in ascending order.
1410            // We can't push existing, possibly out-of-order, index
1411            // as we check if we already saw this syntax context above.
1412            // This property is important for deterministic output (see #129094).
1413            self.latest_ctxts.push((index, ctxt));
1414        }
1415
1416        index
1417    }
1418}
1419
1420/// Additional information used to assist in decoding hygiene data
1421#[derive(#[automatically_derived]
impl ::core::default::Default for HygieneDecodeContext {
    #[inline]
    fn default() -> Self {
        HygieneDecodeContext {
            remapped_ctxts: ::core::default::Default::default(),
        }
    }
}Default)]
1422pub struct HygieneDecodeContext {
1423    // A cache mapping raw serialized per-crate syntax context ids to corresponding decoded
1424    // `SyntaxContext`s in the current global `HygieneData`.
1425    remapped_ctxts: Lock<IndexVec<u32, Option<SyntaxContext>>>,
1426}
1427
1428/// Register an expansion which has been decoded from the on-disk-cache for the local crate.
1429pub fn register_local_expn_id(data: ExpnData, hash: ExpnHash) -> ExpnId {
1430    HygieneData::with(|hygiene_data| {
1431        let expn_id = hygiene_data.local_expn_data.next_index();
1432        hygiene_data.local_expn_data.push(Some(data));
1433        let _eid = hygiene_data.local_expn_hashes.push(hash);
1434        if true {
    {
        match (&expn_id, &_eid) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(expn_id, _eid);
1435
1436        let expn_id = expn_id.to_expn_id();
1437
1438        let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id);
1439        if true {
    if !_old_id.is_none() {
        ::core::panicking::panic("assertion failed: _old_id.is_none()")
    };
};debug_assert!(_old_id.is_none());
1440        expn_id
1441    })
1442}
1443
1444/// Register an expansion which has been decoded from the metadata of a foreign crate.
1445pub fn register_expn_id(
1446    krate: CrateNum,
1447    local_id: ExpnIndex,
1448    data: ExpnData,
1449    hash: ExpnHash,
1450) -> ExpnId {
1451    if true {
    if !(data.parent == ExpnId::root() || krate == data.parent.krate) {
        ::core::panicking::panic("assertion failed: data.parent == ExpnId::root() || krate == data.parent.krate")
    };
};debug_assert!(data.parent == ExpnId::root() || krate == data.parent.krate);
1452    let expn_id = ExpnId { krate, local_id };
1453    HygieneData::with(|hygiene_data| {
1454        let _old_data = hygiene_data.foreign_expn_data.insert(expn_id, data);
1455        let _old_hash = hygiene_data.foreign_expn_hashes.insert(expn_id, hash);
1456        if true {
    if !(_old_hash.is_none() || _old_hash == Some(hash)) {
        ::core::panicking::panic("assertion failed: _old_hash.is_none() || _old_hash == Some(hash)")
    };
};debug_assert!(_old_hash.is_none() || _old_hash == Some(hash));
1457        let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id);
1458        if true {
    if !(_old_id.is_none() || _old_id == Some(expn_id)) {
        ::core::panicking::panic("assertion failed: _old_id.is_none() || _old_id == Some(expn_id)")
    };
};debug_assert!(_old_id.is_none() || _old_id == Some(expn_id));
1459    });
1460    expn_id
1461}
1462
1463/// Decode an expansion from the metadata of a foreign crate.
1464pub fn decode_expn_id(
1465    krate: CrateNum,
1466    index: u32,
1467    decode_data: impl FnOnce(ExpnId) -> (ExpnData, ExpnHash),
1468) -> ExpnId {
1469    if index == 0 {
1470        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:1470",
                        "rustc_span::hygiene", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(1470u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("decode_expn_id: deserialized root")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("decode_expn_id: deserialized root");
1471        return ExpnId::root();
1472    }
1473
1474    let index = ExpnIndex::from_u32(index);
1475
1476    // This function is used to decode metadata, so it cannot decode information about LOCAL_CRATE.
1477    if true {
    {
        match (&krate, &LOCAL_CRATE) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_ne!(krate, LOCAL_CRATE);
1478    let expn_id = ExpnId { krate, local_id: index };
1479
1480    // Fast path if the expansion has already been decoded.
1481    if HygieneData::with(|hygiene_data| hygiene_data.foreign_expn_data.contains_key(&expn_id)) {
1482        return expn_id;
1483    }
1484
1485    // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1486    // other ExpnIds
1487    let (expn_data, hash) = decode_data(expn_id);
1488
1489    register_expn_id(krate, index, expn_data, hash)
1490}
1491
1492// Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1493// to track which `SyntaxContext`s we have already decoded.
1494// The provided closure will be invoked to deserialize a `SyntaxContextData`
1495// if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1496pub fn decode_syntax_context<D: Decoder>(
1497    d: &mut D,
1498    context: &HygieneDecodeContext,
1499    decode_data: impl FnOnce(&mut D, u32) -> SyntaxContextKey,
1500) -> SyntaxContext {
1501    let raw_id: u32 = Decodable::decode(d);
1502    if raw_id == 0 {
1503        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:1503",
                        "rustc_span::hygiene", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(1503u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("decode_syntax_context: deserialized root")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!("decode_syntax_context: deserialized root");
1504        // The root is special
1505        return SyntaxContext::root();
1506    }
1507
1508    // Look into the cache first.
1509    // Reminder: `HygieneDecodeContext` is per-crate, so there are no collisions between
1510    // raw ids from different crate metadatas.
1511    if let Some(Some(ctxt)) = context.remapped_ctxts.lock().get(raw_id) {
1512        return *ctxt;
1513    }
1514
1515    // Don't try to decode data while holding the lock, since we need to
1516    // be able to recursively decode a SyntaxContext
1517    let (parent, expn_id, transparency) = decode_data(d, raw_id);
1518    let ctxt =
1519        HygieneData::with(|hygiene_data| hygiene_data.alloc_ctxt(parent, expn_id, transparency));
1520
1521    context.remapped_ctxts.lock().insert(raw_id, ctxt);
1522
1523    ctxt
1524}
1525
1526impl<E: SpanEncoder> Encodable<E> for LocalExpnId {
1527    fn encode(&self, e: &mut E) {
1528        self.to_expn_id().encode(e);
1529    }
1530}
1531
1532impl<D: SpanDecoder> Decodable<D> for LocalExpnId {
1533    fn decode(d: &mut D) -> Self {
1534        ExpnId::expect_local(ExpnId::decode(d))
1535    }
1536}
1537
1538/// Updates the `disambiguator` field of the corresponding `ExpnData`
1539/// such that the `Fingerprint` of the `ExpnData` does not collide with
1540/// any other `ExpnIds`.
1541///
1542/// This method is called only when an `ExpnData` is first associated
1543/// with an `ExpnId` (when the `ExpnId` is initially constructed, or via
1544/// `set_expn_data`). It is *not* called for foreign `ExpnId`s deserialized
1545/// from another crate's metadata - since `ExpnHash` includes the stable crate id,
1546/// collisions are only possible between `ExpnId`s within the same crate.
1547fn update_disambiguator(expn_data: &mut ExpnData, mut hcx: impl StableHashCtxt) -> ExpnHash {
1548    // This disambiguator should not have been set yet.
1549    {
    match (&expn_data.disambiguator, &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("Already set disambiguator for ExpnData: {0:?}",
                            expn_data)));
            }
        }
    }
};assert_eq!(expn_data.disambiguator, 0, "Already set disambiguator for ExpnData: {expn_data:?}");
1550    hcx.assert_default_stable_hash_controls("ExpnData (disambiguator)");
1551    let mut expn_hash = expn_data.hash_expn(&mut hcx);
1552
1553    let disambiguator = HygieneData::with(|data| {
1554        // If this is the first ExpnData with a given hash, then keep our
1555        // disambiguator at 0 (the default u32 value)
1556        let disambig = data.expn_data_disambiguators.entry(expn_hash).or_default();
1557        let disambiguator = *disambig;
1558        *disambig += 1;
1559        disambiguator
1560    });
1561
1562    if disambiguator != 0 {
1563        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs:1563",
                        "rustc_span::hygiene", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/7df81381d027710708209f36b98d11b1c88f8d2e/compiler/rustc_span/src/hygiene.rs"),
                        ::tracing_core::__macro_support::Option::Some(1563u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::hygiene"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Set disambiguator for expn_data={0:?} expn_hash={1:?}",
                                                    expn_data, expn_hash) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Set disambiguator for expn_data={:?} expn_hash={:?}", expn_data, expn_hash);
1564
1565        expn_data.disambiguator = disambiguator;
1566        expn_hash = expn_data.hash_expn(&mut hcx);
1567
1568        // Verify that the new disambiguator makes the hash unique
1569        #[cfg(debug_assertions)]
1570        HygieneData::with(|data| {
1571            {
    match (&data.expn_data_disambiguators.get(&expn_hash), &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("Hash collision after disambiguator update!")));
            }
        }
    }
};assert_eq!(
1572                data.expn_data_disambiguators.get(&expn_hash),
1573                None,
1574                "Hash collision after disambiguator update!",
1575            );
1576        });
1577    }
1578
1579    ExpnHash::new(LOCAL_CRATE.as_def_id().to_stable_hash_key(&mut hcx).stable_crate_id(), expn_hash)
1580}
1581
1582impl StableHash for SyntaxContext {
1583    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
1584        const TAG_EXPANSION: u8 = 0;
1585        const TAG_NO_EXPANSION: u8 = 1;
1586
1587        if self.is_root() {
1588            TAG_NO_EXPANSION.stable_hash(hcx, hasher);
1589        } else {
1590            TAG_EXPANSION.stable_hash(hcx, hasher);
1591            // This duplicates `ExpnId::stable_hash`, but reads the outer mark and
1592            // expansion hash in a single `HygieneData::with` call to avoid extra locking.
1593            hcx.assert_default_stable_hash_controls("ExpnId");
1594            let (hash, transparency) = HygieneData::with(|data| {
1595                let (expn_id, transparency) = data.outer_mark(*self);
1596                (data.expn_hash(expn_id).0, transparency)
1597            });
1598            hash.stable_hash(hcx, hasher);
1599            transparency.stable_hash(hcx, hasher);
1600        }
1601    }
1602}
1603
1604impl StableHash for ExpnId {
1605    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
1606        hcx.assert_default_stable_hash_controls("ExpnId");
1607        let hash = if *self == ExpnId::root() {
1608            // Avoid fetching TLS storage for a trivial often-used value.
1609            Fingerprint::ZERO
1610        } else {
1611            self.expn_hash().0
1612        };
1613
1614        hash.stable_hash(hcx, hasher);
1615    }
1616}
1617
1618impl StableHash for LocalExpnId {
1619    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
1620        self.to_expn_id().stable_hash(hcx, hasher);
1621    }
1622}