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