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.
7 use crate::ich::Fingerprint;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_data_structures::stable_hasher::StableHasher;
11 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_index::vec::IndexVec;
13 use rustc_session::node_id::NodeMap;
14 use rustc_session::CrateDisambiguator;
15 use rustc_span::hygiene::ExpnId;
16 use rustc_span::symbol::{sym, Symbol};
18 use std::borrow::Borrow;
23 /// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa.
24 /// Internally the `DefPathTable` holds a tree of `DefKey`s, 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: IndexVec<DefIndex, DefKey>,
30 def_path_hashes: IndexVec<DefIndex, DefPathHash>,
34 fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
36 let index = DefIndex::from(self.index_to_key.len());
37 debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
38 self.index_to_key.push(key);
41 self.def_path_hashes.push(def_path_hash);
42 debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
46 pub fn next_id(&self) -> DefIndex {
47 DefIndex::from(self.index_to_key.len())
51 pub fn def_key(&self, index: DefIndex) -> DefKey {
52 self.index_to_key[index]
56 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
57 let hash = self.def_path_hashes[index];
58 debug!("def_path_hash({:?}) = {:?}", index, hash);
62 pub fn add_def_path_hashes_to(&self, cnum: CrateNum, out: &mut FxHashMap<DefPathHash, DefId>) {
63 out.extend(self.def_path_hashes.iter().enumerate().map(|(index, &hash)| {
64 let def_id = DefId { krate: cnum, index: DefIndex::from(index) };
69 pub fn size(&self) -> usize {
70 self.index_to_key.len()
74 /// The definition table containing node definitions.
75 /// It holds the `DefPathTable` for local `DefId`s/`DefPath`s and it also stores a
76 /// mapping from `NodeId`s to local `DefId`s.
77 #[derive(Clone, Default)]
78 pub struct Definitions {
80 node_to_def_index: NodeMap<DefIndex>,
81 def_index_to_node: IndexVec<DefIndex, ast::NodeId>,
82 pub(super) node_to_hir_id: IndexVec<ast::NodeId, hir::HirId>,
83 /// If `ExpnId` is an ID of some macro expansion,
84 /// then `DefId` is the normal module (`mod`) in which the expanded macro was defined.
85 parent_modules_of_macro_defs: FxHashMap<ExpnId, DefId>,
86 /// Item with a given `DefIndex` was defined during macro expansion with ID `ExpnId`.
87 expansions_that_defined: FxHashMap<DefIndex, ExpnId>,
88 next_disambiguator: FxHashMap<(DefIndex, DefPathData), u32>,
89 def_index_to_span: FxHashMap<DefIndex, Span>,
90 /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
91 /// we know what parent node that fragment should be attached to thanks to this table.
92 invocation_parents: FxHashMap<ExpnId, DefIndex>,
93 /// Indices of unnamed struct or variant fields with unresolved attributes.
94 placeholder_field_indices: NodeMap<usize>,
97 /// A unique identifier that we can use to lookup a definition
98 /// precisely. It combines the index of the definition's parent (if
99 /// any) with a `DisambiguatedDefPathData`.
100 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
103 pub parent: Option<DefIndex>,
105 /// The identifier of this node.
106 pub disambiguated_data: DisambiguatedDefPathData,
110 fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
111 let mut hasher = StableHasher::new();
113 // We hash a `0u8` here to disambiguate between regular `DefPath` hashes,
114 // and the special "root_parent" below.
115 0u8.hash(&mut hasher);
116 parent_hash.hash(&mut hasher);
118 let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
120 ::std::mem::discriminant(data).hash(&mut hasher);
121 if let Some(name) = data.get_opt_name() {
122 // Get a stable hash by considering the symbol chars rather than
124 name.as_str().hash(&mut hasher);
127 disambiguator.hash(&mut hasher);
129 DefPathHash(hasher.finish())
132 fn root_parent_stable_hash(
134 crate_disambiguator: CrateDisambiguator,
136 let mut hasher = StableHasher::new();
137 // Disambiguate this from a regular `DefPath` hash; see `compute_stable_hash()` above.
138 1u8.hash(&mut hasher);
139 crate_name.hash(&mut hasher);
140 crate_disambiguator.hash(&mut hasher);
141 DefPathHash(hasher.finish())
145 /// A pair of `DefPathData` and an integer disambiguator. The integer is
146 /// normally `0`, but in the event that there are multiple defs with the
147 /// same `parent` and `data`, we use this field to disambiguate
148 /// between them. This introduces some artificial ordering dependency
149 /// but means that if you have, e.g., two impls for the same type in
150 /// the same module, they do get distinct `DefId`s.
151 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
152 pub struct DisambiguatedDefPathData {
153 pub data: DefPathData,
154 pub disambiguator: u32,
157 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
159 /// The path leading from the crate root to the item.
160 pub data: Vec<DisambiguatedDefPathData>,
162 /// The crate root this path is relative to.
167 pub fn is_local(&self) -> bool {
168 self.krate == LOCAL_CRATE
171 pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
173 FN: FnMut(DefIndex) -> DefKey,
175 let mut data = vec![];
176 let mut index = Some(start_index);
178 debug!("DefPath::make: krate={:?} index={:?}", krate, index);
179 let p = index.unwrap();
180 let key = get_key(p);
181 debug!("DefPath::make: key={:?}", key);
182 match key.disambiguated_data.data {
183 DefPathData::CrateRoot => {
184 assert!(key.parent.is_none());
188 data.push(key.disambiguated_data);
194 DefPath { data: data, krate: krate }
197 /// Returns a string representation of the `DefPath` without
198 /// the crate-prefix. This method is useful if you don't have
199 /// a `TyCtxt` available.
200 pub fn to_string_no_crate(&self) -> String {
201 let mut s = String::with_capacity(self.data.len() * 16);
203 for component in &self.data {
204 write!(s, "::{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
210 /// Returns a filename-friendly string for the `DefPath`, with the
212 pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
214 F: FnOnce(CrateNum) -> Symbol,
216 let crate_name_str = crate_imported_name(self.krate).as_str();
217 let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
219 write!(s, "::{}", crate_name_str).unwrap();
221 for component in &self.data {
222 if component.disambiguator == 0 {
223 write!(s, "::{}", component.data.as_symbol()).unwrap();
225 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
232 /// Returns a filename-friendly string of the `DefPath`, without
233 /// the crate-prefix. This method is useful if you don't have
234 /// a `TyCtxt` available.
235 pub fn to_filename_friendly_no_crate(&self) -> String {
236 let mut s = String::with_capacity(self.data.len() * 16);
238 let mut opt_delimiter = None;
239 for component in &self.data {
240 opt_delimiter.map(|d| s.push(d));
241 opt_delimiter = Some('-');
242 if component.disambiguator == 0 {
243 write!(s, "{}", component.data.as_symbol()).unwrap();
245 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
252 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
253 pub enum DefPathData {
254 // Root: these should only be used for the root nodes, because
255 // they are treated specially by the `def_path` function.
256 /// The crate root (marker).
258 // Catch-all for random `DefId` things like `DUMMY_NODE_ID`.
261 // Different kinds of items and item-like things:
264 /// Something in the type namespace.
266 /// Something in the value namespace.
268 /// Something in the macro namespace.
270 /// Something in the lifetime namespace.
272 /// A closure expression.
275 // Subportions of items:
276 /// Implicit constructor for a unit or tuple-like struct or enum variant.
278 /// A constant expression (see `{ast,hir}::AnonConst`).
280 /// An `impl Trait` type node.
297 pub struct DefPathHash(pub Fingerprint);
299 impl Borrow<Fingerprint> for DefPathHash {
301 fn borrow(&self) -> &Fingerprint {
307 pub fn def_path_table(&self) -> &DefPathTable {
311 /// Gets the number of definitions.
312 pub fn def_index_count(&self) -> usize {
313 self.table.index_to_key.len()
316 pub fn def_key(&self, index: DefIndex) -> DefKey {
317 self.table.def_key(index)
321 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
322 self.table.def_path_hash(index)
325 /// Returns the path from the crate root to `index`. The root
326 /// nodes are not included in the path (i.e., this will be an
327 /// empty vector for the crate root). For an inlined item, this
328 /// will be the path of the item in the external crate (but the
329 /// path will begin with the path to the external crate).
330 pub fn def_path(&self, index: DefIndex) -> DefPath {
331 DefPath::make(LOCAL_CRATE, index, |p| self.def_key(p))
335 pub fn opt_def_index(&self, node: ast::NodeId) -> Option<DefIndex> {
336 self.node_to_def_index.get(&node).copied()
340 pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<DefId> {
341 self.opt_def_index(node).map(DefId::local)
345 pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
346 self.opt_local_def_id(node).unwrap()
350 pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
351 if def_id.krate == LOCAL_CRATE {
352 let node_id = self.def_index_to_node[def_id.index];
353 if node_id != ast::DUMMY_NODE_ID {
354 return Some(node_id);
361 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<hir::HirId> {
362 if def_id.krate == LOCAL_CRATE {
363 let hir_id = self.def_index_to_hir_id(def_id.index);
364 if hir_id != hir::DUMMY_HIR_ID { Some(hir_id) } else { None }
371 pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
372 self.node_to_hir_id[node_id]
376 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> hir::HirId {
377 let node_id = self.def_index_to_node[def_index];
378 self.node_to_hir_id[node_id]
381 /// Retrieves the span of the given `DefId` if `DefId` is in the local crate, the span exists
382 /// and it's not `DUMMY_SP`.
384 pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
385 if def_id.krate == LOCAL_CRATE {
386 self.def_index_to_span.get(&def_id.index).copied()
392 /// Adds a root definition (no parent) and a few other reserved definitions.
393 pub fn create_root_def(
396 crate_disambiguator: CrateDisambiguator,
400 disambiguated_data: DisambiguatedDefPathData {
401 data: DefPathData::CrateRoot,
406 let parent_hash = DefKey::root_parent_stable_hash(crate_name, crate_disambiguator);
407 let def_path_hash = key.compute_stable_hash(parent_hash);
409 // Create the definition.
410 let root_index = self.table.allocate(key, def_path_hash);
411 assert_eq!(root_index, CRATE_DEF_INDEX);
412 assert!(self.def_index_to_node.is_empty());
413 self.def_index_to_node.push(ast::CRATE_NODE_ID);
414 self.node_to_def_index.insert(ast::CRATE_NODE_ID, root_index);
415 self.set_invocation_parent(ExpnId::root(), root_index);
420 /// Adds a definition with a parent definition.
421 pub fn create_def_with_parent(
424 node_id: ast::NodeId,
430 "create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
431 parent, node_id, data
435 !self.node_to_def_index.contains_key(&node_id),
436 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
439 self.table.def_key(self.node_to_def_index[&node_id])
442 // The root node must be created with `create_root_def()`.
443 assert!(data != DefPathData::CrateRoot);
445 // Find the next free disambiguator for this key.
446 let disambiguator = {
447 let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
448 let disambiguator = *next_disamb;
449 *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
454 parent: Some(parent),
455 disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
458 let parent_hash = self.table.def_path_hash(parent);
459 let def_path_hash = key.compute_stable_hash(parent_hash);
461 debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
463 // Create the definition.
464 let index = self.table.allocate(key, def_path_hash);
465 assert_eq!(index.index(), self.def_index_to_node.len());
466 self.def_index_to_node.push(node_id);
468 // Some things for which we allocate `DefIndex`es don't correspond to
469 // anything in the AST, so they don't have a `NodeId`. For these cases
470 // we don't need a mapping from `NodeId` to `DefIndex`.
471 if node_id != ast::DUMMY_NODE_ID {
472 debug!("create_def_with_parent: def_index_to_node[{:?} <-> {:?}", index, node_id);
473 self.node_to_def_index.insert(node_id, index);
476 if expn_id != ExpnId::root() {
477 self.expansions_that_defined.insert(index, expn_id);
480 // The span is added if it isn't dummy.
481 if !span.is_dummy() {
482 self.def_index_to_span.insert(index, span);
488 /// Initializes the `ast::NodeId` to `HirId` mapping once it has been generated during
489 /// AST to HIR lowering.
490 pub fn init_node_id_to_hir_id_mapping(&mut self, mapping: IndexVec<ast::NodeId, hir::HirId>) {
492 self.node_to_hir_id.is_empty(),
493 "trying to initialize `NodeId` -> `HirId` mapping twice"
495 self.node_to_hir_id = mapping;
498 pub fn expansion_that_defined(&self, index: DefIndex) -> ExpnId {
499 self.expansions_that_defined.get(&index).copied().unwrap_or(ExpnId::root())
502 pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {
503 self.parent_modules_of_macro_defs[&expn_id]
506 pub fn add_parent_module_of_macro_def(&mut self, expn_id: ExpnId, module: DefId) {
507 self.parent_modules_of_macro_defs.insert(expn_id, module);
510 pub fn invocation_parent(&self, invoc_id: ExpnId) -> DefIndex {
511 self.invocation_parents[&invoc_id]
514 pub fn set_invocation_parent(&mut self, invoc_id: ExpnId, parent: DefIndex) {
515 let old_parent = self.invocation_parents.insert(invoc_id, parent);
516 assert!(old_parent.is_none(), "parent `DefIndex` is reset for an invocation");
519 pub fn placeholder_field_index(&self, node_id: ast::NodeId) -> usize {
520 self.placeholder_field_indices[&node_id]
523 pub fn set_placeholder_field_index(&mut self, node_id: ast::NodeId, index: usize) {
524 let old_index = self.placeholder_field_indices.insert(node_id, index);
525 assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
530 pub fn get_opt_name(&self) -> Option<Symbol> {
531 use self::DefPathData::*;
533 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
535 Impl | CrateRoot | Misc | ClosureExpr | Ctor | AnonConst | ImplTrait => None,
539 pub fn as_symbol(&self) -> Symbol {
540 use self::DefPathData::*;
542 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => name,
543 // Note that this does not show up in user print-outs.
544 CrateRoot => sym::double_braced_crate,
545 Impl => sym::double_braced_impl,
546 Misc => sym::double_braced_misc,
547 ClosureExpr => sym::double_braced_closure,
548 Ctor => sym::double_braced_constructor,
549 AnonConst => sym::double_braced_constant,
550 ImplTrait => sym::double_braced_opaque,
554 pub fn to_string(&self) -> String {
555 self.as_symbol().to_string()