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