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