]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/map/definitions.rs
Improve some compiletest documentation
[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     /// A trait
341     Trait(InternedString),
342     /// An associated type **declaration** (i.e., in a trait)
343     AssocTypeInTrait(InternedString),
344     /// An associated type **value** (i.e., in an impl)
345     AssocTypeInImpl(InternedString),
346     /// An existential associated type **value** (i.e., in an impl)
347     AssocExistentialInImpl(InternedString),
348     /// Something in the type NS
349     TypeNs(InternedString),
350     /// Something in the value NS
351     ValueNs(InternedString),
352     /// A module declaration
353     Module(InternedString),
354     /// A macro rule
355     MacroDef(InternedString),
356     /// A closure expression
357     ClosureExpr,
358     // Subportions of items
359     /// A type (generic) parameter
360     TypeParam(InternedString),
361     /// A lifetime (generic) parameter
362     LifetimeParam(InternedString),
363     /// A const (generic) parameter
364     ConstParam(InternedString),
365     /// A variant of a enum
366     EnumVariant(InternedString),
367     /// A struct field
368     Field(InternedString),
369     /// Implicit ctor for a tuple-like struct
370     StructCtor,
371     /// A constant expression (see {ast,hir}::AnonConst).
372     AnonConst,
373     /// An `impl Trait` type node
374     ImplTrait,
375     /// GlobalMetaData identifies a piece of crate metadata that is global to
376     /// a whole crate (as opposed to just one item). GlobalMetaData components
377     /// are only supposed to show up right below the crate root.
378     GlobalMetaData(InternedString),
379     /// A trait alias.
380     TraitAlias(InternedString),
381 }
382
383 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug,
384          RustcEncodable, RustcDecodable)]
385 pub struct DefPathHash(pub Fingerprint);
386
387 impl_stable_hash_for!(tuple_struct DefPathHash { fingerprint });
388
389 impl Borrow<Fingerprint> for DefPathHash {
390     #[inline]
391     fn borrow(&self) -> &Fingerprint {
392         &self.0
393     }
394 }
395
396 impl Definitions {
397     /// Creates new empty definition map.
398     ///
399     /// The `DefIndex` returned from a new `Definitions` are as follows:
400     /// 1. At `DefIndexAddressSpace::Low`,
401     ///     CRATE_ROOT has index 0:0, and then new indexes are allocated in
402     ///     ascending order.
403     /// 2. At `DefIndexAddressSpace::High`,
404     ///     the first `FIRST_FREE_HIGH_DEF_INDEX` indexes are reserved for
405     ///     internal use, then `1:FIRST_FREE_HIGH_DEF_INDEX` are allocated in
406     ///     ascending order.
407     //
408     // FIXME: there is probably a better place to put this comment.
409     pub fn new() -> Self {
410         Self::default()
411     }
412
413     pub fn def_path_table(&self) -> &DefPathTable {
414         &self.table
415     }
416
417     /// Gets the number of definitions.
418     pub fn def_index_counts_lo_hi(&self) -> (usize, usize) {
419         (self.table.index_to_key[DefIndexAddressSpace::Low.index()].len(),
420          self.table.index_to_key[DefIndexAddressSpace::High.index()].len())
421     }
422
423     pub fn def_key(&self, index: DefIndex) -> DefKey {
424         self.table.def_key(index)
425     }
426
427     #[inline(always)]
428     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
429         self.table.def_path_hash(index)
430     }
431
432     /// Returns the path from the crate root to `index`. The root
433     /// nodes are not included in the path (i.e., this will be an
434     /// empty vector for the crate root). For an inlined item, this
435     /// will be the path of the item in the external crate (but the
436     /// path will begin with the path to the external crate).
437     pub fn def_path(&self, index: DefIndex) -> DefPath {
438         DefPath::make(LOCAL_CRATE, index, |p| self.def_key(p))
439     }
440
441     #[inline]
442     pub fn opt_def_index(&self, node: ast::NodeId) -> Option<DefIndex> {
443         self.node_to_def_index.get(&node).cloned()
444     }
445
446     #[inline]
447     pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<DefId> {
448         self.opt_def_index(node).map(DefId::local)
449     }
450
451     #[inline]
452     pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
453         self.opt_local_def_id(node).unwrap()
454     }
455
456     #[inline]
457     pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
458         if def_id.krate == LOCAL_CRATE {
459             let space_index = def_id.index.address_space().index();
460             let array_index = def_id.index.as_array_index();
461             let node_id = self.def_index_to_node[space_index][array_index];
462             if node_id != ast::DUMMY_NODE_ID {
463                 Some(node_id)
464             } else {
465                 None
466             }
467         } else {
468             None
469         }
470     }
471
472     // FIXME(@ljedrz): replace the NodeId variant
473     #[inline]
474     pub fn as_local_hir_id(&self, def_id: DefId) -> Option<hir::HirId> {
475         if def_id.krate == LOCAL_CRATE {
476             let hir_id = self.def_index_to_hir_id(def_id.index);
477             if hir_id != hir::DUMMY_HIR_ID {
478                 Some(hir_id)
479             } else {
480                 None
481             }
482         } else {
483             None
484         }
485     }
486
487     #[inline]
488     pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
489         self.node_to_hir_id[node_id]
490     }
491
492     #[inline]
493     pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> hir::HirId {
494         let space_index = def_index.address_space().index();
495         let array_index = def_index.as_array_index();
496         let node_id = self.def_index_to_node[space_index][array_index];
497         self.node_to_hir_id[node_id]
498     }
499
500     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate, the span exists
501     /// and it's not `DUMMY_SP`.
502     #[inline]
503     pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
504         if def_id.krate == LOCAL_CRATE {
505             self.def_index_to_span.get(&def_id.index).cloned()
506         } else {
507             None
508         }
509     }
510
511     /// Adds a root definition (no parent).
512     pub fn create_root_def(&mut self,
513                            crate_name: &str,
514                            crate_disambiguator: CrateDisambiguator)
515                            -> DefIndex {
516         let key = DefKey {
517             parent: None,
518             disambiguated_data: DisambiguatedDefPathData {
519                 data: DefPathData::CrateRoot,
520                 disambiguator: 0
521             }
522         };
523
524         let parent_hash = DefKey::root_parent_stable_hash(crate_name,
525                                                           crate_disambiguator);
526         let def_path_hash = key.compute_stable_hash(parent_hash);
527
528         // Create the definition.
529         let address_space = super::ITEM_LIKE_SPACE;
530         let root_index = self.table.allocate(key, def_path_hash, address_space);
531         assert_eq!(root_index, CRATE_DEF_INDEX);
532         assert!(self.def_index_to_node[address_space.index()].is_empty());
533         self.def_index_to_node[address_space.index()].push(ast::CRATE_NODE_ID);
534         self.node_to_def_index.insert(ast::CRATE_NODE_ID, root_index);
535
536         // Allocate some other DefIndices that always must exist.
537         GlobalMetaDataKind::allocate_def_indices(self);
538
539         root_index
540     }
541
542     /// Add a definition with a parent definition.
543     pub fn create_def_with_parent(&mut self,
544                                   parent: DefIndex,
545                                   node_id: ast::NodeId,
546                                   data: DefPathData,
547                                   address_space: DefIndexAddressSpace,
548                                   expansion: Mark,
549                                   span: Span)
550                                   -> DefIndex {
551         debug!("create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
552                parent, node_id, data);
553
554         assert!(!self.node_to_def_index.contains_key(&node_id),
555                 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
556                 node_id,
557                 data,
558                 self.table.def_key(self.node_to_def_index[&node_id]));
559
560         // The root node must be created with create_root_def()
561         assert!(data != DefPathData::CrateRoot);
562
563         // Find the next free disambiguator for this key.
564         let disambiguator = {
565             let next_disamb = self.next_disambiguator.entry((parent, data.clone())).or_insert(0);
566             let disambiguator = *next_disamb;
567             *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
568             disambiguator
569         };
570
571         let key = DefKey {
572             parent: Some(parent),
573             disambiguated_data: DisambiguatedDefPathData {
574                 data, disambiguator
575             }
576         };
577
578         let parent_hash = self.table.def_path_hash(parent);
579         let def_path_hash = key.compute_stable_hash(parent_hash);
580
581         debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
582
583         // Create the definition.
584         let index = self.table.allocate(key, def_path_hash, address_space);
585         assert_eq!(index.as_array_index(),
586                    self.def_index_to_node[address_space.index()].len());
587         self.def_index_to_node[address_space.index()].push(node_id);
588
589         // Some things for which we allocate DefIndices don't correspond to
590         // anything in the AST, so they don't have a NodeId. For these cases
591         // we don't need a mapping from NodeId to DefIndex.
592         if node_id != ast::DUMMY_NODE_ID {
593             debug!("create_def_with_parent: def_index_to_node[{:?} <-> {:?}", index, node_id);
594             self.node_to_def_index.insert(node_id, index);
595         }
596
597         if expansion != Mark::root() {
598             self.expansions_that_defined.insert(index, expansion);
599         }
600
601         // The span is added if it isn't dummy
602         if !span.is_dummy() {
603             self.def_index_to_span.insert(index, span);
604         }
605
606         index
607     }
608
609     /// Initialize the `ast::NodeId` to `HirId` mapping once it has been generated during
610     /// AST to HIR lowering.
611     pub fn init_node_id_to_hir_id_mapping(&mut self,
612                                           mapping: IndexVec<ast::NodeId, hir::HirId>) {
613         assert!(self.node_to_hir_id.is_empty(),
614                 "Trying initialize NodeId -> HirId mapping twice");
615         self.node_to_hir_id = mapping;
616     }
617
618     pub fn expansion_that_defined(&self, index: DefIndex) -> Mark {
619         self.expansions_that_defined.get(&index).cloned().unwrap_or(Mark::root())
620     }
621
622     pub fn parent_module_of_macro_def(&self, mark: Mark) -> DefId {
623         self.parent_modules_of_macro_defs[&mark]
624     }
625
626     pub fn add_parent_module_of_macro_def(&mut self, mark: Mark, module: DefId) {
627         self.parent_modules_of_macro_defs.insert(mark, module);
628     }
629 }
630
631 impl DefPathData {
632     pub fn get_opt_name(&self) -> Option<InternedString> {
633         use self::DefPathData::*;
634         match *self {
635             TypeNs(name) |
636             Trait(name) |
637             TraitAlias(name) |
638             AssocTypeInTrait(name) |
639             AssocTypeInImpl(name) |
640             AssocExistentialInImpl(name) |
641             ValueNs(name) |
642             Module(name) |
643             MacroDef(name) |
644             TypeParam(name) |
645             LifetimeParam(name) |
646             ConstParam(name) |
647             EnumVariant(name) |
648             Field(name) |
649             GlobalMetaData(name) => Some(name),
650
651             Impl |
652             CrateRoot |
653             Misc |
654             ClosureExpr |
655             StructCtor |
656             AnonConst |
657             ImplTrait => None
658         }
659     }
660
661     pub fn as_interned_str(&self) -> InternedString {
662         use self::DefPathData::*;
663         let s = match *self {
664             TypeNs(name) |
665             Trait(name) |
666             TraitAlias(name) |
667             AssocTypeInTrait(name) |
668             AssocTypeInImpl(name) |
669             AssocExistentialInImpl(name) |
670             ValueNs(name) |
671             Module(name) |
672             MacroDef(name) |
673             TypeParam(name) |
674             LifetimeParam(name) |
675             ConstParam(name) |
676             EnumVariant(name) |
677             Field(name) |
678             GlobalMetaData(name) => {
679                 return name
680             }
681             // note that this does not show up in user printouts
682             CrateRoot => "{{crate}}",
683             Impl => "{{impl}}",
684             Misc => "{{misc}}",
685             ClosureExpr => "{{closure}}",
686             StructCtor => "{{constructor}}",
687             AnonConst => "{{constant}}",
688             ImplTrait => "{{opaque}}",
689         };
690
691         Symbol::intern(s).as_interned_str()
692     }
693
694     pub fn to_string(&self) -> String {
695         self.as_interned_str().to_string()
696     }
697 }
698
699 macro_rules! count {
700     () => (0usize);
701     ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));
702 }
703
704 // We define the GlobalMetaDataKind enum with this macro because we want to
705 // make sure that we exhaustively iterate over all variants when registering
706 // the corresponding DefIndices in the DefTable.
707 macro_rules! define_global_metadata_kind {
708     (pub enum GlobalMetaDataKind {
709         $($variant:ident),*
710     }) => (
711         #[derive(Clone, Copy, Debug, Hash, RustcEncodable, RustcDecodable)]
712         pub enum GlobalMetaDataKind {
713             $($variant),*
714         }
715
716         const GLOBAL_MD_ADDRESS_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
717         pub const FIRST_FREE_HIGH_DEF_INDEX: usize = count!($($variant)*);
718
719         impl GlobalMetaDataKind {
720             fn allocate_def_indices(definitions: &mut Definitions) {
721                 $({
722                     let instance = GlobalMetaDataKind::$variant;
723                     definitions.create_def_with_parent(
724                         CRATE_DEF_INDEX,
725                         ast::DUMMY_NODE_ID,
726                         DefPathData::GlobalMetaData(instance.name().as_interned_str()),
727                         GLOBAL_MD_ADDRESS_SPACE,
728                         Mark::root(),
729                         DUMMY_SP
730                     );
731
732                     // Make sure calling def_index does not crash.
733                     instance.def_index(&definitions.table);
734                 })*
735             }
736
737             pub fn def_index(&self, def_path_table: &DefPathTable) -> DefIndex {
738                 let def_key = DefKey {
739                     parent: Some(CRATE_DEF_INDEX),
740                     disambiguated_data: DisambiguatedDefPathData {
741                         data: DefPathData::GlobalMetaData(self.name().as_interned_str()),
742                         disambiguator: 0,
743                     }
744                 };
745
746                 // These DefKeys are all right after the root,
747                 // so a linear search is fine.
748                 let index = def_path_table.index_to_key[GLOBAL_MD_ADDRESS_SPACE.index()]
749                                           .iter()
750                                           .position(|k| *k == def_key)
751                                           .unwrap();
752
753                 DefIndex::from_array_index(index, GLOBAL_MD_ADDRESS_SPACE)
754             }
755
756             fn name(&self) -> Symbol {
757
758                 let string = match *self {
759                     $(
760                         GlobalMetaDataKind::$variant => {
761                             concat!("{{GlobalMetaData::", stringify!($variant), "}}")
762                         }
763                     )*
764                 };
765
766                 Symbol::intern(string)
767             }
768         }
769     )
770 }
771
772 define_global_metadata_kind!(pub enum GlobalMetaDataKind {
773     Krate,
774     CrateDeps,
775     DylibDependencyFormats,
776     LangItems,
777     LangItemsMissing,
778     NativeLibraries,
779     SourceMap,
780     Impls,
781     ExportedSymbols
782 });