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_data_structures::fx::FxHashMap;
9 use rustc_data_structures::stable_hasher::StableHasher;
11 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_index::vec::IndexVec;
13 use rustc_session::CrateDisambiguator;
14 use rustc_span::hygiene::ExpnId;
15 use rustc_span::symbol::{sym, Symbol};
21 pub use rustc_hir::def_id::DefPathHash;
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 {
81 def_id_to_span: IndexVec<LocalDefId, Span>,
83 // FIXME(eddyb) don't go through `ast::NodeId` to convert between `HirId`
84 // and `LocalDefId` - ideally all `LocalDefId`s would be HIR owners.
85 node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
86 def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
88 pub(super) node_id_to_hir_id: IndexVec<ast::NodeId, hir::HirId>,
89 /// The reverse mapping of `node_id_to_hir_id`.
90 pub(super) hir_id_to_node_id: FxHashMap<hir::HirId, ast::NodeId>,
92 /// If `ExpnId` is an ID of some macro expansion,
93 /// then `DefId` is the normal module (`mod`) in which the expanded macro was defined.
94 parent_modules_of_macro_defs: FxHashMap<ExpnId, DefId>,
95 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
96 expansions_that_defined: FxHashMap<LocalDefId, ExpnId>,
97 next_disambiguator: FxHashMap<(LocalDefId, DefPathData), u32>,
98 /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
99 /// we know what parent node that fragment should be attached to thanks to this table.
100 invocation_parents: FxHashMap<ExpnId, LocalDefId>,
101 /// Indices of unnamed struct or variant fields with unresolved attributes.
102 placeholder_field_indices: FxHashMap<ast::NodeId, usize>,
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(Copy, Clone, PartialEq, Debug, 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 { ref data, disambiguator } = self.disambiguated_data;
128 ::std::mem::discriminant(data).hash(&mut hasher);
129 if let Some(name) = data.get_opt_name() {
130 // Get a stable hash by considering the symbol chars rather than
132 name.as_str().hash(&mut hasher);
135 disambiguator.hash(&mut hasher);
137 DefPathHash(hasher.finish())
140 fn root_parent_stable_hash(
142 crate_disambiguator: CrateDisambiguator,
144 let mut hasher = StableHasher::new();
145 // Disambiguate this from a regular `DefPath` hash; see `compute_stable_hash()` above.
146 1u8.hash(&mut hasher);
147 crate_name.hash(&mut hasher);
148 crate_disambiguator.hash(&mut hasher);
149 DefPathHash(hasher.finish())
153 /// A pair of `DefPathData` and an integer disambiguator. The integer is
154 /// normally `0`, but in the event that there are multiple defs with the
155 /// same `parent` and `data`, we use this field to disambiguate
156 /// between them. This introduces some artificial ordering dependency
157 /// but means that if you have, e.g., two impls for the same type in
158 /// the same module, they do get distinct `DefId`s.
159 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
160 pub struct DisambiguatedDefPathData {
161 pub data: DefPathData,
162 pub disambiguator: u32,
165 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
167 /// The path leading from the crate root to the item.
168 pub data: Vec<DisambiguatedDefPathData>,
170 /// The crate root this path is relative to.
175 pub fn is_local(&self) -> bool {
176 self.krate == LOCAL_CRATE
179 pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
181 FN: FnMut(DefIndex) -> DefKey,
183 let mut data = vec![];
184 let mut index = Some(start_index);
186 debug!("DefPath::make: krate={:?} index={:?}", krate, index);
187 let p = index.unwrap();
188 let key = get_key(p);
189 debug!("DefPath::make: key={:?}", key);
190 match key.disambiguated_data.data {
191 DefPathData::CrateRoot => {
192 assert!(key.parent.is_none());
196 data.push(key.disambiguated_data);
202 DefPath { data, krate }
205 /// Returns a string representation of the `DefPath` without
206 /// the crate-prefix. This method is useful if you don't have
207 /// a `TyCtxt` available.
208 pub fn to_string_no_crate(&self) -> String {
209 let mut s = String::with_capacity(self.data.len() * 16);
211 for component in &self.data {
212 write!(s, "::{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
218 /// Returns a filename-friendly string for the `DefPath`, with the
220 pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
222 F: FnOnce(CrateNum) -> Symbol,
224 let crate_name_str = crate_imported_name(self.krate).as_str();
225 let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
227 write!(s, "::{}", crate_name_str).unwrap();
229 for component in &self.data {
230 if component.disambiguator == 0 {
231 write!(s, "::{}", component.data.as_symbol()).unwrap();
233 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
240 /// Returns a filename-friendly string of the `DefPath`, without
241 /// the crate-prefix. This method is useful if you don't have
242 /// a `TyCtxt` available.
243 pub fn to_filename_friendly_no_crate(&self) -> String {
244 let mut s = String::with_capacity(self.data.len() * 16);
246 let mut opt_delimiter = None;
247 for component in &self.data {
248 opt_delimiter.map(|d| s.push(d));
249 opt_delimiter = Some('-');
250 if component.disambiguator == 0 {
251 write!(s, "{}", component.data.as_symbol()).unwrap();
253 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
260 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
261 pub enum DefPathData {
262 // Root: these should only be used for the root nodes, because
263 // they are treated specially by the `def_path` function.
264 /// The crate root (marker).
266 // Catch-all for random `DefId` things like `DUMMY_NODE_ID`.
269 // Different kinds of items and item-like things:
272 /// Something in the type namespace.
274 /// Something in the value namespace.
276 /// Something in the macro namespace.
278 /// Something in the lifetime namespace.
280 /// A closure expression.
283 // Subportions of items:
284 /// Implicit constructor for a unit or tuple-like struct or enum variant.
286 /// A constant expression (see `{ast,hir}::AnonConst`).
288 /// An `impl Trait` type node.
293 pub fn def_path_table(&self) -> &DefPathTable {
297 /// Gets the number of definitions.
298 pub fn def_index_count(&self) -> usize {
299 self.table.index_to_key.len()
302 pub fn def_key(&self, id: LocalDefId) -> DefKey {
303 self.table.def_key(id.local_def_index)
307 pub fn def_path_hash(&self, id: LocalDefId) -> DefPathHash {
308 self.table.def_path_hash(id.local_def_index)
311 /// Returns the path from the crate root to `index`. The root
312 /// nodes are not included in the path (i.e., this will be an
313 /// empty vector for the crate root). For an inlined item, this
314 /// will be the path of the item in the external crate (but the
315 /// path will begin with the path to the external crate).
316 pub fn def_path(&self, id: LocalDefId) -> DefPath {
317 DefPath::make(LOCAL_CRATE, id.local_def_index, |index| {
318 self.def_key(LocalDefId { local_def_index: index })
323 pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<LocalDefId> {
324 self.node_id_to_def_id.get(&node).copied()
327 // FIXME(eddyb) this function can and should return `LocalDefId`.
329 pub fn local_def_id(&self, node: ast::NodeId) -> DefId {
330 self.opt_local_def_id(node).unwrap().to_def_id()
334 pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
335 if let Some(def_id) = def_id.as_local() {
336 let node_id = self.def_id_to_node_id[def_id];
337 if node_id != ast::DUMMY_NODE_ID {
338 return Some(node_id);
345 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<hir::HirId> {
346 if let Some(def_id) = def_id.as_local() {
347 let hir_id = self.local_def_id_to_hir_id(def_id);
348 if hir_id != hir::DUMMY_HIR_ID { Some(hir_id) } else { None }
354 // FIXME(eddyb) rename to `hir_id_to_node_id`.
356 pub fn hir_to_node_id(&self, hir_id: hir::HirId) -> ast::NodeId {
357 self.hir_id_to_node_id[&hir_id]
360 // FIXME(eddyb) rename to `node_id_to_hir_id`.
362 pub fn node_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
363 self.node_id_to_hir_id[node_id]
367 pub fn local_def_id_to_hir_id(&self, id: LocalDefId) -> hir::HirId {
368 let node_id = self.def_id_to_node_id[id];
369 self.node_id_to_hir_id[node_id]
372 /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
374 pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
375 if let Some(def_id) = def_id.as_local() { Some(self.def_id_to_span[def_id]) } else { None }
378 /// Adds a root definition (no parent) and a few other reserved definitions.
379 pub fn create_root_def(
382 crate_disambiguator: CrateDisambiguator,
386 disambiguated_data: DisambiguatedDefPathData {
387 data: DefPathData::CrateRoot,
392 let parent_hash = DefKey::root_parent_stable_hash(crate_name, crate_disambiguator);
393 let def_path_hash = key.compute_stable_hash(parent_hash);
395 // Create the definition.
396 let root = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) };
397 assert_eq!(root.local_def_index, CRATE_DEF_INDEX);
399 assert_eq!(self.def_id_to_node_id.push(ast::CRATE_NODE_ID), root);
400 assert_eq!(self.def_id_to_span.push(rustc_span::DUMMY_SP), root);
402 self.node_id_to_def_id.insert(ast::CRATE_NODE_ID, root);
403 self.set_invocation_parent(ExpnId::root(), root);
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_id_to_def_id.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_id_to_def_id[&node_id].local_def_index),
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.local_def_index),
443 disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
446 let parent_hash = self.table.def_path_hash(parent.local_def_index);
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 def_id = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) };
454 assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
455 assert_eq!(self.def_id_to_span.push(span), def_id);
457 // Some things for which we allocate `LocalDefId`s don't correspond to
458 // anything in the AST, so they don't have a `NodeId`. For these cases
459 // we don't need a mapping from `NodeId` to `LocalDefId`.
460 if node_id != ast::DUMMY_NODE_ID {
461 debug!("create_def_with_parent: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
462 self.node_id_to_def_id.insert(node_id, def_id);
465 if expn_id != ExpnId::root() {
466 self.expansions_that_defined.insert(def_id, expn_id);
472 /// Initializes the `ast::NodeId` to `HirId` mapping once it has been generated during
473 /// AST to HIR lowering.
474 pub fn init_node_id_to_hir_id_mapping(&mut self, mapping: IndexVec<ast::NodeId, hir::HirId>) {
476 self.node_id_to_hir_id.is_empty(),
477 "trying to initialize `NodeId` -> `HirId` mapping twice"
479 self.node_id_to_hir_id = mapping;
481 // Build the reverse mapping of `node_id_to_hir_id`.
482 self.hir_id_to_node_id = self
485 .map(|(node_id, &hir_id)| (hir_id, node_id))
489 pub fn expansion_that_defined(&self, id: LocalDefId) -> ExpnId {
490 self.expansions_that_defined.get(&id).copied().unwrap_or(ExpnId::root())
493 pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {
494 self.parent_modules_of_macro_defs[&expn_id]
497 pub fn add_parent_module_of_macro_def(&mut self, expn_id: ExpnId, module: DefId) {
498 self.parent_modules_of_macro_defs.insert(expn_id, module);
501 pub fn invocation_parent(&self, invoc_id: ExpnId) -> LocalDefId {
502 self.invocation_parents[&invoc_id]
505 pub fn set_invocation_parent(&mut self, invoc_id: ExpnId, parent: LocalDefId) {
506 let old_parent = self.invocation_parents.insert(invoc_id, parent);
507 assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
510 pub fn placeholder_field_index(&self, node_id: ast::NodeId) -> usize {
511 self.placeholder_field_indices[&node_id]
514 pub fn set_placeholder_field_index(&mut self, node_id: ast::NodeId, index: usize) {
515 let old_index = self.placeholder_field_indices.insert(node_id, index);
516 assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
521 pub fn get_opt_name(&self) -> Option<Symbol> {
522 use self::DefPathData::*;
524 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
526 Impl | CrateRoot | Misc | ClosureExpr | Ctor | AnonConst | ImplTrait => None,
530 pub fn as_symbol(&self) -> Symbol {
531 use self::DefPathData::*;
533 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => name,
534 // Note that this does not show up in user print-outs.
535 CrateRoot => sym::double_braced_crate,
536 Impl => sym::double_braced_impl,
537 Misc => sym::double_braced_misc,
538 ClosureExpr => sym::double_braced_closure,
539 Ctor => sym::double_braced_constructor,
540 AnonConst => sym::double_braced_constant,
541 ImplTrait => sym::double_braced_opaque,
545 pub fn to_string(&self) -> String {
546 self.as_symbol().to_string()