]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/definitions.rs
Rollup merge of #69735 - tmiasko:bootstrap-sanitizers-hash, r=Mark-Simulacrum
[rust.git] / src / librustc / hir / map / 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 use rustc_ast::ast;
8 use rustc_ast::node_id::NodeMap;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::stable_hasher::StableHasher;
11 use rustc_hir as hir;
12 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc_index::vec::IndexVec;
14 use rustc_session::CrateDisambiguator;
15 use rustc_span::hygiene::ExpnId;
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_span::Span;
18
19 use std::fmt::Write;
20 use std::hash::Hash;
21
22 pub use rustc_hir::def_id::DefPathHash;
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, RustcDecodable, RustcEncodable)]
29 pub struct DefPathTable {
30     index_to_key: IndexVec<DefIndex, DefKey>,
31     def_path_hashes: IndexVec<DefIndex, DefPathHash>,
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         index
45     }
46
47     pub fn next_id(&self) -> DefIndex {
48         DefIndex::from(self.index_to_key.len())
49     }
50
51     #[inline(always)]
52     pub fn def_key(&self, index: DefIndex) -> DefKey {
53         self.index_to_key[index]
54     }
55
56     #[inline(always)]
57     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
58         let hash = self.def_path_hashes[index];
59         debug!("def_path_hash({:?}) = {:?}", index, hash);
60         hash
61     }
62
63     pub fn add_def_path_hashes_to(&self, cnum: CrateNum, out: &mut FxHashMap<DefPathHash, DefId>) {
64         out.extend(self.def_path_hashes.iter().enumerate().map(|(index, &hash)| {
65             let def_id = DefId { krate: cnum, index: DefIndex::from(index) };
66             (hash, def_id)
67         }));
68     }
69
70     pub fn size(&self) -> usize {
71         self.index_to_key.len()
72     }
73 }
74
75 /// The definition table containing node definitions.
76 /// It holds the `DefPathTable` for local `DefId`s/`DefPath`s and it also stores a
77 /// mapping from `NodeId`s to local `DefId`s.
78 #[derive(Clone, Default)]
79 pub struct Definitions {
80     table: DefPathTable,
81     node_to_def_index: NodeMap<DefIndex>,
82     def_index_to_node: IndexVec<DefIndex, ast::NodeId>,
83
84     pub(super) node_to_hir_id: IndexVec<ast::NodeId, hir::HirId>,
85     /// The reverse mapping of `node_to_hir_id`.
86     pub(super) hir_to_node_id: FxHashMap<hir::HirId, ast::NodeId>,
87
88     /// If `ExpnId` is an ID of some macro expansion,
89     /// then `DefId` is the normal module (`mod`) in which the expanded macro was defined.
90     parent_modules_of_macro_defs: FxHashMap<ExpnId, DefId>,
91     /// Item with a given `DefIndex` was defined during macro expansion with ID `ExpnId`.
92     expansions_that_defined: FxHashMap<DefIndex, ExpnId>,
93     next_disambiguator: FxHashMap<(DefIndex, DefPathData), u32>,
94     def_index_to_span: FxHashMap<DefIndex, Span>,
95     /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
96     /// we know what parent node that fragment should be attached to thanks to this table.
97     invocation_parents: FxHashMap<ExpnId, DefIndex>,
98     /// Indices of unnamed struct or variant fields with unresolved attributes.
99     placeholder_field_indices: NodeMap<usize>,
100 }
101
102 /// A unique identifier that we can use to lookup a definition
103 /// precisely. It combines the index of the definition's parent (if
104 /// any) with a `DisambiguatedDefPathData`.
105 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
106 pub struct DefKey {
107     /// The parent path.
108     pub parent: Option<DefIndex>,
109
110     /// The identifier of this node.
111     pub disambiguated_data: DisambiguatedDefPathData,
112 }
113
114 impl DefKey {
115     fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
116         let mut hasher = StableHasher::new();
117
118         // We hash a `0u8` here to disambiguate between regular `DefPath` hashes,
119         // and the special "root_parent" below.
120         0u8.hash(&mut hasher);
121         parent_hash.hash(&mut hasher);
122
123         let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
124
125         ::std::mem::discriminant(data).hash(&mut hasher);
126         if let Some(name) = data.get_opt_name() {
127             // Get a stable hash by considering the symbol chars rather than
128             // the symbol index.
129             name.as_str().hash(&mut hasher);
130         }
131
132         disambiguator.hash(&mut hasher);
133
134         DefPathHash(hasher.finish())
135     }
136
137     fn root_parent_stable_hash(
138         crate_name: &str,
139         crate_disambiguator: CrateDisambiguator,
140     ) -> DefPathHash {
141         let mut hasher = StableHasher::new();
142         // Disambiguate this from a regular `DefPath` hash; see `compute_stable_hash()` above.
143         1u8.hash(&mut hasher);
144         crate_name.hash(&mut hasher);
145         crate_disambiguator.hash(&mut hasher);
146         DefPathHash(hasher.finish())
147     }
148 }
149
150 /// A pair of `DefPathData` and an integer disambiguator. The integer is
151 /// normally `0`, but in the event that there are multiple defs with the
152 /// same `parent` and `data`, we use this field to disambiguate
153 /// between them. This introduces some artificial ordering dependency
154 /// but means that if you have, e.g., two impls for the same type in
155 /// the same module, they do get distinct `DefId`s.
156 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
157 pub struct DisambiguatedDefPathData {
158     pub data: DefPathData,
159     pub disambiguator: u32,
160 }
161
162 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
163 pub struct DefPath {
164     /// The path leading from the crate root to the item.
165     pub data: Vec<DisambiguatedDefPathData>,
166
167     /// The crate root this path is relative to.
168     pub krate: CrateNum,
169 }
170
171 impl DefPath {
172     pub fn is_local(&self) -> bool {
173         self.krate == LOCAL_CRATE
174     }
175
176     pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
177     where
178         FN: FnMut(DefIndex) -> DefKey,
179     {
180         let mut data = vec![];
181         let mut index = Some(start_index);
182         loop {
183             debug!("DefPath::make: krate={:?} index={:?}", krate, index);
184             let p = index.unwrap();
185             let key = get_key(p);
186             debug!("DefPath::make: key={:?}", key);
187             match key.disambiguated_data.data {
188                 DefPathData::CrateRoot => {
189                     assert!(key.parent.is_none());
190                     break;
191                 }
192                 _ => {
193                     data.push(key.disambiguated_data);
194                     index = key.parent;
195                 }
196             }
197         }
198         data.reverse();
199         DefPath { data, krate }
200     }
201
202     /// Returns a string representation of the `DefPath` without
203     /// the crate-prefix. This method is useful if you don't have
204     /// a `TyCtxt` available.
205     pub fn to_string_no_crate(&self) -> String {
206         let mut s = String::with_capacity(self.data.len() * 16);
207
208         for component in &self.data {
209             write!(s, "::{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
210         }
211
212         s
213     }
214
215     /// Returns a filename-friendly string for the `DefPath`, with the
216     /// crate-prefix.
217     pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
218     where
219         F: FnOnce(CrateNum) -> Symbol,
220     {
221         let crate_name_str = crate_imported_name(self.krate).as_str();
222         let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
223
224         write!(s, "::{}", crate_name_str).unwrap();
225
226         for component in &self.data {
227             if component.disambiguator == 0 {
228                 write!(s, "::{}", component.data.as_symbol()).unwrap();
229             } else {
230                 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
231             }
232         }
233
234         s
235     }
236
237     /// Returns a filename-friendly string of the `DefPath`, without
238     /// the crate-prefix. This method is useful if you don't have
239     /// a `TyCtxt` available.
240     pub fn to_filename_friendly_no_crate(&self) -> String {
241         let mut s = String::with_capacity(self.data.len() * 16);
242
243         let mut opt_delimiter = None;
244         for component in &self.data {
245             opt_delimiter.map(|d| s.push(d));
246             opt_delimiter = Some('-');
247             if component.disambiguator == 0 {
248                 write!(s, "{}", component.data.as_symbol()).unwrap();
249             } else {
250                 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
251             }
252         }
253         s
254     }
255 }
256
257 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
258 pub enum DefPathData {
259     // Root: these should only be used for the root nodes, because
260     // they are treated specially by the `def_path` function.
261     /// The crate root (marker).
262     CrateRoot,
263     // Catch-all for random `DefId` things like `DUMMY_NODE_ID`.
264     Misc,
265
266     // Different kinds of items and item-like things:
267     /// An impl.
268     Impl,
269     /// Something in the type namespace.
270     TypeNs(Symbol),
271     /// Something in the value namespace.
272     ValueNs(Symbol),
273     /// Something in the macro namespace.
274     MacroNs(Symbol),
275     /// Something in the lifetime namespace.
276     LifetimeNs(Symbol),
277     /// A closure expression.
278     ClosureExpr,
279
280     // Subportions of items:
281     /// Implicit constructor for a unit or tuple-like struct or enum variant.
282     Ctor,
283     /// A constant expression (see `{ast,hir}::AnonConst`).
284     AnonConst,
285     /// An `impl Trait` type node.
286     ImplTrait,
287 }
288
289 impl Definitions {
290     pub fn def_path_table(&self) -> &DefPathTable {
291         &self.table
292     }
293
294     /// Gets the number of definitions.
295     pub fn def_index_count(&self) -> usize {
296         self.table.index_to_key.len()
297     }
298
299     pub fn def_key(&self, index: DefIndex) -> DefKey {
300         self.table.def_key(index)
301     }
302
303     #[inline(always)]
304     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
305         self.table.def_path_hash(index)
306     }
307
308     /// Returns the path from the crate root to `index`. The root
309     /// nodes are not included in the path (i.e., this will be an
310     /// empty vector for the crate root). For an inlined item, this
311     /// will be the path of the item in the external crate (but the
312     /// path will begin with the path to the external crate).
313     pub fn def_path(&self, index: DefIndex) -> DefPath {
314         DefPath::make(LOCAL_CRATE, index, |p| self.def_key(p))
315     }
316
317     #[inline]
318     pub fn opt_def_index(&self, node: ast::NodeId) -> Option<DefIndex> {
319         self.node_to_def_index.get(&node).copied()
320     }
321
322     #[inline]
323     pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<DefId> {
324         self.opt_def_index(node).map(DefId::local)
325     }
326
327     #[inline]
328     pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
329         self.opt_local_def_id(node).unwrap()
330     }
331
332     #[inline]
333     pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
334         if def_id.krate == LOCAL_CRATE {
335             let node_id = self.def_index_to_node[def_id.index];
336             if node_id != ast::DUMMY_NODE_ID {
337                 return Some(node_id);
338             }
339         }
340         None
341     }
342
343     #[inline]
344     pub fn as_local_hir_id(&self, def_id: DefId) -> Option<hir::HirId> {
345         if def_id.krate == LOCAL_CRATE {
346             let hir_id = self.def_index_to_hir_id(def_id.index);
347             if hir_id != hir::DUMMY_HIR_ID { Some(hir_id) } else { None }
348         } else {
349             None
350         }
351     }
352
353     #[inline]
354     pub fn hir_to_node_id(&self, hir_id: hir::HirId) -> ast::NodeId {
355         self.hir_to_node_id[&hir_id]
356     }
357
358     #[inline]
359     pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
360         self.node_to_hir_id[node_id]
361     }
362
363     #[inline]
364     pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> hir::HirId {
365         let node_id = self.def_index_to_node[def_index];
366         self.node_to_hir_id[node_id]
367     }
368
369     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate, the span exists
370     /// and it's not `DUMMY_SP`.
371     #[inline]
372     pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
373         if def_id.krate == LOCAL_CRATE {
374             self.def_index_to_span.get(&def_id.index).copied()
375         } else {
376             None
377         }
378     }
379
380     /// Adds a root definition (no parent) and a few other reserved definitions.
381     pub fn create_root_def(
382         &mut self,
383         crate_name: &str,
384         crate_disambiguator: CrateDisambiguator,
385     ) -> DefIndex {
386         let key = DefKey {
387             parent: None,
388             disambiguated_data: DisambiguatedDefPathData {
389                 data: DefPathData::CrateRoot,
390                 disambiguator: 0,
391             },
392         };
393
394         let parent_hash = DefKey::root_parent_stable_hash(crate_name, crate_disambiguator);
395         let def_path_hash = key.compute_stable_hash(parent_hash);
396
397         // Create the definition.
398         let root_index = self.table.allocate(key, def_path_hash);
399         assert_eq!(root_index, CRATE_DEF_INDEX);
400         assert!(self.def_index_to_node.is_empty());
401         self.def_index_to_node.push(ast::CRATE_NODE_ID);
402         self.node_to_def_index.insert(ast::CRATE_NODE_ID, root_index);
403         self.set_invocation_parent(ExpnId::root(), root_index);
404
405         root_index
406     }
407
408     /// Adds a definition with a parent definition.
409     pub fn create_def_with_parent(
410         &mut self,
411         parent: DefIndex,
412         node_id: ast::NodeId,
413         data: DefPathData,
414         expn_id: ExpnId,
415         span: Span,
416     ) -> DefIndex {
417         debug!(
418             "create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
419             parent, node_id, data
420         );
421
422         assert!(
423             !self.node_to_def_index.contains_key(&node_id),
424             "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
425             node_id,
426             data,
427             self.table.def_key(self.node_to_def_index[&node_id])
428         );
429
430         // The root node must be created with `create_root_def()`.
431         assert!(data != DefPathData::CrateRoot);
432
433         // Find the next free disambiguator for this key.
434         let disambiguator = {
435             let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
436             let disambiguator = *next_disamb;
437             *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
438             disambiguator
439         };
440
441         let key = DefKey {
442             parent: Some(parent),
443             disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
444         };
445
446         let parent_hash = self.table.def_path_hash(parent);
447         let def_path_hash = key.compute_stable_hash(parent_hash);
448
449         debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
450
451         // Create the definition.
452         let index = self.table.allocate(key, def_path_hash);
453         assert_eq!(index.index(), self.def_index_to_node.len());
454         self.def_index_to_node.push(node_id);
455
456         // Some things for which we allocate `DefIndex`es don't correspond to
457         // anything in the AST, so they don't have a `NodeId`. For these cases
458         // we don't need a mapping from `NodeId` to `DefIndex`.
459         if node_id != ast::DUMMY_NODE_ID {
460             debug!("create_def_with_parent: def_index_to_node[{:?} <-> {:?}", index, node_id);
461             self.node_to_def_index.insert(node_id, index);
462         }
463
464         if expn_id != ExpnId::root() {
465             self.expansions_that_defined.insert(index, expn_id);
466         }
467
468         // The span is added if it isn't dummy.
469         if !span.is_dummy() {
470             self.def_index_to_span.insert(index, span);
471         }
472
473         index
474     }
475
476     /// Initializes the `ast::NodeId` to `HirId` mapping once it has been generated during
477     /// AST to HIR lowering.
478     pub fn init_node_id_to_hir_id_mapping(&mut self, mapping: IndexVec<ast::NodeId, hir::HirId>) {
479         assert!(
480             self.node_to_hir_id.is_empty(),
481             "trying to initialize `NodeId` -> `HirId` mapping twice"
482         );
483         self.node_to_hir_id = mapping;
484
485         // Build the reverse mapping of `node_to_hir_id`.
486         self.hir_to_node_id = self
487             .node_to_hir_id
488             .iter_enumerated()
489             .map(|(node_id, &hir_id)| (hir_id, node_id))
490             .collect();
491     }
492
493     pub fn expansion_that_defined(&self, index: DefIndex) -> ExpnId {
494         self.expansions_that_defined.get(&index).copied().unwrap_or(ExpnId::root())
495     }
496
497     pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {
498         self.parent_modules_of_macro_defs[&expn_id]
499     }
500
501     pub fn add_parent_module_of_macro_def(&mut self, expn_id: ExpnId, module: DefId) {
502         self.parent_modules_of_macro_defs.insert(expn_id, module);
503     }
504
505     pub fn invocation_parent(&self, invoc_id: ExpnId) -> DefIndex {
506         self.invocation_parents[&invoc_id]
507     }
508
509     pub fn set_invocation_parent(&mut self, invoc_id: ExpnId, parent: DefIndex) {
510         let old_parent = self.invocation_parents.insert(invoc_id, parent);
511         assert!(old_parent.is_none(), "parent `DefIndex` is reset for an invocation");
512     }
513
514     pub fn placeholder_field_index(&self, node_id: ast::NodeId) -> usize {
515         self.placeholder_field_indices[&node_id]
516     }
517
518     pub fn set_placeholder_field_index(&mut self, node_id: ast::NodeId, index: usize) {
519         let old_index = self.placeholder_field_indices.insert(node_id, index);
520         assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
521     }
522 }
523
524 impl DefPathData {
525     pub fn get_opt_name(&self) -> Option<Symbol> {
526         use self::DefPathData::*;
527         match *self {
528             TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
529
530             Impl | CrateRoot | Misc | ClosureExpr | Ctor | AnonConst | ImplTrait => None,
531         }
532     }
533
534     pub fn as_symbol(&self) -> Symbol {
535         use self::DefPathData::*;
536         match *self {
537             TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => name,
538             // Note that this does not show up in user print-outs.
539             CrateRoot => sym::double_braced_crate,
540             Impl => sym::double_braced_impl,
541             Misc => sym::double_braced_misc,
542             ClosureExpr => sym::double_braced_closure,
543             Ctor => sym::double_braced_constructor,
544             AnonConst => sym::double_braced_constant,
545             ImplTrait => sym::double_braced_opaque,
546         }
547     }
548
549     pub fn to_string(&self) -> String {
550         self.as_symbol().to_string()
551     }
552 }