]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/definitions.rs
Rollup merge of #61878 - RalfJung:pin, r=Dylan-DPC
[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::hir;
8 use crate::hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, CRATE_DEF_INDEX};
9 use crate::ich::Fingerprint;
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_data_structures::indexed_vec::{IndexVec};
12 use rustc_data_structures::stable_hasher::StableHasher;
13 use crate::session::CrateDisambiguator;
14 use std::borrow::Borrow;
15 use std::fmt::Write;
16 use std::hash::Hash;
17 use syntax::ast;
18 use syntax::ext::hygiene::Mark;
19 use syntax::symbol::{Symbol, sym, InternedString};
20 use syntax_pos::{Span, DUMMY_SP};
21 use crate::util::nodemap::NodeMap;
22
23 /// The DefPathTable maps DefIndexes to DefKeys and vice versa.
24 /// Internally the DefPathTable holds a tree of DefKeys, 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: Vec<DefKey>,
30     def_path_hashes: Vec<DefPathHash>,
31 }
32
33 impl DefPathTable {
34     fn allocate(&mut self,
35                 key: DefKey,
36                 def_path_hash: DefPathHash)
37                 -> DefIndex {
38         let index = {
39             let index = DefIndex::from(self.index_to_key.len());
40             debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
41             self.index_to_key.push(key);
42             index
43         };
44         self.def_path_hashes.push(def_path_hash);
45         debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
46         index
47     }
48
49     pub fn next_id(&self) -> DefIndex {
50         DefIndex::from(self.index_to_key.len())
51     }
52
53     #[inline(always)]
54     pub fn def_key(&self, index: DefIndex) -> DefKey {
55         self.index_to_key[index.index()].clone()
56     }
57
58     #[inline(always)]
59     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
60         let ret = self.def_path_hashes[index.index()];
61         debug!("def_path_hash({:?}) = {:?}", index, ret);
62         return ret
63     }
64
65     pub fn add_def_path_hashes_to(&self,
66                                   cnum: CrateNum,
67                                   out: &mut FxHashMap<DefPathHash, DefId>) {
68         out.extend(
69             self.def_path_hashes
70                 .iter()
71                 .enumerate()
72                 .map(|(index, &hash)| {
73                     let def_id = DefId {
74                         krate: cnum,
75                         index: DefIndex::from(index),
76                     };
77                     (hash, def_id)
78                 })
79         );
80     }
81
82     pub fn size(&self) -> usize {
83         self.index_to_key.len()
84     }
85 }
86
87 /// The definition table containing node definitions.
88 /// It holds the `DefPathTable` for local `DefId`s/`DefPath`s and it also stores a
89 /// mapping from `NodeId`s to local `DefId`s.
90 #[derive(Clone, Default)]
91 pub struct Definitions {
92     table: DefPathTable,
93     node_to_def_index: NodeMap<DefIndex>,
94     def_index_to_node: Vec<ast::NodeId>,
95     pub(super) node_to_hir_id: IndexVec<ast::NodeId, hir::HirId>,
96     /// If `Mark` is an ID of some macro expansion,
97     /// then `DefId` is the normal module (`mod`) in which the expanded macro was defined.
98     parent_modules_of_macro_defs: FxHashMap<Mark, DefId>,
99     /// Item with a given `DefIndex` was defined during macro expansion with ID `Mark`.
100     expansions_that_defined: FxHashMap<DefIndex, Mark>,
101     next_disambiguator: FxHashMap<(DefIndex, DefPathData), u32>,
102     def_index_to_span: FxHashMap<DefIndex, Span>,
103 }
104
105 /// A unique identifier that we can use to lookup a definition
106 /// precisely. It combines the index of the definition's parent (if
107 /// any) with a `DisambiguatedDefPathData`.
108 #[derive(Clone, PartialEq, Debug, Hash, RustcEncodable, RustcDecodable)]
109 pub struct DefKey {
110     /// The parent path.
111     pub parent: Option<DefIndex>,
112
113     /// The identifier of this node.
114     pub disambiguated_data: DisambiguatedDefPathData,
115 }
116
117 impl DefKey {
118     fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
119         let mut hasher = StableHasher::new();
120
121         // We hash a 0u8 here to disambiguate between regular DefPath hashes,
122         // and the special "root_parent" below.
123         0u8.hash(&mut hasher);
124         parent_hash.hash(&mut hasher);
125
126         let DisambiguatedDefPathData {
127             ref data,
128             disambiguator,
129         } = self.disambiguated_data;
130
131         ::std::mem::discriminant(data).hash(&mut hasher);
132         if let Some(name) = data.get_opt_name() {
133             name.hash(&mut hasher);
134         }
135
136         disambiguator.hash(&mut hasher);
137
138         DefPathHash(hasher.finish())
139     }
140
141     fn root_parent_stable_hash(crate_name: &str,
142                                crate_disambiguator: CrateDisambiguator)
143                                -> DefPathHash {
144         let mut hasher = StableHasher::new();
145         // Disambiguate this from a regular DefPath hash,
146         // see compute_stable_hash() above.
147         1u8.hash(&mut hasher);
148         crate_name.hash(&mut hasher);
149         crate_disambiguator.hash(&mut hasher);
150         DefPathHash(hasher.finish())
151     }
152 }
153
154 /// A pair of `DefPathData` and an integer disambiguator. The integer is
155 /// normally 0, but in the event that there are multiple defs with the
156 /// same `parent` and `data`, we use this field to disambiguate
157 /// between them. This introduces some artificial ordering dependency
158 /// but means that if you have (e.g.) two impls for the same type in
159 /// the same module, they do get distinct `DefId`s.
160 #[derive(Clone, PartialEq, Debug, Hash, RustcEncodable, RustcDecodable)]
161 pub struct DisambiguatedDefPathData {
162     pub data: DefPathData,
163     pub disambiguator: u32
164 }
165
166 #[derive(Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
167 pub struct DefPath {
168     /// The path leading from the crate root to the item.
169     pub data: Vec<DisambiguatedDefPathData>,
170
171     /// The crate root this path is relative to.
172     pub krate: CrateNum,
173 }
174
175 impl DefPath {
176     pub fn is_local(&self) -> bool {
177         self.krate == LOCAL_CRATE
178     }
179
180     pub fn make<FN>(krate: CrateNum,
181                     start_index: DefIndex,
182                     mut get_key: FN) -> DefPath
183         where 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: data, krate: 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,
215                    "::{}[{}]",
216                    component.data.as_interned_str(),
217                    component.disambiguator)
218                 .unwrap();
219         }
220
221         s
222     }
223
224     /// Returns a filename-friendly string for the `DefPath`, with the
225     /// crate-prefix.
226     pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
227         where F: FnOnce(CrateNum) -> Symbol
228     {
229         let crate_name_str = crate_imported_name(self.krate).as_str();
230         let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
231
232         write!(s, "::{}", crate_name_str).unwrap();
233
234         for component in &self.data {
235             if component.disambiguator == 0 {
236                 write!(s, "::{}", component.data.as_interned_str()).unwrap();
237             } else {
238                 write!(s,
239                        "{}[{}]",
240                        component.data.as_interned_str(),
241                        component.disambiguator)
242                        .unwrap();
243             }
244         }
245
246         s
247     }
248
249     /// Returns a filename-friendly string of the `DefPath`, without
250     /// the crate-prefix. This method is useful if you don't have
251     /// a `TyCtxt` available.
252     pub fn to_filename_friendly_no_crate(&self) -> String {
253         let mut s = String::with_capacity(self.data.len() * 16);
254
255         let mut opt_delimiter = None;
256         for component in &self.data {
257             opt_delimiter.map(|d| s.push(d));
258             opt_delimiter = Some('-');
259             if component.disambiguator == 0 {
260                 write!(s, "{}", component.data.as_interned_str()).unwrap();
261             } else {
262                 write!(s,
263                        "{}[{}]",
264                        component.data.as_interned_str(),
265                        component.disambiguator)
266                        .unwrap();
267             }
268         }
269         s
270     }
271 }
272
273 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
274 pub enum DefPathData {
275     // Root: these should only be used for the root nodes, because
276     // they are treated specially by the `def_path` function.
277     /// The crate root (marker)
278     CrateRoot,
279     // Catch-all for random DefId things like `DUMMY_NODE_ID`
280     Misc,
281     // Different kinds of items and item-like things:
282     /// An impl
283     Impl,
284     /// Something in the type NS
285     TypeNs(InternedString),
286     /// Something in the value NS
287     ValueNs(InternedString),
288     /// Something in the macro NS
289     MacroNs(InternedString),
290     /// Something in the lifetime NS
291     LifetimeNs(InternedString),
292     /// A closure expression
293     ClosureExpr,
294     // Subportions of items
295     /// Implicit ctor for a unit or tuple-like struct or enum variant.
296     Ctor,
297     /// A constant expression (see {ast,hir}::AnonConst).
298     AnonConst,
299     /// An `impl Trait` type node
300     ImplTrait,
301     /// Identifies a piece of crate metadata that is global to a whole crate
302     /// (as opposed to just one item). `GlobalMetaData` components are only
303     /// supposed to show up right below the crate root.
304     GlobalMetaData(InternedString),
305 }
306
307 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug,
308          RustcEncodable, RustcDecodable)]
309 pub struct DefPathHash(pub Fingerprint);
310
311 impl_stable_hash_for!(tuple_struct DefPathHash { fingerprint });
312
313 impl Borrow<Fingerprint> for DefPathHash {
314     #[inline]
315     fn borrow(&self) -> &Fingerprint {
316         &self.0
317     }
318 }
319
320 impl Definitions {
321     pub fn def_path_table(&self) -> &DefPathTable {
322         &self.table
323     }
324
325     /// Gets the number of definitions.
326     pub fn def_index_count(&self) -> usize {
327         self.table.index_to_key.len()
328     }
329
330     pub fn def_key(&self, index: DefIndex) -> DefKey {
331         self.table.def_key(index)
332     }
333
334     #[inline(always)]
335     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
336         self.table.def_path_hash(index)
337     }
338
339     /// Returns the path from the crate root to `index`. The root
340     /// nodes are not included in the path (i.e., this will be an
341     /// empty vector for the crate root). For an inlined item, this
342     /// will be the path of the item in the external crate (but the
343     /// path will begin with the path to the external crate).
344     pub fn def_path(&self, index: DefIndex) -> DefPath {
345         DefPath::make(LOCAL_CRATE, index, |p| self.def_key(p))
346     }
347
348     #[inline]
349     pub fn opt_def_index(&self, node: ast::NodeId) -> Option<DefIndex> {
350         self.node_to_def_index.get(&node).cloned()
351     }
352
353     #[inline]
354     pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<DefId> {
355         self.opt_def_index(node).map(DefId::local)
356     }
357
358     #[inline]
359     pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
360         self.opt_local_def_id(node).unwrap()
361     }
362
363     #[inline]
364     pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
365         if def_id.krate == LOCAL_CRATE {
366             let node_id = self.def_index_to_node[def_id.index.index()];
367             if node_id != ast::DUMMY_NODE_ID {
368                 return Some(node_id);
369             }
370         }
371         None
372     }
373
374     // FIXME(@ljedrz): replace the NodeId variant
375     #[inline]
376     pub fn as_local_hir_id(&self, def_id: DefId) -> Option<hir::HirId> {
377         if def_id.krate == LOCAL_CRATE {
378             let hir_id = self.def_index_to_hir_id(def_id.index);
379             if hir_id != hir::DUMMY_HIR_ID {
380                 Some(hir_id)
381             } else {
382                 None
383             }
384         } else {
385             None
386         }
387     }
388
389     #[inline]
390     pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
391         self.node_to_hir_id[node_id]
392     }
393
394     #[inline]
395     pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> hir::HirId {
396         let node_id = self.def_index_to_node[def_index.index()];
397         self.node_to_hir_id[node_id]
398     }
399
400     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate, the span exists
401     /// and it's not `DUMMY_SP`.
402     #[inline]
403     pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
404         if def_id.krate == LOCAL_CRATE {
405             self.def_index_to_span.get(&def_id.index).cloned()
406         } else {
407             None
408         }
409     }
410
411     /// Adds a root definition (no parent) and a few other reserved definitions.
412     ///
413     /// After the initial definitions are created the first `FIRST_FREE_DEF_INDEX` indexes
414     /// are taken, so the "user" indexes will be allocated starting with `FIRST_FREE_DEF_INDEX`
415     /// in ascending order.
416     pub fn create_root_def(&mut self,
417                            crate_name: &str,
418                            crate_disambiguator: CrateDisambiguator)
419                            -> DefIndex {
420         let key = DefKey {
421             parent: None,
422             disambiguated_data: DisambiguatedDefPathData {
423                 data: DefPathData::CrateRoot,
424                 disambiguator: 0
425             }
426         };
427
428         let parent_hash = DefKey::root_parent_stable_hash(crate_name,
429                                                           crate_disambiguator);
430         let def_path_hash = key.compute_stable_hash(parent_hash);
431
432         // Create the definition.
433         let root_index = self.table.allocate(key, def_path_hash);
434         assert_eq!(root_index, CRATE_DEF_INDEX);
435         assert!(self.def_index_to_node.is_empty());
436         self.def_index_to_node.push(ast::CRATE_NODE_ID);
437         self.node_to_def_index.insert(ast::CRATE_NODE_ID, root_index);
438
439         // Allocate some other DefIndices that always must exist.
440         GlobalMetaDataKind::allocate_def_indices(self);
441
442         root_index
443     }
444
445     /// Adds a definition with a parent definition.
446     pub fn create_def_with_parent(&mut self,
447                                   parent: DefIndex,
448                                   node_id: ast::NodeId,
449                                   data: DefPathData,
450                                   expansion: Mark,
451                                   span: Span)
452                                   -> DefIndex {
453         debug!("create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
454                parent, node_id, data);
455
456         assert!(!self.node_to_def_index.contains_key(&node_id),
457                 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
458                 node_id,
459                 data,
460                 self.table.def_key(self.node_to_def_index[&node_id]));
461
462         // The root node must be created with create_root_def()
463         assert!(data != DefPathData::CrateRoot);
464
465         // Find the next free disambiguator for this key.
466         let disambiguator = {
467             let next_disamb = self.next_disambiguator.entry((parent, data.clone())).or_insert(0);
468             let disambiguator = *next_disamb;
469             *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
470             disambiguator
471         };
472
473         let key = DefKey {
474             parent: Some(parent),
475             disambiguated_data: DisambiguatedDefPathData {
476                 data, disambiguator
477             }
478         };
479
480         let parent_hash = self.table.def_path_hash(parent);
481         let def_path_hash = key.compute_stable_hash(parent_hash);
482
483         debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
484
485         // Create the definition.
486         let index = self.table.allocate(key, def_path_hash);
487         assert_eq!(index.index(), self.def_index_to_node.len());
488         self.def_index_to_node.push(node_id);
489
490         // Some things for which we allocate DefIndices don't correspond to
491         // anything in the AST, so they don't have a NodeId. For these cases
492         // we don't need a mapping from NodeId to DefIndex.
493         if node_id != ast::DUMMY_NODE_ID {
494             debug!("create_def_with_parent: def_index_to_node[{:?} <-> {:?}", index, node_id);
495             self.node_to_def_index.insert(node_id, index);
496         }
497
498         if expansion != Mark::root() {
499             self.expansions_that_defined.insert(index, expansion);
500         }
501
502         // The span is added if it isn't dummy
503         if !span.is_dummy() {
504             self.def_index_to_span.insert(index, span);
505         }
506
507         index
508     }
509
510     /// Initialize the `ast::NodeId` to `HirId` mapping once it has been generated during
511     /// AST to HIR lowering.
512     pub fn init_node_id_to_hir_id_mapping(&mut self,
513                                           mapping: IndexVec<ast::NodeId, hir::HirId>) {
514         assert!(self.node_to_hir_id.is_empty(),
515                 "Trying initialize NodeId -> HirId mapping twice");
516         self.node_to_hir_id = mapping;
517     }
518
519     pub fn expansion_that_defined(&self, index: DefIndex) -> Mark {
520         self.expansions_that_defined.get(&index).cloned().unwrap_or(Mark::root())
521     }
522
523     pub fn parent_module_of_macro_def(&self, mark: Mark) -> DefId {
524         self.parent_modules_of_macro_defs[&mark]
525     }
526
527     pub fn add_parent_module_of_macro_def(&mut self, mark: Mark, module: DefId) {
528         self.parent_modules_of_macro_defs.insert(mark, module);
529     }
530 }
531
532 impl DefPathData {
533     pub fn get_opt_name(&self) -> Option<InternedString> {
534         use self::DefPathData::*;
535         match *self {
536             TypeNs(name) |
537             ValueNs(name) |
538             MacroNs(name) |
539             LifetimeNs(name) |
540             GlobalMetaData(name) => Some(name),
541
542             Impl |
543             CrateRoot |
544             Misc |
545             ClosureExpr |
546             Ctor |
547             AnonConst |
548             ImplTrait => None
549         }
550     }
551
552     pub fn as_interned_str(&self) -> InternedString {
553         use self::DefPathData::*;
554         let s = match *self {
555             TypeNs(name) |
556             ValueNs(name) |
557             MacroNs(name) |
558             LifetimeNs(name) |
559             GlobalMetaData(name) => {
560                 return name
561             }
562             // Note that this does not show up in user print-outs.
563             CrateRoot => sym::double_braced_crate,
564             Impl => sym::double_braced_impl,
565             Misc => sym::double_braced_misc,
566             ClosureExpr => sym::double_braced_closure,
567             Ctor => sym::double_braced_constructor,
568             AnonConst => sym::double_braced_constant,
569             ImplTrait => sym::double_braced_opaque,
570         };
571
572         s.as_interned_str()
573     }
574
575     pub fn to_string(&self) -> String {
576         self.as_interned_str().to_string()
577     }
578 }
579
580 /// Evaluates to the number of tokens passed to it.
581 ///
582 /// Logarithmic counting: every one or two recursive expansions, the number of
583 /// tokens to count is divided by two, instead of being reduced by one.
584 /// Therefore, the recursion depth is the binary logarithm of the number of
585 /// tokens to count, and the expanded tree is likewise very small.
586 macro_rules! count {
587     ()                     => (0usize);
588     ($one:tt)              => (1usize);
589     ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
590     ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
591 }
592
593 // We define the GlobalMetaDataKind enum with this macro because we want to
594 // make sure that we exhaustively iterate over all variants when registering
595 // the corresponding DefIndices in the DefTable.
596 macro_rules! define_global_metadata_kind {
597     (pub enum GlobalMetaDataKind {
598         $($variant:ident),*
599     }) => (
600         #[derive(Clone, Copy, Debug, Hash, RustcEncodable, RustcDecodable)]
601         pub enum GlobalMetaDataKind {
602             $($variant),*
603         }
604
605         pub const FIRST_FREE_DEF_INDEX: usize = 1 + count!($($variant)*);
606
607         impl GlobalMetaDataKind {
608             fn allocate_def_indices(definitions: &mut Definitions) {
609                 $({
610                     let instance = GlobalMetaDataKind::$variant;
611                     definitions.create_def_with_parent(
612                         CRATE_DEF_INDEX,
613                         ast::DUMMY_NODE_ID,
614                         DefPathData::GlobalMetaData(instance.name().as_interned_str()),
615                         Mark::root(),
616                         DUMMY_SP
617                     );
618
619                     // Make sure calling def_index does not crash.
620                     instance.def_index(&definitions.table);
621                 })*
622             }
623
624             pub fn def_index(&self, def_path_table: &DefPathTable) -> DefIndex {
625                 let def_key = DefKey {
626                     parent: Some(CRATE_DEF_INDEX),
627                     disambiguated_data: DisambiguatedDefPathData {
628                         data: DefPathData::GlobalMetaData(self.name().as_interned_str()),
629                         disambiguator: 0,
630                     }
631                 };
632
633                 // These DefKeys are all right after the root,
634                 // so a linear search is fine.
635                 let index = def_path_table.index_to_key
636                                           .iter()
637                                           .position(|k| *k == def_key)
638                                           .unwrap();
639
640                 DefIndex::from(index)
641             }
642
643             fn name(&self) -> Symbol {
644
645                 let string = match *self {
646                     $(
647                         GlobalMetaDataKind::$variant => {
648                             concat!("{{GlobalMetaData::", stringify!($variant), "}}")
649                         }
650                     )*
651                 };
652
653                 Symbol::intern(string)
654             }
655         }
656     )
657 }
658
659 define_global_metadata_kind!(pub enum GlobalMetaDataKind {
660     Krate,
661     CrateDeps,
662     DylibDependencyFormats,
663     LangItems,
664     LangItemsMissing,
665     NativeLibraries,
666     SourceMap,
667     Impls,
668     ExportedSymbols
669 });