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