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