Skip to main content

rustc_hir/
definitions.rs

1//! For each definition, we track the following data. A definition
2//! here is defined somewhat circularly as "something with a `DefId`",
3//! but it generally corresponds to things like structs, enums, etc.
4//! There are also some rather random cases (like const initializer
5//! expressions) that are mostly just leftovers.
6
7use std::fmt::{self, Write};
8use std::hash::Hash;
9
10use rustc_data_structures::fx::FxHashMap;
11use rustc_data_structures::stable_hasher::StableHasher;
12use rustc_hashes::Hash64;
13use rustc_index::IndexVec;
14use rustc_macros::{BlobDecodable, Decodable, Encodable, extension};
15use rustc_span::def_id::LocalDefIdMap;
16use rustc_span::{Symbol, kw, sym};
17use tracing::{debug, instrument};
18
19pub use crate::def_id::DefPathHash;
20use crate::def_id::{CRATE_DEF_INDEX, CrateNum, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId};
21use crate::def_path_hash_map::DefPathHashMap;
22
23/// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa.
24/// Internally the `DefPathTable` holds a tree of `DefKey`s, where each `DefKey`
25/// stores the `DefIndex` of its parent.
26/// There is one `DefPathTable` for each crate.
27#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DefPathTable {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "DefPathTable",
            "stable_crate_id", &self.stable_crate_id, "index_to_key",
            &self.index_to_key, "def_path_hashes", &self.def_path_hashes,
            "def_path_hash_to_index", &&self.def_path_hash_to_index)
    }
}Debug)]
28pub struct DefPathTable {
29    stable_crate_id: StableCrateId,
30    index_to_key: IndexVec<DefIndex, DefKey>,
31    // We do only store the local hash, as all the definitions are from the current crate.
32    def_path_hashes: IndexVec<DefIndex, Hash64>,
33    def_path_hash_to_index: DefPathHashMap,
34}
35
36impl DefPathTable {
37    fn new(stable_crate_id: StableCrateId) -> DefPathTable {
38        DefPathTable {
39            stable_crate_id,
40            index_to_key: Default::default(),
41            def_path_hashes: Default::default(),
42            def_path_hash_to_index: Default::default(),
43        }
44    }
45
46    fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
47        // Assert that all DefPathHashes correctly contain the local crate's StableCrateId.
48        if true {
    match (&self.stable_crate_id, &def_path_hash.stable_crate_id()) {
        (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!(self.stable_crate_id, def_path_hash.stable_crate_id());
49        let local_hash = def_path_hash.local_hash();
50
51        let index = self.index_to_key.push(key);
52        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir/src/definitions.rs:52",
                        "rustc_hir::definitions", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir/src/definitions.rs"),
                        ::tracing_core::__macro_support::Option::Some(52u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir::definitions"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("DefPathTable::insert() - {0:?} <-> {1:?}",
                                                    key, index) as &dyn Value))])
            });
    } else { ; }
};debug!("DefPathTable::insert() - {key:?} <-> {index:?}");
53
54        self.def_path_hashes.push(local_hash);
55        if true {
    if !(self.def_path_hashes.len() == self.index_to_key.len()) {
        ::core::panicking::panic("assertion failed: self.def_path_hashes.len() == self.index_to_key.len()")
    };
};debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
56
57        // Check for hash collisions of DefPathHashes. These should be
58        // exceedingly rare.
59        if let Some(existing) = self.def_path_hash_to_index.insert(&local_hash, &index) {
60            let def_path1 = DefPath::make(LOCAL_CRATE, existing, |idx| self.def_key(idx));
61            let def_path2 = DefPath::make(LOCAL_CRATE, index, |idx| self.def_key(idx));
62
63            // Continuing with colliding DefPathHashes can lead to correctness
64            // issues. We must abort compilation.
65            //
66            // The likelihood of such a collision is very small, so actually
67            // running into one could be indicative of a poor hash function
68            // being used.
69            //
70            // See the documentation for DefPathHash for more information.
71            {
    ::core::panicking::panic_fmt(format_args!("found DefPathHash collision between {0:#?} and {1:#?}. Compilation cannot continue.",
            def_path1, def_path2));
};panic!(
72                "found DefPathHash collision between {def_path1:#?} and {def_path2:#?}. \
73                    Compilation cannot continue."
74            );
75        }
76
77        index
78    }
79
80    #[inline(always)]
81    pub fn def_key(&self, index: DefIndex) -> DefKey {
82        self.index_to_key[index]
83    }
84
85    x;#[instrument(level = "trace", skip(self), ret)]
86    #[inline(always)]
87    pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
88        let hash = self.def_path_hashes[index];
89        DefPathHash::new(self.stable_crate_id, hash)
90    }
91
92    pub fn enumerated_keys_and_path_hashes(
93        &self,
94    ) -> impl Iterator<Item = (DefIndex, &DefKey, DefPathHash)> + ExactSizeIterator {
95        self.index_to_key
96            .iter_enumerated()
97            .map(move |(index, key)| (index, key, self.def_path_hash(index)))
98    }
99}
100
101#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PerParentDisambiguatorState {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "PerParentDisambiguatorState", "parent", &self.parent, "next",
            &&self.next)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for PerParentDisambiguatorState {
    #[inline]
    fn default() -> PerParentDisambiguatorState {
        PerParentDisambiguatorState {
            parent: ::core::default::Default::default(),
            next: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl ::core::clone::Clone for PerParentDisambiguatorState {
    #[inline]
    fn clone(&self) -> PerParentDisambiguatorState {
        PerParentDisambiguatorState {
            parent: ::core::clone::Clone::clone(&self.parent),
            next: ::core::clone::Clone::clone(&self.next),
        }
    }
}Clone)]
102pub struct PerParentDisambiguatorState {
103    #[cfg(debug_assertions)]
104    parent: Option<LocalDefId>,
105    next: FxHashMap<DefPathData, u32>,
106}
107
108impl PerParentDisambiguatorState {
109    #[inline(always)]
110    pub fn new(_parent: LocalDefId) -> PerParentDisambiguatorState {
111        PerParentDisambiguatorState {
112            #[cfg(debug_assertions)]
113            parent: Some(_parent),
114            next: Default::default(),
115        }
116    }
117}
118
119impl PerParentDisambiguatorsMap for LocalDefIdMap<PerParentDisambiguatorState>
    {
    fn get_or_create(&mut self, parent: LocalDefId)
        -> &mut PerParentDisambiguatorState {
        self.entry(parent).or_insert_with(||
                PerParentDisambiguatorState::new(parent))
    }
}#[extension(pub trait PerParentDisambiguatorsMap)]
120impl LocalDefIdMap<PerParentDisambiguatorState> {
121    fn get_or_create(&mut self, parent: LocalDefId) -> &mut PerParentDisambiguatorState {
122        self.entry(parent).or_insert_with(|| PerParentDisambiguatorState::new(parent))
123    }
124}
125
126/// The definition table containing node definitions.
127/// It holds the `DefPathTable` for `LocalDefId`s/`DefPath`s.
128/// It also stores mappings to convert `LocalDefId`s to/from `HirId`s.
129#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Definitions {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "Definitions",
            "table", &&self.table)
    }
}Debug)]
130pub struct Definitions {
131    table: DefPathTable,
132}
133
134/// A unique identifier that we can use to lookup a definition
135/// precisely. It combines the index of the definition's parent (if
136/// any) with a `DisambiguatedDefPathData`.
137#[derive(#[automatically_derived]
impl ::core::marker::Copy for DefKey { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DefKey {
    #[inline]
    fn clone(&self) -> DefKey {
        let _: ::core::clone::AssertParamIsClone<Option<DefIndex>>;
        let _: ::core::clone::AssertParamIsClone<DisambiguatedDefPathData>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for DefKey {
    #[inline]
    fn eq(&self, other: &DefKey) -> bool {
        self.parent == other.parent &&
            self.disambiguated_data == other.disambiguated_data
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for DefKey {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "DefKey",
            "parent", &self.parent, "disambiguated_data",
            &&self.disambiguated_data)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DefKey {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    DefKey {
                        parent: ref __binding_0, disambiguated_data: ref __binding_1
                        } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::BlobDecoder> ::rustc_serialize::Decodable<__D>
            for DefKey {
            fn decode(__decoder: &mut __D) -> Self {
                DefKey {
                    parent: ::rustc_serialize::Decodable::decode(__decoder),
                    disambiguated_data: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };BlobDecodable)]
138pub struct DefKey {
139    /// The parent path.
140    pub parent: Option<DefIndex>,
141
142    /// The identifier of this node.
143    pub disambiguated_data: DisambiguatedDefPathData,
144}
145
146impl DefKey {
147    pub(crate) fn compute_stable_hash(&self, parent: DefPathHash) -> DefPathHash {
148        let mut hasher = StableHasher::new();
149
150        // The new path is in the same crate as `parent`, and will contain the stable_crate_id.
151        // Therefore, we only need to include information of the parent's local hash.
152        parent.local_hash().hash(&mut hasher);
153
154        let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
155
156        std::mem::discriminant(data).hash(&mut hasher);
157        if let Some(name) = data.hashed_symbol() {
158            // Get a stable hash by considering the symbol chars rather than
159            // the symbol index.
160            name.as_str().hash(&mut hasher);
161        }
162
163        disambiguator.hash(&mut hasher);
164
165        let local_hash = hasher.finish();
166
167        // Construct the new DefPathHash, making sure that the `crate_id`
168        // portion of the hash is properly copied from the parent. This way the
169        // `crate_id` part will be recursively propagated from the root to all
170        // DefPathHashes in this DefPathTable.
171        DefPathHash::new(parent.stable_crate_id(), local_hash)
172    }
173
174    #[inline]
175    pub fn get_opt_name(&self) -> Option<Symbol> {
176        self.disambiguated_data.data.get_opt_name()
177    }
178}
179
180/// A pair of `DefPathData` and an integer disambiguator. The integer is
181/// normally `0`, but in the event that there are multiple defs with the
182/// same `parent` and `data`, we use this field to disambiguate
183/// between them. This introduces some artificial ordering dependency
184/// but means that if you have, e.g., two impls for the same type in
185/// the same module, they do get distinct `DefId`s.
186#[derive(#[automatically_derived]
impl ::core::marker::Copy for DisambiguatedDefPathData { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DisambiguatedDefPathData {
    #[inline]
    fn clone(&self) -> DisambiguatedDefPathData {
        let _: ::core::clone::AssertParamIsClone<DefPathData>;
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for DisambiguatedDefPathData {
    #[inline]
    fn eq(&self, other: &DisambiguatedDefPathData) -> bool {
        self.disambiguator == other.disambiguator && self.data == other.data
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for DisambiguatedDefPathData {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "DisambiguatedDefPathData", "data", &self.data, "disambiguator",
            &&self.disambiguator)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DisambiguatedDefPathData {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    DisambiguatedDefPathData {
                        data: ref __binding_0, disambiguator: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::BlobDecoder> ::rustc_serialize::Decodable<__D>
            for DisambiguatedDefPathData {
            fn decode(__decoder: &mut __D) -> Self {
                DisambiguatedDefPathData {
                    data: ::rustc_serialize::Decodable::decode(__decoder),
                    disambiguator: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };BlobDecodable)]
187pub struct DisambiguatedDefPathData {
188    pub data: DefPathData,
189    pub disambiguator: u32,
190}
191
192impl DisambiguatedDefPathData {
193    pub fn as_sym(&self, verbose: bool) -> Symbol {
194        match self.data.name() {
195            DefPathDataName::Named(name) => {
196                if verbose && self.disambiguator != 0 {
197                    Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}#{1}", name,
                self.disambiguator))
    })format!("{}#{}", name, self.disambiguator))
198                } else {
199                    name
200                }
201            }
202            DefPathDataName::Anon { namespace } => {
203                if let DefPathData::AnonAssocTy(method) = self.data {
204                    Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{{{1}#{2}}}", method,
                namespace, self.disambiguator))
    })format!("{}::{{{}#{}}}", method, namespace, self.disambiguator))
205                } else {
206                    Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}#{1}}}", namespace,
                self.disambiguator))
    })format!("{{{}#{}}}", namespace, self.disambiguator))
207                }
208            }
209        }
210    }
211}
212
213#[derive(#[automatically_derived]
impl ::core::clone::Clone for DefPath {
    #[inline]
    fn clone(&self) -> DefPath {
        DefPath {
            data: ::core::clone::Clone::clone(&self.data),
            krate: ::core::clone::Clone::clone(&self.krate),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for DefPath {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "DefPath",
            "data", &self.data, "krate", &&self.krate)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DefPath {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    DefPath { data: ref __binding_0, krate: ref __binding_1 } =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for DefPath {
            fn decode(__decoder: &mut __D) -> Self {
                DefPath {
                    data: ::rustc_serialize::Decodable::decode(__decoder),
                    krate: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
214pub struct DefPath {
215    /// The path leading from the crate root to the item.
216    pub data: Vec<DisambiguatedDefPathData>,
217
218    /// The crate root this path is relative to.
219    pub krate: CrateNum,
220}
221
222impl DefPath {
223    pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
224    where
225        FN: FnMut(DefIndex) -> DefKey,
226    {
227        let mut data = ::alloc::vec::Vec::new()vec![];
228        let mut index = Some(start_index);
229        loop {
230            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir/src/definitions.rs:230",
                        "rustc_hir::definitions", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir/src/definitions.rs"),
                        ::tracing_core::__macro_support::Option::Some(230u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir::definitions"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("DefPath::make: krate={0:?} index={1:?}",
                                                    krate, index) as &dyn Value))])
            });
    } else { ; }
};debug!("DefPath::make: krate={:?} index={:?}", krate, index);
231            let p = index.unwrap();
232            let key = get_key(p);
233            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir/src/definitions.rs:233",
                        "rustc_hir::definitions", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir/src/definitions.rs"),
                        ::tracing_core::__macro_support::Option::Some(233u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir::definitions"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("DefPath::make: key={0:?}",
                                                    key) as &dyn Value))])
            });
    } else { ; }
};debug!("DefPath::make: key={:?}", key);
234            match key.disambiguated_data.data {
235                DefPathData::CrateRoot => {
236                    if !key.parent.is_none() {
    ::core::panicking::panic("assertion failed: key.parent.is_none()")
};assert!(key.parent.is_none());
237                    break;
238                }
239                _ => {
240                    data.push(key.disambiguated_data);
241                    index = key.parent;
242                }
243            }
244        }
245        data.reverse();
246        DefPath { data, krate }
247    }
248
249    /// Returns a string representation of the `DefPath` without
250    /// the crate-prefix. This method is useful if you don't have
251    /// a `TyCtxt` available.
252    pub fn to_string_no_crate_verbose(&self) -> String {
253        let mut s = String::with_capacity(self.data.len() * 16);
254
255        for component in &self.data {
256            s.write_fmt(format_args!("::{0}", component.as_sym(true)))write!(s, "::{}", component.as_sym(true)).unwrap();
257        }
258
259        s
260    }
261
262    /// Returns a filename-friendly string of the `DefPath`, without
263    /// the crate-prefix. This method is useful if you don't have
264    /// a `TyCtxt` available.
265    pub fn to_filename_friendly_no_crate(&self) -> String {
266        let mut s = String::with_capacity(self.data.len() * 16);
267
268        let mut opt_delimiter = None;
269        for component in &self.data {
270            s.extend(opt_delimiter);
271            opt_delimiter = Some('-');
272            s.write_fmt(format_args!("{0}", component.as_sym(true)))write!(s, "{}", component.as_sym(true)).unwrap();
273        }
274
275        s
276    }
277}
278
279/// New variants should only be added in synchronization with `enum DefKind`.
280#[derive(#[automatically_derived]
impl ::core::marker::Copy for DefPathData { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DefPathData {
    #[inline]
    fn clone(&self) -> DefPathData {
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for DefPathData {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            DefPathData::CrateRoot =>
                ::core::fmt::Formatter::write_str(f, "CrateRoot"),
            DefPathData::Impl => ::core::fmt::Formatter::write_str(f, "Impl"),
            DefPathData::ForeignMod =>
                ::core::fmt::Formatter::write_str(f, "ForeignMod"),
            DefPathData::Use => ::core::fmt::Formatter::write_str(f, "Use"),
            DefPathData::GlobalAsm =>
                ::core::fmt::Formatter::write_str(f, "GlobalAsm"),
            DefPathData::TypeNs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "TypeNs",
                    &__self_0),
            DefPathData::ValueNs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ValueNs", &__self_0),
            DefPathData::MacroNs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MacroNs", &__self_0),
            DefPathData::LifetimeNs(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "LifetimeNs", &__self_0),
            DefPathData::Closure =>
                ::core::fmt::Formatter::write_str(f, "Closure"),
            DefPathData::Ctor => ::core::fmt::Formatter::write_str(f, "Ctor"),
            DefPathData::AnonConst =>
                ::core::fmt::Formatter::write_str(f, "AnonConst"),
            DefPathData::OpaqueTy =>
                ::core::fmt::Formatter::write_str(f, "OpaqueTy"),
            DefPathData::OpaqueLifetime(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "OpaqueLifetime", &__self_0),
            DefPathData::AnonAssocTy(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AnonAssocTy", &__self_0),
            DefPathData::SyntheticCoroutineBody =>
                ::core::fmt::Formatter::write_str(f,
                    "SyntheticCoroutineBody"),
            DefPathData::NestedStatic =>
                ::core::fmt::Formatter::write_str(f, "NestedStatic"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for DefPathData {
    #[inline]
    fn eq(&self, other: &DefPathData) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (DefPathData::TypeNs(__self_0), DefPathData::TypeNs(__arg1_0))
                    => __self_0 == __arg1_0,
                (DefPathData::ValueNs(__self_0),
                    DefPathData::ValueNs(__arg1_0)) => __self_0 == __arg1_0,
                (DefPathData::MacroNs(__self_0),
                    DefPathData::MacroNs(__arg1_0)) => __self_0 == __arg1_0,
                (DefPathData::LifetimeNs(__self_0),
                    DefPathData::LifetimeNs(__arg1_0)) => __self_0 == __arg1_0,
                (DefPathData::OpaqueLifetime(__self_0),
                    DefPathData::OpaqueLifetime(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (DefPathData::AnonAssocTy(__self_0),
                    DefPathData::AnonAssocTy(__arg1_0)) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DefPathData {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Symbol>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for DefPathData {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            DefPathData::TypeNs(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            DefPathData::ValueNs(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            DefPathData::MacroNs(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            DefPathData::LifetimeNs(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            DefPathData::OpaqueLifetime(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            DefPathData::AnonAssocTy(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DefPathData {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        DefPathData::CrateRoot => { 0usize }
                        DefPathData::Impl => { 1usize }
                        DefPathData::ForeignMod => { 2usize }
                        DefPathData::Use => { 3usize }
                        DefPathData::GlobalAsm => { 4usize }
                        DefPathData::TypeNs(ref __binding_0) => { 5usize }
                        DefPathData::ValueNs(ref __binding_0) => { 6usize }
                        DefPathData::MacroNs(ref __binding_0) => { 7usize }
                        DefPathData::LifetimeNs(ref __binding_0) => { 8usize }
                        DefPathData::Closure => { 9usize }
                        DefPathData::Ctor => { 10usize }
                        DefPathData::AnonConst => { 11usize }
                        DefPathData::OpaqueTy => { 12usize }
                        DefPathData::OpaqueLifetime(ref __binding_0) => { 13usize }
                        DefPathData::AnonAssocTy(ref __binding_0) => { 14usize }
                        DefPathData::SyntheticCoroutineBody => { 15usize }
                        DefPathData::NestedStatic => { 16usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    DefPathData::CrateRoot => {}
                    DefPathData::Impl => {}
                    DefPathData::ForeignMod => {}
                    DefPathData::Use => {}
                    DefPathData::GlobalAsm => {}
                    DefPathData::TypeNs(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    DefPathData::ValueNs(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    DefPathData::MacroNs(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    DefPathData::LifetimeNs(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    DefPathData::Closure => {}
                    DefPathData::Ctor => {}
                    DefPathData::AnonConst => {}
                    DefPathData::OpaqueTy => {}
                    DefPathData::OpaqueLifetime(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    DefPathData::AnonAssocTy(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    DefPathData::SyntheticCoroutineBody => {}
                    DefPathData::NestedStatic => {}
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::BlobDecoder> ::rustc_serialize::Decodable<__D>
            for DefPathData {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { DefPathData::CrateRoot }
                    1usize => { DefPathData::Impl }
                    2usize => { DefPathData::ForeignMod }
                    3usize => { DefPathData::Use }
                    4usize => { DefPathData::GlobalAsm }
                    5usize => {
                        DefPathData::TypeNs(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    6usize => {
                        DefPathData::ValueNs(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    7usize => {
                        DefPathData::MacroNs(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    8usize => {
                        DefPathData::LifetimeNs(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    9usize => { DefPathData::Closure }
                    10usize => { DefPathData::Ctor }
                    11usize => { DefPathData::AnonConst }
                    12usize => { DefPathData::OpaqueTy }
                    13usize => {
                        DefPathData::OpaqueLifetime(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    14usize => {
                        DefPathData::AnonAssocTy(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    15usize => { DefPathData::SyntheticCoroutineBody }
                    16usize => { DefPathData::NestedStatic }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `DefPathData`, expected 0..17, actual {0}",
                                n));
                    }
                }
            }
        }
    };BlobDecodable)]
281pub enum DefPathData {
282    // Root: these should only be used for the root nodes, because
283    // they are treated specially by the `def_path` function.
284    /// The crate root (marker).
285    CrateRoot,
286
287    // Different kinds of items and item-like things:
288    /// An impl.
289    Impl,
290    /// An `extern` block.
291    ForeignMod,
292    /// A `use` item.
293    Use,
294    /// A global asm item.
295    GlobalAsm,
296    /// Something in the type namespace.
297    TypeNs(Symbol),
298    /// Something in the value namespace.
299    ValueNs(Symbol),
300    /// Something in the macro namespace.
301    MacroNs(Symbol),
302    /// Something in the lifetime namespace.
303    LifetimeNs(Symbol),
304    /// A closure expression.
305    Closure,
306
307    // Subportions of items:
308    /// Implicit constructor for a unit or tuple-like struct or enum variant.
309    Ctor,
310    /// A constant expression (see `{ast,hir}::AnonConst`).
311    AnonConst,
312    /// An existential `impl Trait` type node.
313    /// Argument position `impl Trait` have a `TypeNs` with their pretty-printed name.
314    OpaqueTy,
315    /// Used for remapped captured lifetimes in an existential `impl Trait` type node.
316    OpaqueLifetime(Symbol),
317    /// An anonymous associated type from an RPITIT. The symbol refers to the name of the method
318    /// that defined the type.
319    AnonAssocTy(Symbol),
320    /// A synthetic body for a coroutine's by-move body.
321    SyntheticCoroutineBody,
322    /// Additional static data referred to by a static.
323    NestedStatic,
324}
325
326impl Definitions {
327    pub fn def_path_table(&self) -> &DefPathTable {
328        &self.table
329    }
330
331    /// Gets the number of definitions.
332    pub fn def_index_count(&self) -> usize {
333        self.table.index_to_key.len()
334    }
335
336    #[inline]
337    pub fn def_key(&self, id: LocalDefId) -> DefKey {
338        self.table.def_key(id.local_def_index)
339    }
340
341    #[inline(always)]
342    pub fn def_path_hash(&self, id: LocalDefId) -> DefPathHash {
343        self.table.def_path_hash(id.local_def_index)
344    }
345
346    /// Returns the path from the crate root to `index`. The root
347    /// nodes are not included in the path (i.e., this will be an
348    /// empty vector for the crate root). For an inlined item, this
349    /// will be the path of the item in the external crate (but the
350    /// path will begin with the path to the external crate).
351    pub fn def_path(&self, id: LocalDefId) -> DefPath {
352        DefPath::make(LOCAL_CRATE, id.local_def_index, |index| {
353            self.def_key(LocalDefId { local_def_index: index })
354        })
355    }
356
357    /// Adds a root definition (no parent) and a few other reserved definitions.
358    pub fn new(stable_crate_id: StableCrateId) -> Definitions {
359        let key = DefKey {
360            parent: None,
361            disambiguated_data: DisambiguatedDefPathData {
362                data: DefPathData::CrateRoot,
363                disambiguator: 0,
364            },
365        };
366
367        // We want *both* halves of a DefPathHash to depend on the crate-id of the defining crate.
368        // The crate-id can be more easily changed than the DefPath of an item, so, in the case of
369        // a crate-local DefPathHash collision, the user can simply "roll the dice again" for all
370        // DefPathHashes in the crate by changing the crate disambiguator (e.g. via bumping the
371        // crate's version number).
372        //
373        // Children paths will only hash the local portion, and still inherit the change to the
374        // root hash.
375        let def_path_hash =
376            DefPathHash::new(stable_crate_id, Hash64::new(stable_crate_id.as_u64()));
377
378        // Create the root definition.
379        let mut table = DefPathTable::new(stable_crate_id);
380        let root = LocalDefId { local_def_index: table.allocate(key, def_path_hash) };
381        match (&root.local_def_index, &CRATE_DEF_INDEX) {
    (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);
        }
    }
};assert_eq!(root.local_def_index, CRATE_DEF_INDEX);
382
383        Definitions { table }
384    }
385
386    /// Creates a definition with a parent definition.
387    /// If there are multiple definitions with the same DefPathData and the same parent, use
388    /// `disambiguator` to differentiate them. Distinct `DisambiguatorState` instances are not
389    /// guaranteed to generate unique disambiguators and should instead ensure that the `parent`
390    /// and `data` pair is distinct from other instances.
391    pub fn create_def(
392        &mut self,
393        parent: LocalDefId,
394        data: DefPathData,
395        disambiguator: &mut PerParentDisambiguatorState,
396    ) -> LocalDefId {
397        // We can't use `Debug` implementation for `LocalDefId` here, since it tries to acquire a
398        // reference to `Definitions` and we're already holding a mutable reference.
399        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir/src/definitions.rs:399",
                        "rustc_hir::definitions", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir/src/definitions.rs"),
                        ::tracing_core::__macro_support::Option::Some(399u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir::definitions"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("create_def(parent={0}, data={1:?})",
                                                    self.def_path(parent).to_string_no_crate_verbose(), data) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
400            "create_def(parent={}, data={data:?})",
401            self.def_path(parent).to_string_no_crate_verbose(),
402        );
403
404        // The root node must be created in `new()`.
405        if !(data != DefPathData::CrateRoot) {
    ::core::panicking::panic("assertion failed: data != DefPathData::CrateRoot")
};assert!(data != DefPathData::CrateRoot);
406
407        // Find the next free disambiguator for this key.
408        let disambiguator = {
409            #[cfg(debug_assertions)]
410            if true {
    match (&parent, &disambiguator.parent.expect("must be set")) {
        (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!("provided parent and parent in disambiguator must be the same")));
            }
        }
    };
};debug_assert_eq!(
411                parent,
412                disambiguator.parent.expect("must be set"),
413                "provided parent and parent in disambiguator must be the same"
414            );
415
416            let next_disamb = disambiguator.next.entry(data).or_insert(0);
417            let disambiguator = *next_disamb;
418            *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
419            disambiguator
420        };
421        let key = DefKey {
422            parent: Some(parent.local_def_index),
423            disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
424        };
425
426        let parent_hash = self.table.def_path_hash(parent.local_def_index);
427        let def_path_hash = key.compute_stable_hash(parent_hash);
428
429        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir/src/definitions.rs:429",
                        "rustc_hir::definitions", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir/src/definitions.rs"),
                        ::tracing_core::__macro_support::Option::Some(429u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir::definitions"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("create_def: after disambiguation, key = {0:?}",
                                                    key) as &dyn Value))])
            });
    } else { ; }
};debug!("create_def: after disambiguation, key = {:?}", key);
430
431        // Create the definition.
432        LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) }
433    }
434
435    #[inline(always)]
436    /// Returns `None` if the `DefPathHash` does not correspond to a `LocalDefId`
437    /// in the current compilation session. This can legitimately happen if the
438    /// `DefPathHash` is from a `DefId` in an upstream crate or, during incr. comp.,
439    /// if the `DefPathHash` is from a previous compilation session and
440    /// the def-path does not exist anymore.
441    pub fn local_def_path_hash_to_def_id(&self, hash: DefPathHash) -> Option<LocalDefId> {
442        if true {
    if !(hash.stable_crate_id() == self.table.stable_crate_id) {
        ::core::panicking::panic("assertion failed: hash.stable_crate_id() == self.table.stable_crate_id")
    };
};debug_assert!(hash.stable_crate_id() == self.table.stable_crate_id);
443        self.table
444            .def_path_hash_to_index
445            .get(&hash.local_hash())
446            .map(|local_def_index| LocalDefId { local_def_index })
447    }
448
449    pub fn def_path_hash_to_def_index_map(&self) -> &DefPathHashMap {
450        &self.table.def_path_hash_to_index
451    }
452
453    pub fn num_definitions(&self) -> usize {
454        self.table.def_path_hashes.len()
455    }
456}
457
458#[derive(#[automatically_derived]
impl ::core::marker::Copy for DefPathDataName { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DefPathDataName {
    #[inline]
    fn clone(&self) -> DefPathDataName {
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for DefPathDataName {
    #[inline]
    fn eq(&self, other: &DefPathDataName) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (DefPathDataName::Named(__self_0),
                    DefPathDataName::Named(__arg1_0)) => __self_0 == __arg1_0,
                (DefPathDataName::Anon { namespace: __self_0 },
                    DefPathDataName::Anon { namespace: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for DefPathDataName {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            DefPathDataName::Named(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Named",
                    &__self_0),
            DefPathDataName::Anon { namespace: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Anon",
                    "namespace", &__self_0),
        }
    }
}Debug)]
459pub enum DefPathDataName {
460    Named(Symbol),
461    Anon { namespace: Symbol },
462}
463
464impl DefPathData {
465    pub fn get_opt_name(&self) -> Option<Symbol> {
466        use self::DefPathData::*;
467        match *self {
468            TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name)
469            | OpaqueLifetime(name) => Some(name),
470
471            Impl
472            | ForeignMod
473            | CrateRoot
474            | Use
475            | GlobalAsm
476            | Closure
477            | Ctor
478            | AnonConst
479            | OpaqueTy
480            | AnonAssocTy(..)
481            | SyntheticCoroutineBody
482            | NestedStatic => None,
483        }
484    }
485
486    fn hashed_symbol(&self) -> Option<Symbol> {
487        use self::DefPathData::*;
488        match *self {
489            TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) | AnonAssocTy(name)
490            | OpaqueLifetime(name) => Some(name),
491
492            Impl
493            | ForeignMod
494            | CrateRoot
495            | Use
496            | GlobalAsm
497            | Closure
498            | Ctor
499            | AnonConst
500            | OpaqueTy
501            | SyntheticCoroutineBody
502            | NestedStatic => None,
503        }
504    }
505
506    pub fn name(&self) -> DefPathDataName {
507        use self::DefPathData::*;
508        match *self {
509            TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name)
510            | OpaqueLifetime(name) => DefPathDataName::Named(name),
511            // Note that this does not show up in user print-outs.
512            CrateRoot => DefPathDataName::Anon { namespace: kw::Crate },
513            Impl => DefPathDataName::Anon { namespace: kw::Impl },
514            ForeignMod => DefPathDataName::Anon { namespace: kw::Extern },
515            Use => DefPathDataName::Anon { namespace: kw::Use },
516            GlobalAsm => DefPathDataName::Anon { namespace: sym::global_asm },
517            Closure => DefPathDataName::Anon { namespace: sym::closure },
518            Ctor => DefPathDataName::Anon { namespace: sym::constructor },
519            AnonConst => DefPathDataName::Anon { namespace: sym::constant },
520            OpaqueTy => DefPathDataName::Anon { namespace: sym::opaque },
521            AnonAssocTy(..) => DefPathDataName::Anon { namespace: sym::anon_assoc },
522            SyntheticCoroutineBody => DefPathDataName::Anon { namespace: sym::synthetic },
523            NestedStatic => DefPathDataName::Anon { namespace: sym::nested },
524        }
525    }
526}
527
528impl fmt::Display for DefPathData {
529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530        match self.name() {
531            DefPathDataName::Named(name) => f.write_str(name.as_str()),
532            // FIXME(#70334): this will generate legacy {{closure}}, {{impl}}, etc
533            DefPathDataName::Anon { namespace } => f.write_fmt(format_args!("{{{{{0}}}}}", namespace))write!(f, "{{{{{namespace}}}}}"),
534        }
535    }
536}