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, 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;
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;
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>,
34 fn allocate(&mut self,
36 def_path_hash: DefPathHash)
39 let index = DefIndex::from(self.index_to_key.len());
40 debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
41 self.index_to_key.push(key);
44 self.def_path_hashes.push(def_path_hash);
45 debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
49 pub fn next_id(&self) -> DefIndex {
50 DefIndex::from(self.index_to_key.len())
54 pub fn def_key(&self, index: DefIndex) -> DefKey {
55 self.index_to_key[index.index()].clone()
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);
65 pub fn add_def_path_hashes_to(&self,
67 out: &mut FxHashMap<DefPathHash, DefId>) {
72 .map(|(index, &hash)| {
75 index: DefIndex::from(index),
82 pub fn size(&self) -> usize {
83 self.index_to_key.len()
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 {
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>,
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)]
111 pub parent: Option<DefIndex>,
113 /// The identifier of this node.
114 pub disambiguated_data: DisambiguatedDefPathData,
118 fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
119 let mut hasher = StableHasher::new();
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);
126 let DisambiguatedDefPathData {
129 } = self.disambiguated_data;
131 ::std::mem::discriminant(data).hash(&mut hasher);
132 if let Some(name) = data.get_opt_name() {
133 name.hash(&mut hasher);
136 disambiguator.hash(&mut hasher);
138 DefPathHash(hasher.finish())
141 fn root_parent_stable_hash(crate_name: &str,
142 crate_disambiguator: CrateDisambiguator)
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())
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
166 #[derive(Clone, Debug, Hash, RustcEncodable, RustcDecodable)]
168 /// The path leading from the crate root to the item.
169 pub data: Vec<DisambiguatedDefPathData>,
171 /// The crate root this path is relative to.
176 pub fn is_local(&self) -> bool {
177 self.krate == LOCAL_CRATE
180 pub fn make<FN>(krate: CrateNum,
181 start_index: DefIndex,
182 mut get_key: FN) -> DefPath
183 where FN: FnMut(DefIndex) -> DefKey
185 let mut data = vec![];
186 let mut index = Some(start_index);
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());
198 data.push(key.disambiguated_data);
204 DefPath { data: data, krate: krate }
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);
213 for component in &self.data {
216 component.data.as_interned_str(),
217 component.disambiguator)
224 /// Returns a filename-friendly string for the `DefPath`, with the
226 pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
227 where F: FnOnce(CrateNum) -> Symbol
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);
232 write!(s, "::{}", crate_name_str).unwrap();
234 for component in &self.data {
235 if component.disambiguator == 0 {
236 write!(s, "::{}", component.data.as_interned_str()).unwrap();
240 component.data.as_interned_str(),
241 component.disambiguator)
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);
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();
264 component.data.as_interned_str(),
265 component.disambiguator)
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)
279 // Catch-all for random DefId things like `DUMMY_NODE_ID`
281 // Different kinds of items and item-like things:
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
294 // Subportions of items
295 /// Implicit ctor for a unit or tuple-like struct or enum variant.
297 /// A constant expression (see {ast,hir}::AnonConst).
299 /// An `impl Trait` type node
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),
307 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug,
308 RustcEncodable, RustcDecodable)]
309 pub struct DefPathHash(pub Fingerprint);
311 impl_stable_hash_for!(tuple_struct DefPathHash { fingerprint });
313 impl Borrow<Fingerprint> for DefPathHash {
315 fn borrow(&self) -> &Fingerprint {
321 pub fn def_path_table(&self) -> &DefPathTable {
325 /// Gets the number of definitions.
326 pub fn def_index_count(&self) -> usize {
327 self.table.index_to_key.len()
330 pub fn def_key(&self, index: DefIndex) -> DefKey {
331 self.table.def_key(index)
335 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
336 self.table.def_path_hash(index)
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))
349 pub fn opt_def_index(&self, node: ast::NodeId) -> Option<DefIndex> {
350 self.node_to_def_index.get(&node).cloned()
354 pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<DefId> {
355 self.opt_def_index(node).map(DefId::local)
359 pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
360 self.opt_local_def_id(node).unwrap()
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);
374 // FIXME(@ljedrz): replace the NodeId variant
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 {
390 pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
391 self.node_to_hir_id[node_id]
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]
400 /// Retrieves the span of the given `DefId` if `DefId` is in the local crate, the span exists
401 /// and it's not `DUMMY_SP`.
403 pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
404 if def_id.krate == LOCAL_CRATE {
405 self.def_index_to_span.get(&def_id.index).cloned()
411 /// Adds a root definition (no parent) and a few other reserved definitions.
413 /// After the initial definitions are created the first `FIRST_FREE_DEF_INDEX` indexes
414 /// are taken, so the "user" indexes will be allocated starting with `FIRST_FREE_DEF_INDEX`
415 /// in ascending order.
416 pub fn create_root_def(&mut self,
418 crate_disambiguator: CrateDisambiguator)
422 disambiguated_data: DisambiguatedDefPathData {
423 data: DefPathData::CrateRoot,
428 let parent_hash = DefKey::root_parent_stable_hash(crate_name,
429 crate_disambiguator);
430 let def_path_hash = key.compute_stable_hash(parent_hash);
432 // Create the definition.
433 let root_index = self.table.allocate(key, def_path_hash);
434 assert_eq!(root_index, CRATE_DEF_INDEX);
435 assert!(self.def_index_to_node.is_empty());
436 self.def_index_to_node.push(ast::CRATE_NODE_ID);
437 self.node_to_def_index.insert(ast::CRATE_NODE_ID, root_index);
439 // Allocate some other DefIndices that always must exist.
440 GlobalMetaDataKind::allocate_def_indices(self);
445 /// Adds a definition with a parent definition.
446 pub fn create_def_with_parent(&mut self,
448 node_id: ast::NodeId,
453 debug!("create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
454 parent, node_id, data);
456 assert!(!self.node_to_def_index.contains_key(&node_id),
457 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
460 self.table.def_key(self.node_to_def_index[&node_id]));
462 // The root node must be created with create_root_def()
463 assert!(data != DefPathData::CrateRoot);
465 // Find the next free disambiguator for this key.
466 let disambiguator = {
467 let next_disamb = self.next_disambiguator.entry((parent, data.clone())).or_insert(0);
468 let disambiguator = *next_disamb;
469 *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
474 parent: Some(parent),
475 disambiguated_data: DisambiguatedDefPathData {
480 let parent_hash = self.table.def_path_hash(parent);
481 let def_path_hash = key.compute_stable_hash(parent_hash);
483 debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
485 // Create the definition.
486 let index = self.table.allocate(key, def_path_hash);
487 assert_eq!(index.index(), self.def_index_to_node.len());
488 self.def_index_to_node.push(node_id);
490 // Some things for which we allocate DefIndices don't correspond to
491 // anything in the AST, so they don't have a NodeId. For these cases
492 // we don't need a mapping from NodeId to DefIndex.
493 if node_id != ast::DUMMY_NODE_ID {
494 debug!("create_def_with_parent: def_index_to_node[{:?} <-> {:?}", index, node_id);
495 self.node_to_def_index.insert(node_id, index);
498 if expansion != Mark::root() {
499 self.expansions_that_defined.insert(index, expansion);
502 // The span is added if it isn't dummy
503 if !span.is_dummy() {
504 self.def_index_to_span.insert(index, span);
510 /// Initialize the `ast::NodeId` to `HirId` mapping once it has been generated during
511 /// AST to HIR lowering.
512 pub fn init_node_id_to_hir_id_mapping(&mut self,
513 mapping: IndexVec<ast::NodeId, hir::HirId>) {
514 assert!(self.node_to_hir_id.is_empty(),
515 "Trying initialize NodeId -> HirId mapping twice");
516 self.node_to_hir_id = mapping;
519 pub fn expansion_that_defined(&self, index: DefIndex) -> Mark {
520 self.expansions_that_defined.get(&index).cloned().unwrap_or(Mark::root())
523 pub fn parent_module_of_macro_def(&self, mark: Mark) -> DefId {
524 self.parent_modules_of_macro_defs[&mark]
527 pub fn add_parent_module_of_macro_def(&mut self, mark: Mark, module: DefId) {
528 self.parent_modules_of_macro_defs.insert(mark, module);
533 pub fn get_opt_name(&self) -> Option<InternedString> {
534 use self::DefPathData::*;
540 GlobalMetaData(name) => Some(name),
552 pub fn as_interned_str(&self) -> InternedString {
553 use self::DefPathData::*;
554 let s = match *self {
559 GlobalMetaData(name) => {
562 // Note that this does not show up in user print-outs.
563 CrateRoot => sym::double_braced_crate,
564 Impl => sym::double_braced_impl,
565 Misc => sym::double_braced_misc,
566 ClosureExpr => sym::double_braced_closure,
567 Ctor => sym::double_braced_constructor,
568 AnonConst => sym::double_braced_constant,
569 ImplTrait => sym::double_braced_opaque,
575 pub fn to_string(&self) -> String {
576 self.as_interned_str().to_string()
580 /// Evaluates to the number of tokens passed to it.
582 /// Logarithmic counting: every one or two recursive expansions, the number of
583 /// tokens to count is divided by two, instead of being reduced by one.
584 /// Therefore, the recursion depth is the binary logarithm of the number of
585 /// tokens to count, and the expanded tree is likewise very small.
588 ($one:tt) => (1usize);
589 ($($pairs:tt $_p:tt)*) => (count!($($pairs)*) << 1usize);
590 ($odd:tt $($rest:tt)*) => (count!($($rest)*) | 1usize);
593 // We define the GlobalMetaDataKind enum with this macro because we want to
594 // make sure that we exhaustively iterate over all variants when registering
595 // the corresponding DefIndices in the DefTable.
596 macro_rules! define_global_metadata_kind {
597 (pub enum GlobalMetaDataKind {
600 #[derive(Clone, Copy, Debug, Hash, RustcEncodable, RustcDecodable)]
601 pub enum GlobalMetaDataKind {
605 pub const FIRST_FREE_DEF_INDEX: usize = 1 + count!($($variant)*);
607 impl GlobalMetaDataKind {
608 fn allocate_def_indices(definitions: &mut Definitions) {
610 let instance = GlobalMetaDataKind::$variant;
611 definitions.create_def_with_parent(
614 DefPathData::GlobalMetaData(instance.name().as_interned_str()),
619 // Make sure calling def_index does not crash.
620 instance.def_index(&definitions.table);
624 pub fn def_index(&self, def_path_table: &DefPathTable) -> DefIndex {
625 let def_key = DefKey {
626 parent: Some(CRATE_DEF_INDEX),
627 disambiguated_data: DisambiguatedDefPathData {
628 data: DefPathData::GlobalMetaData(self.name().as_interned_str()),
633 // These DefKeys are all right after the root,
634 // so a linear search is fine.
635 let index = def_path_table.index_to_key
637 .position(|k| *k == def_key)
640 DefIndex::from(index)
643 fn name(&self) -> Symbol {
645 let string = match *self {
647 GlobalMetaDataKind::$variant => {
648 concat!("{{GlobalMetaData::", stringify!($variant), "}}")
653 Symbol::intern(string)
659 define_global_metadata_kind!(pub enum GlobalMetaDataKind {
662 DylibDependencyFormats,