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 pub use crate::def_id::DefPathHash;
8 use crate::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
10 use crate::hir_id::DUMMY_HIR_ID;
13 use rustc_ast::crate_disambiguator::CrateDisambiguator;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_data_structures::stable_hasher::StableHasher;
16 use rustc_index::vec::IndexVec;
17 use rustc_span::hygiene::ExpnId;
18 use rustc_span::symbol::{sym, Symbol};
25 /// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa.
26 /// Internally the `DefPathTable` holds a tree of `DefKey`s, where each `DefKey`
27 /// stores the `DefIndex` of its parent.
28 /// There is one `DefPathTable` for each crate.
29 #[derive(Clone, Default, RustcDecodable, RustcEncodable)]
30 pub struct DefPathTable {
31 index_to_key: IndexVec<DefIndex, DefKey>,
32 def_path_hashes: IndexVec<DefIndex, DefPathHash>,
36 fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
38 let index = DefIndex::from(self.index_to_key.len());
39 debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
40 self.index_to_key.push(key);
43 self.def_path_hashes.push(def_path_hash);
44 debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
48 pub fn next_id(&self) -> DefIndex {
49 DefIndex::from(self.index_to_key.len())
53 pub fn def_key(&self, index: DefIndex) -> DefKey {
54 self.index_to_key[index]
58 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
59 let hash = self.def_path_hashes[index];
60 debug!("def_path_hash({:?}) = {:?}", index, hash);
64 pub fn add_def_path_hashes_to(&self, cnum: CrateNum, out: &mut FxHashMap<DefPathHash, DefId>) {
65 out.extend(self.def_path_hashes.iter().enumerate().map(|(index, &hash)| {
66 let def_id = DefId { krate: cnum, index: DefIndex::from(index) };
71 pub fn size(&self) -> usize {
72 self.index_to_key.len()
76 /// The definition table containing node definitions.
77 /// It holds the `DefPathTable` for local `DefId`s/`DefPath`s and it also stores a
78 /// mapping from `NodeId`s to local `DefId`s.
79 #[derive(Clone, Default)]
80 pub struct Definitions {
83 def_id_to_span: IndexVec<LocalDefId, Span>,
85 // FIXME(eddyb) don't go through `ast::NodeId` to convert between `HirId`
86 // and `LocalDefId` - ideally all `LocalDefId`s would be HIR owners.
87 node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
88 def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
90 pub(super) node_id_to_hir_id: IndexVec<ast::NodeId, hir::HirId>,
91 /// The reverse mapping of `node_id_to_hir_id`.
92 pub(super) hir_id_to_node_id: FxHashMap<hir::HirId, ast::NodeId>,
94 /// If `ExpnId` is an ID of some macro expansion,
95 /// then `DefId` is the normal module (`mod`) in which the expanded macro was defined.
96 parent_modules_of_macro_defs: FxHashMap<ExpnId, DefId>,
97 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
98 expansions_that_defined: FxHashMap<LocalDefId, ExpnId>,
99 next_disambiguator: FxHashMap<(LocalDefId, DefPathData), u32>,
100 /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
101 /// we know what parent node that fragment should be attached to thanks to this table.
102 invocation_parents: FxHashMap<ExpnId, LocalDefId>,
103 /// Indices of unnamed struct or variant fields with unresolved attributes.
104 placeholder_field_indices: FxHashMap<ast::NodeId, usize>,
107 /// A unique identifier that we can use to lookup a definition
108 /// precisely. It combines the index of the definition's parent (if
109 /// any) with a `DisambiguatedDefPathData`.
110 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
113 pub parent: Option<DefIndex>,
115 /// The identifier of this node.
116 pub disambiguated_data: DisambiguatedDefPathData,
120 fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
121 let mut hasher = StableHasher::new();
123 // We hash a `0u8` here to disambiguate between regular `DefPath` hashes,
124 // and the special "root_parent" below.
125 0u8.hash(&mut hasher);
126 parent_hash.hash(&mut hasher);
128 let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
130 ::std::mem::discriminant(data).hash(&mut hasher);
131 if let Some(name) = data.get_opt_name() {
132 // Get a stable hash by considering the symbol chars rather than
134 name.as_str().hash(&mut hasher);
137 disambiguator.hash(&mut hasher);
139 DefPathHash(hasher.finish())
142 fn root_parent_stable_hash(
144 crate_disambiguator: CrateDisambiguator,
146 let mut hasher = StableHasher::new();
147 // Disambiguate this from a regular `DefPath` hash; see `compute_stable_hash()` above.
148 1u8.hash(&mut hasher);
149 crate_name.hash(&mut hasher);
150 crate_disambiguator.hash(&mut hasher);
151 DefPathHash(hasher.finish())
155 /// A pair of `DefPathData` and an integer disambiguator. The integer is
156 /// normally `0`, but in the event that there are multiple defs with the
157 /// same `parent` and `data`, we use this field to disambiguate
158 /// between them. This introduces some artificial ordering dependency
159 /// but means that if you have, e.g., two impls for the same type in
160 /// the same module, they do get distinct `DefId`s.
161 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
162 pub struct DisambiguatedDefPathData {
163 pub data: DefPathData,
164 pub disambiguator: u32,
167 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
169 /// The path leading from the crate root to the item.
170 pub data: Vec<DisambiguatedDefPathData>,
172 /// The crate root this path is relative to.
177 pub fn is_local(&self) -> bool {
178 self.krate == LOCAL_CRATE
181 pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
183 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, 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 {
214 write!(s, "::{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
220 /// Returns a filename-friendly string for the `DefPath`, with the
222 pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
224 F: FnOnce(CrateNum) -> Symbol,
226 let crate_name_str = crate_imported_name(self.krate).as_str();
227 let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
229 write!(s, "::{}", crate_name_str).unwrap();
231 for component in &self.data {
232 if component.disambiguator == 0 {
233 write!(s, "::{}", component.data.as_symbol()).unwrap();
235 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
242 /// Returns a filename-friendly string of the `DefPath`, without
243 /// the crate-prefix. This method is useful if you don't have
244 /// a `TyCtxt` available.
245 pub fn to_filename_friendly_no_crate(&self) -> String {
246 let mut s = String::with_capacity(self.data.len() * 16);
248 let mut opt_delimiter = None;
249 for component in &self.data {
250 opt_delimiter.map(|d| s.push(d));
251 opt_delimiter = Some('-');
252 if component.disambiguator == 0 {
253 write!(s, "{}", component.data.as_symbol()).unwrap();
255 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
262 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
263 pub enum DefPathData {
264 // Root: these should only be used for the root nodes, because
265 // they are treated specially by the `def_path` function.
266 /// The crate root (marker).
268 // Catch-all for random `DefId` things like `DUMMY_NODE_ID`.
271 // Different kinds of items and item-like things:
274 /// Something in the type namespace.
276 /// Something in the value namespace.
278 /// Something in the macro namespace.
280 /// Something in the lifetime namespace.
282 /// A closure expression.
285 // Subportions of items:
286 /// Implicit constructor for a unit or tuple-like struct or enum variant.
288 /// A constant expression (see `{ast,hir}::AnonConst`).
290 /// An `impl Trait` type node.
295 pub fn def_path_table(&self) -> &DefPathTable {
299 /// Gets the number of definitions.
300 pub fn def_index_count(&self) -> usize {
301 self.table.index_to_key.len()
304 pub fn def_key(&self, id: LocalDefId) -> DefKey {
305 self.table.def_key(id.local_def_index)
309 pub fn def_path_hash(&self, id: LocalDefId) -> DefPathHash {
310 self.table.def_path_hash(id.local_def_index)
313 /// Returns the path from the crate root to `index`. The root
314 /// nodes are not included in the path (i.e., this will be an
315 /// empty vector for the crate root). For an inlined item, this
316 /// will be the path of the item in the external crate (but the
317 /// path will begin with the path to the external crate).
318 pub fn def_path(&self, id: LocalDefId) -> DefPath {
319 DefPath::make(LOCAL_CRATE, id.local_def_index, |index| {
320 self.def_key(LocalDefId { local_def_index: index })
325 pub fn opt_local_def_id(&self, node: ast::NodeId) -> Option<LocalDefId> {
326 self.node_id_to_def_id.get(&node).copied()
330 pub fn local_def_id(&self, node: ast::NodeId) -> LocalDefId {
331 self.opt_local_def_id(node).unwrap()
335 pub fn as_local_node_id(&self, def_id: DefId) -> Option<ast::NodeId> {
336 if let Some(def_id) = def_id.as_local() {
337 let node_id = self.def_id_to_node_id[def_id];
338 if node_id != ast::DUMMY_NODE_ID {
339 return Some(node_id);
346 pub fn as_local_hir_id(&self, def_id: DefId) -> Option<hir::HirId> {
347 if let Some(def_id) = def_id.as_local() {
348 let hir_id = self.local_def_id_to_hir_id(def_id);
349 if hir_id != DUMMY_HIR_ID { Some(hir_id) } else { None }
356 pub fn hir_id_to_node_id(&self, hir_id: hir::HirId) -> ast::NodeId {
357 self.hir_id_to_node_id[&hir_id]
361 pub fn node_id_to_hir_id(&self, node_id: ast::NodeId) -> hir::HirId {
362 self.node_id_to_hir_id[node_id]
366 pub fn local_def_id_to_hir_id(&self, id: LocalDefId) -> hir::HirId {
367 let node_id = self.def_id_to_node_id[id];
368 self.node_id_to_hir_id[node_id]
371 /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
373 pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
374 if let Some(def_id) = def_id.as_local() { Some(self.def_id_to_span[def_id]) } else { None }
377 /// Adds a root definition (no parent) and a few other reserved definitions.
378 pub fn create_root_def(
381 crate_disambiguator: CrateDisambiguator,
385 disambiguated_data: DisambiguatedDefPathData {
386 data: DefPathData::CrateRoot,
391 let parent_hash = DefKey::root_parent_stable_hash(crate_name, crate_disambiguator);
392 let def_path_hash = key.compute_stable_hash(parent_hash);
394 // Create the definition.
395 let root = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) };
396 assert_eq!(root.local_def_index, CRATE_DEF_INDEX);
398 assert_eq!(self.def_id_to_node_id.push(ast::CRATE_NODE_ID), root);
399 assert_eq!(self.def_id_to_span.push(rustc_span::DUMMY_SP), root);
401 self.node_id_to_def_id.insert(ast::CRATE_NODE_ID, root);
402 self.set_invocation_parent(ExpnId::root(), root);
407 /// Adds a definition with a parent definition.
408 pub fn create_def_with_parent(
411 node_id: ast::NodeId,
417 "create_def_with_parent(parent={:?}, node_id={:?}, data={:?})",
418 parent, node_id, data
422 !self.node_id_to_def_id.contains_key(&node_id),
423 "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
426 self.table.def_key(self.node_id_to_def_id[&node_id].local_def_index),
429 // The root node must be created with `create_root_def()`.
430 assert!(data != DefPathData::CrateRoot);
432 // Find the next free disambiguator for this key.
433 let disambiguator = {
434 let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
435 let disambiguator = *next_disamb;
436 *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
441 parent: Some(parent.local_def_index),
442 disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
445 let parent_hash = self.table.def_path_hash(parent.local_def_index);
446 let def_path_hash = key.compute_stable_hash(parent_hash);
448 debug!("create_def_with_parent: after disambiguation, key = {:?}", key);
450 // Create the definition.
451 let def_id = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) };
453 assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
454 assert_eq!(self.def_id_to_span.push(span), def_id);
456 // Some things for which we allocate `LocalDefId`s 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 `LocalDefId`.
459 if node_id != ast::DUMMY_NODE_ID {
460 debug!("create_def_with_parent: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
461 self.node_id_to_def_id.insert(node_id, def_id);
464 if expn_id != ExpnId::root() {
465 self.expansions_that_defined.insert(def_id, expn_id);
471 /// Initializes the `ast::NodeId` to `HirId` mapping once it has been generated during
472 /// AST to HIR lowering.
473 pub fn init_node_id_to_hir_id_mapping(&mut self, mapping: IndexVec<ast::NodeId, hir::HirId>) {
475 self.node_id_to_hir_id.is_empty(),
476 "trying to initialize `NodeId` -> `HirId` mapping twice"
478 self.node_id_to_hir_id = mapping;
480 // Build the reverse mapping of `node_id_to_hir_id`.
481 self.hir_id_to_node_id = self
484 .map(|(node_id, &hir_id)| (hir_id, node_id))
488 pub fn expansion_that_defined(&self, id: LocalDefId) -> ExpnId {
489 self.expansions_that_defined.get(&id).copied().unwrap_or(ExpnId::root())
492 pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {
493 self.parent_modules_of_macro_defs[&expn_id]
496 pub fn add_parent_module_of_macro_def(&mut self, expn_id: ExpnId, module: DefId) {
497 self.parent_modules_of_macro_defs.insert(expn_id, module);
500 pub fn invocation_parent(&self, invoc_id: ExpnId) -> LocalDefId {
501 self.invocation_parents[&invoc_id]
504 pub fn set_invocation_parent(&mut self, invoc_id: ExpnId, parent: LocalDefId) {
505 let old_parent = self.invocation_parents.insert(invoc_id, parent);
506 assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
509 pub fn placeholder_field_index(&self, node_id: ast::NodeId) -> usize {
510 self.placeholder_field_indices[&node_id]
513 pub fn set_placeholder_field_index(&mut self, node_id: ast::NodeId, index: usize) {
514 let old_index = self.placeholder_field_indices.insert(node_id, index);
515 assert!(old_index.is_none(), "placeholder field index is reset for a node ID");
520 pub fn get_opt_name(&self) -> Option<Symbol> {
521 use self::DefPathData::*;
523 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
525 Impl | CrateRoot | Misc | ClosureExpr | Ctor | AnonConst | ImplTrait => None,
529 pub fn as_symbol(&self) -> Symbol {
530 use self::DefPathData::*;
532 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => name,
533 // Note that this does not show up in user print-outs.
534 CrateRoot => sym::double_braced_crate,
535 Impl => sym::double_braced_impl,
536 Misc => sym::double_braced_misc,
537 ClosureExpr => sym::double_braced_closure,
538 Ctor => sym::double_braced_constructor,
539 AnonConst => sym::double_braced_constant,
540 ImplTrait => sym::double_braced_opaque,
544 pub fn to_string(&self) -> String {
545 self.as_symbol().to_string()