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};
11 use rustc_ast::crate_disambiguator::CrateDisambiguator;
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_data_structures::stable_hasher::StableHasher;
14 use rustc_index::vec::IndexVec;
15 use rustc_span::hygiene::ExpnId;
16 use rustc_span::symbol::{sym, Symbol};
22 /// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa.
23 /// Internally the `DefPathTable` holds a tree of `DefKey`s, where each `DefKey`
24 /// stores the `DefIndex` of its parent.
25 /// There is one `DefPathTable` for each crate.
26 #[derive(Clone, Default, RustcDecodable, RustcEncodable)]
27 pub struct DefPathTable {
28 index_to_key: IndexVec<DefIndex, DefKey>,
29 def_path_hashes: IndexVec<DefIndex, DefPathHash>,
33 fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
35 let index = DefIndex::from(self.index_to_key.len());
36 debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
37 self.index_to_key.push(key);
40 self.def_path_hashes.push(def_path_hash);
41 debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
45 pub fn next_id(&self) -> DefIndex {
46 DefIndex::from(self.index_to_key.len())
50 pub fn def_key(&self, index: DefIndex) -> DefKey {
51 self.index_to_key[index]
55 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
56 let hash = self.def_path_hashes[index];
57 debug!("def_path_hash({:?}) = {:?}", index, hash);
61 pub fn add_def_path_hashes_to(&self, cnum: CrateNum, out: &mut FxHashMap<DefPathHash, DefId>) {
62 out.extend(self.def_path_hashes.iter().enumerate().map(|(index, &hash)| {
63 let def_id = DefId { krate: cnum, index: DefIndex::from(index) };
68 pub fn size(&self) -> usize {
69 self.index_to_key.len()
73 /// The definition table containing node definitions.
74 /// It holds the `DefPathTable` for `LocalDefId`s/`DefPath`s.
75 /// It also stores mappings to convert `LocalDefId`s to/from `HirId`s.
77 pub struct Definitions {
80 // FIXME(eddyb) ideally all `LocalDefId`s would be HIR owners.
81 pub(super) def_id_to_hir_id: IndexVec<LocalDefId, Option<hir::HirId>>,
82 /// The reverse mapping of `def_id_to_hir_id`.
83 pub(super) hir_id_to_def_id: FxHashMap<hir::HirId, LocalDefId>,
85 /// If `ExpnId` is an ID of some macro expansion,
86 /// then `DefId` is the normal module (`mod`) in which the expanded macro was defined.
87 parent_modules_of_macro_defs: FxHashMap<ExpnId, DefId>,
88 /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
89 expansions_that_defined: FxHashMap<LocalDefId, ExpnId>,
90 next_disambiguator: FxHashMap<(LocalDefId, DefPathData), u32>,
93 /// A unique identifier that we can use to lookup a definition
94 /// precisely. It combines the index of the definition's parent (if
95 /// any) with a `DisambiguatedDefPathData`.
96 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
99 pub parent: Option<DefIndex>,
101 /// The identifier of this node.
102 pub disambiguated_data: DisambiguatedDefPathData,
106 fn compute_stable_hash(&self, parent_hash: DefPathHash) -> DefPathHash {
107 let mut hasher = StableHasher::new();
109 // We hash a `0u8` here to disambiguate between regular `DefPath` hashes,
110 // and the special "root_parent" below.
111 0u8.hash(&mut hasher);
112 parent_hash.hash(&mut hasher);
114 let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
116 ::std::mem::discriminant(data).hash(&mut hasher);
117 if let Some(name) = data.get_opt_name() {
118 // Get a stable hash by considering the symbol chars rather than
120 name.as_str().hash(&mut hasher);
123 disambiguator.hash(&mut hasher);
125 DefPathHash(hasher.finish())
128 fn root_parent_stable_hash(
130 crate_disambiguator: CrateDisambiguator,
132 let mut hasher = StableHasher::new();
133 // Disambiguate this from a regular `DefPath` hash; see `compute_stable_hash()` above.
134 1u8.hash(&mut hasher);
135 crate_name.hash(&mut hasher);
136 crate_disambiguator.hash(&mut hasher);
137 DefPathHash(hasher.finish())
141 /// A pair of `DefPathData` and an integer disambiguator. The integer is
142 /// normally `0`, but in the event that there are multiple defs with the
143 /// same `parent` and `data`, we use this field to disambiguate
144 /// between them. This introduces some artificial ordering dependency
145 /// but means that if you have, e.g., two impls for the same type in
146 /// the same module, they do get distinct `DefId`s.
147 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
148 pub struct DisambiguatedDefPathData {
149 pub data: DefPathData,
150 pub disambiguator: u32,
153 #[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
155 /// The path leading from the crate root to the item.
156 pub data: Vec<DisambiguatedDefPathData>,
158 /// The crate root this path is relative to.
163 pub fn is_local(&self) -> bool {
164 self.krate == LOCAL_CRATE
167 pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
169 FN: FnMut(DefIndex) -> DefKey,
171 let mut data = vec![];
172 let mut index = Some(start_index);
174 debug!("DefPath::make: krate={:?} index={:?}", krate, index);
175 let p = index.unwrap();
176 let key = get_key(p);
177 debug!("DefPath::make: key={:?}", key);
178 match key.disambiguated_data.data {
179 DefPathData::CrateRoot => {
180 assert!(key.parent.is_none());
184 data.push(key.disambiguated_data);
190 DefPath { data, krate }
193 /// Returns a string representation of the `DefPath` without
194 /// the crate-prefix. This method is useful if you don't have
195 /// a `TyCtxt` available.
196 pub fn to_string_no_crate(&self) -> String {
197 let mut s = String::with_capacity(self.data.len() * 16);
199 for component in &self.data {
200 write!(s, "::{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
206 /// Returns a filename-friendly string for the `DefPath`, with the
208 pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
210 F: FnOnce(CrateNum) -> Symbol,
212 let crate_name_str = crate_imported_name(self.krate).as_str();
213 let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
215 write!(s, "::{}", crate_name_str).unwrap();
217 for component in &self.data {
218 if component.disambiguator == 0 {
219 write!(s, "::{}", component.data.as_symbol()).unwrap();
221 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
228 /// Returns a filename-friendly string of the `DefPath`, without
229 /// the crate-prefix. This method is useful if you don't have
230 /// a `TyCtxt` available.
231 pub fn to_filename_friendly_no_crate(&self) -> String {
232 let mut s = String::with_capacity(self.data.len() * 16);
234 let mut opt_delimiter = None;
235 for component in &self.data {
236 s.extend(opt_delimiter);
237 opt_delimiter = Some('-');
238 if component.disambiguator == 0 {
239 write!(s, "{}", component.data.as_symbol()).unwrap();
241 write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
248 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
249 pub enum DefPathData {
250 // Root: these should only be used for the root nodes, because
251 // they are treated specially by the `def_path` function.
252 /// The crate root (marker).
254 // Catch-all for random `DefId` things like `DUMMY_NODE_ID`.
257 // Different kinds of items and item-like things:
260 /// Something in the type namespace.
262 /// Something in the value namespace.
264 /// Something in the macro namespace.
266 /// Something in the lifetime namespace.
268 /// A closure expression.
271 // Subportions of items:
272 /// Implicit constructor for a unit or tuple-like struct or enum variant.
274 /// A constant expression (see `{ast,hir}::AnonConst`).
276 /// An `impl Trait` type node.
281 pub fn def_path_table(&self) -> &DefPathTable {
285 /// Gets the number of definitions.
286 pub fn def_index_count(&self) -> usize {
287 self.table.index_to_key.len()
290 pub fn def_key(&self, id: LocalDefId) -> DefKey {
291 self.table.def_key(id.local_def_index)
295 pub fn def_path_hash(&self, id: LocalDefId) -> DefPathHash {
296 self.table.def_path_hash(id.local_def_index)
299 /// Returns the path from the crate root to `index`. The root
300 /// nodes are not included in the path (i.e., this will be an
301 /// empty vector for the crate root). For an inlined item, this
302 /// will be the path of the item in the external crate (but the
303 /// path will begin with the path to the external crate).
304 pub fn def_path(&self, id: LocalDefId) -> DefPath {
305 DefPath::make(LOCAL_CRATE, id.local_def_index, |index| {
306 self.def_key(LocalDefId { local_def_index: index })
311 pub fn as_local_hir_id(&self, def_id: LocalDefId) -> hir::HirId {
312 self.local_def_id_to_hir_id(def_id)
316 pub fn local_def_id_to_hir_id(&self, id: LocalDefId) -> hir::HirId {
317 self.def_id_to_hir_id[id].unwrap()
321 pub fn opt_local_def_id_to_hir_id(&self, id: LocalDefId) -> Option<hir::HirId> {
322 self.def_id_to_hir_id[id]
326 pub fn opt_hir_id_to_local_def_id(&self, hir_id: hir::HirId) -> Option<LocalDefId> {
327 self.hir_id_to_def_id.get(&hir_id).copied()
330 /// Adds a root definition (no parent) and a few other reserved definitions.
331 pub fn new(crate_name: &str, crate_disambiguator: CrateDisambiguator) -> Definitions {
334 disambiguated_data: DisambiguatedDefPathData {
335 data: DefPathData::CrateRoot,
340 let parent_hash = DefKey::root_parent_stable_hash(crate_name, crate_disambiguator);
341 let def_path_hash = key.compute_stable_hash(parent_hash);
343 // Create the root definition.
344 let mut table = DefPathTable::default();
345 let root = LocalDefId { local_def_index: table.allocate(key, def_path_hash) };
346 assert_eq!(root.local_def_index, CRATE_DEF_INDEX);
350 def_id_to_hir_id: Default::default(),
351 hir_id_to_def_id: Default::default(),
352 expansions_that_defined: Default::default(),
353 next_disambiguator: Default::default(),
354 parent_modules_of_macro_defs: Default::default(),
358 /// Retrieves the root definition.
359 pub fn get_root_def(&self) -> LocalDefId {
360 LocalDefId { local_def_index: CRATE_DEF_INDEX }
363 /// Adds a definition with a parent definition.
370 debug!("create_def(parent={:?}, data={:?}, expn_id={:?})", parent, data, expn_id);
372 // The root node must be created with `create_root_def()`.
373 assert!(data != DefPathData::CrateRoot);
375 // Find the next free disambiguator for this key.
376 let disambiguator = {
377 let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
378 let disambiguator = *next_disamb;
379 *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
384 parent: Some(parent.local_def_index),
385 disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
388 let parent_hash = self.table.def_path_hash(parent.local_def_index);
389 let def_path_hash = key.compute_stable_hash(parent_hash);
391 debug!("create_def: after disambiguation, key = {:?}", key);
393 // Create the definition.
394 let def_id = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) };
396 if expn_id != ExpnId::root() {
397 self.expansions_that_defined.insert(def_id, expn_id);
403 /// Initializes the `LocalDefId` to `HirId` mapping once it has been generated during
404 /// AST to HIR lowering.
405 pub fn init_def_id_to_hir_id_mapping(
407 mapping: IndexVec<LocalDefId, Option<hir::HirId>>,
410 self.def_id_to_hir_id.is_empty(),
411 "trying to initialize `LocalDefId` <-> `HirId` mappings twice"
414 // Build the reverse mapping of `def_id_to_hir_id`.
415 self.hir_id_to_def_id = mapping
417 .filter_map(|(def_id, hir_id)| hir_id.map(|hir_id| (hir_id, def_id)))
420 self.def_id_to_hir_id = mapping;
423 pub fn expansion_that_defined(&self, id: LocalDefId) -> ExpnId {
424 self.expansions_that_defined.get(&id).copied().unwrap_or(ExpnId::root())
427 pub fn parent_module_of_macro_def(&self, expn_id: ExpnId) -> DefId {
428 self.parent_modules_of_macro_defs[&expn_id]
431 pub fn add_parent_module_of_macro_def(&mut self, expn_id: ExpnId, module: DefId) {
432 self.parent_modules_of_macro_defs.insert(expn_id, module);
437 pub fn get_opt_name(&self) -> Option<Symbol> {
438 use self::DefPathData::*;
440 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
442 Impl | CrateRoot | Misc | ClosureExpr | Ctor | AnonConst | ImplTrait => None,
446 pub fn as_symbol(&self) -> Symbol {
447 use self::DefPathData::*;
449 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => name,
450 // Note that this does not show up in user print-outs.
451 CrateRoot => sym::double_braced_crate,
452 Impl => sym::double_braced_impl,
453 Misc => sym::double_braced_misc,
454 ClosureExpr => sym::double_braced_closure,
455 Ctor => sym::double_braced_constructor,
456 AnonConst => sym::double_braced_constant,
457 ImplTrait => sym::double_braced_opaque,
461 pub fn to_string(&self) -> String {
462 self.as_symbol().to_string()