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