]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/definitions.rs
Rollup merge of #61586 - alexcrichton:asmjs-no-assertions, r=pietroalbini
[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     #[inline]
401     pub fn def_index_to_node_id(&self, def_index: DefIndex) -> ast::NodeId {
402         self.as_local_node_id(DefId::local(def_index)).unwrap()
403     }
404
405     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate, the span exists
406     /// and it's not `DUMMY_SP`.
407     #[inline]
408     pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
409         if def_id.krate == LOCAL_CRATE {
410             self.def_index_to_span.get(&def_id.index).cloned()
411         } else {
412             None
413         }
414     }
415
416     /// Adds a root definition (no parent) and a few other reserved definitions.
417     ///
418     /// After the initial definitions are created the first `FIRST_FREE_DEF_INDEX` indexes
419     /// are taken, so the "user" indexes will be allocated starting with `FIRST_FREE_DEF_INDEX`
420     /// in ascending order.
421     pub fn create_root_def(&mut self,
422                            crate_name: &str,
423                            crate_disambiguator: CrateDisambiguator)
424                            -> DefIndex {
425         let key = DefKey {
426             parent: None,
427             disambiguated_data: DisambiguatedDefPathData {
428                 data: DefPathData::CrateRoot,
429                 disambiguator: 0
430             }
431         };
432
433         let parent_hash = DefKey::root_parent_stable_hash(crate_name,
434                                                           crate_disambiguator);
435         let def_path_hash = key.compute_stable_hash(parent_hash);
436
437         // Create the definition.
438         let root_index = self.table.allocate(key, def_path_hash);
439         assert_eq!(root_index, CRATE_DEF_INDEX);
440         assert!(self.def_index_to_node.is_empty());
441         self.def_index_to_node.push(ast::CRATE_NODE_ID);
442         self.node_to_def_index.insert(ast::CRATE_NODE_ID, root_index);
443
444         // Allocate some other DefIndices that always must exist.
445         GlobalMetaDataKind::allocate_def_indices(self);
446
447         root_index
448     }
449
450     /// Adds a definition with a parent definition.
451     pub fn create_def_with_parent(&mut self,
452                                   parent: DefIndex,
453                                   node_id: ast::NodeId,
454                                   data: DefPathData,
455                                   expansion: Mark,
456                                   span: Span)
457                                   -> DefIndex {
458         debug!("create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
459                parent, node_id, data);
460
461         assert!(!self.node_to_def_index.contains_key(&node_id),
462                 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
463                 node_id,
464                 data,
465                 self.table.def_key(self.node_to_def_index[&node_id]));
466
467         // The root node must be created with create_root_def()
468         assert!(data != DefPathData::CrateRoot);
469
470         // Find the next free disambiguator for this key.
471         let disambiguator = {
472             let next_disamb = self.next_disambiguator.entry((parent, data.clone())).or_insert(0);
473             let disambiguator = *next_disamb;
474             *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
475             disambiguator
476         };
477
478         let key = DefKey {
479             parent: Some(parent),
480             disambiguated_data: DisambiguatedDefPathData {
481                 data, disambiguator
482             }
483         };
484
485         let parent_hash = self.table.def_path_hash(parent);
486         let def_path_hash = key.compute_stable_hash(parent_hash);
487
488         debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
489
490         // Create the definition.
491         let index = self.table.allocate(key, def_path_hash);
492         assert_eq!(index.index(), self.def_index_to_node.len());
493         self.def_index_to_node.push(node_id);
494
495         // Some things for which we allocate DefIndices don't correspond to
496         // anything in the AST, so they don't have a NodeId. For these cases
497         // we don't need a mapping from NodeId to DefIndex.
498         if node_id != ast::DUMMY_NODE_ID {
499             debug!("create_def_with_parent: def_index_to_node[{:?} <-> {:?}", index, node_id);
500             self.node_to_def_index.insert(node_id, index);
501         }
502
503         if expansion != Mark::root() {
504             self.expansions_that_defined.insert(index, expansion);
505         }
506
507         // The span is added if it isn't dummy
508         if !span.is_dummy() {
509             self.def_index_to_span.insert(index, span);
510         }
511
512         index
513     }
514
515     /// Initialize the `ast::NodeId` to `HirId` mapping once it has been generated during
516     /// AST to HIR lowering.
517     pub fn init_node_id_to_hir_id_mapping(&mut self,
518                                           mapping: IndexVec<ast::NodeId, hir::HirId>) {
519         assert!(self.node_to_hir_id.is_empty(),
520                 "Trying initialize NodeId -> HirId mapping twice");
521         self.node_to_hir_id = mapping;
522     }
523
524     pub fn expansion_that_defined(&self, index: DefIndex) -> Mark {
525         self.expansions_that_defined.get(&index).cloned().unwrap_or(Mark::root())
526     }
527
528     pub fn parent_module_of_macro_def(&self, mark: Mark) -> DefId {
529         self.parent_modules_of_macro_defs[&mark]
530     }
531
532     pub fn add_parent_module_of_macro_def(&mut self, mark: Mark, module: DefId) {
533         self.parent_modules_of_macro_defs.insert(mark, module);
534     }
535 }
536
537 impl DefPathData {
538     pub fn get_opt_name(&self) -> Option<InternedString> {
539         use self::DefPathData::*;
540         match *self {
541             TypeNs(name) |
542             ValueNs(name) |
543             MacroNs(name) |
544             LifetimeNs(name) |
545             GlobalMetaData(name) => Some(name),
546
547             Impl |
548             CrateRoot |
549             Misc |
550             ClosureExpr |
551             Ctor |
552             AnonConst |
553             ImplTrait => None
554         }
555     }
556
557     pub fn as_interned_str(&self) -> InternedString {
558         use self::DefPathData::*;
559         let s = match *self {
560             TypeNs(name) |
561             ValueNs(name) |
562             MacroNs(name) |
563             LifetimeNs(name) |
564             GlobalMetaData(name) => {
565                 return name
566             }
567             // Note that this does not show up in user print-outs.
568             CrateRoot => sym::double_braced_crate,
569             Impl => sym::double_braced_impl,
570             Misc => sym::double_braced_misc,
571             ClosureExpr => sym::double_braced_closure,
572             Ctor => sym::double_braced_constructor,
573             AnonConst => sym::double_braced_constant,
574             ImplTrait => sym::double_braced_opaque,
575         };
576
577         s.as_interned_str()
578     }
579
580     pub fn to_string(&self) -> String {
581         self.as_interned_str().to_string()
582     }
583 }
584
585 macro_rules! count {
586     () => (0usize);
587     ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));
588 }
589
590 // We define the GlobalMetaDataKind enum with this macro because we want to
591 // make sure that we exhaustively iterate over all variants when registering
592 // the corresponding DefIndices in the DefTable.
593 macro_rules! define_global_metadata_kind {
594     (pub enum GlobalMetaDataKind {
595         $($variant:ident),*
596     }) => (
597         #[derive(Clone, Copy, Debug, Hash, RustcEncodable, RustcDecodable)]
598         pub enum GlobalMetaDataKind {
599             $($variant),*
600         }
601
602         pub const FIRST_FREE_DEF_INDEX: usize = 1 + count!($($variant)*);
603
604         impl GlobalMetaDataKind {
605             fn allocate_def_indices(definitions: &mut Definitions) {
606                 $({
607                     let instance = GlobalMetaDataKind::$variant;
608                     definitions.create_def_with_parent(
609                         CRATE_DEF_INDEX,
610                         ast::DUMMY_NODE_ID,
611                         DefPathData::GlobalMetaData(instance.name().as_interned_str()),
612                         Mark::root(),
613                         DUMMY_SP
614                     );
615
616                     // Make sure calling def_index does not crash.
617                     instance.def_index(&definitions.table);
618                 })*
619             }
620
621             pub fn def_index(&self, def_path_table: &DefPathTable) -> DefIndex {
622                 let def_key = DefKey {
623                     parent: Some(CRATE_DEF_INDEX),
624                     disambiguated_data: DisambiguatedDefPathData {
625                         data: DefPathData::GlobalMetaData(self.name().as_interned_str()),
626                         disambiguator: 0,
627                     }
628                 };
629
630                 // These DefKeys are all right after the root,
631                 // so a linear search is fine.
632                 let index = def_path_table.index_to_key
633                                           .iter()
634                                           .position(|k| *k == def_key)
635                                           .unwrap();
636
637                 DefIndex::from(index)
638             }
639
640             fn name(&self) -> Symbol {
641
642                 let string = match *self {
643                     $(
644                         GlobalMetaDataKind::$variant => {
645                             concat!("{{GlobalMetaData::", stringify!($variant), "}}")
646                         }
647                     )*
648                 };
649
650                 Symbol::intern(string)
651             }
652         }
653     )
654 }
655
656 define_global_metadata_kind!(pub enum GlobalMetaDataKind {
657     Krate,
658     CrateDeps,
659     DylibDependencyFormats,
660     LangItems,
661     LangItemsMissing,
662     NativeLibraries,
663     SourceMap,
664     Impls,
665     ExportedSymbols
666 });