1use std::fmt::{self, Write};
8use std::hash::Hash;
9
10use rustc_data_structures::stable_hasher::{Hash64, StableHasher};
11use rustc_data_structures::unord::UnordMap;
12use rustc_index::IndexVec;
13use rustc_macros::{Decodable, Encodable};
14use rustc_span::{Symbol, kw, sym};
15use tracing::{debug, instrument};
16
17pub use crate::def_id::DefPathHash;
18use crate::def_id::{CRATE_DEF_INDEX, CrateNum, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId};
19use crate::def_path_hash_map::DefPathHashMap;
20
21#[derive(Debug)]
26pub struct DefPathTable {
27 stable_crate_id: StableCrateId,
28 index_to_key: IndexVec<DefIndex, DefKey>,
29 def_path_hashes: IndexVec<DefIndex, Hash64>,
31 def_path_hash_to_index: DefPathHashMap,
32}
33
34impl DefPathTable {
35 fn new(stable_crate_id: StableCrateId) -> DefPathTable {
36 DefPathTable {
37 stable_crate_id,
38 index_to_key: Default::default(),
39 def_path_hashes: Default::default(),
40 def_path_hash_to_index: Default::default(),
41 }
42 }
43
44 fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) -> DefIndex {
45 debug_assert_eq!(self.stable_crate_id, def_path_hash.stable_crate_id());
47 let local_hash = def_path_hash.local_hash();
48
49 let index = {
50 let index = DefIndex::from(self.index_to_key.len());
51 debug!("DefPathTable::insert() - {:?} <-> {:?}", key, index);
52 self.index_to_key.push(key);
53 index
54 };
55 self.def_path_hashes.push(local_hash);
56 debug_assert!(self.def_path_hashes.len() == self.index_to_key.len());
57
58 if let Some(existing) = self.def_path_hash_to_index.insert(&local_hash, &index) {
61 let def_path1 = DefPath::make(LOCAL_CRATE, existing, |idx| self.def_key(idx));
62 let def_path2 = DefPath::make(LOCAL_CRATE, index, |idx| self.def_key(idx));
63
64 panic!(
73 "found DefPathHash collision between {def_path1:?} and {def_path2:?}. \
74 Compilation cannot continue."
75 );
76 }
77
78 index
79 }
80
81 #[inline(always)]
82 pub fn def_key(&self, index: DefIndex) -> DefKey {
83 self.index_to_key[index]
84 }
85
86 #[instrument(level = "trace", skip(self), ret)]
87 #[inline(always)]
88 pub fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
89 let hash = self.def_path_hashes[index];
90 DefPathHash::new(self.stable_crate_id, hash)
91 }
92
93 pub fn enumerated_keys_and_path_hashes(
94 &self,
95 ) -> impl Iterator<Item = (DefIndex, &DefKey, DefPathHash)> + ExactSizeIterator + '_ {
96 self.index_to_key
97 .iter_enumerated()
98 .map(move |(index, key)| (index, key, self.def_path_hash(index)))
99 }
100}
101
102#[derive(Debug)]
106pub struct Definitions {
107 table: DefPathTable,
108 next_disambiguator: UnordMap<(LocalDefId, DefPathData), u32>,
109}
110
111#[derive(Copy, Clone, PartialEq, Debug, Encodable, Decodable)]
115pub struct DefKey {
116 pub parent: Option<DefIndex>,
118
119 pub disambiguated_data: DisambiguatedDefPathData,
121}
122
123impl DefKey {
124 pub(crate) fn compute_stable_hash(&self, parent: DefPathHash) -> DefPathHash {
125 let mut hasher = StableHasher::new();
126
127 parent.hash(&mut hasher);
128
129 let DisambiguatedDefPathData { ref data, disambiguator } = self.disambiguated_data;
130
131 std::mem::discriminant(data).hash(&mut hasher);
132 if let Some(name) = data.get_opt_name() {
133 name.as_str().hash(&mut hasher);
136 }
137
138 disambiguator.hash(&mut hasher);
139
140 let local_hash = hasher.finish();
141
142 DefPathHash::new(parent.stable_crate_id(), local_hash)
147 }
148
149 #[inline]
150 pub fn get_opt_name(&self) -> Option<Symbol> {
151 self.disambiguated_data.data.get_opt_name()
152 }
153}
154
155#[derive(Copy, Clone, PartialEq, Debug, Encodable, Decodable)]
162pub struct DisambiguatedDefPathData {
163 pub data: DefPathData,
164 pub disambiguator: u32,
165}
166
167impl DisambiguatedDefPathData {
168 pub fn fmt_maybe_verbose(&self, writer: &mut impl Write, verbose: bool) -> fmt::Result {
169 match self.data.name() {
170 DefPathDataName::Named(name) => {
171 if verbose && self.disambiguator != 0 {
172 write!(writer, "{}#{}", name, self.disambiguator)
173 } else {
174 writer.write_str(name.as_str())
175 }
176 }
177 DefPathDataName::Anon { namespace } => {
178 write!(writer, "{{{}#{}}}", namespace, self.disambiguator)
179 }
180 }
181 }
182}
183
184impl fmt::Display for DisambiguatedDefPathData {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 self.fmt_maybe_verbose(f, true)
187 }
188}
189
190#[derive(Clone, Debug, Encodable, Decodable)]
191pub struct DefPath {
192 pub data: Vec<DisambiguatedDefPathData>,
194
195 pub krate: CrateNum,
197}
198
199impl DefPath {
200 pub fn make<FN>(krate: CrateNum, start_index: DefIndex, mut get_key: FN) -> DefPath
201 where
202 FN: FnMut(DefIndex) -> DefKey,
203 {
204 let mut data = vec![];
205 let mut index = Some(start_index);
206 loop {
207 debug!("DefPath::make: krate={:?} index={:?}", krate, index);
208 let p = index.unwrap();
209 let key = get_key(p);
210 debug!("DefPath::make: key={:?}", key);
211 match key.disambiguated_data.data {
212 DefPathData::CrateRoot => {
213 assert!(key.parent.is_none());
214 break;
215 }
216 _ => {
217 data.push(key.disambiguated_data);
218 index = key.parent;
219 }
220 }
221 }
222 data.reverse();
223 DefPath { data, krate }
224 }
225
226 pub fn to_string_no_crate_verbose(&self) -> String {
230 let mut s = String::with_capacity(self.data.len() * 16);
231
232 for component in &self.data {
233 write!(s, "::{component}").unwrap();
234 }
235
236 s
237 }
238
239 pub fn to_filename_friendly_no_crate(&self) -> String {
243 let mut s = String::with_capacity(self.data.len() * 16);
244
245 let mut opt_delimiter = None;
246 for component in &self.data {
247 s.extend(opt_delimiter);
248 opt_delimiter = Some('-');
249 write!(s, "{component}").unwrap();
250 }
251
252 s
253 }
254}
255
256#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
258pub enum DefPathData {
259 CrateRoot,
263
264 Impl,
267 ForeignMod,
269 Use,
271 GlobalAsm,
273 TypeNs(Symbol),
275 ValueNs(Symbol),
277 MacroNs(Symbol),
279 LifetimeNs(Symbol),
281 Closure,
283
284 Ctor,
287 AnonConst,
289 OpaqueTy,
292}
293
294impl Definitions {
295 pub fn def_path_table(&self) -> &DefPathTable {
296 &self.table
297 }
298
299 pub fn def_index_count(&self) -> usize {
301 self.table.index_to_key.len()
302 }
303
304 #[inline]
305 pub fn def_key(&self, id: LocalDefId) -> DefKey {
306 self.table.def_key(id.local_def_index)
307 }
308
309 #[inline(always)]
310 pub fn def_path_hash(&self, id: LocalDefId) -> DefPathHash {
311 self.table.def_path_hash(id.local_def_index)
312 }
313
314 pub fn def_path(&self, id: LocalDefId) -> DefPath {
320 DefPath::make(LOCAL_CRATE, id.local_def_index, |index| {
321 self.def_key(LocalDefId { local_def_index: index })
322 })
323 }
324
325 pub fn new(stable_crate_id: StableCrateId) -> Definitions {
327 let key = DefKey {
328 parent: None,
329 disambiguated_data: DisambiguatedDefPathData {
330 data: DefPathData::CrateRoot,
331 disambiguator: 0,
332 },
333 };
334
335 let parent_hash = DefPathHash::new(stable_crate_id, Hash64::ZERO);
336 let def_path_hash = key.compute_stable_hash(parent_hash);
337
338 let mut table = DefPathTable::new(stable_crate_id);
340 let root = LocalDefId { local_def_index: table.allocate(key, def_path_hash) };
341 assert_eq!(root.local_def_index, CRATE_DEF_INDEX);
342
343 Definitions { table, next_disambiguator: Default::default() }
344 }
345
346 pub fn create_def(&mut self, parent: LocalDefId, data: DefPathData) -> LocalDefId {
348 debug!(
351 "create_def(parent={}, data={data:?})",
352 self.def_path(parent).to_string_no_crate_verbose(),
353 );
354
355 assert!(data != DefPathData::CrateRoot);
357
358 let disambiguator = {
360 let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
361 let disambiguator = *next_disamb;
362 *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
363 disambiguator
364 };
365 let key = DefKey {
366 parent: Some(parent.local_def_index),
367 disambiguated_data: DisambiguatedDefPathData { data, disambiguator },
368 };
369
370 let parent_hash = self.table.def_path_hash(parent.local_def_index);
371 let def_path_hash = key.compute_stable_hash(parent_hash);
372
373 debug!("create_def: after disambiguation, key = {:?}", key);
374
375 LocalDefId { local_def_index: self.table.allocate(key, def_path_hash) }
377 }
378
379 #[inline(always)]
380 pub fn local_def_path_hash_to_def_id(&self, hash: DefPathHash) -> Option<LocalDefId> {
386 debug_assert!(hash.stable_crate_id() == self.table.stable_crate_id);
387 self.table
388 .def_path_hash_to_index
389 .get(&hash.local_hash())
390 .map(|local_def_index| LocalDefId { local_def_index })
391 }
392
393 pub fn def_path_hash_to_def_index_map(&self) -> &DefPathHashMap {
394 &self.table.def_path_hash_to_index
395 }
396
397 pub fn num_definitions(&self) -> usize {
398 self.table.def_path_hashes.len()
399 }
400}
401
402#[derive(Copy, Clone, PartialEq, Debug)]
403pub enum DefPathDataName {
404 Named(Symbol),
405 Anon { namespace: Symbol },
406}
407
408impl DefPathData {
409 pub fn get_opt_name(&self) -> Option<Symbol> {
410 use self::DefPathData::*;
411 match *self {
412 TypeNs(name) if name == kw::Empty => None,
413 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
414
415 Impl | ForeignMod | CrateRoot | Use | GlobalAsm | Closure | Ctor | AnonConst
416 | OpaqueTy => None,
417 }
418 }
419
420 pub fn name(&self) -> DefPathDataName {
421 use self::DefPathData::*;
422 match *self {
423 TypeNs(name) if name == kw::Empty => {
424 DefPathDataName::Anon { namespace: sym::synthetic }
425 }
426 TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => {
427 DefPathDataName::Named(name)
428 }
429 CrateRoot => DefPathDataName::Anon { namespace: kw::Crate },
431 Impl => DefPathDataName::Anon { namespace: kw::Impl },
432 ForeignMod => DefPathDataName::Anon { namespace: kw::Extern },
433 Use => DefPathDataName::Anon { namespace: kw::Use },
434 GlobalAsm => DefPathDataName::Anon { namespace: sym::global_asm },
435 Closure => DefPathDataName::Anon { namespace: sym::closure },
436 Ctor => DefPathDataName::Anon { namespace: sym::constructor },
437 AnonConst => DefPathDataName::Anon { namespace: sym::constant },
438 OpaqueTy => DefPathDataName::Anon { namespace: sym::opaque },
439 }
440 }
441}
442
443impl fmt::Display for DefPathData {
444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445 match self.name() {
446 DefPathDataName::Named(name) => f.write_str(name.as_str()),
447 DefPathDataName::Anon { namespace } => write!(f, "{{{{{namespace}}}}}"),
449 }
450 }
451}