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::stable_hasher::{Hash64, StableHasher};
11use rustc_data_structures::unord::UnordMap;
12use rustc_index::IndexVec;
13use rustc_macros::{Decodable, Encodable};
14use rustc_span::{Symbol, kw, sym};
15use tracing::{debug, instrument};
16
17pub use crate::def_id::DefPathHash;
18use crate::def_id::{CRATE_DEF_INDEX, CrateNum, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId};
19use crate::def_path_hash_map::DefPathHashMap;
20
21/// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa.
22/// Internally the `DefPathTable` holds a tree of `DefKey`s, where each `DefKey`
23/// stores the `DefIndex` of its parent.
24/// There is one `DefPathTable` for each crate.
25#[derive(Debug)]
26pub struct DefPathTable {
27    stable_crate_id: StableCrateId,
28    index_to_key: IndexVec<DefIndex, DefKey>,
29    // We do only store the local hash, as all the definitions are from the current crate.
30    def_path_hashes: IndexVec<DefIndex, Hash64>,
31    def_path_hash_to_index: DefPathHashMap,
32}
33
34impl DefPathTable {
35    fn new(stable_crate_id: StableCrateId) -> DefPathTable {
36        DefPathTable {
37            stable_crate_id,
38            index_to_key: Default::default(),
39            def_path_hashes: Default::default(),
40            def_path_hash_to_index: Default::default(),
41        }
42    }
43
44    fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
45        // Assert that all DefPathHashes correctly contain the local crate's StableCrateId.
46        debug_assert_eq!(self.stable_crate_id, def_path_hash.stable_crate_id());
47        let local_hash = def_path_hash.local_hash();
48
49        let index = {
50            let index = DefIndex::from(self.index_to_key.len());
51            debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
52            self.index_to_key.push(key);
53            index
54        };
55        self.def_path_hashes.push(local_hash);
56        debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
57
58        // Check for hash collisions of DefPathHashes. These should be
59        // exceedingly rare.
60        if let Some(existing) = self.def_path_hash_to_index.insert(&local_hash, &index) {
61            let def_path1 = DefPath::make(LOCAL_CRATE, existing, |idx| self.def_key(idx));
62            let def_path2 = DefPath::make(LOCAL_CRATE, index, |idx| self.def_key(idx));
63
64            // Continuing with colliding DefPathHashes can lead to correctness
65            // issues. We must abort compilation.
66            //
67            // The likelihood of such a collision is very small, so actually
68            // running into one could be indicative of a poor hash function
69            // being used.
70            //
71            // See the documentation for DefPathHash for more information.
72            panic!(
73                "found DefPathHash collision between {def_path1:?} and {def_path2:?}. \
74                    Compilation cannot continue."
75            );
76        }
77
78        index
79    }
80
81    #[inline(always)]
82    pub fn def_key(&self, index: DefIndex) -> DefKey {
83        self.index_to_key[index]
84    }
85
86    #[instrument(level = "trace", skip(self), ret)]
87    #[inline(always)]
88    pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
89        let hash = self.def_path_hashes[index];
90        DefPathHash::new(self.stable_crate_id, hash)
91    }
92
93    pub fn enumerated_keys_and_path_hashes(
94        &self,
95    ) -> impl Iterator<Item = (DefIndex, &DefKey, DefPathHash)> + ExactSizeIterator + '_ {
96        self.index_to_key
97            .iter_enumerated()
98            .map(move |(index, key)| (index, key, self.def_path_hash(index)))
99    }
100}
101
102/// The definition table containing node definitions.
103/// It holds the `DefPathTable` for `LocalDefId`s/`DefPath`s.
104/// It also stores mappings to convert `LocalDefId`s to/from `HirId`s.
105#[derive(Debug)]
106pub struct Definitions {
107    table: DefPathTable,
108    next_disambiguator: UnordMap<(LocalDefId, DefPathData), u32>,
109}
110
111/// A unique identifier that we can use to lookup a definition
112/// precisely. It combines the index of the definition's parent (if
113/// any) with a `DisambiguatedDefPathData`.
114#[derive(Copy, Clone, PartialEq, Debug, Encodable, Decodable)]
115pub struct DefKey {
116    /// The parent path.
117    pub parent: Option<DefIndex>,
118
119    /// The identifier of this node.
120    pub disambiguated_data: DisambiguatedDefPathData,
121}
122
123impl DefKey {
124    pub(crate) fn compute_stable_hash(&self, parent: DefPathHash) -> DefPathHash {
125        let mut hasher = StableHasher::new();
126
127        parent.hash(&mut hasher);
128
129        let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
130
131        std::mem::discriminant(data).hash(&mut hasher);
132        if let Some(name) = data.get_opt_name() {
133            // Get a stable hash by considering the symbol chars rather than
134            // the symbol index.
135            name.as_str().hash(&mut hasher);
136        }
137
138        disambiguator.hash(&mut hasher);
139
140        let local_hash = hasher.finish();
141
142        // Construct the new DefPathHash, making sure that the `crate_id`
143        // portion of the hash is properly copied from the parent. This way the
144        // `crate_id` part will be recursively propagated from the root to all
145        // DefPathHashes in this DefPathTable.
146        DefPathHash::new(parent.stable_crate_id(), local_hash)
147    }
148
149    #[inline]
150    pub fn get_opt_name(&self) -> Option<Symbol> {
151        self.disambiguated_data.data.get_opt_name()
152    }
153}
154
155/// A pair of `DefPathData` and an integer disambiguator. The integer is
156/// normally `0`, but in the event that there are multiple defs with the
157/// same `parent` and `data`, we use this field to disambiguate
158/// between them. This introduces some artificial ordering dependency
159/// but means that if you have, e.g., two impls for the same type in
160/// the same module, they do get distinct `DefId`s.
161#[derive(Copy, Clone, PartialEq, Debug, Encodable, Decodable)]
162pub struct DisambiguatedDefPathData {
163    pub data: DefPathData,
164    pub disambiguator: u32,
165}
166
167impl DisambiguatedDefPathData {
168    pub fn fmt_maybe_verbose(&self, writer: &mut impl Write, verbose: bool) -> fmt::Result {
169        match self.data.name() {
170            DefPathDataName::Named(name) => {
171                if verbose && self.disambiguator != 0 {
172                    write!(writer, "{}#{}", name, self.disambiguator)
173                } else {
174                    writer.write_str(name.as_str())
175                }
176            }
177            DefPathDataName::Anon { namespace } => {
178                write!(writer, "{{{}#{}}}", namespace, self.disambiguator)
179            }
180        }
181    }
182}
183
184impl fmt::Display for DisambiguatedDefPathData {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        self.fmt_maybe_verbose(f, true)
187    }
188}
189
190#[derive(Clone, Debug, Encodable, Decodable)]
191pub struct DefPath {
192    /// The path leading from the crate root to the item.
193    pub data: Vec<DisambiguatedDefPathData>,
194
195    /// The crate root this path is relative to.
196    pub krate: CrateNum,
197}
198
199impl DefPath {
200    pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
201    where
202        FN: FnMut(DefIndex) -> DefKey,
203    {
204        let mut data = vec![];
205        let mut index = Some(start_index);
206        loop {
207            debug!("DefPath::make: krate={:?} index={:?}", krate, index);
208            let p = index.unwrap();
209            let key = get_key(p);
210            debug!("DefPath::make: key={:?}", key);
211            match key.disambiguated_data.data {
212                DefPathData::CrateRoot => {
213                    assert!(key.parent.is_none());
214                    break;
215                }
216                _ => {
217                    data.push(key.disambiguated_data);
218                    index = key.parent;
219                }
220            }
221        }
222        data.reverse();
223        DefPath { data, krate }
224    }
225
226    /// Returns a string representation of the `DefPath` without
227    /// the crate-prefix. This method is useful if you don't have
228    /// a `TyCtxt` available.
229    pub fn to_string_no_crate_verbose(&self) -> String {
230        let mut s = String::with_capacity(self.data.len() * 16);
231
232        for component in &self.data {
233            write!(s, "::{component}").unwrap();
234        }
235
236        s
237    }
238
239    /// Returns a filename-friendly string of the `DefPath`, without
240    /// the crate-prefix. This method is useful if you don't have
241    /// a `TyCtxt` available.
242    pub fn to_filename_friendly_no_crate(&self) -> String {
243        let mut s = String::with_capacity(self.data.len() * 16);
244
245        let mut opt_delimiter = None;
246        for component in &self.data {
247            s.extend(opt_delimiter);
248            opt_delimiter = Some('-');
249            write!(s, "{component}").unwrap();
250        }
251
252        s
253    }
254}
255
256/// New variants should only be added in synchronization with `enum DefKind`.
257#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
258pub enum DefPathData {
259    // Root: these should only be used for the root nodes, because
260    // they are treated specially by the `def_path` function.
261    /// The crate root (marker).
262    CrateRoot,
263
264    // Different kinds of items and item-like things:
265    /// An impl.
266    Impl,
267    /// An `extern` block.
268    ForeignMod,
269    /// A `use` item.
270    Use,
271    /// A global asm item.
272    GlobalAsm,
273    /// Something in the type namespace.
274    TypeNs(Symbol),
275    /// Something in the value namespace.
276    ValueNs(Symbol),
277    /// Something in the macro namespace.
278    MacroNs(Symbol),
279    /// Something in the lifetime namespace.
280    LifetimeNs(Symbol),
281    /// A closure expression.
282    Closure,
283
284    // Subportions of items:
285    /// Implicit constructor for a unit or tuple-like struct or enum variant.
286    Ctor,
287    /// A constant expression (see `{ast,hir}::AnonConst`).
288    AnonConst,
289    /// An existential `impl Trait` type node.
290    /// Argument position `impl Trait` have a `TypeNs` with their pretty-printed name.
291    OpaqueTy,
292}
293
294impl Definitions {
295    pub fn def_path_table(&self) -> &DefPathTable {
296        &self.table
297    }
298
299    /// Gets the number of definitions.
300    pub fn def_index_count(&self) -> usize {
301        self.table.index_to_key.len()
302    }
303
304    #[inline]
305    pub fn def_key(&self, id: LocalDefId) -> DefKey {
306        self.table.def_key(id.local_def_index)
307    }
308
309    #[inline(always)]
310    pub fn def_path_hash(&self, id: LocalDefId) -> DefPathHash {
311        self.table.def_path_hash(id.local_def_index)
312    }
313
314    /// Returns the path from the crate root to `index`. The root
315    /// nodes are not included in the path (i.e., this will be an
316    /// empty vector for the crate root). For an inlined item, this
317    /// will be the path of the item in the external crate (but the
318    /// path will begin with the path to the external crate).
319    pub fn def_path(&self, id: LocalDefId) -> DefPath {
320        DefPath::make(LOCAL_CRATE, id.local_def_index, |index| {
321            self.def_key(LocalDefId { local_def_index: index })
322        })
323    }
324
325    /// Adds a root definition (no parent) and a few other reserved definitions.
326    pub fn new(stable_crate_id: StableCrateId) -> Definitions {
327        let key = DefKey {
328            parent: None,
329            disambiguated_data: DisambiguatedDefPathData {
330                data: DefPathData::CrateRoot,
331                disambiguator: 0,
332            },
333        };
334
335        let parent_hash = DefPathHash::new(stable_crate_id, Hash64::ZERO);
336        let def_path_hash = key.compute_stable_hash(parent_hash);
337
338        // Create the root definition.
339        let mut table = DefPathTable::new(stable_crate_id);
340        let root = LocalDefId { local_def_index: table.allocate(key, def_path_hash) };
341        assert_eq!(root.local_def_index, CRATE_DEF_INDEX);
342
343        Definitions { table, next_disambiguator: Default::default() }
344    }
345
346    /// Adds a definition with a parent definition.
347    pub fn create_def(&mut self, parent: LocalDefId, data: DefPathData) -> LocalDefId {
348        // We can't use `Debug` implementation for `LocalDefId` here, since it tries to acquire a
349        // reference to `Definitions` and we're already holding a mutable reference.
350        debug!(
351            "create_def(parent={}, data={data:?})",
352            self.def_path(parent).to_string_no_crate_verbose(),
353        );
354
355        // The root node must be created with `create_root_def()`.
356        assert!(data != DefPathData::CrateRoot);
357
358        // Find the next free disambiguator for this key.
359        let disambiguator = {
360            let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
361            let disambiguator = *next_disamb;
362            *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
363            disambiguator
364        };
365        let key = DefKey {
366            parent: Some(parent.local_def_index),
367            disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
368        };
369
370        let parent_hash = self.table.def_path_hash(parent.local_def_index);
371        let def_path_hash = key.compute_stable_hash(parent_hash);
372
373        debug!("create_def: after disambiguation, key = {:?}", key);
374
375        // Create the definition.
376        LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) }
377    }
378
379    #[inline(always)]
380    /// Returns `None` if the `DefPathHash` does not correspond to a `LocalDefId`
381    /// in the current compilation session. This can legitimately happen if the
382    /// `DefPathHash` is from a `DefId` in an upstream crate or, during incr. comp.,
383    /// if the `DefPathHash` is from a previous compilation session and
384    /// the def-path does not exist anymore.
385    pub fn local_def_path_hash_to_def_id(&self, hash: DefPathHash) -> Option<LocalDefId> {
386        debug_assert!(hash.stable_crate_id() == self.table.stable_crate_id);
387        self.table
388            .def_path_hash_to_index
389            .get(&hash.local_hash())
390            .map(|local_def_index| LocalDefId { local_def_index })
391    }
392
393    pub fn def_path_hash_to_def_index_map(&self) -> &DefPathHashMap {
394        &self.table.def_path_hash_to_index
395    }
396
397    pub fn num_definitions(&self) -> usize {
398        self.table.def_path_hashes.len()
399    }
400}
401
402#[derive(Copy, Clone, PartialEq, Debug)]
403pub enum DefPathDataName {
404    Named(Symbol),
405    Anon { namespace: Symbol },
406}
407
408impl DefPathData {
409    pub fn get_opt_name(&self) -> Option<Symbol> {
410        use self::DefPathData::*;
411        match *self {
412            TypeNs(name) if name == kw::Empty => None,
413            TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
414
415            Impl | ForeignMod | CrateRoot | Use | GlobalAsm | Closure | Ctor | AnonConst
416            | OpaqueTy => None,
417        }
418    }
419
420    pub fn name(&self) -> DefPathDataName {
421        use self::DefPathData::*;
422        match *self {
423            TypeNs(name) if name == kw::Empty => {
424                DefPathDataName::Anon { namespace: sym::synthetic }
425            }
426            TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => {
427                DefPathDataName::Named(name)
428            }
429            // Note that this does not show up in user print-outs.
430            CrateRoot => DefPathDataName::Anon { namespace: kw::Crate },
431            Impl => DefPathDataName::Anon { namespace: kw::Impl },
432            ForeignMod => DefPathDataName::Anon { namespace: kw::Extern },
433            Use => DefPathDataName::Anon { namespace: kw::Use },
434            GlobalAsm => DefPathDataName::Anon { namespace: sym::global_asm },
435            Closure => DefPathDataName::Anon { namespace: sym::closure },
436            Ctor => DefPathDataName::Anon { namespace: sym::constructor },
437            AnonConst => DefPathDataName::Anon { namespace: sym::constant },
438            OpaqueTy => DefPathDataName::Anon { namespace: sym::opaque },
439        }
440    }
441}
442
443impl fmt::Display for DefPathData {
444    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445        match self.name() {
446            DefPathDataName::Named(name) => f.write_str(name.as_str()),
447            // FIXME(#70334): this will generate legacy {{closure}}, {{impl}}, etc
448            DefPathDataName::Anon { namespace } => write!(f, "{{{{{namespace}}}}}"),
449        }
450    }
451}