1use crate::frontend::AdtInto;
5use crate::frontend::prelude::*;
6use charon_lib::ast::HashConsed;
7
8use itertools::Itertools;
9use rustc_hash::FxHashSet as HashSet;
10pub use rustc_middle::mir::Promoted as PromotedId;
11pub use rustc_middle::mir::interpret::AllocId as RAllocId;
12use rustc_middle::ty::CallerBoundsIterator;
13use rustc_span::DUMMY_SP;
14use rustc_trait_elaboration::{GenericParams, param_env_from_clauses};
15use {rustc_hir as hir, rustc_hir::def_id::DefId as RDefId, rustc_middle::ty};
16
17sinto_reexport!(
18 hir::Safety,
19 hir::Mutability,
20 hir::def::CtorKind,
21 hir::def::MacroKinds,
22 hir::def::CtorOf,
23 rustc_span::symbol::Symbol,
24 rustc_span::symbol::ByteSymbol
25);
26
27#[derive(AdtInto)]
29#[args(<S>, from: rustc_hir::def::DefKind, state: S as tcx)]
30#[derive(Debug, Clone, PartialEq, Eq, Hash)]
31pub enum DefKind {
32 Mod,
33 Struct,
34 Union,
35 Enum,
36 Variant,
37 Trait,
38 TyAlias,
39 ForeignTy,
40 TraitAlias,
41 AssocTy,
42 TyParam,
43 Fn,
44 #[disable_mapping]
45 FnPtr,
46 Const,
47 ConstParam,
48 Static {
49 safety: Safety,
50 mutability: Mutability,
51 nested: bool,
52 },
53 Ctor(CtorOf, CtorKind),
54 AssocFn,
55 AssocConst,
56 Macro(MacroKinds),
57 ExternCrate,
58 Use,
59 ForeignMod,
60 AnonConst,
61 #[disable_mapping]
62 PromotedConst,
64 OpaqueTy,
65 Field,
66 LifetimeParam,
67 GlobalAsm,
68 Impl {
69 of_trait: bool,
70 },
71 Closure,
72 SyntheticCoroutineBody,
73 TestBinderConstraints,
74}
75
76const SYNTHETIC_CRATE_NAME: &str = "<synthetic>";
78
79#[derive(Clone, PartialEq, Eq)]
82pub struct DefId {
83 pub(crate) contents: HashConsed<DefIdContents>,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Hash)]
87pub struct DefIdContents {
88 pub base: DefIdBase,
89 pub kind: crate::frontend::DefKind,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Hash)]
94pub enum DefIdBase {
95 Real(RDefId),
96 DerivedItem(DefId, DerivedItemKind),
99 Promoted(RDefId, PromotedId),
101 ImplAssocItem(VirtualImplAssocItem),
105 Synthetic(SyntheticItem),
108 Alloc(RAllocId),
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Hash)]
114pub enum DerivedItemKind {
115 Initializer,
118 IntrinsicFallback,
121 ClosureAsFnCast,
124 TraitAliasImpl,
126 MarkerImpl,
129 DropGlueMethodDef,
132 BuiltinAssocItemImpl(DefId),
135 DestructImpl,
139 FnImpl(ClosureKind),
142 VTableDef,
145 VTableImpl,
148 VTableMethodShim,
152 VTableDropShim,
157}
158
159impl DerivedItemKind {
160 pub fn def_kind(&self) -> DefKind {
161 match self {
162 DerivedItemKind::Initializer
163 | DerivedItemKind::IntrinsicFallback
164 | DerivedItemKind::ClosureAsFnCast
165 | DerivedItemKind::VTableMethodShim
166 | DerivedItemKind::VTableDropShim => DefKind::Fn,
167 DerivedItemKind::VTableDef => DefKind::Struct,
168 DerivedItemKind::VTableImpl => DefKind::Static {
169 safety: Safety::Safe,
170 mutability: Mutability::Not,
171 nested: false,
172 },
173 DerivedItemKind::DropGlueMethodDef => DefKind::AssocFn,
174 DerivedItemKind::BuiltinAssocItemImpl(decl) => decl.kind.clone(),
175 DerivedItemKind::TraitAliasImpl
176 | DerivedItemKind::MarkerImpl
177 | DerivedItemKind::DestructImpl
178 | DerivedItemKind::FnImpl(_) => DefKind::Impl { of_trait: true },
179 }
180 }
181}
182
183#[derive(Debug, Clone, PartialEq, Eq, Hash)]
184pub struct VirtualImplAssocItem {
185 pub trait_impl_id: DefId,
187 pub item_decl_id: DefId,
189 pub item_impl_id: DefId,
191}
192
193impl VirtualImplAssocItem {
194 pub fn new(trait_impl_id: DefId, item_decl_id: DefId, item_impl_id: DefId) -> Self {
195 Self {
196 trait_impl_id,
197 item_decl_id,
198 item_impl_id,
199 }
200 }
201
202 fn own_args<'tcx>(&self, s: &impl BaseState<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
205 let tcx = s.base().tcx;
206 DefId::make_assoc_item_impl(s, self.clone())
207 .generics_of(s)
208 .own_params
209 .iter()
210 .map(|param| tcx.mk_param_from_def(param))
211 .collect()
212 }
213
214 pub fn args_for_item_decl<'tcx>(
216 &self,
217 s: &impl BaseState<'tcx>,
218 trait_args: ty::GenericArgs<'tcx>,
219 ) -> ty::GenericArgs<'tcx> {
220 let tcx = s.base().tcx;
221 tcx.mk_args_from_iter(trait_args.iter().chain(self.own_args(s)))
222 }
223
224 pub fn args_for_item_impl<'tcx>(
226 &self,
227 s: &impl BaseState<'tcx>,
228 impl_args: ty::GenericArgs<'tcx>,
229 ) -> ty::GenericArgs<'tcx> {
230 let tcx = s.base().tcx;
231 tcx.mk_args_from_iter(impl_args.iter().chain(self.own_args(s)))
232 }
233
234 pub fn identity_args_for_item_decl<'tcx>(
236 &self,
237 s: &impl BaseState<'tcx>,
238 ) -> ty::GenericArgs<'tcx> {
239 let impl_trait_ref = self
240 .trait_impl_id
241 .impl_trait_ref(s)
242 .instantiate_identity()
243 .skip_normalization();
244 self.args_for_item_decl(s, impl_trait_ref.args)
245 }
246}
247
248impl DefIdContents {
249 pub fn make_def_id<'tcx, S: BaseState<'tcx>>(self, _s: &S) -> DefId {
250 let contents = HashConsed::new(self);
251 DefId { contents }
252 }
253}
254
255impl rustc_trait_elaboration::ItemId for DefId {
256 type State<'tcx> = StateWithBase<'tcx>;
257
258 fn from_rust_def_id<'tcx>(s: &Self::State<'tcx>, def_id: RDefId) -> Self {
259 def_id.sinto(s)
260 }
261
262 fn predicate_owner(&self) -> Self {
263 match &self.base {
264 DefIdBase::DerivedItem(_, kind)
265 if matches!(kind.def_kind(), DefKind::AssocFn | DefKind::AssocTy)
266 || matches!(
267 kind,
268 DerivedItemKind::VTableDropShim
269 | DerivedItemKind::TraitAliasImpl
270 | DerivedItemKind::MarkerImpl
271 ) =>
272 {
273 self.clone()
274 }
275 DefIdBase::DerivedItem(base, _) => base.predicate_owner(),
276 _ => self.clone(),
277 }
278 }
279
280 fn generics_of<'tcx>(&self, s: &Self::State<'tcx>) -> GenericParams<'tcx, Self> {
281 DefId::generics_of(self, s)
282 }
283
284 fn param_env<'tcx>(&self, s: &Self::State<'tcx>) -> ty::ParamEnv<'tcx> {
285 DefId::param_env(self, s)
286 }
287
288 fn predicates_defined_on<'tcx>(
289 &self,
290 s: &Self::State<'tcx>,
291 direction: PredicateDirection,
292 ) -> ItemPredicates<'tcx, Self> {
293 let tcx = s.base().tcx;
294 match &self.base {
295 DefIdBase::Real(def_id)
297 if self.kind == DefKind::TyAlias && direction == PredicateDirection::Required =>
298 {
299 let predicates: ItemPredicates<'tcx, Self> =
300 ItemPredicates::defined_on(tcx, s, *def_id, direction);
301 ItemPredicates::new(
302 self.clone(),
303 direction,
304 predicates
305 .iter()
306 .map(|pred| (pred.clause, pred.span))
307 .chain(
308 self.extra_ty_alias_clauses(s)
309 .into_iter()
310 .map(|clause| (clause, tcx.def_span(*def_id))),
311 ),
312 )
313 }
314 DefIdBase::Real(def_id) => ItemPredicates::defined_on(tcx, s, *def_id, direction),
315 DefIdBase::DerivedItem(base, DerivedItemKind::TraitAliasImpl) => {
316 let predicates = if direction == PredicateDirection::Required {
318 base.predicates_defined_on(s, PredicateDirection::Implied)
319 } else {
320 ItemPredicates::default()
321 };
322 ItemPredicates::new(
323 self.clone(),
324 direction,
325 predicates.iter().map(|pred| (pred.clause, pred.span)),
326 )
327 }
328 DefIdBase::DerivedItem(_, kind)
329 if matches!(kind.def_kind(), DefKind::AssocFn | DefKind::AssocTy)
330 || matches!(
331 kind,
332 DerivedItemKind::VTableDropShim | DerivedItemKind::MarkerImpl
333 ) =>
334 {
335 ItemPredicates::new(self.clone(), direction, [])
336 }
337 DefIdBase::DerivedItem(def_id, _) => def_id.predicates_defined_on(s, direction),
338 DefIdBase::ImplAssocItem(id) => {
339 let item_args = id.identity_args_for_item_decl(s);
340 id.item_decl_id
341 .predicates_defined_on(s, direction)
342 .instantiate(tcx, item_args)
343 }
344 DefIdBase::Synthetic(synthetic) => {
345 synthetic.predicates_defined_on(s, self.clone(), direction)
346 }
347 DefIdBase::Promoted(..) | DefIdBase::Alloc(..) => {
348 ItemPredicates::new_unmapped(DUMMY_SP, [])
349 }
350 }
351 }
352
353 fn self_pred<'tcx>(&self, s: &Self::State<'tcx>) -> Option<ty::PolyTraitRef<'tcx>> {
354 let tcx = s.base().tcx;
355 match &self.base {
356 DefIdBase::Real(def_id) => def_id.self_pred(&tcx),
357 DefIdBase::DerivedItem(_, kind)
358 if matches!(kind.def_kind(), DefKind::AssocFn | DefKind::AssocTy)
359 || matches!(
360 kind,
361 DerivedItemKind::TraitAliasImpl | DerivedItemKind::MarkerImpl
362 ) =>
363 {
364 None
365 }
366 DefIdBase::DerivedItem(def_id, _) => def_id.self_pred(s),
367 _ => None,
368 }
369 }
370
371 fn as_identity_assoc_ty<'tcx>(&self, s: &Self::State<'tcx>) -> Option<ty::Ty<'tcx>> {
372 let tcx = s.base().tcx;
373 match self.base {
374 DefIdBase::Real(def_id) => def_id.as_identity_assoc_ty(&tcx),
375 _ => None,
376 }
377 }
378
379 fn typeck_parent<'tcx>(&self, s: &Self::State<'tcx>) -> Option<Self> {
380 let tcx = s.base().tcx;
381 match &self.base {
382 DefIdBase::Real(def_id) => def_id.typeck_parent(&tcx).map(|def_id| def_id.sinto(s)),
383 DefIdBase::DerivedItem(_, kind)
384 if matches!(kind.def_kind(), DefKind::AssocFn | DefKind::AssocTy)
385 || *kind == DerivedItemKind::VTableDropShim =>
386 {
387 None
388 }
389 DefIdBase::DerivedItem(def_id, _) => def_id.typeck_parent(s),
390 DefIdBase::Promoted(def_id, ..) => Some(tcx.typeck_root_def_id(*def_id).sinto(s)),
391 DefIdBase::ImplAssocItem(..) | DefIdBase::Synthetic(..) | DefIdBase::Alloc(..) => None,
392 }
393 }
394
395 fn parent_of_assoc<'tcx>(&self, s: &Self::State<'tcx>) -> Option<Self> {
396 let tcx = s.base().tcx;
397 match &self.base {
398 DefIdBase::Real(def_id) => def_id.parent_of_assoc(&tcx).map(|def_id| def_id.sinto(s)),
399 DefIdBase::DerivedItem(_, kind)
400 if matches!(kind.def_kind(), DefKind::AssocFn | DefKind::AssocTy) =>
401 {
402 self.typing_parent(s)
403 }
404 DefIdBase::DerivedItem(def_id, _) => def_id.parent_of_assoc(s),
405 DefIdBase::ImplAssocItem(id) => Some(id.trait_impl_id.clone()),
406 _ => None,
407 }
408 }
409
410 fn parent_for_clauses<'tcx>(&self, s: &Self::State<'tcx>) -> Option<Self> {
411 let tcx = s.base().tcx;
412 match &self.base {
413 DefIdBase::Real(def_id) => def_id
414 .parent_for_clauses(&tcx)
415 .map(|def_id| def_id.sinto(s)),
416 DefIdBase::DerivedItem(_, kind)
417 if matches!(kind.def_kind(), DefKind::AssocFn | DefKind::AssocTy)
418 || *kind == DerivedItemKind::VTableDropShim =>
419 {
420 self.typing_parent(s)
421 }
422 DefIdBase::DerivedItem(def_id, _) => def_id.parent_for_clauses(s),
423 DefIdBase::ImplAssocItem(id) => Some(id.trait_impl_id.clone()),
424 DefIdBase::Promoted(def_id, _) => Some(def_id.sinto(s)),
425 DefIdBase::Synthetic(..) | DefIdBase::Alloc(..) => None,
426 }
427 }
428
429 fn takes_explicit_self_clause<'tcx>(&self, s: &Self::State<'tcx>) -> bool {
430 let tcx = s.base().tcx;
431 match &self.base {
432 DefIdBase::Real(def_id) | DefIdBase::Promoted(def_id, ..) => {
433 def_id.takes_explicit_self_clause(&tcx)
434 }
435 DefIdBase::DerivedItem(_, kind)
436 if matches!(kind.def_kind(), DefKind::AssocFn | DefKind::AssocTy) =>
437 {
438 true
439 }
440 DefIdBase::DerivedItem(def_id, _) => def_id.takes_explicit_self_clause(s),
441 DefIdBase::ImplAssocItem(id) => id.item_decl_id.takes_explicit_self_clause(s),
442 DefIdBase::Synthetic(..) | DefIdBase::Alloc(..) => false,
443 }
444 }
445
446 fn find_in_impl<'tcx>(
447 &self,
448 s: &Self::State<'tcx>,
449 typing_env: ty::TypingEnv<'tcx>,
450 trait_impl: &Self,
451 impl_generics: ty::GenericArgs<'tcx>,
452 ) -> Option<(Self, ty::GenericArgs<'tcx>, bool)> {
453 let tcx = s.base().tcx;
454 if let DefIdBase::DerivedItem(_, kind) = &trait_impl.base {
455 let item = match (kind, &self.kind) {
456 (DerivedItemKind::FnImpl(_) | DerivedItemKind::DestructImpl, DefKind::AssocFn)
457 | (DerivedItemKind::FnImpl(ClosureKind::FnOnce), DefKind::AssocTy) => trait_impl
458 .clone()
459 .make_derived(DerivedItemKind::BuiltinAssocItemImpl(self.clone())),
460 _ => return None,
461 };
462 return Some((item, impl_generics, true));
464 }
465 match self.base {
466 DefIdBase::Real(def_id) => {
467 let trait_impl = trait_impl.as_real_def_id()?;
468 def_id
469 .find_in_impl(&tcx, typing_env, &trait_impl, impl_generics)
470 .map(|(item, generics, is_final)| (item.sinto(s), generics, is_final))
471 }
472 _ => None,
473 }
474 }
475}
476
477impl DefId {
478 pub fn as_real_def_id(&self) -> Option<RDefId> {
481 match self.base {
482 DefIdBase::Real(did) => Some(did),
483 _ => None,
484 }
485 }
486 pub fn real_rust_def_id(&self) -> RDefId {
488 self.as_real_def_id().unwrap()
489 }
490 pub fn as_real_or_promoted(&self) -> Option<RDefId> {
492 match self.base {
493 DefIdBase::Real(did) | DefIdBase::Promoted(did, ..) => Some(did),
494 _ => None,
495 }
496 }
497 pub fn promoted_id(&self) -> Option<PromotedId> {
498 match self.base {
499 DefIdBase::Promoted(_, promoted) => Some(promoted),
500 _ => None,
501 }
502 }
503 pub fn as_derived(&self) -> Option<&DerivedItemKind> {
505 match &self.base {
506 DefIdBase::DerivedItem(_, kind) => Some(kind),
507 _ => None,
508 }
509 }
510 pub fn as_synthetic<'tcx>(&self, _s: &impl BaseState<'tcx>) -> Option<SyntheticItem> {
512 match self.base {
513 DefIdBase::Synthetic(v) => Some(v),
514 _ => None,
515 }
516 }
517
518 pub fn peel_derived(&self) -> &Self {
520 match &self.base {
521 DefIdBase::DerivedItem(base, _) => base,
522 _ => self,
523 }
524 }
525
526 pub fn derived_base(&self) -> &Self {
528 match &self.base {
529 DefIdBase::DerivedItem(base, _) => base.derived_base(),
530 _ => self,
531 }
532 }
533
534 pub fn is_local(&self) -> bool {
535 match &self.base {
536 DefIdBase::Real(did) | DefIdBase::Promoted(did, ..) => did.is_local(),
537 DefIdBase::DerivedItem(def_id, _) => def_id.is_local(),
538 DefIdBase::ImplAssocItem(id) => id.trait_impl_id.is_local(),
539 DefIdBase::Synthetic(..) => false,
540 DefIdBase::Alloc(..) => true,
541 }
542 }
543 pub fn is_typeck_child<'tcx>(&self, s: &impl BaseState<'tcx>) -> bool {
544 match self.base {
545 DefIdBase::Real(did) => s.base().tcx.is_typeck_child(did),
546 _ => false,
547 }
548 }
549
550 fn make<'tcx, S: BaseState<'tcx>>(s: &S, def_id: RDefId) -> Self {
551 let base = DefIdBase::Real(def_id);
552 let tcx = s.base().tcx;
553 let contents = DefIdContents {
554 base,
555 kind: get_def_kind(tcx, def_id).sinto(s),
556 };
557 contents.make_def_id(s)
558 }
559
560 pub fn make_derived(self, kind: DerivedItemKind) -> Self {
562 let def_kind = kind.def_kind();
563 Self {
564 contents: HashConsed::new(DefIdContents {
565 base: DefIdBase::DerivedItem(self, kind),
566 kind: def_kind,
567 }),
568 }
569 }
570
571 pub fn make_synthetic<'tcx, S: BaseState<'tcx>>(s: &S, synthetic: SyntheticItem) -> Self {
572 let kind = match synthetic {
573 SyntheticItem::FnPtr(_) => DefKind::FnPtr,
574 _ => DefKind::Struct,
575 };
576 let contents = DefIdContents {
577 base: DefIdBase::Synthetic(synthetic),
578 kind,
579 };
580 contents.make_def_id(s)
581 }
582
583 pub fn make_promoted_child<'tcx, S: BaseState<'tcx>>(
586 &self,
587 s: &S,
588 promoted_id: PromotedId,
589 ) -> Self {
590 let contents = DefIdContents {
591 base: DefIdBase::Promoted(self.real_rust_def_id(), promoted_id),
592 kind: DefKind::PromotedConst,
593 };
594 contents.make_def_id(s)
595 }
596
597 pub fn make_assoc_item_impl<'tcx, S: BaseState<'tcx>>(
598 s: &S,
599 vitem: VirtualImplAssocItem,
600 ) -> Self {
601 let contents = DefIdContents {
602 kind: vitem.item_decl_id.kind.clone(),
603 base: DefIdBase::ImplAssocItem(vitem),
604 };
605 contents.make_def_id(s)
606 }
607
608 pub fn make_anon_alloc<'tcx, S: BaseState<'tcx>>(s: &S, alloc_id: RAllocId) -> Self {
610 let tcx = s.base().tcx;
611 s.with_global_cache(|cache| cache.anon_allocs.insert(alloc_id));
612 let mutability = GlobalRef::Alloc(alloc_id).mutability(tcx);
613 let contents = DefIdContents {
614 base: DefIdBase::Alloc(alloc_id),
615 kind: DefKind::Static {
616 safety: Safety::Safe,
617 mutability,
618 nested: true,
619 },
620 };
621 contents.make_def_id(s)
622 }
623}
624
625impl DefId {
626 fn crate_name_and_disambig<'tcx>(&self, s: &impl BaseState<'tcx>) -> (Symbol, u32) {
627 let tcx = s.base().tcx;
628 match &self.base {
629 DefIdBase::Real(def_id) | DefIdBase::Promoted(def_id, ..) => {
630 s.with_global_cache(|cache| cache.crate_name(tcx, def_id.krate))
631 }
632 DefIdBase::ImplAssocItem(id) => id.trait_impl_id.crate_name_and_disambig(s),
633 DefIdBase::DerivedItem(def_id, _) => def_id.crate_name_and_disambig(s),
634 DefIdBase::Synthetic(..) => (Symbol::intern(SYNTHETIC_CRATE_NAME), 0),
635 DefIdBase::Alloc(..) => {
636 s.with_global_cache(|cache| cache.crate_name(tcx, rustc_hir::def_id::LOCAL_CRATE))
637 }
638 }
639 }
640
641 pub fn crate_name<'tcx>(&self, s: &impl BaseState<'tcx>) -> Symbol {
642 self.crate_name_and_disambig(s).0
643 }
644
645 pub fn def_span<'tcx>(&self, s: &impl BaseState<'tcx>) -> Span {
648 use DefKind::*;
649 let tcx = s.base().tcx;
650 match &self.base {
651 DefIdBase::Real(def_id) | DefIdBase::Promoted(def_id, ..) => {
652 if let ForeignMod = &self.kind {
653 rustc_span::DUMMY_SP
655 } else if let Some(ldid) = def_id.as_local()
656 && let hir_id = tcx.local_def_id_to_hir_id(ldid)
657 && matches!(tcx.hir_node(hir_id), rustc_hir::Node::Synthetic)
658 {
659 rustc_span::DUMMY_SP
661 } else {
662 tcx.def_span(*def_id)
663 }
664 }
665 DefIdBase::DerivedItem(def_id, _) => def_id.def_span(s),
666 DefIdBase::ImplAssocItem(id) => id.item_impl_id.def_span(s),
667 DefIdBase::Synthetic(..) | DefIdBase::Alloc(..) => rustc_span::DUMMY_SP,
668 }
669 }
670
671 pub fn path_item<'tcx>(&self, s: &impl BaseState<'tcx>) -> DisambiguatedDefPathItem {
673 match &self.base {
674 DefIdBase::Real(def_id) => {
675 let tcx = s.base().tcx;
676 let s = &s.with_frontend_owner(self);
678 tcx.def_path(*def_id)
679 .data
680 .last()
681 .map(|x| x.sinto(s))
682 .unwrap_or_else(|| {
683 let (name, disambiguator) = self.crate_name_and_disambig(s);
684 DisambiguatedDefPathItem {
685 disambiguator,
686 data: DefPathItem::CrateRoot { name },
687 }
688 })
689 }
690 DefIdBase::DerivedItem(def_id, _) => def_id.path_item(s),
693 DefIdBase::Promoted(_, id) => DisambiguatedDefPathItem {
694 data: DefPathItem::PromotedConst,
695 disambiguator: id.as_u32(),
697 },
698 DefIdBase::ImplAssocItem(id) => id.item_decl_id.path_item(s),
699 DefIdBase::Synthetic(synthetic) => DisambiguatedDefPathItem {
700 disambiguator: 0,
701 data: DefPathItem::TypeNs(Symbol::intern(&synthetic.name())),
702 },
703 DefIdBase::Alloc(alloc_id) => DisambiguatedDefPathItem {
704 data: DefPathItem::PromotedConst,
705 disambiguator: s.with_global_cache(|cache| {
707 cache.anon_allocs.get_index_of(alloc_id).unwrap() as u32
708 }),
709 },
710 }
711 }
712
713 pub fn parent<'tcx>(&self, s: &impl BaseState<'tcx>) -> Option<DefId> {
715 match &self.base {
716 DefIdBase::Real(def_id) => s.tcx().opt_parent(*def_id),
717 DefIdBase::DerivedItem(def_id, _) => return def_id.parent(s),
718 DefIdBase::Promoted(def_id, _) => Some(*def_id),
719 DefIdBase::ImplAssocItem(id) => return Some(id.trait_impl_id.clone()),
720 DefIdBase::Synthetic(..) | DefIdBase::Alloc(..) => {
721 Some(rustc_span::def_id::CRATE_DEF_ID.to_def_id())
722 }
723 }
724 .sinto(s)
725 }
726
727 pub fn typing_parent<'tcx>(&self, s: &impl BaseState<'tcx>) -> Option<DefId> {
729 match self.as_derived() {
730 Some(
731 DerivedItemKind::DropGlueMethodDef
732 | DerivedItemKind::BuiltinAssocItemImpl(_)
733 | DerivedItemKind::VTableDropShim,
734 ) => {
735 return Some(self.peel_derived().clone());
736 }
737 Some(DerivedItemKind::VTableMethodShim) => return self.peel_derived().typing_parent(s),
738 _ => {}
739 }
740 let base = self.derived_base();
742 match base.kind {
743 DefKind::AssocTy
744 | DefKind::AssocFn
745 | DefKind::AssocConst
746 | DefKind::Closure
747 | DefKind::AnonConst
748 | DefKind::PromotedConst => base.generics_of(s).parent,
749 DefKind::Ctor(..) | DefKind::Variant => Some(self.parent(s).unwrap()),
750 _ => None,
751 }
752 }
753}
754
755impl DefId {
756 pub fn can_have_generics<'tcx>(&self, s: &impl BaseState<'tcx>) -> bool {
757 match &self.base {
758 DefIdBase::Real(..) | DefIdBase::ImplAssocItem(..) => can_have_generics(&self.kind),
759 DefIdBase::DerivedItem(def_id, _) => def_id.can_have_generics(s),
760 DefIdBase::Promoted(def_id, ..) => def_id.sinto(s).can_have_generics(s),
761 DefIdBase::Synthetic(synthetic) => synthetic.can_have_generics(s),
762 DefIdBase::Alloc(..) => false,
763 }
764 }
765
766 pub fn has_generics<'tcx>(&self, s: &impl BaseState<'tcx>) -> bool {
768 self.can_have_generics(s) && self.generics_of(s).count() != 0
769 }
770
771 pub fn generics_of<'tcx>(&self, s: &impl BaseState<'tcx>) -> GenericParams<'tcx, Self> {
772 let tcx = s.base().tcx;
773 match &self.base {
774 DefIdBase::Real(def_id) => {
775 GenericParams::from_rustc(&s.base_state(), tcx.generics_of(*def_id))
776 }
777 DefIdBase::Synthetic(synthetic) => {
778 GenericParams::from_rustc(&s.base_state(), synthetic.generics_of(s))
779 }
780 DefIdBase::DerivedItem(_, kind)
781 if matches!(kind.def_kind(), DefKind::AssocFn | DefKind::AssocTy)
782 || *kind == DerivedItemKind::VTableDropShim =>
783 {
784 let parent = self.typing_parent(s).unwrap();
785 GenericParams {
786 parent_count: parent.generics_of(s).count(),
787 parent: Some(parent),
788 own_params: &[],
789 }
790 }
791 DefIdBase::DerivedItem(def_id, _) => def_id.generics_of(s),
792 DefIdBase::Promoted(..) | DefIdBase::Alloc(..) => {
793 let parent: Option<DefId> = match self.base {
794 DefIdBase::Promoted(def_id, ..) => Some(def_id.sinto(s)),
795 _ => None,
796 };
797 GenericParams {
798 parent_count: parent.as_ref().map_or(0, |p| p.generics_of(s).count()),
799 parent,
800 own_params: &[],
801 }
802 }
803 DefIdBase::ImplAssocItem(id) => s.with_item_cache(self, |cache| {
804 if let Some(generics) = &cache.virtual_generics {
805 return generics.clone();
806 }
807 let decl_generics = id.item_decl_id.generics_of(s);
809 let parent_count = id.trait_impl_id.generics_of(s).count();
810 let own_params = decl_generics
811 .own_params
812 .iter()
813 .cloned()
814 .enumerate()
815 .map(|(i, mut param)| {
816 param.index = parent_count as u32 + i as u32;
817 param
818 })
819 .collect_vec();
820 let generics = GenericParams {
821 parent: Some(id.trait_impl_id.clone()),
822 parent_count,
823 own_params: Box::leak(own_params.into_boxed_slice()),
824 };
825 cache.virtual_generics = Some(generics.clone());
826 generics
827 }),
828 }
829 }
830
831 pub fn identity_args<'tcx>(&self, s: &impl BaseState<'tcx>) -> ty::GenericArgs<'tcx> {
832 let tcx = s.base().tcx;
833 match &self.base {
834 DefIdBase::Real(def_id) | DefIdBase::Promoted(def_id, ..) => {
835 if self.can_have_generics(s) {
836 identity_args_with_inferred(tcx, *def_id)
837 } else {
838 ty::GenericArgs::default()
839 }
840 }
841 DefIdBase::DerivedItem(def_id, _) => def_id.identity_args(s),
842 DefIdBase::Synthetic(synthetic) => synthetic.identity_args(s),
843 DefIdBase::Alloc(..) => ty::GenericArgs::default(),
844 DefIdBase::ImplAssocItem(_) => panic!(
845 "virtual trait impl associated items do not have a \
846 sensible `identity_args`. consider `identity_args_for_item_decl`"
847 ),
848 }
849 }
850
851 pub fn identity_args_with_extra_regions<'tcx>(
853 &self,
854 s: &impl BaseState<'tcx>,
855 ) -> (ty::GenericArgs<'tcx>, Vec<ty::PlaceholderRegion<'tcx>>) {
856 let this = self.derived_base();
857 let args = this.identity_args(s);
858 if this.is_typeck_child(s) {
860 let name = rustc_span::Symbol::intern(&format!("__unerased_region_{this:?}"));
861 unerase_lifetimes(s, args, name)
862 } else {
863 (args, Vec::new())
864 }
865 }
866
867 fn extra_ty_alias_clauses<'tcx>(&self, s: &impl BaseState<'tcx>) -> Vec<ty::Clause<'tcx>> {
869 let DefIdBase::Real(def_id) = self.base else {
870 unreachable!()
871 };
872 let tcx = s.base().tcx;
873 s.with_item_cache(self, |cache| {
874 cache
875 .alias_clauses
876 .get_or_insert_with(|| {
877 let alias_ty = tcx
878 .type_of(def_id)
879 .instantiate_identity()
880 .skip_normalization();
881 let mut clauses = type_alias_trait_clauses(tcx, alias_ty);
882 let existing: HashSet<_> = tcx
883 .param_env(def_id)
884 .caller_bounds()
885 .all_clauses_interned(tcx)
886 .iter()
887 .map(|clause| tcx.anonymize_bound_vars(clause.kind()))
888 .collect();
889 clauses.retain(|clause| {
890 !existing.contains(&tcx.anonymize_bound_vars(clause.kind()))
891 });
892 clauses
893 })
894 .clone()
895 })
896 }
897
898 pub fn param_env<'tcx>(&self, s: &impl BaseState<'tcx>) -> ty::ParamEnv<'tcx> {
899 let tcx = s.base().tcx;
900 match &self.base {
901 DefIdBase::Real(def_id) if self.kind == DefKind::TyAlias => {
902 let param_env = tcx.param_env(*def_id);
903 param_env_from_clauses(
904 tcx,
905 param_env
906 .caller_bounds()
907 .all_clauses_interned(tcx)
908 .iter()
909 .chain(self.extra_ty_alias_clauses(s)),
910 )
911 }
912 DefIdBase::Real(def_id) | DefIdBase::Promoted(def_id, ..) => {
913 if self.can_have_generics(s) {
914 tcx.param_env(*def_id)
915 } else {
916 ty::ParamEnv::empty()
917 }
918 }
919 DefIdBase::DerivedItem(
920 _,
921 DerivedItemKind::TraitAliasImpl | DerivedItemKind::MarkerImpl,
922 ) => {
923 let predicates =
924 self.predicates_defined_on(&s.base_state(), PredicateDirection::Required);
925 param_env_from_clauses(tcx, predicates.iter().map(|pred| pred.clause))
926 }
927 DefIdBase::DerivedItem(def_id, _) => def_id.param_env(s),
928 DefIdBase::ImplAssocItem(id) => {
929 let item_args = id.identity_args_for_item_decl(s);
930 let impl_predicates = id
931 .trait_impl_id
932 .param_env(s)
933 .caller_bounds()
934 .all_clauses_interned(tcx)
935 .iter();
936 let item_predicates = id
937 .item_decl_id
938 .predicates_defined_on(&s.base_state(), PredicateDirection::Required)
939 .instantiate(tcx, item_args);
940 param_env_from_clauses(
941 tcx,
942 impl_predicates.chain(item_predicates.iter().map(|pred| pred.clause)),
943 )
944 }
945 DefIdBase::Synthetic(synthetic) => synthetic.param_env(s),
946 DefIdBase::Alloc(..) => ty::ParamEnv::empty(),
947 }
948 }
949
950 pub fn typing_env<'tcx>(&self, s: &impl BaseState<'tcx>) -> ty::TypingEnv<'tcx> {
951 ty::TypingEnv::new(self.param_env(s), ty::TypingMode::PostAnalysis)
952 }
953
954 pub fn required_predicates<'tcx, S: BaseState<'tcx>>(
955 &self,
956 s: &S,
957 ) -> ItemPredicates<'tcx, Self> {
958 let state = s.base_state();
959 ItemPredicates::required(s.base().elab_ctx, &state, self.clone())
960 }
961
962 pub fn type_of<'tcx, S: BaseState<'tcx>>(&self, s: &S) -> ty::EarlyBinder<'tcx, ty::Ty<'tcx>> {
963 let tcx: ty::TyCtxt<'tcx> = s.base().tcx;
964 match &self.base {
965 DefIdBase::Real(def_id) => tcx.type_of(*def_id),
966 DefIdBase::Promoted(def_id, promoted) => {
967 let ty = rustc_const_uneval::promoted_body(tcx, *def_id, *promoted, |body| {
968 body.local_decls[rustc_middle::mir::RETURN_PLACE].ty
969 });
970 ty::EarlyBinder::bind(tcx, ty)
971 }
972 DefIdBase::DerivedItem(parent, DerivedItemKind::BuiltinAssocItemImpl(decl))
973 if decl.kind == DefKind::AssocTy =>
974 {
975 let trait_ref = parent
976 .impl_trait_ref(s)
977 .instantiate_identity()
978 .skip_normalization();
979 ty::EarlyBinder::bind(
980 tcx,
981 ty::Ty::new_projection(
982 tcx,
983 ty::IsRigid::No,
984 decl.real_rust_def_id(),
985 trait_ref.args,
986 ),
987 )
988 }
989 DefIdBase::DerivedItem(..) => unimplemented!("`DerivedItem::type_of`"),
990 DefIdBase::Synthetic(synthetic) => synthetic.type_of(s),
991 DefIdBase::ImplAssocItem(id) => id.item_decl_id.type_of(s),
992 DefIdBase::Alloc(alloc_id) => s.with_global_cache(|cache| {
993 ty::EarlyBinder::bind(tcx, cache.const_reader_state.ty_or_default(tcx, *alloc_id))
994 }),
995 }
996 }
997}
998
999impl DefId {
1000 pub fn visibility<'tcx>(&self, tcx: ty::TyCtxt<'tcx>) -> Option<bool> {
1003 use DefKind::*;
1004 let base = self.derived_base();
1005 match base.kind {
1006 AssocConst { .. }
1007 | AssocFn
1008 | Const { .. }
1009 | Enum
1010 | Field
1011 | Fn
1012 | ForeignTy
1013 | Macro { .. }
1014 | Mod
1015 | Static { .. }
1016 | Struct
1017 | Trait
1018 | TraitAlias
1019 | TyAlias { .. }
1020 | Union
1021 | Use
1022 | Variant => {
1023 let def_id = base.as_real_def_id()?;
1024 Some(tcx.visibility(def_id).is_public())
1025 }
1026 AnonConst
1028 | AssocTy
1029 | Closure
1030 | ConstParam
1031 | Ctor { .. }
1032 | ExternCrate
1033 | ForeignMod
1034 | GlobalAsm
1035 | Impl { .. }
1036 | PromotedConst
1037 | FnPtr
1038 | LifetimeParam
1039 | OpaqueTy
1040 | SyntheticCoroutineBody
1041 | TestBinderConstraints
1042 | TyParam => None,
1043 }
1044 }
1045
1046 pub fn attrs<'tcx>(&self, tcx: ty::TyCtxt<'tcx>) -> &'tcx [rustc_attr_ir::Attribute] {
1048 use DefKind::*;
1049 let base = self.derived_base();
1050 let Some(def_id) = base.as_real_def_id() else {
1051 return &[];
1052 };
1053 if let Some(ldid) = def_id.as_local() {
1054 tcx.hir_attrs(tcx.local_def_id_to_hir_id(ldid))
1055 } else if matches!(
1056 base.kind,
1057 TyParam
1058 | LifetimeParam
1059 | ForeignMod
1060 | ExternCrate
1061 | AnonConst
1062 | OpaqueTy
1063 | Static { nested: true, .. }
1064 | GlobalAsm
1065 | TestBinderConstraints
1066 ) {
1067 &[]
1070 } else {
1071 let attrs = tcx.attrs_for_def(def_id);
1072
1073 let restored = if matches!(base.kind, Fn | AssocFn | Static { .. }) {
1075 use rustc_attr_ir::AttributeKind::*;
1076 let codegen_attrs = tcx.codegen_fn_attrs(def_id);
1077 let span = tcx.def_span(def_id);
1078
1079 use rustc_middle::middle::codegen_fn_attrs::TargetFeatureKind;
1081 let target_features = [
1082 (TargetFeatureKind::Enabled, false),
1083 (TargetFeatureKind::Forced, true),
1084 ]
1085 .into_iter()
1086 .map(|(kind, was_forced)| TargetFeature {
1087 features: codegen_attrs
1088 .target_features
1089 .iter()
1090 .filter(|feature| feature.kind == kind)
1091 .map(|feature| (feature.name, span))
1092 .collect(),
1093 attr_span: span,
1094 was_forced,
1095 })
1096 .filter(
1097 |attr| !matches!(attr, TargetFeature { features, .. } if features.is_empty()),
1098 );
1099
1100 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
1102 let allocator_flags = [
1103 (CodegenFnAttrFlags::ALLOCATOR, RustcAllocator),
1104 (CodegenFnAttrFlags::DEALLOCATOR, RustcDeallocator),
1105 (CodegenFnAttrFlags::REALLOCATOR, RustcReallocator),
1106 (CodegenFnAttrFlags::ALLOCATOR_ZEROED, RustcAllocatorZeroed),
1107 ]
1108 .into_iter()
1109 .filter(|(flag, _)| codegen_attrs.flags.contains(*flag))
1110 .map(|(_, attr)| attr);
1111
1112 let linkage = codegen_attrs
1114 .import_linkage
1115 .or(codegen_attrs.linkage)
1116 .map(|linkage| Linkage(linkage, span));
1117
1118 allocator_flags
1119 .chain(target_features)
1120 .chain(linkage)
1121 .map(rustc_attr_ir::Attribute::Parsed)
1122 .collect_vec()
1123 } else {
1124 vec![]
1125 };
1126
1127 if restored.is_empty() {
1128 attrs
1129 } else {
1130 tcx.arena
1131 .alloc_from_iter(attrs.iter().cloned().chain(restored))
1132 }
1133 }
1134 }
1135}
1136
1137impl std::ops::Deref for DefId {
1138 type Target = DefIdContents;
1139 fn deref(&self) -> &Self::Target {
1140 &self.contents
1141 }
1142}
1143
1144impl std::fmt::Debug for DefId {
1145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1146 match &self.base {
1147 DefIdBase::Real(def_id) => write!(f, "{def_id:?}"),
1148 DefIdBase::DerivedItem(def_id, kind) => write!(f, "{def_id:?}::{kind:?}"),
1149 DefIdBase::Promoted(def_id, promoted) => {
1150 write!(f, "{def_id:?}::promoted#{}", promoted.as_u32())
1151 }
1152 DefIdBase::Synthetic(item) => write!(f, "{}", item.name()),
1153 DefIdBase::Alloc(alloc_id) => write!(f, "{alloc_id:?}"),
1154 DefIdBase::ImplAssocItem(id) => {
1155 write!(f, "{:?}::{:?}", id.trait_impl_id, id.item_decl_id)
1156 }
1157 }
1158 }
1159}
1160
1161impl std::hash::Hash for DefId {
1162 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1163 self.base.hash(state);
1164 }
1165}
1166
1167pub(crate) fn get_def_kind<'tcx>(tcx: ty::TyCtxt<'tcx>, def_id: RDefId) -> hir::def::DefKind {
1170 if def_id == rustc_span::def_id::CRATE_DEF_ID.to_def_id() {
1171 let _ = tcx.def_span(def_id);
1174 };
1175 tcx.def_kind(def_id)
1176}
1177
1178impl<'s, S: BaseState<'s>> SInto<S, DefId> for RDefId {
1179 fn sinto(&self, s: &S) -> DefId {
1180 if let Some(def_id) = s.with_global_cache(|cache| cache.def_ids.get(self).cloned()) {
1181 return def_id;
1182 }
1183 let def_id = DefId::make(s, *self);
1184 s.with_global_cache(|cache| {
1185 cache.def_ids.insert(*self, def_id.clone());
1186 });
1187 def_id
1188 }
1189}
1190
1191impl<S> SInto<S, DefId> for DefId {
1192 fn sinto(&self, _s: &S) -> DefId {
1193 self.clone()
1194 }
1195}
1196
1197#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1199#[derive(AdtInto)]
1200#[args(<'ctx, S: UnderOwnerState<'ctx>>, from: rustc_hir::definitions::DefPathData, state: S as s)]
1201pub enum DefPathItem {
1202 CrateRoot {
1203 #[value(s.owner().crate_name(s))]
1204 name: Symbol,
1205 },
1206 Impl,
1207 ForeignMod,
1208 Use,
1209 GlobalAsm,
1210 TypeNs(Symbol),
1211 ValueNs(Symbol),
1212 MacroNs(Symbol),
1213 LifetimeNs(Symbol),
1214 Closure,
1215 TestBinderConstraints,
1216 Ctor,
1217 AnonConst,
1218 #[disable_mapping]
1219 PromotedConst,
1220 OpaqueTy,
1221 OpaqueLifetime(Symbol),
1222 AnonAssocTy(Symbol),
1223 SyntheticCoroutineBody,
1224 NestedStatic,
1225}
1226
1227#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1228#[derive(AdtInto)]
1229#[args(<'a, S: UnderOwnerState<'a>>, from: rustc_hir::definitions::DisambiguatedDefPathData, state: S as s)]
1230pub struct DisambiguatedDefPathItem {
1232 pub data: DefPathItem,
1233 pub disambiguator: u32,
1234}