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