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