]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/definitions.rs
Auto merge of #96003 - aswild:pr/bootstrap-subcommands-cleanup, r=jyn514
[rust.git] / compiler / rustc_hir / src / definitions.rs
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.
6
7 pub use crate::def_id::DefPathHash;
8 use crate::def_id::{CrateNum, DefIndex, LocalDefId, StableCrateId, CRATE_DEF_INDEX, LOCAL_CRATE};
9 use crate::def_path_hash_map::DefPathHashMap;
10
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::stable_hasher::StableHasher;
13 use rustc_index::vec::IndexVec;
14 use rustc_span::hygiene::ExpnId;
15 use rustc_span::symbol::{kw, sym, Symbol};
16 use rustc_span::Span;
17
18 use std::fmt::{self, Write};
19 use std::hash::Hash;
20 use tracing::debug;
21
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, Debug)]
27 pub struct DefPathTable {
28     index_to_key: IndexVec<DefIndex, DefKey>,
29     def_path_hashes: IndexVec<DefIndex, DefPathHash>,
30     def_path_hash_to_index: DefPathHashMap,
31 }
32
33 impl DefPathTable {
34     fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
35         let index = {
36             let index = DefIndex::from(self.index_to_key.len());
37             debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
38             self.index_to_key.push(key);
39             index
40         };
41         self.def_path_hashes.push(def_path_hash);
42         debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
43
44         // Check for hash collisions of DefPathHashes. These should be
45         // exceedingly rare.
46         if let Some(existing) = self.def_path_hash_to_index.insert(&def_path_hash, &index) {
47             let def_path1 = DefPath::make(LOCAL_CRATE, existing, |idx| self.def_key(idx));
48             let def_path2 = DefPath::make(LOCAL_CRATE, index, |idx| self.def_key(idx));
49
50             // Continuing with colliding DefPathHashes can lead to correctness
51             // issues. We must abort compilation.
52             //
53             // The likelihood of such a collision is very small, so actually
54             // running into one could be indicative of a poor hash function
55             // being used.
56             //
57             // See the documentation for DefPathHash for more information.
58             panic!(
59                 "found DefPathHash collision between {:?} and {:?}. \
60                     Compilation cannot continue.",
61                 def_path1, def_path2
62             );
63         }
64
65         // Assert that all DefPathHashes correctly contain the local crate's
66         // StableCrateId
67         #[cfg(debug_assertions)]
68         if let Some(root) = self.def_path_hashes.get(CRATE_DEF_INDEX) {
69             assert!(def_path_hash.stable_crate_id() == root.stable_crate_id());
70         }
71
72         index
73     }
74
75     #[inline(always)]
76     pub fn def_key(&self, index: DefIndex) -> DefKey {
77         self.index_to_key[index]
78     }
79
80     #[inline(always)]
81     pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
82         let hash = self.def_path_hashes[index];
83         debug!("def_path_hash({:?}) = {:?}", index, hash);
84         hash
85     }
86
87     pub fn enumerated_keys_and_path_hashes(
88         &self,
89     ) -> impl Iterator<Item = (DefIndex, &DefKey, &DefPathHash)> + ExactSizeIterator + '_ {
90         self.index_to_key
91             .iter_enumerated()
92             .map(move |(index, key)| (index, key, &self.def_path_hashes[index]))
93     }
94 }
95
96 /// The definition table containing node definitions.
97 /// It holds the `DefPathTable` for `LocalDefId`s/`DefPath`s.
98 /// It also stores mappings to convert `LocalDefId`s to/from `HirId`s.
99 #[derive(Clone, Debug)]
100 pub struct Definitions {
101     table: DefPathTable,
102     next_disambiguator: FxHashMap<(LocalDefId, DefPathData), u32>,
103
104     /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
105     expansions_that_defined: FxHashMap<LocalDefId, ExpnId>,
106
107     def_id_to_span: IndexVec<LocalDefId, Span>,
108
109     /// The [StableCrateId] of the local crate.
110     stable_crate_id: StableCrateId,
111 }
112
113 /// A unique identifier that we can use to lookup a definition
114 /// precisely. It combines the index of the definition's parent (if
115 /// any) with a `DisambiguatedDefPathData`.
116 #[derive(Copy, Clone, PartialEq, Debug, Encodable, Decodable)]
117 pub struct DefKey {
118     /// The parent path.
119     pub parent: Option<DefIndex>,
120
121     /// The identifier of this node.
122     pub disambiguated_data: DisambiguatedDefPathData,
123 }
124
125 impl DefKey {
126     pub(crate) fn compute_stable_hash(&self, parent: DefPathHash) -> DefPathHash {
127         let mut hasher = StableHasher::new();
128
129         parent.hash(&mut hasher);
130
131         let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
132
133         std::mem::discriminant(data).hash(&mut hasher);
134         if let Some(name) = data.get_opt_name() {
135             // Get a stable hash by considering the symbol chars rather than
136             // the symbol index.
137             name.as_str().hash(&mut hasher);
138         }
139
140         disambiguator.hash(&mut hasher);
141
142         let local_hash: u64 = hasher.finish();
143
144         // Construct the new DefPathHash, making sure that the `crate_id`
145         // portion of the hash is properly copied from the parent. This way the
146         // `crate_id` part will be recursively propagated from the root to all
147         // DefPathHashes in this DefPathTable.
148         DefPathHash::new(parent.stable_crate_id(), local_hash)
149     }
150
151     #[inline]
152     pub fn get_opt_name(&self) -> Option<Symbol> {
153         self.disambiguated_data.data.get_opt_name()
154     }
155 }
156
157 /// A pair of `DefPathData` and an integer disambiguator. The integer is
158 /// normally `0`, but in the event that there are multiple defs with the
159 /// same `parent` and `data`, we use this field to disambiguate
160 /// between them. This introduces some artificial ordering dependency
161 /// but means that if you have, e.g., two impls for the same type in
162 /// the same module, they do get distinct `DefId`s.
163 #[derive(Copy, Clone, PartialEq, Debug, Encodable, Decodable)]
164 pub struct DisambiguatedDefPathData {
165     pub data: DefPathData,
166     pub disambiguator: u32,
167 }
168
169 impl DisambiguatedDefPathData {
170     pub fn fmt_maybe_verbose(&self, writer: &mut impl Write, verbose: bool) -> fmt::Result {
171         match self.data.name() {
172             DefPathDataName::Named(name) => {
173                 if verbose && self.disambiguator != 0 {
174                     write!(writer, "{}#{}", name, self.disambiguator)
175                 } else {
176                     writer.write_str(name.as_str())
177                 }
178             }
179             DefPathDataName::Anon { namespace } => {
180                 write!(writer, "{{{}#{}}}", namespace, self.disambiguator)
181             }
182         }
183     }
184 }
185
186 impl fmt::Display for DisambiguatedDefPathData {
187     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188         self.fmt_maybe_verbose(f, true)
189     }
190 }
191
192 #[derive(Clone, Debug, Encodable, Decodable)]
193 pub struct DefPath {
194     /// The path leading from the crate root to the item.
195     pub data: Vec<DisambiguatedDefPathData>,
196
197     /// The crate root this path is relative to.
198     pub krate: CrateNum,
199 }
200
201 impl DefPath {
202     pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
203     where
204         FN: FnMut(DefIndex) -> DefKey,
205     {
206         let mut data = vec![];
207         let mut index = Some(start_index);
208         loop {
209             debug!("DefPath::make: krate={:?} index={:?}", krate, index);
210             let p = index.unwrap();
211             let key = get_key(p);
212             debug!("DefPath::make: key={:?}", key);
213             match key.disambiguated_data.data {
214                 DefPathData::CrateRoot => {
215                     assert!(key.parent.is_none());
216                     break;
217                 }
218                 _ => {
219                     data.push(key.disambiguated_data);
220                     index = key.parent;
221                 }
222             }
223         }
224         data.reverse();
225         DefPath { data, krate }
226     }
227
228     /// Returns a string representation 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_string_no_crate_verbose(&self) -> String {
232         let mut s = String::with_capacity(self.data.len() * 16);
233
234         for component in &self.data {
235             write!(s, "::{}", component).unwrap();
236         }
237
238         s
239     }
240
241     /// Returns a filename-friendly string of the `DefPath`, without
242     /// the crate-prefix. This method is useful if you don't have
243     /// a `TyCtxt` available.
244     pub fn to_filename_friendly_no_crate(&self) -> String {
245         let mut s = String::with_capacity(self.data.len() * 16);
246
247         let mut opt_delimiter = None;
248         for component in &self.data {
249             s.extend(opt_delimiter);
250             opt_delimiter = Some('-');
251             write!(s, "{}", component).unwrap();
252         }
253
254         s
255     }
256 }
257
258 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
259 pub enum DefPathData {
260     // Root: these should only be used for the root nodes, because
261     // they are treated specially by the `def_path` function.
262     /// The crate root (marker).
263     CrateRoot,
264     // Catch-all for random `DefId` things like `DUMMY_NODE_ID`.
265     Misc,
266
267     // Different kinds of items and item-like things:
268     /// An impl.
269     Impl,
270     /// An `extern` block.
271     ForeignMod,
272     /// Something in the type namespace.
273     TypeNs(Symbol),
274     /// Something in the value namespace.
275     ValueNs(Symbol),
276     /// Something in the macro namespace.
277     MacroNs(Symbol),
278     /// Something in the lifetime namespace.
279     LifetimeNs(Symbol),
280     /// A closure expression.
281     ClosureExpr,
282
283     // Subportions of items:
284     /// Implicit constructor for a unit or tuple-like struct or enum variant.
285     Ctor,
286     /// A constant expression (see `{ast,hir}::AnonConst`).
287     AnonConst,
288     /// An `impl Trait` type node.
289     ImplTrait,
290 }
291
292 impl Definitions {
293     pub fn def_path_table(&self) -> &DefPathTable {
294         &self.table
295     }
296
297     /// Gets the number of definitions.
298     pub fn def_index_count(&self) -> usize {
299         self.table.index_to_key.len()
300     }
301
302     #[inline]
303     pub fn def_key(&self, id: LocalDefId) -> DefKey {
304         self.table.def_key(id.local_def_index)
305     }
306
307     #[inline(always)]
308     pub fn def_path_hash(&self, id: LocalDefId) -> DefPathHash {
309         self.table.def_path_hash(id.local_def_index)
310     }
311
312     /// Returns the path from the crate root to `index`. The root
313     /// nodes are not included in the path (i.e., this will be an
314     /// empty vector for the crate root). For an inlined item, this
315     /// will be the path of the item in the external crate (but the
316     /// path will begin with the path to the external crate).
317     pub fn def_path(&self, id: LocalDefId) -> DefPath {
318         DefPath::make(LOCAL_CRATE, id.local_def_index, |index| {
319             self.def_key(LocalDefId { local_def_index: index })
320         })
321     }
322
323     /// Adds a root definition (no parent) and a few other reserved definitions.
324     pub fn new(stable_crate_id: StableCrateId, crate_span: Span) -> Definitions {
325         let key = DefKey {
326             parent: None,
327             disambiguated_data: DisambiguatedDefPathData {
328                 data: DefPathData::CrateRoot,
329                 disambiguator: 0,
330             },
331         };
332
333         let parent_hash = DefPathHash::new(stable_crate_id, 0);
334         let def_path_hash = key.compute_stable_hash(parent_hash);
335
336         // Create the root definition.
337         let mut table = DefPathTable::default();
338         let root = LocalDefId { local_def_index: table.allocate(key, def_path_hash) };
339         assert_eq!(root.local_def_index, CRATE_DEF_INDEX);
340
341         let mut def_id_to_span = IndexVec::new();
342         // A relative span's parent must be an absolute span.
343         debug_assert_eq!(crate_span.data_untracked().parent, None);
344         let _root = def_id_to_span.push(crate_span);
345         debug_assert_eq!(_root, root);
346
347         Definitions {
348             table,
349             next_disambiguator: Default::default(),
350             expansions_that_defined: Default::default(),
351             def_id_to_span,
352             stable_crate_id,
353         }
354     }
355
356     /// Adds a definition with a parent definition.
357     pub fn create_def(
358         &mut self,
359         parent: LocalDefId,
360         data: DefPathData,
361         expn_id: ExpnId,
362         span: Span,
363     ) -> LocalDefId {
364         debug!("create_def(parent={:?}, data={:?}, expn_id={:?})", parent, data, expn_id);
365
366         // The root node must be created with `create_root_def()`.
367         assert!(data != DefPathData::CrateRoot);
368
369         // Find the next free disambiguator for this key.
370         let disambiguator = {
371             let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
372             let disambiguator = *next_disamb;
373             *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
374             disambiguator
375         };
376         let key = DefKey {
377             parent: Some(parent.local_def_index),
378             disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
379         };
380
381         let parent_hash = self.table.def_path_hash(parent.local_def_index);
382         let def_path_hash = key.compute_stable_hash(parent_hash);
383
384         debug!("create_def: after disambiguation, key = {:?}", key);
385
386         // Create the definition.
387         let def_id = LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) };
388
389         if expn_id != ExpnId::root() {
390             self.expansions_that_defined.insert(def_id, expn_id);
391         }
392
393         // A relative span's parent must be an absolute span.
394         debug_assert_eq!(span.data_untracked().parent, None);
395         let _id = self.def_id_to_span.push(span);
396         debug_assert_eq!(_id, def_id);
397
398         def_id
399     }
400
401     pub fn expansion_that_defined(&self, id: LocalDefId) -> ExpnId {
402         self.expansions_that_defined.get(&id).copied().unwrap_or_else(ExpnId::root)
403     }
404
405     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
406     #[inline]
407     pub fn def_span(&self, def_id: LocalDefId) -> Span {
408         self.def_id_to_span[def_id]
409     }
410
411     pub fn iter_local_def_id(&self) -> impl Iterator<Item = LocalDefId> + '_ {
412         self.table.def_path_hashes.indices().map(|local_def_index| LocalDefId { local_def_index })
413     }
414
415     #[inline(always)]
416     pub fn local_def_path_hash_to_def_id(
417         &self,
418         hash: DefPathHash,
419         err: &mut dyn FnMut() -> !,
420     ) -> LocalDefId {
421         debug_assert!(hash.stable_crate_id() == self.stable_crate_id);
422         self.table
423             .def_path_hash_to_index
424             .get(&hash)
425             .map(|local_def_index| LocalDefId { local_def_index })
426             .unwrap_or_else(|| err())
427     }
428
429     pub fn def_path_hash_to_def_index_map(&self) -> &DefPathHashMap {
430         &self.table.def_path_hash_to_index
431     }
432 }
433
434 #[derive(Copy, Clone, PartialEq, Debug)]
435 pub enum DefPathDataName {
436     Named(Symbol),
437     Anon { namespace: Symbol },
438 }
439
440 impl DefPathData {
441     pub fn get_opt_name(&self) -> Option<Symbol> {
442         use self::DefPathData::*;
443         match *self {
444             TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
445
446             Impl | ForeignMod | CrateRoot | Misc | ClosureExpr | Ctor | AnonConst | ImplTrait => {
447                 None
448             }
449         }
450     }
451
452     pub fn name(&self) -> DefPathDataName {
453         use self::DefPathData::*;
454         match *self {
455             TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => {
456                 DefPathDataName::Named(name)
457             }
458             // Note that this does not show up in user print-outs.
459             CrateRoot => DefPathDataName::Anon { namespace: kw::Crate },
460             Impl => DefPathDataName::Anon { namespace: kw::Impl },
461             ForeignMod => DefPathDataName::Anon { namespace: kw::Extern },
462             Misc => DefPathDataName::Anon { namespace: sym::misc },
463             ClosureExpr => DefPathDataName::Anon { namespace: sym::closure },
464             Ctor => DefPathDataName::Anon { namespace: sym::constructor },
465             AnonConst => DefPathDataName::Anon { namespace: sym::constant },
466             ImplTrait => DefPathDataName::Anon { namespace: sym::opaque },
467         }
468     }
469 }
470
471 impl fmt::Display for DefPathData {
472     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
473         match self.name() {
474             DefPathDataName::Named(name) => f.write_str(name.as_str()),
475             // FIXME(#70334): this will generate legacy {{closure}}, {{impl}}, etc
476             DefPathDataName::Anon { namespace } => write!(f, "{{{{{}}}}}", namespace),
477         }
478     }
479 }