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