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.
8 use crate::hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, DefIndexAddressSpace,
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;
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;
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.
30 pub struct DefPathTable {
31 index_to_key: [Vec<DefKey>; 2],
32 def_path_hashes: [Vec<DefPathHash>; 2],
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 {
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()],
50 fn allocate(&mut self,
52 def_path_hash: DefPathHash,
53 address_space: DefIndexAddressSpace)
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);
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());
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)
73 pub fn def_key(&self, index: DefIndex) -> DefKey {
74 self.index_to_key[index.address_space().index()]
75 [index.as_array_index()].clone()
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);
86 pub fn add_def_path_hashes_to(&self,
88 out: &mut FxHashMap<DefPathHash, DefId>) {
89 for &address_space in &[DefIndexAddressSpace::Low, DefIndexAddressSpace::High] {
91 (&self.def_path_hashes[address_space.index()])
94 .map(|(index, &hash)| {
97 index: DefIndex::from_array_index(index, address_space),
105 pub fn size(&self) -> usize {
106 self.index_to_key.iter().map(|v| v.len()).sum()
111 impl Encodable for DefPathTable {
112 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
114 self.index_to_key[DefIndexAddressSpace::Low.index()].encode(s)?;
115 self.index_to_key[DefIndexAddressSpace::High.index()].encode(s)?;
118 self.def_path_hashes[DefIndexAddressSpace::Low.index()].encode(s)?;
119 self.def_path_hashes[DefIndexAddressSpace::High.index()].encode(s)?;
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)?;
130 let def_path_hashes_lo: Vec<DefPathHash> = Decodable::decode(d)?;
131 let def_path_hashes_hi: Vec<DefPathHash> = Decodable::decode(d)?;
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];
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 {
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>,
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)]
167 pub parent: Option<DefIndex>,
169 /// The identifier of this node.
170 pub disambiguated_data: DisambiguatedDefPathData,
174 fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
175 let mut hasher = StableHasher::new();
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);
182 let DisambiguatedDefPathData {
185 } = self.disambiguated_data;
187 ::std::mem::discriminant(data).hash(&mut hasher);
188 if let Some(name) = data.get_opt_name() {
189 name.hash(&mut hasher);
192 disambiguator.hash(&mut hasher);
194 DefPathHash(hasher.finish())
197 fn root_parent_stable_hash(crate_name: &str,
198 crate_disambiguator: CrateDisambiguator)
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())
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
222 #[derive(Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
224 /// The path leading from the crate root to the item.
225 pub data: Vec<DisambiguatedDefPathData>,
227 /// The crate root this path is relative to.
232 pub fn is_local(&self) -> bool {
233 self.krate == LOCAL_CRATE
236 pub fn make<FN>(krate: CrateNum,
237 start_index: DefIndex,
238 mut get_key: FN) -> DefPath
239 where FN: FnMut(DefIndex) -> DefKey
241 let mut data = vec![];
242 let mut index = Some(start_index);
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());
254 data.push(key.disambiguated_data);
260 DefPath { data: data, krate: krate }
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);
269 for component in &self.data {
272 component.data.as_interned_str(),
273 component.disambiguator)
280 /// Returns a filename-friendly string for the `DefPath`, with the
282 pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
283 where F: FnOnce(CrateNum) -> Symbol
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);
288 write!(s, "::{}", crate_name_str).unwrap();
290 for component in &self.data {
291 if component.disambiguator == 0 {
292 write!(s, "::{}", component.data.as_interned_str()).unwrap();
296 component.data.as_interned_str(),
297 component.disambiguator)
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);
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();
320 component.data.as_interned_str(),
321 component.disambiguator)
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)
335 // Catch-all for random DefId things like DUMMY_NODE_ID
337 // Different kinds of items and item-like things:
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),
355 MacroDef(InternedString),
356 /// A closure expression
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),
368 Field(InternedString),
369 /// Implicit ctor for a tuple-like struct
371 /// A constant expression (see {ast,hir}::AnonConst).
373 /// An `impl Trait` type node
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),
380 TraitAlias(InternedString),
383 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug,
384 RustcEncodable, RustcDecodable)]
385 pub struct DefPathHash(pub Fingerprint);
387 impl_stable_hash_for!(tuple_struct DefPathHash { fingerprint });
389 impl Borrow<Fingerprint> for DefPathHash {
391 fn borrow(&self) -> &Fingerprint {
397 /// Creates new empty definition map.
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
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
408 // FIXME: there is probably a better place to put this comment.
409 pub fn new() -> Self {
413 pub fn def_path_table(&self) -> &DefPathTable {
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())
423 pub fn def_key(&self, index: DefIndex) -> DefKey {
424 self.table.def_key(index)
428 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
429 self.table.def_path_hash(index)
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))
442 pub fn opt_def_index(&self, node: ast::NodeId) -> Option<DefIndex> {
443 self.node_to_def_index.get(&node).cloned()
447 pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<DefId> {
448 self.opt_def_index(node).map(DefId::local)
452 pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
453 self.opt_local_def_id(node).unwrap()
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 {
472 // FIXME(@ljedrz): replace the NodeId variant
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 {
488 pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
489 self.node_to_hir_id[node_id]
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]
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`.
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()
511 /// Adds a root definition (no parent).
512 pub fn create_root_def(&mut self,
514 crate_disambiguator: CrateDisambiguator)
518 disambiguated_data: DisambiguatedDefPathData {
519 data: DefPathData::CrateRoot,
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);
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);
536 // Allocate some other DefIndices that always must exist.
537 GlobalMetaDataKind::allocate_def_indices(self);
542 /// Add a definition with a parent definition.
543 pub fn create_def_with_parent(&mut self,
545 node_id: ast::NodeId,
547 address_space: DefIndexAddressSpace,
551 debug!("create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
552 parent, node_id, data);
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: {:?}",
558 self.table.def_key(self.node_to_def_index[&node_id]));
560 // The root node must be created with create_root_def()
561 assert!(data != DefPathData::CrateRoot);
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");
572 parent: Some(parent),
573 disambiguated_data: DisambiguatedDefPathData {
578 let parent_hash = self.table.def_path_hash(parent);
579 let def_path_hash = key.compute_stable_hash(parent_hash);
581 debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
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);
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);
597 if expansion != Mark::root() {
598 self.expansions_that_defined.insert(index, expansion);
601 // The span is added if it isn't dummy
602 if !span.is_dummy() {
603 self.def_index_to_span.insert(index, span);
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;
618 pub fn expansion_that_defined(&self, index: DefIndex) -> Mark {
619 self.expansions_that_defined.get(&index).cloned().unwrap_or(Mark::root())
622 pub fn parent_module_of_macro_def(&self, mark: Mark) -> DefId {
623 self.parent_modules_of_macro_defs[&mark]
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);
632 pub fn get_opt_name(&self) -> Option<InternedString> {
633 use self::DefPathData::*;
638 AssocTypeInTrait(name) |
639 AssocTypeInImpl(name) |
640 AssocExistentialInImpl(name) |
645 LifetimeParam(name) |
649 GlobalMetaData(name) => Some(name),
661 pub fn as_interned_str(&self) -> InternedString {
662 use self::DefPathData::*;
663 let s = match *self {
667 AssocTypeInTrait(name) |
668 AssocTypeInImpl(name) |
669 AssocExistentialInImpl(name) |
674 LifetimeParam(name) |
678 GlobalMetaData(name) => {
681 // note that this does not show up in user printouts
682 CrateRoot => "{{crate}}",
685 ClosureExpr => "{{closure}}",
686 StructCtor => "{{constructor}}",
687 AnonConst => "{{constant}}",
688 ImplTrait => "{{opaque}}",
691 Symbol::intern(s).as_interned_str()
694 pub fn to_string(&self) -> String {
695 self.as_interned_str().to_string()
701 ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));
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 {
711 #[derive(Clone, Copy, Debug, Hash, RustcEncodable, RustcDecodable)]
712 pub enum GlobalMetaDataKind {
716 const GLOBAL_MD_ADDRESS_SPACE: DefIndexAddressSpace = DefIndexAddressSpace::High;
717 pub const FIRST_FREE_HIGH_DEF_INDEX: usize = count!($($variant)*);
719 impl GlobalMetaDataKind {
720 fn allocate_def_indices(definitions: &mut Definitions) {
722 let instance = GlobalMetaDataKind::$variant;
723 definitions.create_def_with_parent(
726 DefPathData::GlobalMetaData(instance.name().as_interned_str()),
727 GLOBAL_MD_ADDRESS_SPACE,
732 // Make sure calling def_index does not crash.
733 instance.def_index(&definitions.table);
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()),
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()]
750 .position(|k| *k == def_key)
753 DefIndex::from_array_index(index, GLOBAL_MD_ADDRESS_SPACE)
756 fn name(&self) -> Symbol {
758 let string = match *self {
760 GlobalMetaDataKind::$variant => {
761 concat!("{{GlobalMetaData::", stringify!($variant), "}}")
766 Symbol::intern(string)
772 define_global_metadata_kind!(pub enum GlobalMetaDataKind {
775 DylibDependencyFormats,