]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/definitions.rs
Auto merge of #81427 - klensy:eat-digits, r=m-ou-se
[rust.git] / compiler / rustc_hir / src / 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
7 pub use crate::def_id::DefPathHash;
8 use crate::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
9 use crate::hir;
10
11 use rustc_ast::crate_disambiguator::CrateDisambiguator;
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_data_structures::stable_hasher::StableHasher;
14 use rustc_index::vec::IndexVec;
15 use rustc_span::hygiene::ExpnId;
16 use rustc_span::symbol::{kw, sym, Symbol};
17
18 use std::fmt::{self, Write};
19 use std::hash::Hash;
20 use tracing::debug;
21
22 /// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa.
23 /// Internally the `DefPathTable` holds a tree of `DefKey`s, where each `DefKey`
24 /// stores the `DefIndex` of its parent.
25 /// There is one `DefPathTable` for each crate.
26 #[derive(Clone, Default)]
27 pub struct DefPathTable {
28     index_to_key: IndexVec<DefIndex, DefKey>,
29     def_path_hashes: IndexVec<DefIndex, DefPathHash>,
30 }
31
32 impl DefPathTable {
33     fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
34         let index = {
35             let index = DefIndex::from(self.index_to_key.len());
36             debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
37             self.index_to_key.push(key);
38             index
39         };
40         self.def_path_hashes.push(def_path_hash);
41         debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
42         index
43     }
44
45     #[inline(always)]
46     pub fn def_key(&self, index: DefIndex) -> DefKey {
47         self.index_to_key[index]
48     }
49
50     #[inline(always)]
51     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
52         let hash = self.def_path_hashes[index];
53         debug!("def_path_hash({:?}) = {:?}", index, hash);
54         hash
55     }
56
57     pub fn num_def_ids(&self) -> usize {
58         self.index_to_key.len()
59     }
60
61     pub fn enumerated_keys_and_path_hashes(
62         &self,
63     ) -> impl Iterator<Item = (DefIndex, &DefKey, &DefPathHash)> + '_ {
64         self.index_to_key
65             .iter_enumerated()
66             .map(move |(index, key)| (index, key, &self.def_path_hashes[index]))
67     }
68
69     pub fn all_def_path_hashes_and_def_ids(
70         &self,
71         krate: CrateNum,
72     ) -> impl Iterator<Item = (DefPathHash, DefId)> + '_ {
73         self.def_path_hashes
74             .iter_enumerated()
75             .map(move |(index, hash)| (*hash, DefId { krate, index }))
76     }
77 }
78
79 /// The definition table containing node definitions.
80 /// It holds the `DefPathTable` for `LocalDefId`s/`DefPath`s.
81 /// It also stores mappings to convert `LocalDefId`s to/from `HirId`s.
82 #[derive(Clone)]
83 pub struct Definitions {
84     table: DefPathTable,
85
86     // FIXME(eddyb) ideally all `LocalDefId`s would be HIR owners.
87     pub(super) def_id_to_hir_id: IndexVec<LocalDefId, Option<hir::HirId>>,
88     /// The reverse mapping of `def_id_to_hir_id`.
89     pub(super) hir_id_to_def_id: FxHashMap<hir::HirId, LocalDefId>,
90
91     /// If `ExpnId` is an ID of some macro expansion,
92     /// then `DefId` is the normal module (`mod`) in which the expanded macro was defined.
93     parent_modules_of_macro_defs: FxHashMap<ExpnId, DefId>,
94     /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
95     expansions_that_defined: FxHashMap<LocalDefId, ExpnId>,
96 }
97
98 /// A unique identifier that we can use to lookup a definition
99 /// precisely. It combines the index of the definition's parent (if
100 /// any) with a `DisambiguatedDefPathData`.
101 #[derive(Copy, Clone, PartialEq, Debug, Encodable, Decodable)]
102 pub struct DefKey {
103     /// The parent path.
104     pub parent: Option<DefIndex>,
105
106     /// The identifier of this node.
107     pub disambiguated_data: DisambiguatedDefPathData,
108 }
109
110 impl DefKey {
111     fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
112         let mut hasher = StableHasher::new();
113
114         // We hash a `0u8` here to disambiguate between regular `DefPath` hashes,
115         // and the special "root_parent" below.
116         0u8.hash(&mut hasher);
117         parent_hash.hash(&mut hasher);
118
119         let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
120
121         std::mem::discriminant(data).hash(&mut hasher);
122         if let Some(name) = data.get_opt_name() {
123             // Get a stable hash by considering the symbol chars rather than
124             // the symbol index.
125             name.as_str().hash(&mut hasher);
126         }
127
128         disambiguator.hash(&mut hasher);
129
130         DefPathHash(hasher.finish())
131     }
132
133     fn root_parent_stable_hash(
134         crate_name: &str,
135         crate_disambiguator: CrateDisambiguator,
136     ) -> DefPathHash {
137         let mut hasher = StableHasher::new();
138         // Disambiguate this from a regular `DefPath` hash; see `compute_stable_hash()` above.
139         1u8.hash(&mut hasher);
140         crate_name.hash(&mut hasher);
141         crate_disambiguator.hash(&mut hasher);
142         DefPathHash(hasher.finish())
143     }
144 }
145
146 /// A pair of `DefPathData` and an integer disambiguator. The integer is
147 /// normally `0`, but in the event that there are multiple defs with the
148 /// same `parent` and `data`, we use this field to disambiguate
149 /// between them. This introduces some artificial ordering dependency
150 /// but means that if you have, e.g., two impls for the same type in
151 /// the same module, they do get distinct `DefId`s.
152 #[derive(Copy, Clone, PartialEq, Debug, Encodable, Decodable)]
153 pub struct DisambiguatedDefPathData {
154     pub data: DefPathData,
155     pub disambiguator: u32,
156 }
157
158 impl DisambiguatedDefPathData {
159     pub fn fmt_maybe_verbose(&self, writer: &mut impl Write, verbose: bool) -> fmt::Result {
160         match self.data.name() {
161             DefPathDataName::Named(name) => {
162                 if verbose && self.disambiguator != 0 {
163                     write!(writer, "{}#{}", name, self.disambiguator)
164                 } else {
165                     writer.write_str(&name.as_str())
166                 }
167             }
168             DefPathDataName::Anon { namespace } => {
169                 write!(writer, "{{{}#{}}}", namespace, self.disambiguator)
170             }
171         }
172     }
173 }
174
175 impl fmt::Display for DisambiguatedDefPathData {
176     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177         self.fmt_maybe_verbose(f, true)
178     }
179 }
180
181 #[derive(Clone, Debug, Encodable, Decodable)]
182 pub struct DefPath {
183     /// The path leading from the crate root to the item.
184     pub data: Vec<DisambiguatedDefPathData>,
185
186     /// The crate root this path is relative to.
187     pub krate: CrateNum,
188 }
189
190 impl DefPath {
191     pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
192     where
193         FN: FnMut(DefIndex) -> DefKey,
194     {
195         let mut data = vec![];
196         let mut index = Some(start_index);
197         loop {
198             debug!("DefPath::make: krate={:?} index={:?}", krate, index);
199             let p = index.unwrap();
200             let key = get_key(p);
201             debug!("DefPath::make: key={:?}", key);
202             match key.disambiguated_data.data {
203                 DefPathData::CrateRoot => {
204                     assert!(key.parent.is_none());
205                     break;
206                 }
207                 _ => {
208                     data.push(key.disambiguated_data);
209                     index = key.parent;
210                 }
211             }
212         }
213         data.reverse();
214         DefPath { data, krate }
215     }
216
217     /// Returns a string representation of the `DefPath` without
218     /// the crate-prefix. This method is useful if you don't have
219     /// a `TyCtxt` available.
220     pub fn to_string_no_crate_verbose(&self) -> String {
221         let mut s = String::with_capacity(self.data.len() * 16);
222
223         for component in &self.data {
224             write!(s, "::{}", component).unwrap();
225         }
226
227         s
228     }
229
230     /// Returns a filename-friendly string of the `DefPath`, without
231     /// the crate-prefix. This method is useful if you don't have
232     /// a `TyCtxt` available.
233     pub fn to_filename_friendly_no_crate(&self) -> String {
234         let mut s = String::with_capacity(self.data.len() * 16);
235
236         let mut opt_delimiter = None;
237         for component in &self.data {
238             s.extend(opt_delimiter);
239             opt_delimiter = Some('-');
240             write!(s, "{}", component).unwrap();
241         }
242
243         s
244     }
245 }
246
247 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
248 pub enum DefPathData {
249     // Root: these should only be used for the root nodes, because
250     // they are treated specially by the `def_path` function.
251     /// The crate root (marker).
252     CrateRoot,
253     // Catch-all for random `DefId` things like `DUMMY_NODE_ID`.
254     Misc,
255
256     // Different kinds of items and item-like things:
257     /// An impl.
258     Impl,
259     /// Something in the type namespace.
260     TypeNs(Symbol),
261     /// Something in the value namespace.
262     ValueNs(Symbol),
263     /// Something in the macro namespace.
264     MacroNs(Symbol),
265     /// Something in the lifetime namespace.
266     LifetimeNs(Symbol),
267     /// A closure expression.
268     ClosureExpr,
269
270     // Subportions of items:
271     /// Implicit constructor for a unit or tuple-like struct or enum variant.
272     Ctor,
273     /// A constant expression (see `{ast,hir}::AnonConst`).
274     AnonConst,
275     /// An `impl Trait` type node.
276     ImplTrait,
277 }
278
279 impl Definitions {
280     pub fn def_path_table(&self) -> &DefPathTable {
281         &self.table
282     }
283
284     /// Gets the number of definitions.
285     pub fn def_index_count(&self) -> usize {
286         self.table.index_to_key.len()
287     }
288
289     pub fn def_key(&self, id: LocalDefId) -> DefKey {
290         self.table.def_key(id.local_def_index)
291     }
292
293     #[inline(always)]
294     pub fn def_path_hash(&self, id: LocalDefId) -> DefPathHash {
295         self.table.def_path_hash(id.local_def_index)
296     }
297
298     /// Returns the path from the crate root to `index`. The root
299     /// nodes are not included in the path (i.e., this will be an
300     /// empty vector for the crate root). For an inlined item, this
301     /// will be the path of the item in the external crate (but the
302     /// path will begin with the path to the external crate).
303     pub fn def_path(&self, id: LocalDefId) -> DefPath {
304         DefPath::make(LOCAL_CRATE, id.local_def_index, |index| {
305             self.def_key(LocalDefId { local_def_index: index })
306         })
307     }
308
309     #[inline]
310     #[track_caller]
311     pub fn local_def_id_to_hir_id(&self, id: LocalDefId) -> hir::HirId {
312         self.def_id_to_hir_id[id].unwrap()
313     }
314
315     #[inline]
316     pub fn opt_local_def_id_to_hir_id(&self, id: LocalDefId) -> Option<hir::HirId> {
317         self.def_id_to_hir_id[id]
318     }
319
320     #[inline]
321     pub fn opt_hir_id_to_local_def_id(&self, hir_id: hir::HirId) -> Option<LocalDefId> {
322         self.hir_id_to_def_id.get(&hir_id).copied()
323     }
324
325     /// Adds a root definition (no parent) and a few other reserved definitions.
326     pub fn new(crate_name: &str, crate_disambiguator: CrateDisambiguator) -> 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 = DefKey::root_parent_stable_hash(crate_name, crate_disambiguator);
336         let def_path_hash = key.compute_stable_hash(parent_hash);
337
338         // Create the root definition.
339         let mut table = DefPathTable::default();
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 {
344             table,
345             def_id_to_hir_id: Default::default(),
346             hir_id_to_def_id: Default::default(),
347             expansions_that_defined: Default::default(),
348             parent_modules_of_macro_defs: Default::default(),
349         }
350     }
351
352     /// Retrieves the root definition.
353     pub fn get_root_def(&self) -> LocalDefId {
354         LocalDefId { local_def_index: CRATE_DEF_INDEX }
355     }
356
357     /// Adds a definition with a parent definition.
358     pub fn create_def(
359         &mut self,
360         parent: LocalDefId,
361         data: DefPathData,
362         expn_id: ExpnId,
363         mut next_disambiguator: impl FnMut(LocalDefId, DefPathData) -> u32,
364     ) -> LocalDefId {
365         debug!("create_def(parent={:?}, data={:?}, expn_id={:?})", parent, data, expn_id);
366
367         // The root node must be created with `create_root_def()`.
368         assert!(data != DefPathData::CrateRoot);
369
370         let disambiguator = next_disambiguator(parent, data);
371         let key = DefKey {
372             parent: Some(parent.local_def_index),
373             disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
374         };
375
376         let parent_hash = self.table.def_path_hash(parent.local_def_index);
377         let def_path_hash = key.compute_stable_hash(parent_hash);
378
379         debug!("create_def: after disambiguation, key = {:?}", key);
380
381         // Create the definition.
382         let def_id = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) };
383
384         if expn_id != ExpnId::root() {
385             self.expansions_that_defined.insert(def_id, expn_id);
386         }
387
388         def_id
389     }
390
391     /// Initializes the `LocalDefId` to `HirId` mapping once it has been generated during
392     /// AST to HIR lowering.
393     pub fn init_def_id_to_hir_id_mapping(
394         &mut self,
395         mapping: IndexVec<LocalDefId, Option<hir::HirId>>,
396     ) {
397         assert!(
398             self.def_id_to_hir_id.is_empty(),
399             "trying to initialize `LocalDefId` <-> `HirId` mappings twice"
400         );
401
402         // Build the reverse mapping of `def_id_to_hir_id`.
403         self.hir_id_to_def_id = mapping
404             .iter_enumerated()
405             .filter_map(|(def_id, hir_id)| hir_id.map(|hir_id| (hir_id, def_id)))
406             .collect();
407
408         self.def_id_to_hir_id = mapping;
409     }
410
411     pub fn expansion_that_defined(&self, id: LocalDefId) -> ExpnId {
412         self.expansions_that_defined.get(&id).copied().unwrap_or_else(ExpnId::root)
413     }
414
415     pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {
416         self.parent_modules_of_macro_defs[&expn_id]
417     }
418
419     pub fn add_parent_module_of_macro_def(&mut self, expn_id: ExpnId, module: DefId) {
420         self.parent_modules_of_macro_defs.insert(expn_id, module);
421     }
422
423     pub fn iter_local_def_id(&self) -> impl Iterator<Item = LocalDefId> + '_ {
424         self.def_id_to_hir_id.iter_enumerated().map(|(k, _)| k)
425     }
426 }
427
428 #[derive(Copy, Clone, PartialEq, Debug)]
429 pub enum DefPathDataName {
430     Named(Symbol),
431     Anon { namespace: Symbol },
432 }
433
434 impl DefPathData {
435     pub fn get_opt_name(&self) -> Option<Symbol> {
436         use self::DefPathData::*;
437         match *self {
438             TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
439
440             Impl | CrateRoot | Misc | ClosureExpr | Ctor | AnonConst | ImplTrait => None,
441         }
442     }
443
444     pub fn name(&self) -> DefPathDataName {
445         use self::DefPathData::*;
446         match *self {
447             TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => {
448                 DefPathDataName::Named(name)
449             }
450             // Note that this does not show up in user print-outs.
451             CrateRoot => DefPathDataName::Anon { namespace: kw::Crate },
452             Impl => DefPathDataName::Anon { namespace: kw::Impl },
453             Misc => DefPathDataName::Anon { namespace: sym::misc },
454             ClosureExpr => DefPathDataName::Anon { namespace: sym::closure },
455             Ctor => DefPathDataName::Anon { namespace: sym::constructor },
456             AnonConst => DefPathDataName::Anon { namespace: sym::constant },
457             ImplTrait => DefPathDataName::Anon { namespace: sym::opaque },
458         }
459     }
460 }
461
462 impl fmt::Display for DefPathData {
463     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464         match self.name() {
465             DefPathDataName::Named(name) => f.write_str(&name.as_str()),
466             // FIXME(#70334): this will generate legacy {{closure}}, {{impl}}, etc
467             DefPathDataName::Anon { namespace } => write!(f, "{{{{{}}}}}", namespace),
468         }
469     }
470 }