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 rustc_ast::node_id::NodeMap;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::stable_hasher::StableHasher;
12 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc_index::vec::IndexVec;
14 use rustc_session::CrateDisambiguator;
15 use rustc_span::hygiene::ExpnId;
16 use rustc_span::symbol::{sym, Symbol};
22 pub use rustc_hir::def_id::DefPathHash;
24 /// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa.
25 /// Internally the `DefPathTable` holds a tree of `DefKey`s, where each `DefKey`
26 /// stores the `DefIndex` of its parent.
27 /// There is one `DefPathTable` for each crate.
28 #[derive(Clone, Default, RustcDecodable, RustcEncodable)]
29 pub struct DefPathTable {
30 index_to_key: IndexVec<DefIndex, DefKey>,
31 def_path_hashes: IndexVec<DefIndex, DefPathHash>,
35 fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
37 let index = DefIndex::from(self.index_to_key.len());
38 debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
39 self.index_to_key.push(key);
42 self.def_path_hashes.push(def_path_hash);
43 debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
47 pub fn next_id(&self) -> DefIndex {
48 DefIndex::from(self.index_to_key.len())
52 pub fn def_key(&self, index: DefIndex) -> DefKey {
53 self.index_to_key[index]
57 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
58 let hash = self.def_path_hashes[index];
59 debug!("def_path_hash({:?}) = {:?}", index, hash);
63 pub fn add_def_path_hashes_to(&self, cnum: CrateNum, out: &mut FxHashMap<DefPathHash, DefId>) {
64 out.extend(self.def_path_hashes.iter().enumerate().map(|(index, &hash)| {
65 let def_id = DefId { krate: cnum, index: DefIndex::from(index) };
70 pub fn size(&self) -> usize {
71 self.index_to_key.len()
75 /// The definition table containing node definitions.
76 /// It holds the `DefPathTable` for local `DefId`s/`DefPath`s and it also stores a
77 /// mapping from `NodeId`s to local `DefId`s.
78 #[derive(Clone, Default)]
79 pub struct Definitions {
81 node_to_def_index: NodeMap<DefIndex>,
82 def_index_to_node: IndexVec<DefIndex, ast::NodeId>,
84 pub(super) node_to_hir_id: IndexVec<ast::NodeId, hir::HirId>,
85 /// The reverse mapping of `node_to_hir_id`.
86 pub(super) hir_to_node_id: FxHashMap<hir::HirId, ast::NodeId>,
88 /// If `ExpnId` is an ID of some macro expansion,
89 /// then `DefId` is the normal module (`mod`) in which the expanded macro was defined.
90 parent_modules_of_macro_defs: FxHashMap<ExpnId, DefId>,
91 /// Item with a given `DefIndex` was defined during macro expansion with ID `ExpnId`.
92 expansions_that_defined: FxHashMap<DefIndex, ExpnId>,
93 next_disambiguator: FxHashMap<(DefIndex, DefPathData), u32>,
94 def_index_to_span: FxHashMap<DefIndex, Span>,
95 /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
96 /// we know what parent node that fragment should be attached to thanks to this table.
97 invocation_parents: FxHashMap<ExpnId, DefIndex>,
98 /// Indices of unnamed struct or variant fields with unresolved attributes.
99 placeholder_field_indices: NodeMap<usize>,
102 /// A unique identifier that we can use to lookup a definition
103 /// precisely. It combines the index of the definition's parent (if
104 /// any) with a `DisambiguatedDefPathData`.
105 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
108 pub parent: Option<DefIndex>,
110 /// The identifier of this node.
111 pub disambiguated_data: DisambiguatedDefPathData,
115 fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
116 let mut hasher = StableHasher::new();
118 // We hash a `0u8` here to disambiguate between regular `DefPath` hashes,
119 // and the special "root_parent" below.
120 0u8.hash(&mut hasher);
121 parent_hash.hash(&mut hasher);
123 let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
125 ::std::mem::discriminant(data).hash(&mut hasher);
126 if let Some(name) = data.get_opt_name() {
127 // Get a stable hash by considering the symbol chars rather than
129 name.as_str().hash(&mut hasher);
132 disambiguator.hash(&mut hasher);
134 DefPathHash(hasher.finish())
137 fn root_parent_stable_hash(
139 crate_disambiguator: CrateDisambiguator,
141 let mut hasher = StableHasher::new();
142 // Disambiguate this from a regular `DefPath` hash; see `compute_stable_hash()` above.
143 1u8.hash(&mut hasher);
144 crate_name.hash(&mut hasher);
145 crate_disambiguator.hash(&mut hasher);
146 DefPathHash(hasher.finish())
150 /// A pair of `DefPathData` and an integer disambiguator. The integer is
151 /// normally `0`, but in the event that there are multiple defs with the
152 /// same `parent` and `data`, we use this field to disambiguate
153 /// between them. This introduces some artificial ordering dependency
154 /// but means that if you have, e.g., two impls for the same type in
155 /// the same module, they do get distinct `DefId`s.
156 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
157 pub struct DisambiguatedDefPathData {
158 pub data: DefPathData,
159 pub disambiguator: u32,
162 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
164 /// The path leading from the crate root to the item.
165 pub data: Vec<DisambiguatedDefPathData>,
167 /// The crate root this path is relative to.
172 pub fn is_local(&self) -> bool {
173 self.krate == LOCAL_CRATE
176 pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
178 FN: FnMut(DefIndex) -> DefKey,
180 let mut data = vec![];
181 let mut index = Some(start_index);
183 debug!("DefPath::make: krate={:?} index={:?}", krate, index);
184 let p = index.unwrap();
185 let key = get_key(p);
186 debug!("DefPath::make: key={:?}", key);
187 match key.disambiguated_data.data {
188 DefPathData::CrateRoot => {
189 assert!(key.parent.is_none());
193 data.push(key.disambiguated_data);
199 DefPath { data, krate }
202 /// Returns a string representation of the `DefPath` without
203 /// the crate-prefix. This method is useful if you don't have
204 /// a `TyCtxt` available.
205 pub fn to_string_no_crate(&self) -> String {
206 let mut s = String::with_capacity(self.data.len() * 16);
208 for component in &self.data {
209 write!(s, "::{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
215 /// Returns a filename-friendly string for the `DefPath`, with the
217 pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
219 F: FnOnce(CrateNum) -> Symbol,
221 let crate_name_str = crate_imported_name(self.krate).as_str();
222 let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
224 write!(s, "::{}", crate_name_str).unwrap();
226 for component in &self.data {
227 if component.disambiguator == 0 {
228 write!(s, "::{}", component.data.as_symbol()).unwrap();
230 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
237 /// Returns a filename-friendly string of the `DefPath`, without
238 /// the crate-prefix. This method is useful if you don't have
239 /// a `TyCtxt` available.
240 pub fn to_filename_friendly_no_crate(&self) -> String {
241 let mut s = String::with_capacity(self.data.len() * 16);
243 let mut opt_delimiter = None;
244 for component in &self.data {
245 opt_delimiter.map(|d| s.push(d));
246 opt_delimiter = Some('-');
247 if component.disambiguator == 0 {
248 write!(s, "{}", component.data.as_symbol()).unwrap();
250 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
257 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
258 pub enum DefPathData {
259 // Root: these should only be used for the root nodes, because
260 // they are treated specially by the `def_path` function.
261 /// The crate root (marker).
263 // Catch-all for random `DefId` things like `DUMMY_NODE_ID`.
266 // Different kinds of items and item-like things:
269 /// Something in the type namespace.
271 /// Something in the value namespace.
273 /// Something in the macro namespace.
275 /// Something in the lifetime namespace.
277 /// A closure expression.
280 // Subportions of items:
281 /// Implicit constructor for a unit or tuple-like struct or enum variant.
283 /// A constant expression (see `{ast,hir}::AnonConst`).
285 /// An `impl Trait` type node.
290 pub fn def_path_table(&self) -> &DefPathTable {
294 /// Gets the number of definitions.
295 pub fn def_index_count(&self) -> usize {
296 self.table.index_to_key.len()
299 pub fn def_key(&self, index: DefIndex) -> DefKey {
300 self.table.def_key(index)
304 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
305 self.table.def_path_hash(index)
308 /// Returns the path from the crate root to `index`. The root
309 /// nodes are not included in the path (i.e., this will be an
310 /// empty vector for the crate root). For an inlined item, this
311 /// will be the path of the item in the external crate (but the
312 /// path will begin with the path to the external crate).
313 pub fn def_path(&self, index: DefIndex) -> DefPath {
314 DefPath::make(LOCAL_CRATE, index, |p| self.def_key(p))
318 pub fn opt_def_index(&self, node: ast::NodeId) -> Option<DefIndex> {
319 self.node_to_def_index.get(&node).copied()
323 pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<DefId> {
324 self.opt_def_index(node).map(DefId::local)
328 pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
329 self.opt_local_def_id(node).unwrap()
333 pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
334 if def_id.krate == LOCAL_CRATE {
335 let node_id = self.def_index_to_node[def_id.index];
336 if node_id != ast::DUMMY_NODE_ID {
337 return Some(node_id);
344 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<hir::HirId> {
345 if def_id.krate == LOCAL_CRATE {
346 let hir_id = self.def_index_to_hir_id(def_id.index);
347 if hir_id != hir::DUMMY_HIR_ID { Some(hir_id) } else { None }
354 pub fn hir_to_node_id(&self, hir_id: hir::HirId) -> ast::NodeId {
355 self.hir_to_node_id[&hir_id]
359 pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
360 self.node_to_hir_id[node_id]
364 pub fn def_index_to_hir_id(&self, def_index: DefIndex) -> hir::HirId {
365 let node_id = self.def_index_to_node[def_index];
366 self.node_to_hir_id[node_id]
369 /// Retrieves the span of the given `DefId` if `DefId` is in the local crate, the span exists
370 /// and it's not `DUMMY_SP`.
372 pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
373 if def_id.krate == LOCAL_CRATE {
374 self.def_index_to_span.get(&def_id.index).copied()
380 /// Adds a root definition (no parent) and a few other reserved definitions.
381 pub fn create_root_def(
384 crate_disambiguator: CrateDisambiguator,
388 disambiguated_data: DisambiguatedDefPathData {
389 data: DefPathData::CrateRoot,
394 let parent_hash = DefKey::root_parent_stable_hash(crate_name, crate_disambiguator);
395 let def_path_hash = key.compute_stable_hash(parent_hash);
397 // Create the definition.
398 let root_index = self.table.allocate(key, def_path_hash);
399 assert_eq!(root_index, CRATE_DEF_INDEX);
400 assert!(self.def_index_to_node.is_empty());
401 self.def_index_to_node.push(ast::CRATE_NODE_ID);
402 self.node_to_def_index.insert(ast::CRATE_NODE_ID, root_index);
403 self.set_invocation_parent(ExpnId::root(), root_index);
408 /// Adds a definition with a parent definition.
409 pub fn create_def_with_parent(
412 node_id: ast::NodeId,
418 "create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
419 parent, node_id, data
423 !self.node_to_def_index.contains_key(&node_id),
424 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
427 self.table.def_key(self.node_to_def_index[&node_id])
430 // The root node must be created with `create_root_def()`.
431 assert!(data != DefPathData::CrateRoot);
433 // Find the next free disambiguator for this key.
434 let disambiguator = {
435 let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
436 let disambiguator = *next_disamb;
437 *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
442 parent: Some(parent),
443 disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
446 let parent_hash = self.table.def_path_hash(parent);
447 let def_path_hash = key.compute_stable_hash(parent_hash);
449 debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
451 // Create the definition.
452 let index = self.table.allocate(key, def_path_hash);
453 assert_eq!(index.index(), self.def_index_to_node.len());
454 self.def_index_to_node.push(node_id);
456 // Some things for which we allocate `DefIndex`es don't correspond to
457 // anything in the AST, so they don't have a `NodeId`. For these cases
458 // we don't need a mapping from `NodeId` to `DefIndex`.
459 if node_id != ast::DUMMY_NODE_ID {
460 debug!("create_def_with_parent: def_index_to_node[{:?} <-> {:?}", index, node_id);
461 self.node_to_def_index.insert(node_id, index);
464 if expn_id != ExpnId::root() {
465 self.expansions_that_defined.insert(index, expn_id);
468 // The span is added if it isn't dummy.
469 if !span.is_dummy() {
470 self.def_index_to_span.insert(index, span);
476 /// Initializes the `ast::NodeId` to `HirId` mapping once it has been generated during
477 /// AST to HIR lowering.
478 pub fn init_node_id_to_hir_id_mapping(&mut self, mapping: IndexVec<ast::NodeId, hir::HirId>) {
480 self.node_to_hir_id.is_empty(),
481 "trying to initialize `NodeId` -> `HirId` mapping twice"
483 self.node_to_hir_id = mapping;
485 // Build the reverse mapping of `node_to_hir_id`.
486 self.hir_to_node_id = self
489 .map(|(node_id, &hir_id)| (hir_id, node_id))
493 pub fn expansion_that_defined(&self, index: DefIndex) -> ExpnId {
494 self.expansions_that_defined.get(&index).copied().unwrap_or(ExpnId::root())
497 pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {
498 self.parent_modules_of_macro_defs[&expn_id]
501 pub fn add_parent_module_of_macro_def(&mut self, expn_id: ExpnId, module: DefId) {
502 self.parent_modules_of_macro_defs.insert(expn_id, module);
505 pub fn invocation_parent(&self, invoc_id: ExpnId) -> DefIndex {
506 self.invocation_parents[&invoc_id]
509 pub fn set_invocation_parent(&mut self, invoc_id: ExpnId, parent: DefIndex) {
510 let old_parent = self.invocation_parents.insert(invoc_id, parent);
511 assert!(old_parent.is_none(), "parent `DefIndex` is reset for an invocation");
514 pub fn placeholder_field_index(&self, node_id: ast::NodeId) -> usize {
515 self.placeholder_field_indices[&node_id]
518 pub fn set_placeholder_field_index(&mut self, node_id: ast::NodeId, index: usize) {
519 let old_index = self.placeholder_field_indices.insert(node_id, index);
520 assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
525 pub fn get_opt_name(&self) -> Option<Symbol> {
526 use self::DefPathData::*;
528 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
530 Impl | CrateRoot | Misc | ClosureExpr | Ctor | AnonConst | ImplTrait => None,
534 pub fn as_symbol(&self) -> Symbol {
535 use self::DefPathData::*;
537 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => name,
538 // Note that this does not show up in user print-outs.
539 CrateRoot => sym::double_braced_crate,
540 Impl => sym::double_braced_impl,
541 Misc => sym::double_braced_misc,
542 ClosureExpr => sym::double_braced_closure,
543 Ctor => sym::double_braced_constructor,
544 AnonConst => sym::double_braced_constant,
545 ImplTrait => sym::double_braced_opaque,
549 pub fn to_string(&self) -> String {
550 self.as_symbol().to_string()