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