Skip to main content

charon_driver/frontend/types/
def_id.rs

1//! This module contains the type definition for `DefId` and the types
2//! `DefId` depends on.
3
4use 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/// Reflects [`rustc_hir::def::DefKind`]
28#[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    /// Added by the frontend: promoted constants don't have def_ids in rustc but they do in the frontend.
63    PromotedConst,
64    OpaqueTy,
65    Field,
66    LifetimeParam,
67    GlobalAsm,
68    Impl {
69        of_trait: bool,
70    },
71    Closure,
72    SyntheticCoroutineBody,
73    TestBinderConstraints,
74}
75
76/// The crate name under which synthetic items are exported under.
77const SYNTHETIC_CRATE_NAME: &str = "<synthetic>";
78
79/// Reflects [`rustc_hir::def_id::DefId`], augmented to also give ids to promoted constants (which
80/// have their own ad-hoc numbering scheme in rustc for now).
81#[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    /// The kind of definition this `DefId` points to.
90    pub kind: crate::frontend::DefKind,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Hash)]
94pub enum DefIdBase {
95    Real(RDefId),
96    /// An item with the same definition as `DefId`, but interpreted differently. E.g. the
97    /// initializer of a global, or the blanket impl of a trait alias.
98    DerivedItem(DefId, DerivedItemKind),
99    /// A promoted constant coming from the body of `RDefId`.
100    Promoted(RDefId, PromotedId),
101    /// This represents the context made of the trait impl generics plus the associated item
102    /// generics declared in the trait. We use that context to trait solve the mapping from
103    /// declared method generics to implemented method generics.
104    ImplAssocItem(VirtualImplAssocItem),
105    /// A fictitious item, used to make monomorphization and other shenanigans easier for builtin
106    /// types.
107    Synthetic(SyntheticItem),
108    /// A global standing for an anonymous const-eval allocation (e.g. the `[42]` in `&[42]`), so
109    /// that pointers to the same memory stay aliased.
110    Alloc(RAllocId),
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Hash)]
114pub enum DerivedItemKind {
115    /// A function with no arguments and the body of a constant/static, working as its initializer.
116    /// The `DefId` is that of the constant/static.
117    Initializer,
118    /// A function that holds the fallback body of an intrinsic, for intrinsics that have one. The
119    /// `DefId` is that of the intrinsic.
120    IntrinsicFallback,
121    /// A function that casts a stateless closure to a function pointer. The `DefId` is that of the
122    /// closure.
123    ClosureAsFnCast,
124    /// The blanket impl we generate for a trait alias. The `DefId` is that of the trait alias.
125    TraitAliasImpl,
126    /// A fictitious `impl<T> Marker for T {}` impl for marker traits like `Send`. This
127    /// is used only for vtable generation. The `DefId` is that of the trait.
128    MarkerImpl,
129    /// The ficticions `drop_glue` method we add to the `Destruct` trait. The `DefId` is that of
130    /// the trait.
131    DropGlueMethodDef,
132    /// An associated item of one of our built-in impls. The base `DefId` is that of the impl, and
133    /// the argument `DefId` is that of the item declaration.
134    BuiltinAssocItemImpl(DefId),
135    /// A fictitious `impl Destruct for Type` whose `drop_glue` method contains the drop glue code
136    /// for `Type`: it calls `Drop::drop` for the type and then drops its fields. The `DefId` is
137    /// that of the ADT or closure.
138    DestructImpl,
139    /// An impl of the appropriate `Fn*` trait for a closure, function item or function pointer.
140    /// The `DefId` is that of the closure or synthetic `FnPtr` `DefId`.
141    FnImpl(ClosureKind),
142    /// A struct that defines the vtable for a trait. It has fields for the methods and supertraits
143    /// of the trait. The `DefId` is that of the trait.
144    VTableDef,
145    /// A `static` that contains the vtable value for a specific impl. The `DefId` is that of the
146    /// impl.
147    VTableImpl,
148    /// A standalone function used to store a method in a vtable; given a method with `self:
149    /// Ptr<Self>` argument, this takes a `Ptr<dyn Trait>` and casts it to `Ptr<Self>` before
150    /// calling the method. The `DefId` is that of the method implementation.
151    VTableMethodShim,
152    /// A standalone function that stores the drop glue for a vtable. It's a function that takes
153    /// `&mut dyn Trait` and casts it to `&mut Self` before calling the drop glue on it. The
154    /// `DefId` is that of the impl the vtable is for.
155    // FIXME: record `Destruct` as a supertrait instead.
156    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    /// The trait impl.
186    pub trait_impl_id: DefId,
187    /// The item declaration.
188    pub item_decl_id: DefId,
189    /// The item implementation.
190    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    /// Arguments just for the item itself (works for both decl and impl), valid in the virtual
203    /// item context.
204    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    /// Construct generic args for the item declaration, valid in the virtual item context.
215    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    /// Construct generic args for the item implementation, valid in the virtual item context.
225    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    /// Construct generic args for the item declaration, valid in the virtual item context.
235    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            // We give extra clauses to type aliases so that we can resolve the trait refs they mention.
296            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                // The blanket impl requires exactly the predicates the alias promises.
317                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            // These items don't have early params of their own.
463            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    /// The rustc def_id corresponding to this item, if there is one. Promoted constants don't have
479    /// a rustc def_id.
480    pub fn as_real_def_id(&self) -> Option<RDefId> {
481        match self.base {
482            DefIdBase::Real(did) => Some(did),
483            _ => None,
484        }
485    }
486    /// The rustc def_id of this item. Panics if this is not a real rustc item.
487    pub fn real_rust_def_id(&self) -> RDefId {
488        self.as_real_def_id().unwrap()
489    }
490    /// The def_id of this item or its parent if this is a promoted constant.
491    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    /// Returns the [`DerivedItemKind`] of this item, if it is derived.
504    pub fn as_derived(&self) -> Option<&DerivedItemKind> {
505        match &self.base {
506            DefIdBase::DerivedItem(_, kind) => Some(kind),
507            _ => None,
508        }
509    }
510    /// Returns the [`SyntheticItem`] encoded by this frontend [`DefId`], if any.
511    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    /// Remove one derived-item layer, if any.
519    pub fn peel_derived(&self) -> &Self {
520        match &self.base {
521            DefIdBase::DerivedItem(base, _) => base,
522            _ => self,
523        }
524    }
525
526    /// Return the (recursive) base item if this item is derived.
527    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    /// Construct a derived item based on this one.
561    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    /// Construct a frontend `DefId` for the nth promoted constant of the current item. That `DefId` has
584    /// no corresponding rustc `DefId`.
585    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    /// The global standing for an anonymous allocation.
609    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    /// Get the span of the definition of this item. This is the span used in diagnostics when
646    /// referring to the item.
647    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                    // This kind causes `def_span` to panic.
654                    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                    // This kind causes `def_span` to panic.
660                    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    /// The `PathItem` corresponding to this item.
672    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                // Set the def_id so the `CrateRoot` path item can fetch the crate name.
677                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            // We can't change the item parent right now as it's entangled with generics, so we let
691            // Charon handle names for now.
692            DefIdBase::DerivedItem(def_id, _) => def_id.path_item(s),
693            DefIdBase::Promoted(_, id) => DisambiguatedDefPathItem {
694                data: DefPathItem::PromotedConst,
695                // Reuse the promoted id as disambiguator, like for inline consts.
696                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                // Number anonymous allocations in the order we encountered them.
706                disambiguator: s.with_global_cache(|cache| {
707                    cache.anon_allocs.get_index_of(alloc_id).unwrap() as u32
708                }),
709            },
710        }
711    }
712
713    /// The syntactic parent of this item.
714    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    /// The semantic parent of this item, i.e. parent if they share typing contexts.
728    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        // The other derived items inherit the generic context of their base.
741        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    /// Whether the item has generic parameters, its parents' included.
767    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                // We build a custom environment here.
808                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    /// The identity arguments, with any erased lifetimes replaced with placeholders regions.
852    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        // Only typeck children have erased regions in their identity args.
859        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    /// Additional clauses we add to type aliases to make them well-formed.
868    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    /// Gets the visibility (`pub` or not) of the definition. Returns `None` for defs that don't have a
1001    /// meaningful visibility.
1002    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            // These kinds don't have visibility modifiers (which would cause `visibility` to panic).
1027            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    /// Gets the attributes of the definition.
1047    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            // Rustc doesn't store the attributes of these kinds of definitions in crate
1068            // metadata; asking for them panics.
1069            &[]
1070        } else {
1071            let attrs = tcx.attrs_for_def(def_id);
1072
1073            // Restore the attributes that aren't encoded in crate metadata.
1074            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                // get the target features attributes
1080                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                // get the allocator attributes
1101                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                // get the linkage attribute
1113                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
1167/// Gets the kind of the definition. Can't use `def_kind` directly because this crashes on the
1168/// crate root.
1169pub(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        // Horrible hack: without this, `def_kind` crashes on the crate root. Presumably some table
1172        // isn't properly initialized otherwise.
1173        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/// Reflects [`rustc_hir::definitions::DefPathData`]
1198#[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)]
1230/// Reflects [`rustc_hir::definitions::DisambiguatedDefPathData`]
1231pub struct DisambiguatedDefPathItem {
1232    pub data: DefPathItem,
1233    pub disambiguator: u32,
1234}