Skip to main content

rustc_span/
hygiene.rs

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