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