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