rustc_middle/ty/
mod.rs

1//! Defines how the compiler represents types internally.
2//!
3//! Two important entities in this module are:
4//!
5//! - [`rustc_middle::ty::Ty`], used to represent the semantics of a type.
6//! - [`rustc_middle::ty::TyCtxt`], the central data structure in the compiler.
7//!
8//! For more information, see ["The `ty` module: representing types"] in the rustc-dev-guide.
9//!
10//! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
11
12#![allow(rustc::usage_of_ty_tykind)]
13
14use std::assert_matches::assert_matches;
15use std::fmt::Debug;
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18use std::num::NonZero;
19use std::ptr::NonNull;
20use std::{fmt, iter, str};
21
22pub use adt::*;
23pub use assoc::*;
24pub use generic_args::{GenericArgKind, TermKind, *};
25pub use generics::*;
26pub use intrinsic::IntrinsicDef;
27use rustc_abi::{
28    Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, ScalableElt, VariantIdx,
29};
30use rustc_ast::AttrVec;
31use rustc_ast::expand::typetree::{FncTree, Kind, Type, TypeTree};
32use rustc_ast::node_id::NodeMap;
33pub use rustc_ast_ir::{Movability, Mutability, try_visit};
34use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
35use rustc_data_structures::intern::Interned;
36use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
37use rustc_data_structures::steal::Steal;
38use rustc_data_structures::unord::{UnordMap, UnordSet};
39use rustc_errors::{Diag, ErrorGuaranteed, LintBuffer};
40use rustc_hir::attrs::{AttributeKind, StrippedCfgItem};
41use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
42use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
43use rustc_hir::{LangItem, attrs as attr, find_attr};
44use rustc_index::IndexVec;
45use rustc_index::bit_set::BitMatrix;
46use rustc_macros::{
47    BlobDecodable, Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable,
48    TypeVisitable, extension,
49};
50use rustc_query_system::ich::StableHashingContext;
51use rustc_serialize::{Decodable, Encodable};
52pub use rustc_session::lint::RegisteredTools;
53use rustc_span::hygiene::MacroKind;
54use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, sym};
55pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
56pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
57#[allow(
58    hidden_glob_reexports,
59    rustc::usage_of_type_ir_inherent,
60    rustc::non_glob_import_of_type_ir_inherent
61)]
62use rustc_type_ir::inherent;
63pub use rustc_type_ir::relate::VarianceDiagInfo;
64pub use rustc_type_ir::solve::{CandidatePreferenceMode, SizedTraitKind};
65pub use rustc_type_ir::*;
66#[allow(hidden_glob_reexports, unused_imports)]
67use rustc_type_ir::{InferCtxtLike, Interner};
68use tracing::{debug, instrument, trace};
69pub use vtable::*;
70use {rustc_ast as ast, rustc_hir as hir};
71
72pub use self::closure::{
73    BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
74    MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
75    UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
76    place_to_string_for_capture,
77};
78pub use self::consts::{
79    AnonConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr,
80    ExprKind, ScalarInt, SimdAlign, UnevaluatedConst, ValTree, ValTreeKindExt, Value,
81};
82pub use self::context::{
83    CtxtInterners, CurrentGcx, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, tls,
84};
85pub use self::fold::*;
86pub use self::instance::{Instance, InstanceKind, ReifyReason, UnusedGenericParams};
87pub use self::list::{List, ListWithCachedTypeInfo};
88pub use self::opaque_types::OpaqueTypeKey;
89pub use self::pattern::{Pattern, PatternKind};
90pub use self::predicate::{
91    AliasTerm, ArgOutlivesPredicate, Clause, ClauseKind, CoercePredicate, ExistentialPredicate,
92    ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef,
93    HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
94    PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
95    PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
96    PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
97    RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate,
98};
99pub use self::region::{
100    BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
101    RegionKind, RegionVid,
102};
103pub use self::sty::{
104    AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
105    CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
106    ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
107};
108pub use self::trait_def::TraitDef;
109pub use self::typeck_results::{
110    CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
111    Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
112};
113use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
114use crate::metadata::{AmbigModChild, ModChild};
115use crate::middle::privacy::EffectiveVisibilities;
116use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
117use crate::query::{IntoQueryParam, Providers};
118use crate::ty;
119use crate::ty::codec::{TyDecoder, TyEncoder};
120pub use crate::ty::diagnostics::*;
121use crate::ty::fast_reject::SimplifiedType;
122use crate::ty::layout::LayoutError;
123use crate::ty::util::Discr;
124use crate::ty::walk::TypeWalker;
125
126pub mod abstract_const;
127pub mod adjustment;
128pub mod cast;
129pub mod codec;
130pub mod error;
131pub mod fast_reject;
132pub mod inhabitedness;
133pub mod layout;
134pub mod normalize_erasing_regions;
135pub mod offload_meta;
136pub mod pattern;
137pub mod print;
138pub mod relate;
139pub mod significant_drop_order;
140pub mod trait_def;
141pub mod util;
142pub mod vtable;
143
144mod adt;
145mod assoc;
146mod closure;
147mod consts;
148mod context;
149mod diagnostics;
150mod elaborate_impl;
151mod erase_regions;
152mod fold;
153mod generic_args;
154mod generics;
155mod impls_ty;
156mod instance;
157mod intrinsic;
158mod list;
159mod opaque_types;
160mod predicate;
161mod region;
162mod structural_impls;
163#[allow(hidden_glob_reexports)]
164mod sty;
165mod typeck_results;
166mod visit;
167
168// Data types
169
170#[derive(Debug, HashStable)]
171pub struct ResolverGlobalCtxt {
172    pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
173    /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
174    pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
175    pub effective_visibilities: EffectiveVisibilities,
176    pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
177    pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
178    pub module_children: LocalDefIdMap<Vec<ModChild>>,
179    pub ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,
180    pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
181    pub main_def: Option<MainDefinition>,
182    pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
183    /// A list of proc macro LocalDefIds, written out in the order in which
184    /// they are declared in the static array generated by proc_macro_harness.
185    pub proc_macros: Vec<LocalDefId>,
186    /// Mapping from ident span to path span for paths that don't exist as written, but that
187    /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
188    pub confused_type_with_std_module: FxIndexMap<Span, Span>,
189    pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
190    pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
191    pub all_macro_rules: UnordSet<Symbol>,
192    pub stripped_cfg_items: Vec<StrippedCfgItem>,
193}
194
195/// Resolutions that should only be used for lowering.
196/// This struct is meant to be consumed by lowering.
197#[derive(Debug)]
198pub struct ResolverAstLowering {
199    /// Resolutions for nodes that have a single resolution.
200    pub partial_res_map: NodeMap<hir::def::PartialRes>,
201    /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
202    pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
203    /// Resolutions for labels (node IDs of their corresponding blocks or loops).
204    pub label_res_map: NodeMap<ast::NodeId>,
205    /// Resolutions for lifetimes.
206    pub lifetimes_res_map: NodeMap<LifetimeRes>,
207    /// Lifetime parameters that lowering will have to introduce.
208    pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
209
210    pub next_node_id: ast::NodeId,
211
212    pub node_id_to_def_id: NodeMap<LocalDefId>,
213
214    pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
215    /// List functions and methods for which lifetime elision was successful.
216    pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
217
218    /// Lints that were emitted by the resolver and early lints.
219    pub lint_buffer: Steal<LintBuffer>,
220
221    /// Information about functions signatures for delegation items expansion
222    pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
223    // NodeIds (either delegation.id or item_id in case of a trait impl) for signature resolution,
224    // for details see https://github.com/rust-lang/rust/issues/118212#issuecomment-2160686914
225    pub delegation_sig_resolution_nodes: LocalDefIdMap<ast::NodeId>,
226}
227
228bitflags::bitflags! {
229    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
230    pub struct DelegationFnSigAttrs: u8 {
231        const TARGET_FEATURE = 1 << 0;
232        const MUST_USE = 1 << 1;
233    }
234}
235
236pub const DELEGATION_INHERIT_ATTRS_START: DelegationFnSigAttrs = DelegationFnSigAttrs::MUST_USE;
237
238#[derive(Debug)]
239pub struct DelegationFnSig {
240    pub header: ast::FnHeader,
241    pub param_count: usize,
242    pub has_self: bool,
243    pub c_variadic: bool,
244    pub attrs_flags: DelegationFnSigAttrs,
245    pub to_inherit_attrs: AttrVec,
246}
247
248#[derive(Clone, Copy, Debug, HashStable)]
249pub struct MainDefinition {
250    pub res: Res<ast::NodeId>,
251    pub is_import: bool,
252    pub span: Span,
253}
254
255impl MainDefinition {
256    pub fn opt_fn_def_id(self) -> Option<DefId> {
257        if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
258    }
259}
260
261#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
262pub struct ImplTraitHeader<'tcx> {
263    pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
264    pub polarity: ImplPolarity,
265    pub safety: hir::Safety,
266    pub constness: hir::Constness,
267}
268
269#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
270#[derive(TypeFoldable, TypeVisitable, Default)]
271pub enum Asyncness {
272    Yes,
273    #[default]
274    No,
275}
276
277impl Asyncness {
278    pub fn is_async(self) -> bool {
279        matches!(self, Asyncness::Yes)
280    }
281}
282
283#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, BlobDecodable, HashStable)]
284pub enum Visibility<Id = LocalDefId> {
285    /// Visible everywhere (including in other crates).
286    Public,
287    /// Visible only in the given crate-local module.
288    Restricted(Id),
289}
290
291impl Visibility {
292    pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
293        match self {
294            ty::Visibility::Restricted(restricted_id) => {
295                if restricted_id.is_top_level_module() {
296                    "pub(crate)".to_string()
297                } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
298                    "pub(self)".to_string()
299                } else {
300                    format!(
301                        "pub(in crate{})",
302                        tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
303                    )
304                }
305            }
306            ty::Visibility::Public => "pub".to_string(),
307        }
308    }
309}
310
311#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
312#[derive(TypeFoldable, TypeVisitable)]
313pub struct ClosureSizeProfileData<'tcx> {
314    /// Tuple containing the types of closure captures before the feature `capture_disjoint_fields`
315    pub before_feature_tys: Ty<'tcx>,
316    /// Tuple containing the types of closure captures after the feature `capture_disjoint_fields`
317    pub after_feature_tys: Ty<'tcx>,
318}
319
320impl TyCtxt<'_> {
321    #[inline]
322    pub fn opt_parent(self, id: DefId) -> Option<DefId> {
323        self.def_key(id).parent.map(|index| DefId { index, ..id })
324    }
325
326    #[inline]
327    #[track_caller]
328    pub fn parent(self, id: DefId) -> DefId {
329        match self.opt_parent(id) {
330            Some(id) => id,
331            // not `unwrap_or_else` to avoid breaking caller tracking
332            None => bug!("{id:?} doesn't have a parent"),
333        }
334    }
335
336    #[inline]
337    #[track_caller]
338    pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
339        self.opt_parent(id.to_def_id()).map(DefId::expect_local)
340    }
341
342    #[inline]
343    #[track_caller]
344    pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
345        self.parent(id.into().to_def_id()).expect_local()
346    }
347
348    pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
349        if descendant.krate != ancestor.krate {
350            return false;
351        }
352
353        while descendant != ancestor {
354            match self.opt_parent(descendant) {
355                Some(parent) => descendant = parent,
356                None => return false,
357            }
358        }
359        true
360    }
361}
362
363impl<Id> Visibility<Id> {
364    pub fn is_public(self) -> bool {
365        matches!(self, Visibility::Public)
366    }
367
368    pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
369        match self {
370            Visibility::Public => Visibility::Public,
371            Visibility::Restricted(id) => Visibility::Restricted(f(id)),
372        }
373    }
374}
375
376impl<Id: Into<DefId>> Visibility<Id> {
377    pub fn to_def_id(self) -> Visibility<DefId> {
378        self.map_id(Into::into)
379    }
380
381    /// Returns `true` if an item with this visibility is accessible from the given module.
382    pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
383        match self {
384            // Public items are visible everywhere.
385            Visibility::Public => true,
386            Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
387        }
388    }
389
390    /// Returns `true` if this visibility is at least as accessible as the given visibility
391    pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
392        match vis {
393            Visibility::Public => self.is_public(),
394            Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
395        }
396    }
397}
398
399impl Visibility<DefId> {
400    pub fn expect_local(self) -> Visibility {
401        self.map_id(|id| id.expect_local())
402    }
403
404    /// Returns `true` if this item is visible anywhere in the local crate.
405    pub fn is_visible_locally(self) -> bool {
406        match self {
407            Visibility::Public => true,
408            Visibility::Restricted(def_id) => def_id.is_local(),
409        }
410    }
411}
412
413/// The crate variances map is computed during typeck and contains the
414/// variance of every item in the local crate. You should not use it
415/// directly, because to do so will make your pass dependent on the
416/// HIR of every item in the local crate. Instead, use
417/// `tcx.variances_of()` to get the variance for a *particular*
418/// item.
419#[derive(HashStable, Debug)]
420pub struct CrateVariancesMap<'tcx> {
421    /// For each item with generics, maps to a vector of the variance
422    /// of its generics. If an item has no generics, it will have no
423    /// entry.
424    pub variances: DefIdMap<&'tcx [ty::Variance]>,
425}
426
427// Contains information needed to resolve types and (in the future) look up
428// the types of AST nodes.
429#[derive(Copy, Clone, PartialEq, Eq, Hash)]
430pub struct CReaderCacheKey {
431    pub cnum: Option<CrateNum>,
432    pub pos: usize,
433}
434
435/// Use this rather than `TyKind`, whenever possible.
436#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
437#[rustc_diagnostic_item = "Ty"]
438#[rustc_pass_by_value]
439pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
440
441impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
442    type Kind = TyKind<'tcx>;
443
444    fn kind(self) -> TyKind<'tcx> {
445        *self.kind()
446    }
447}
448
449impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
450    fn flags(&self) -> TypeFlags {
451        self.0.flags
452    }
453
454    fn outer_exclusive_binder(&self) -> DebruijnIndex {
455        self.0.outer_exclusive_binder
456    }
457}
458
459/// The crate outlives map is computed during typeck and contains the
460/// outlives of every item in the local crate. You should not use it
461/// directly, because to do so will make your pass dependent on the
462/// HIR of every item in the local crate. Instead, use
463/// `tcx.inferred_outlives_of()` to get the outlives for a *particular*
464/// item.
465#[derive(HashStable, Debug)]
466pub struct CratePredicatesMap<'tcx> {
467    /// For each struct with outlive bounds, maps to a vector of the
468    /// predicate of its outlive bounds. If an item has no outlives
469    /// bounds, it will have no entry.
470    pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
471}
472
473#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
474pub struct Term<'tcx> {
475    ptr: NonNull<()>,
476    marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
477}
478
479impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
480
481impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
482    type Kind = TermKind<'tcx>;
483
484    fn kind(self) -> Self::Kind {
485        self.kind()
486    }
487}
488
489unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
490    &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
491{
492}
493unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
494    &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
495{
496}
497unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
498unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
499
500impl Debug for Term<'_> {
501    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502        match self.kind() {
503            TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
504            TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
505        }
506    }
507}
508
509impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
510    fn from(ty: Ty<'tcx>) -> Self {
511        TermKind::Ty(ty).pack()
512    }
513}
514
515impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
516    fn from(c: Const<'tcx>) -> Self {
517        TermKind::Const(c).pack()
518    }
519}
520
521impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
522    fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
523        self.kind().hash_stable(hcx, hasher);
524    }
525}
526
527impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
528    fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
529        self,
530        folder: &mut F,
531    ) -> Result<Self, F::Error> {
532        match self.kind() {
533            ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
534            ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
535        }
536    }
537
538    fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
539        match self.kind() {
540            ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
541            ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
542        }
543    }
544}
545
546impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
547    fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
548        match self.kind() {
549            ty::TermKind::Ty(ty) => ty.visit_with(visitor),
550            ty::TermKind::Const(ct) => ct.visit_with(visitor),
551        }
552    }
553}
554
555impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
556    fn encode(&self, e: &mut E) {
557        self.kind().encode(e)
558    }
559}
560
561impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
562    fn decode(d: &mut D) -> Self {
563        let res: TermKind<'tcx> = Decodable::decode(d);
564        res.pack()
565    }
566}
567
568impl<'tcx> Term<'tcx> {
569    #[inline]
570    pub fn kind(self) -> TermKind<'tcx> {
571        let ptr =
572            unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
573        // SAFETY: use of `Interned::new_unchecked` here is ok because these
574        // pointers were originally created from `Interned` types in `pack()`,
575        // and this is just going in the other direction.
576        unsafe {
577            match self.ptr.addr().get() & TAG_MASK {
578                TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
579                    ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
580                ))),
581                CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
582                    ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
583                ))),
584                _ => core::intrinsics::unreachable(),
585            }
586        }
587    }
588
589    pub fn as_type(&self) -> Option<Ty<'tcx>> {
590        if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
591    }
592
593    pub fn expect_type(&self) -> Ty<'tcx> {
594        self.as_type().expect("expected a type, but found a const")
595    }
596
597    pub fn as_const(&self) -> Option<Const<'tcx>> {
598        if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
599    }
600
601    pub fn expect_const(&self) -> Const<'tcx> {
602        self.as_const().expect("expected a const, but found a type")
603    }
604
605    pub fn into_arg(self) -> GenericArg<'tcx> {
606        match self.kind() {
607            TermKind::Ty(ty) => ty.into(),
608            TermKind::Const(c) => c.into(),
609        }
610    }
611
612    pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
613        match self.kind() {
614            TermKind::Ty(ty) => match *ty.kind() {
615                ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
616                _ => None,
617            },
618            TermKind::Const(ct) => match ct.kind() {
619                ConstKind::Unevaluated(uv) => Some(uv.into()),
620                _ => None,
621            },
622        }
623    }
624
625    pub fn is_infer(&self) -> bool {
626        match self.kind() {
627            TermKind::Ty(ty) => ty.is_ty_var(),
628            TermKind::Const(ct) => ct.is_ct_infer(),
629        }
630    }
631
632    pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
633        match self.kind() {
634            TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
635            TermKind::Const(ct) => ct.is_trivially_wf(),
636        }
637    }
638
639    /// Iterator that walks `self` and any types reachable from
640    /// `self`, in depth-first order. Note that just walks the types
641    /// that appear in `self`, it does not descend into the fields of
642    /// structs or variants. For example:
643    ///
644    /// ```text
645    /// isize => { isize }
646    /// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
647    /// [isize] => { [isize], isize }
648    /// ```
649    pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
650        TypeWalker::new(self.into())
651    }
652}
653
654const TAG_MASK: usize = 0b11;
655const TYPE_TAG: usize = 0b00;
656const CONST_TAG: usize = 0b01;
657
658#[extension(pub trait TermKindPackExt<'tcx>)]
659impl<'tcx> TermKind<'tcx> {
660    #[inline]
661    fn pack(self) -> Term<'tcx> {
662        let (tag, ptr) = match self {
663            TermKind::Ty(ty) => {
664                // Ensure we can use the tag bits.
665                assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
666                (TYPE_TAG, NonNull::from(ty.0.0).cast())
667            }
668            TermKind::Const(ct) => {
669                // Ensure we can use the tag bits.
670                assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
671                (CONST_TAG, NonNull::from(ct.0.0).cast())
672            }
673        };
674
675        Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
676    }
677}
678
679/// Represents the bounds declared on a particular set of type
680/// parameters. Should eventually be generalized into a flag list of
681/// where-clauses. You can obtain an `InstantiatedPredicates` list from a
682/// `GenericPredicates` by using the `instantiate` method. Note that this method
683/// reflects an important semantic invariant of `InstantiatedPredicates`: while
684/// the `GenericPredicates` are expressed in terms of the bound type
685/// parameters of the impl/trait/whatever, an `InstantiatedPredicates` instance
686/// represented a set of bounds for some particular instantiation,
687/// meaning that the generic parameters have been instantiated with
688/// their values.
689///
690/// Example:
691/// ```ignore (illustrative)
692/// struct Foo<T, U: Bar<T>> { ... }
693/// ```
694/// Here, the `GenericPredicates` for `Foo` would contain a list of bounds like
695/// `[[], [U:Bar<T>]]`. Now if there were some particular reference
696/// like `Foo<isize,usize>`, then the `InstantiatedPredicates` would be `[[],
697/// [usize:Bar<isize>]]`.
698#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
699pub struct InstantiatedPredicates<'tcx> {
700    pub predicates: Vec<Clause<'tcx>>,
701    pub spans: Vec<Span>,
702}
703
704impl<'tcx> InstantiatedPredicates<'tcx> {
705    pub fn empty() -> InstantiatedPredicates<'tcx> {
706        InstantiatedPredicates { predicates: vec![], spans: vec![] }
707    }
708
709    pub fn is_empty(&self) -> bool {
710        self.predicates.is_empty()
711    }
712
713    pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
714        self.into_iter()
715    }
716}
717
718impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
719    type Item = (Clause<'tcx>, Span);
720
721    type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
722
723    fn into_iter(self) -> Self::IntoIter {
724        debug_assert_eq!(self.predicates.len(), self.spans.len());
725        std::iter::zip(self.predicates, self.spans)
726    }
727}
728
729impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
730    type Item = (Clause<'tcx>, Span);
731
732    type IntoIter = std::iter::Zip<
733        std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
734        std::iter::Copied<std::slice::Iter<'a, Span>>,
735    >;
736
737    fn into_iter(self) -> Self::IntoIter {
738        debug_assert_eq!(self.predicates.len(), self.spans.len());
739        std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
740    }
741}
742
743#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
744pub struct ProvisionalHiddenType<'tcx> {
745    /// The span of this particular definition of the opaque type. So
746    /// for example:
747    ///
748    /// ```ignore (incomplete snippet)
749    /// type Foo = impl Baz;
750    /// fn bar() -> Foo {
751    /// //          ^^^ This is the span we are looking for!
752    /// }
753    /// ```
754    ///
755    /// In cases where the fn returns `(impl Trait, impl Trait)` or
756    /// other such combinations, the result is currently
757    /// over-approximated, but better than nothing.
758    pub span: Span,
759
760    /// The type variable that represents the value of the opaque type
761    /// that we require. In other words, after we compile this function,
762    /// we will be created a constraint like:
763    /// ```ignore (pseudo-rust)
764    /// Foo<'a, T> = ?C
765    /// ```
766    /// where `?C` is the value of this type variable. =) It may
767    /// naturally refer to the type and lifetime parameters in scope
768    /// in this function, though ultimately it should only reference
769    /// those that are arguments to `Foo` in the constraint above. (In
770    /// other words, `?C` should not include `'b`, even though it's a
771    /// lifetime parameter on `foo`.)
772    pub ty: Ty<'tcx>,
773}
774
775/// Whether we're currently in HIR typeck or MIR borrowck.
776#[derive(Debug, Clone, Copy)]
777pub enum DefiningScopeKind {
778    /// During writeback in typeck, we don't care about regions and simply
779    /// erase them. This means we also don't check whether regions are
780    /// universal in the opaque type key. This will only be checked in
781    /// MIR borrowck.
782    HirTypeck,
783    MirBorrowck,
784}
785
786impl<'tcx> ProvisionalHiddenType<'tcx> {
787    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> ProvisionalHiddenType<'tcx> {
788        ProvisionalHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
789    }
790
791    pub fn build_mismatch_error(
792        &self,
793        other: &Self,
794        tcx: TyCtxt<'tcx>,
795    ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
796        (self.ty, other.ty).error_reported()?;
797        // Found different concrete types for the opaque type.
798        let sub_diag = if self.span == other.span {
799            TypeMismatchReason::ConflictType { span: self.span }
800        } else {
801            TypeMismatchReason::PreviousUse { span: self.span }
802        };
803        Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
804            self_ty: self.ty,
805            other_ty: other.ty,
806            other_span: other.span,
807            sub: sub_diag,
808        }))
809    }
810
811    #[instrument(level = "debug", skip(tcx), ret)]
812    pub fn remap_generic_params_to_declaration_params(
813        self,
814        opaque_type_key: OpaqueTypeKey<'tcx>,
815        tcx: TyCtxt<'tcx>,
816        defining_scope_kind: DefiningScopeKind,
817    ) -> DefinitionSiteHiddenType<'tcx> {
818        let OpaqueTypeKey { def_id, args } = opaque_type_key;
819
820        // Use args to build up a reverse map from regions to their
821        // identity mappings. This is necessary because of `impl
822        // Trait` lifetimes are computed by replacing existing
823        // lifetimes with 'static and remapping only those used in the
824        // `impl Trait` return type, resulting in the parameters
825        // shifting.
826        let id_args = GenericArgs::identity_for_item(tcx, def_id);
827        debug!(?id_args);
828
829        // This zip may have several times the same lifetime in `args` paired with a different
830        // lifetime from `id_args`. Simply `collect`ing the iterator is the correct behaviour:
831        // it will pick the last one, which is the one we introduced in the impl-trait desugaring.
832        let map = args.iter().zip(id_args).collect();
833        debug!("map = {:#?}", map);
834
835        // Convert the type from the function into a type valid outside by mapping generic
836        // parameters to into the context of the opaque.
837        //
838        // We erase regions when doing this during HIR typeck. We manually use `fold_regions`
839        // here as we do not want to anonymize bound variables.
840        let ty = match defining_scope_kind {
841            DefiningScopeKind::HirTypeck => {
842                fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
843            }
844            DefiningScopeKind::MirBorrowck => self.ty,
845        };
846        let result_ty = ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
847        if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
848            assert_eq!(result_ty, fold_regions(tcx, result_ty, |_, _| tcx.lifetimes.re_erased));
849        }
850        DefinitionSiteHiddenType { span: self.span, ty: ty::EarlyBinder::bind(result_ty) }
851    }
852}
853
854#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
855pub struct DefinitionSiteHiddenType<'tcx> {
856    /// The span of the definition of the opaque type. So for example:
857    ///
858    /// ```ignore (incomplete snippet)
859    /// type Foo = impl Baz;
860    /// fn bar() -> Foo {
861    /// //          ^^^ This is the span we are looking for!
862    /// }
863    /// ```
864    ///
865    /// In cases where the fn returns `(impl Trait, impl Trait)` or
866    /// other such combinations, the result is currently
867    /// over-approximated, but better than nothing.
868    pub span: Span,
869
870    /// The final type of the opaque.
871    pub ty: ty::EarlyBinder<'tcx, Ty<'tcx>>,
872}
873
874impl<'tcx> DefinitionSiteHiddenType<'tcx> {
875    pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> DefinitionSiteHiddenType<'tcx> {
876        DefinitionSiteHiddenType {
877            span: DUMMY_SP,
878            ty: ty::EarlyBinder::bind(Ty::new_error(tcx, guar)),
879        }
880    }
881
882    pub fn build_mismatch_error(
883        &self,
884        other: &Self,
885        tcx: TyCtxt<'tcx>,
886    ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
887        let self_ty = self.ty.instantiate_identity();
888        let other_ty = other.ty.instantiate_identity();
889        (self_ty, other_ty).error_reported()?;
890        // Found different concrete types for the opaque type.
891        let sub_diag = if self.span == other.span {
892            TypeMismatchReason::ConflictType { span: self.span }
893        } else {
894            TypeMismatchReason::PreviousUse { span: self.span }
895        };
896        Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
897            self_ty,
898            other_ty,
899            other_span: other.span,
900            sub: sub_diag,
901        }))
902    }
903}
904
905pub type PlaceholderRegion<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundRegion>;
906
907impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion<'tcx> {
908    type Bound = BoundRegion;
909
910    fn universe(self) -> UniverseIndex {
911        self.universe
912    }
913
914    fn var(self) -> BoundVar {
915        self.bound.var
916    }
917
918    fn with_updated_universe(self, ui: UniverseIndex) -> Self {
919        ty::Placeholder::new(ui, self.bound)
920    }
921
922    fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
923        ty::Placeholder::new(ui, bound)
924    }
925
926    fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
927        ty::Placeholder::new(ui, BoundRegion { var, kind: BoundRegionKind::Anon })
928    }
929}
930
931pub type PlaceholderType<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundTy>;
932
933impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType<'tcx> {
934    type Bound = BoundTy;
935
936    fn universe(self) -> UniverseIndex {
937        self.universe
938    }
939
940    fn var(self) -> BoundVar {
941        self.bound.var
942    }
943
944    fn with_updated_universe(self, ui: UniverseIndex) -> Self {
945        ty::Placeholder::new(ui, self.bound)
946    }
947
948    fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
949        ty::Placeholder::new(ui, bound)
950    }
951
952    fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
953        ty::Placeholder::new(ui, BoundTy { var, kind: BoundTyKind::Anon })
954    }
955}
956
957#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
958#[derive(TyEncodable, TyDecodable)]
959pub struct BoundConst {
960    pub var: BoundVar,
961}
962
963impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
964    fn var(self) -> BoundVar {
965        self.var
966    }
967
968    fn assert_eq(self, var: ty::BoundVariableKind) {
969        var.expect_const()
970    }
971}
972
973pub type PlaceholderConst<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundConst>;
974
975impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst<'tcx> {
976    type Bound = BoundConst;
977
978    fn universe(self) -> UniverseIndex {
979        self.universe
980    }
981
982    fn var(self) -> BoundVar {
983        self.bound.var
984    }
985
986    fn with_updated_universe(self, ui: UniverseIndex) -> Self {
987        ty::Placeholder::new(ui, self.bound)
988    }
989
990    fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
991        ty::Placeholder::new(ui, bound)
992    }
993
994    fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
995        ty::Placeholder::new(ui, BoundConst { var })
996    }
997}
998
999pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
1000
1001impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
1002    fn flags(&self) -> TypeFlags {
1003        (**self).flags()
1004    }
1005
1006    fn outer_exclusive_binder(&self) -> DebruijnIndex {
1007        (**self).outer_exclusive_binder()
1008    }
1009}
1010
1011/// When interacting with the type system we must provide information about the
1012/// environment. `ParamEnv` is the type that represents this information. See the
1013/// [dev guide chapter][param_env_guide] for more information.
1014///
1015/// [param_env_guide]: https://rustc-dev-guide.rust-lang.org/typing_parameter_envs.html
1016#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1017#[derive(HashStable, TypeVisitable, TypeFoldable)]
1018pub struct ParamEnv<'tcx> {
1019    /// Caller bounds are `Obligation`s that the caller must satisfy. This is
1020    /// basically the set of bounds on the in-scope type parameters, translated
1021    /// into `Obligation`s, and elaborated and normalized.
1022    ///
1023    /// Use the `caller_bounds()` method to access.
1024    caller_bounds: Clauses<'tcx>,
1025}
1026
1027impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1028    fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
1029        self.caller_bounds()
1030    }
1031}
1032
1033impl<'tcx> ParamEnv<'tcx> {
1034    /// Construct a trait environment suitable for contexts where there are
1035    /// no where-clauses in scope. In the majority of cases it is incorrect
1036    /// to use an empty environment. See the [dev guide section][param_env_guide]
1037    /// for information on what a `ParamEnv` is and how to acquire one.
1038    ///
1039    /// [param_env_guide]: https://rustc-dev-guide.rust-lang.org/typing_parameter_envs.html
1040    #[inline]
1041    pub fn empty() -> Self {
1042        Self::new(ListWithCachedTypeInfo::empty())
1043    }
1044
1045    #[inline]
1046    pub fn caller_bounds(self) -> Clauses<'tcx> {
1047        self.caller_bounds
1048    }
1049
1050    /// Construct a trait environment with the given set of predicates.
1051    #[inline]
1052    pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1053        ParamEnv { caller_bounds }
1054    }
1055
1056    /// Creates a pair of param-env and value for use in queries.
1057    pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1058        ParamEnvAnd { param_env: self, value }
1059    }
1060}
1061
1062#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1063#[derive(HashStable)]
1064pub struct ParamEnvAnd<'tcx, T> {
1065    pub param_env: ParamEnv<'tcx>,
1066    pub value: T,
1067}
1068
1069/// The environment in which to do trait solving.
1070///
1071/// Most of the time you only need to care about the `ParamEnv`
1072/// as the `TypingMode` is simply stored in the `InferCtxt`.
1073///
1074/// However, there are some places which rely on trait solving
1075/// without using an `InferCtxt` themselves. For these to be
1076/// able to use the trait system they have to be able to initialize
1077/// such an `InferCtxt` with the right `typing_mode`, so they need
1078/// to track both.
1079#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1080#[derive(TypeVisitable, TypeFoldable)]
1081pub struct TypingEnv<'tcx> {
1082    #[type_foldable(identity)]
1083    #[type_visitable(ignore)]
1084    pub typing_mode: TypingMode<'tcx>,
1085    pub param_env: ParamEnv<'tcx>,
1086}
1087
1088impl<'tcx> TypingEnv<'tcx> {
1089    /// Create a typing environment with no where-clauses in scope
1090    /// where all opaque types and default associated items are revealed.
1091    ///
1092    /// This is only suitable for monomorphized, post-typeck environments.
1093    /// Do not use this for MIR optimizations, as even though they also
1094    /// use `TypingMode::PostAnalysis`, they may still have where-clauses
1095    /// in scope.
1096    pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1097        TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1098    }
1099
1100    /// Create a typing environment for use during analysis outside of a body.
1101    ///
1102    /// Using a typing environment inside of bodies is not supported as the body
1103    /// may define opaque types. In this case the used functions have to be
1104    /// converted to use proper canonical inputs instead.
1105    pub fn non_body_analysis(
1106        tcx: TyCtxt<'tcx>,
1107        def_id: impl IntoQueryParam<DefId>,
1108    ) -> TypingEnv<'tcx> {
1109        TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1110    }
1111
1112    pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1113        tcx.typing_env_normalized_for_post_analysis(def_id)
1114    }
1115
1116    /// Modify the `typing_mode` to `PostAnalysis` and eagerly reveal all
1117    /// opaque types in the `param_env`.
1118    pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1119        let TypingEnv { typing_mode, param_env } = self;
1120        if let TypingMode::PostAnalysis = typing_mode {
1121            return self;
1122        }
1123
1124        // No need to reveal opaques with the new solver enabled,
1125        // since we have lazy norm.
1126        let param_env = if tcx.next_trait_solver_globally() {
1127            param_env
1128        } else {
1129            ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1130        };
1131        TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1132    }
1133
1134    /// Combine this typing environment with the given `value` to be used by
1135    /// not (yet) canonicalized queries. This only works if the value does not
1136    /// contain anything local to some `InferCtxt`, i.e. inference variables or
1137    /// placeholders.
1138    pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1139    where
1140        T: TypeVisitable<TyCtxt<'tcx>>,
1141    {
1142        // FIXME(#132279): We should assert that the value does not contain any placeholders
1143        // as these placeholders are also local to the current inference context. However, we
1144        // currently use pseudo-canonical queries in the trait solver, which replaces params
1145        // with placeholders during canonicalization. We should also simply not use pseudo-
1146        // canonical queries in the trait solver, at which point we can readd this assert.
1147        //
1148        // As of writing this comment, this is only used when normalizing consts that mention
1149        // params.
1150        /* debug_assert!(
1151            !value.has_placeholders(),
1152            "{value:?} which has placeholder shouldn't be pseudo-canonicalized"
1153        ); */
1154        PseudoCanonicalInput { typing_env: self, value }
1155    }
1156}
1157
1158/// Similar to `CanonicalInput`, this carries the `typing_mode` and the environment
1159/// necessary to do any kind of trait solving inside of nested queries.
1160///
1161/// Unlike proper canonicalization, this requires the `param_env` and the `value` to not
1162/// contain anything local to the `infcx` of the caller, so we don't actually canonicalize
1163/// anything.
1164///
1165/// This should be created by using `infcx.pseudo_canonicalize_query(param_env, value)`
1166/// or by using `typing_env.as_query_input(value)`.
1167#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1168#[derive(HashStable, TypeVisitable, TypeFoldable)]
1169pub struct PseudoCanonicalInput<'tcx, T> {
1170    pub typing_env: TypingEnv<'tcx>,
1171    pub value: T,
1172}
1173
1174#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1175pub struct Destructor {
1176    /// The `DefId` of the destructor method
1177    pub did: DefId,
1178}
1179
1180// FIXME: consider combining this definition with regular `Destructor`
1181#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1182pub struct AsyncDestructor {
1183    /// The `DefId` of the `impl AsyncDrop`
1184    pub impl_did: DefId,
1185}
1186
1187#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1188pub struct VariantFlags(u8);
1189bitflags::bitflags! {
1190    impl VariantFlags: u8 {
1191        const NO_VARIANT_FLAGS        = 0;
1192        /// Indicates whether the field list of this variant is `#[non_exhaustive]`.
1193        const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1194    }
1195}
1196rustc_data_structures::external_bitflags_debug! { VariantFlags }
1197
1198/// Definition of a variant -- a struct's fields or an enum variant.
1199#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1200pub struct VariantDef {
1201    /// `DefId` that identifies the variant itself.
1202    /// If this variant belongs to a struct or union, then this is a copy of its `DefId`.
1203    pub def_id: DefId,
1204    /// `DefId` that identifies the variant's constructor.
1205    /// If this variant is a struct variant, then this is `None`.
1206    pub ctor: Option<(CtorKind, DefId)>,
1207    /// Variant or struct name.
1208    pub name: Symbol,
1209    /// Discriminant of this variant.
1210    pub discr: VariantDiscr,
1211    /// Fields of this variant.
1212    pub fields: IndexVec<FieldIdx, FieldDef>,
1213    /// The error guarantees from parser, if any.
1214    tainted: Option<ErrorGuaranteed>,
1215    /// Flags of the variant (e.g. is field list non-exhaustive)?
1216    flags: VariantFlags,
1217}
1218
1219impl VariantDef {
1220    /// Creates a new `VariantDef`.
1221    ///
1222    /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
1223    /// represents an enum variant).
1224    ///
1225    /// `ctor_did` is the `DefId` that identifies the constructor of unit or
1226    /// tuple-variants/structs. If this is a `struct`-variant then this should be `None`.
1227    ///
1228    /// `parent_did` is the `DefId` of the `AdtDef` representing the enum or struct that
1229    /// owns this variant. It is used for checking if a struct has `#[non_exhaustive]` w/out having
1230    /// to go through the redirect of checking the ctor's attributes - but compiling a small crate
1231    /// requires loading the `AdtDef`s for all the structs in the universe (e.g., coherence for any
1232    /// built-in trait), and we do not want to load attributes twice.
1233    ///
1234    /// If someone speeds up attribute loading to not be a performance concern, they can
1235    /// remove this hack and use the constructor `DefId` everywhere.
1236    #[instrument(level = "debug")]
1237    pub fn new(
1238        name: Symbol,
1239        variant_did: Option<DefId>,
1240        ctor: Option<(CtorKind, DefId)>,
1241        discr: VariantDiscr,
1242        fields: IndexVec<FieldIdx, FieldDef>,
1243        parent_did: DefId,
1244        recover_tainted: Option<ErrorGuaranteed>,
1245        is_field_list_non_exhaustive: bool,
1246    ) -> Self {
1247        let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1248        if is_field_list_non_exhaustive {
1249            flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1250        }
1251
1252        VariantDef {
1253            def_id: variant_did.unwrap_or(parent_did),
1254            ctor,
1255            name,
1256            discr,
1257            fields,
1258            flags,
1259            tainted: recover_tainted,
1260        }
1261    }
1262
1263    /// Returns `true` if the field list of this variant is `#[non_exhaustive]`.
1264    ///
1265    /// Note that this function will return `true` even if the type has been
1266    /// defined in the crate currently being compiled. If that's not what you
1267    /// want, see [`Self::field_list_has_applicable_non_exhaustive`].
1268    #[inline]
1269    pub fn is_field_list_non_exhaustive(&self) -> bool {
1270        self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1271    }
1272
1273    /// Returns `true` if the field list of this variant is `#[non_exhaustive]`
1274    /// and the type has been defined in another crate.
1275    #[inline]
1276    pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1277        self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1278    }
1279
1280    /// Computes the `Ident` of this variant by looking up the `Span`
1281    pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1282        Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1283    }
1284
1285    /// Was this variant obtained as part of recovering from a syntactic error?
1286    #[inline]
1287    pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1288        self.tainted.map_or(Ok(()), Err)
1289    }
1290
1291    #[inline]
1292    pub fn ctor_kind(&self) -> Option<CtorKind> {
1293        self.ctor.map(|(kind, _)| kind)
1294    }
1295
1296    #[inline]
1297    pub fn ctor_def_id(&self) -> Option<DefId> {
1298        self.ctor.map(|(_, def_id)| def_id)
1299    }
1300
1301    /// Returns the one field in this variant.
1302    ///
1303    /// `panic!`s if there are no fields or multiple fields.
1304    #[inline]
1305    pub fn single_field(&self) -> &FieldDef {
1306        assert!(self.fields.len() == 1);
1307
1308        &self.fields[FieldIdx::ZERO]
1309    }
1310
1311    /// Returns the last field in this variant, if present.
1312    #[inline]
1313    pub fn tail_opt(&self) -> Option<&FieldDef> {
1314        self.fields.raw.last()
1315    }
1316
1317    /// Returns the last field in this variant.
1318    ///
1319    /// # Panics
1320    ///
1321    /// Panics, if the variant has no fields.
1322    #[inline]
1323    pub fn tail(&self) -> &FieldDef {
1324        self.tail_opt().expect("expected unsized ADT to have a tail field")
1325    }
1326
1327    /// Returns whether this variant has unsafe fields.
1328    pub fn has_unsafe_fields(&self) -> bool {
1329        self.fields.iter().any(|x| x.safety.is_unsafe())
1330    }
1331}
1332
1333impl PartialEq for VariantDef {
1334    #[inline]
1335    fn eq(&self, other: &Self) -> bool {
1336        // There should be only one `VariantDef` for each `def_id`, therefore
1337        // it is fine to implement `PartialEq` only based on `def_id`.
1338        //
1339        // Below, we exhaustively destructure `self` and `other` so that if the
1340        // definition of `VariantDef` changes, a compile-error will be produced,
1341        // reminding us to revisit this assumption.
1342
1343        let Self {
1344            def_id: lhs_def_id,
1345            ctor: _,
1346            name: _,
1347            discr: _,
1348            fields: _,
1349            flags: _,
1350            tainted: _,
1351        } = &self;
1352        let Self {
1353            def_id: rhs_def_id,
1354            ctor: _,
1355            name: _,
1356            discr: _,
1357            fields: _,
1358            flags: _,
1359            tainted: _,
1360        } = other;
1361
1362        let res = lhs_def_id == rhs_def_id;
1363
1364        // Double check that implicit assumption detailed above.
1365        if cfg!(debug_assertions) && res {
1366            let deep = self.ctor == other.ctor
1367                && self.name == other.name
1368                && self.discr == other.discr
1369                && self.fields == other.fields
1370                && self.flags == other.flags;
1371            assert!(deep, "VariantDef for the same def-id has differing data");
1372        }
1373
1374        res
1375    }
1376}
1377
1378impl Eq for VariantDef {}
1379
1380impl Hash for VariantDef {
1381    #[inline]
1382    fn hash<H: Hasher>(&self, s: &mut H) {
1383        // There should be only one `VariantDef` for each `def_id`, therefore
1384        // it is fine to implement `Hash` only based on `def_id`.
1385        //
1386        // Below, we exhaustively destructure `self` so that if the definition
1387        // of `VariantDef` changes, a compile-error will be produced, reminding
1388        // us to revisit this assumption.
1389
1390        let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1391        def_id.hash(s)
1392    }
1393}
1394
1395#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1396pub enum VariantDiscr {
1397    /// Explicit value for this variant, i.e., `X = 123`.
1398    /// The `DefId` corresponds to the embedded constant.
1399    Explicit(DefId),
1400
1401    /// The previous variant's discriminant plus one.
1402    /// For efficiency reasons, the distance from the
1403    /// last `Explicit` discriminant is being stored,
1404    /// or `0` for the first variant, if it has none.
1405    Relative(u32),
1406}
1407
1408#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1409pub struct FieldDef {
1410    pub did: DefId,
1411    pub name: Symbol,
1412    pub vis: Visibility<DefId>,
1413    pub safety: hir::Safety,
1414    pub value: Option<DefId>,
1415}
1416
1417impl PartialEq for FieldDef {
1418    #[inline]
1419    fn eq(&self, other: &Self) -> bool {
1420        // There should be only one `FieldDef` for each `did`, therefore it is
1421        // fine to implement `PartialEq` only based on `did`.
1422        //
1423        // Below, we exhaustively destructure `self` so that if the definition
1424        // of `FieldDef` changes, a compile-error will be produced, reminding
1425        // us to revisit this assumption.
1426
1427        let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1428
1429        let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1430
1431        let res = lhs_did == rhs_did;
1432
1433        // Double check that implicit assumption detailed above.
1434        if cfg!(debug_assertions) && res {
1435            let deep =
1436                self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1437            assert!(deep, "FieldDef for the same def-id has differing data");
1438        }
1439
1440        res
1441    }
1442}
1443
1444impl Eq for FieldDef {}
1445
1446impl Hash for FieldDef {
1447    #[inline]
1448    fn hash<H: Hasher>(&self, s: &mut H) {
1449        // There should be only one `FieldDef` for each `did`, therefore it is
1450        // fine to implement `Hash` only based on `did`.
1451        //
1452        // Below, we exhaustively destructure `self` so that if the definition
1453        // of `FieldDef` changes, a compile-error will be produced, reminding
1454        // us to revisit this assumption.
1455
1456        let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1457
1458        did.hash(s)
1459    }
1460}
1461
1462impl<'tcx> FieldDef {
1463    /// Returns the type of this field. The resulting type is not normalized. The `arg` is
1464    /// typically obtained via the second field of [`TyKind::Adt`].
1465    pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1466        tcx.type_of(self.did).instantiate(tcx, args)
1467    }
1468
1469    /// Computes the `Ident` of this variant by looking up the `Span`
1470    pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1471        Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1472    }
1473}
1474
1475#[derive(Debug, PartialEq, Eq)]
1476pub enum ImplOverlapKind {
1477    /// These impls are always allowed to overlap.
1478    Permitted {
1479        /// Whether or not the impl is permitted due to the trait being a `#[marker]` trait
1480        marker: bool,
1481    },
1482}
1483
1484/// Useful source information about where a desugared associated type for an
1485/// RPITIT originated from.
1486#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1487pub enum ImplTraitInTraitData {
1488    Trait { fn_def_id: DefId, opaque_def_id: DefId },
1489    Impl { fn_def_id: DefId },
1490}
1491
1492impl<'tcx> TyCtxt<'tcx> {
1493    pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1494        self.typeck(self.hir_body_owner_def_id(body))
1495    }
1496
1497    pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1498        self.associated_items(id)
1499            .in_definition_order()
1500            .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1501    }
1502
1503    pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1504        let mut flags = ReprFlags::empty();
1505        let mut size = None;
1506        let mut max_align: Option<Align> = None;
1507        let mut min_pack: Option<Align> = None;
1508
1509        // Generate a deterministically-derived seed from the item's path hash
1510        // to allow for cross-crate compilation to actually work
1511        let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1512
1513        // If the user defined a custom seed for layout randomization, xor the item's
1514        // path hash with the user defined seed, this will allowing determinism while
1515        // still allowing users to further randomize layout generation for e.g. fuzzing
1516        if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1517            field_shuffle_seed ^= user_seed;
1518        }
1519
1520        let attributes = self.get_all_attrs(did);
1521        let elt = find_attr!(
1522            attributes,
1523            AttributeKind::RustcScalableVector { element_count, .. } => element_count
1524        )
1525        .map(|elt| match elt {
1526            Some(n) => ScalableElt::ElementCount(*n),
1527            None => ScalableElt::Container,
1528        });
1529        if elt.is_some() {
1530            flags.insert(ReprFlags::IS_SCALABLE);
1531        }
1532        if let Some(reprs) = find_attr!(attributes, AttributeKind::Repr { reprs, .. } => reprs) {
1533            for (r, _) in reprs {
1534                flags.insert(match *r {
1535                    attr::ReprRust => ReprFlags::empty(),
1536                    attr::ReprC => ReprFlags::IS_C,
1537                    attr::ReprPacked(pack) => {
1538                        min_pack = Some(if let Some(min_pack) = min_pack {
1539                            min_pack.min(pack)
1540                        } else {
1541                            pack
1542                        });
1543                        ReprFlags::empty()
1544                    }
1545                    attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1546                    attr::ReprSimd => ReprFlags::IS_SIMD,
1547                    attr::ReprInt(i) => {
1548                        size = Some(match i {
1549                            attr::IntType::SignedInt(x) => match x {
1550                                ast::IntTy::Isize => IntegerType::Pointer(true),
1551                                ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1552                                ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1553                                ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1554                                ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1555                                ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1556                            },
1557                            attr::IntType::UnsignedInt(x) => match x {
1558                                ast::UintTy::Usize => IntegerType::Pointer(false),
1559                                ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1560                                ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1561                                ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1562                                ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1563                                ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1564                            },
1565                        });
1566                        ReprFlags::empty()
1567                    }
1568                    attr::ReprAlign(align) => {
1569                        max_align = max_align.max(Some(align));
1570                        ReprFlags::empty()
1571                    }
1572                });
1573            }
1574        }
1575
1576        // If `-Z randomize-layout` was enabled for the type definition then we can
1577        // consider performing layout randomization
1578        if self.sess.opts.unstable_opts.randomize_layout {
1579            flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1580        }
1581
1582        // box is special, on the one hand the compiler assumes an ordered layout, with the pointer
1583        // always at offset zero. On the other hand we want scalar abi optimizations.
1584        let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1585
1586        // This is here instead of layout because the choice must make it into metadata.
1587        if is_box {
1588            flags.insert(ReprFlags::IS_LINEAR);
1589        }
1590
1591        // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details.
1592        if find_attr!(attributes, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) {
1593            flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1594        }
1595
1596        ReprOptions {
1597            int: size,
1598            align: max_align,
1599            pack: min_pack,
1600            flags,
1601            field_shuffle_seed,
1602            scalable: elt,
1603        }
1604    }
1605
1606    /// Look up the name of a definition across crates. This does not look at HIR.
1607    pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1608        let def_id = def_id.into_query_param();
1609        if let Some(cnum) = def_id.as_crate_root() {
1610            Some(self.crate_name(cnum))
1611        } else {
1612            let def_key = self.def_key(def_id);
1613            match def_key.disambiguated_data.data {
1614                // The name of a constructor is that of its parent.
1615                rustc_hir::definitions::DefPathData::Ctor => self
1616                    .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1617                _ => def_key.get_opt_name(),
1618            }
1619        }
1620    }
1621
1622    /// Look up the name of a definition across crates. This does not look at HIR.
1623    ///
1624    /// This method will ICE if the corresponding item does not have a name. In these cases, use
1625    /// [`opt_item_name`] instead.
1626    ///
1627    /// [`opt_item_name`]: Self::opt_item_name
1628    pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1629        let id = id.into_query_param();
1630        self.opt_item_name(id).unwrap_or_else(|| {
1631            bug!("item_name: no name for {:?}", self.def_path(id));
1632        })
1633    }
1634
1635    /// Look up the name and span of a definition.
1636    ///
1637    /// See [`item_name`][Self::item_name] for more information.
1638    pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1639        let def_id = def_id.into_query_param();
1640        let def = self.opt_item_name(def_id)?;
1641        let span = self
1642            .def_ident_span(def_id)
1643            .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1644        Some(Ident::new(def, span))
1645    }
1646
1647    /// Look up the name and span of a definition.
1648    ///
1649    /// See [`item_name`][Self::item_name] for more information.
1650    pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1651        let def_id = def_id.into_query_param();
1652        self.opt_item_ident(def_id).unwrap_or_else(|| {
1653            bug!("item_ident: no name for {:?}", self.def_path(def_id));
1654        })
1655    }
1656
1657    pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1658        if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1659            Some(self.associated_item(def_id))
1660        } else {
1661            None
1662        }
1663    }
1664
1665    /// If the `def_id` is an associated type that was desugared from a
1666    /// return-position `impl Trait` from a trait, then provide the source info
1667    /// about where that RPITIT came from.
1668    pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1669        if let DefKind::AssocTy = self.def_kind(def_id)
1670            && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1671                self.associated_item(def_id).kind
1672        {
1673            Some(rpitit_info)
1674        } else {
1675            None
1676        }
1677    }
1678
1679    pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1680        variant.fields.iter_enumerated().find_map(|(i, field)| {
1681            self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1682        })
1683    }
1684
1685    /// Returns `Some` if the impls are the same polarity and the trait either
1686    /// has no items or is annotated `#[marker]` and prevents item overrides.
1687    #[instrument(level = "debug", skip(self), ret)]
1688    pub fn impls_are_allowed_to_overlap(
1689        self,
1690        def_id1: DefId,
1691        def_id2: DefId,
1692    ) -> Option<ImplOverlapKind> {
1693        let impl1 = self.impl_trait_header(def_id1);
1694        let impl2 = self.impl_trait_header(def_id2);
1695
1696        let trait_ref1 = impl1.trait_ref.skip_binder();
1697        let trait_ref2 = impl2.trait_ref.skip_binder();
1698
1699        // If either trait impl references an error, they're allowed to overlap,
1700        // as one of them essentially doesn't exist.
1701        if trait_ref1.references_error() || trait_ref2.references_error() {
1702            return Some(ImplOverlapKind::Permitted { marker: false });
1703        }
1704
1705        match (impl1.polarity, impl2.polarity) {
1706            (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1707                // `#[rustc_reservation_impl]` impls don't overlap with anything
1708                return Some(ImplOverlapKind::Permitted { marker: false });
1709            }
1710            (ImplPolarity::Positive, ImplPolarity::Negative)
1711            | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1712                // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
1713                return None;
1714            }
1715            (ImplPolarity::Positive, ImplPolarity::Positive)
1716            | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1717        };
1718
1719        let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1720        let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1721
1722        if is_marker_overlap {
1723            return Some(ImplOverlapKind::Permitted { marker: true });
1724        }
1725
1726        None
1727    }
1728
1729    /// Returns `ty::VariantDef` if `res` refers to a struct,
1730    /// or variant or their constructors, panics otherwise.
1731    pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1732        match res {
1733            Res::Def(DefKind::Variant, did) => {
1734                let enum_did = self.parent(did);
1735                self.adt_def(enum_did).variant_with_id(did)
1736            }
1737            Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1738            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1739                let variant_did = self.parent(variant_ctor_did);
1740                let enum_did = self.parent(variant_did);
1741                self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1742            }
1743            Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1744                let struct_did = self.parent(ctor_did);
1745                self.adt_def(struct_did).non_enum_variant()
1746            }
1747            _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1748        }
1749    }
1750
1751    /// Returns the possibly-auto-generated MIR of a [`ty::InstanceKind`].
1752    #[instrument(skip(self), level = "debug")]
1753    pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1754        match instance {
1755            ty::InstanceKind::Item(def) => {
1756                debug!("calling def_kind on def: {:?}", def);
1757                let def_kind = self.def_kind(def);
1758                debug!("returned from def_kind: {:?}", def_kind);
1759                match def_kind {
1760                    DefKind::Const
1761                    | DefKind::Static { .. }
1762                    | DefKind::AssocConst
1763                    | DefKind::Ctor(..)
1764                    | DefKind::AnonConst
1765                    | DefKind::InlineConst => self.mir_for_ctfe(def),
1766                    // If the caller wants `mir_for_ctfe` of a function they should not be using
1767                    // `instance_mir`, so we'll assume const fn also wants the optimized version.
1768                    _ => self.optimized_mir(def),
1769                }
1770            }
1771            ty::InstanceKind::VTableShim(..)
1772            | ty::InstanceKind::ReifyShim(..)
1773            | ty::InstanceKind::Intrinsic(..)
1774            | ty::InstanceKind::FnPtrShim(..)
1775            | ty::InstanceKind::Virtual(..)
1776            | ty::InstanceKind::ClosureOnceShim { .. }
1777            | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1778            | ty::InstanceKind::FutureDropPollShim(..)
1779            | ty::InstanceKind::DropGlue(..)
1780            | ty::InstanceKind::CloneShim(..)
1781            | ty::InstanceKind::ThreadLocalShim(..)
1782            | ty::InstanceKind::FnPtrAddrShim(..)
1783            | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1784            | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1785        }
1786    }
1787
1788    /// Gets all attributes with the given name.
1789    pub fn get_attrs(
1790        self,
1791        did: impl Into<DefId>,
1792        attr: Symbol,
1793    ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1794        self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1795    }
1796
1797    /// Gets all attributes.
1798    ///
1799    /// To see if an item has a specific attribute, you should use
1800    /// [`rustc_hir::find_attr!`] so you can use matching.
1801    pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1802        let did: DefId = did.into();
1803        if let Some(did) = did.as_local() {
1804            self.hir_attrs(self.local_def_id_to_hir_id(did))
1805        } else {
1806            self.attrs_for_def(did)
1807        }
1808    }
1809
1810    /// Get an attribute from the diagnostic attribute namespace
1811    ///
1812    /// This function requests an attribute with the following structure:
1813    ///
1814    /// `#[diagnostic::$attr]`
1815    ///
1816    /// This function performs feature checking, so if an attribute is returned
1817    /// it can be used by the consumer
1818    pub fn get_diagnostic_attr(
1819        self,
1820        did: impl Into<DefId>,
1821        attr: Symbol,
1822    ) -> Option<&'tcx hir::Attribute> {
1823        let did: DefId = did.into();
1824        if did.as_local().is_some() {
1825            // it's a crate local item, we need to check feature flags
1826            if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1827                self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1828            } else {
1829                None
1830            }
1831        } else {
1832            // we filter out unstable diagnostic attributes before
1833            // encoding attributes
1834            debug_assert!(rustc_feature::encode_cross_crate(attr));
1835            self.attrs_for_def(did)
1836                .iter()
1837                .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1838        }
1839    }
1840
1841    pub fn get_attrs_by_path(
1842        self,
1843        did: DefId,
1844        attr: &[Symbol],
1845    ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1846        let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1847        if let Some(did) = did.as_local() {
1848            self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1849        } else {
1850            self.attrs_for_def(did).iter().filter(filter_fn)
1851        }
1852    }
1853
1854    pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1855        if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1856            let did: DefId = did.into();
1857            bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1858        } else {
1859            self.get_attrs(did, attr).next()
1860        }
1861    }
1862
1863    /// Determines whether an item is annotated with an attribute.
1864    pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1865        self.get_attrs(did, attr).next().is_some()
1866    }
1867
1868    /// Determines whether an item is annotated with a multi-segment attribute
1869    pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1870        self.get_attrs_by_path(did.into(), attrs).next().is_some()
1871    }
1872
1873    /// Returns `true` if this is an `auto trait`.
1874    pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1875        self.trait_def(trait_def_id).has_auto_impl
1876    }
1877
1878    /// Returns `true` if this is coinductive, either because it is
1879    /// an auto trait or because it has the `#[rustc_coinductive]` attribute.
1880    pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1881        self.trait_def(trait_def_id).is_coinductive
1882    }
1883
1884    /// Returns `true` if this is a trait alias.
1885    pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1886        self.def_kind(trait_def_id) == DefKind::TraitAlias
1887    }
1888
1889    /// Arena-alloc of LayoutError for coroutine layout
1890    fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1891        self.arena.alloc(err)
1892    }
1893
1894    /// Returns layout of a non-async-drop coroutine. Layout might be unavailable if the
1895    /// coroutine is tainted by errors.
1896    ///
1897    /// Takes `coroutine_kind` which can be acquired from the `CoroutineArgs::kind_ty`,
1898    /// e.g. `args.as_coroutine().kind_ty()`.
1899    fn ordinary_coroutine_layout(
1900        self,
1901        def_id: DefId,
1902        args: GenericArgsRef<'tcx>,
1903    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1904        let coroutine_kind_ty = args.as_coroutine().kind_ty();
1905        let mir = self.optimized_mir(def_id);
1906        let ty = || Ty::new_coroutine(self, def_id, args);
1907        // Regular coroutine
1908        if coroutine_kind_ty.is_unit() {
1909            mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1910        } else {
1911            // If we have a `Coroutine` that comes from an coroutine-closure,
1912            // then it may be a by-move or by-ref body.
1913            let ty::Coroutine(_, identity_args) =
1914                *self.type_of(def_id).instantiate_identity().kind()
1915            else {
1916                unreachable!();
1917            };
1918            let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1919            // If the types differ, then we must be getting the by-move body of
1920            // a by-ref coroutine.
1921            if identity_kind_ty == coroutine_kind_ty {
1922                mir.coroutine_layout_raw()
1923                    .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1924            } else {
1925                assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1926                assert_matches!(
1927                    identity_kind_ty.to_opt_closure_kind(),
1928                    Some(ClosureKind::Fn | ClosureKind::FnMut)
1929                );
1930                self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1931                    .coroutine_layout_raw()
1932                    .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1933            }
1934        }
1935    }
1936
1937    /// Returns layout of a `async_drop_in_place::{closure}` coroutine
1938    ///   (returned from `async fn async_drop_in_place<T>(..)`).
1939    /// Layout might be unavailable if the coroutine is tainted by errors.
1940    fn async_drop_coroutine_layout(
1941        self,
1942        def_id: DefId,
1943        args: GenericArgsRef<'tcx>,
1944    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1945        let ty = || Ty::new_coroutine(self, def_id, args);
1946        if args[0].has_placeholders() || args[0].has_non_region_param() {
1947            return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1948        }
1949        let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1950        self.mir_shims(instance)
1951            .coroutine_layout_raw()
1952            .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1953    }
1954
1955    /// Returns layout of a coroutine. Layout might be unavailable if the
1956    /// coroutine is tainted by errors.
1957    pub fn coroutine_layout(
1958        self,
1959        def_id: DefId,
1960        args: GenericArgsRef<'tcx>,
1961    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1962        if self.is_async_drop_in_place_coroutine(def_id) {
1963            // layout of `async_drop_in_place<T>::{closure}` in case,
1964            // when T is a coroutine, contains this internal coroutine's ptr in upvars
1965            // and doesn't require any locals. Here is an `empty coroutine's layout`
1966            let arg_cor_ty = args.first().unwrap().expect_ty();
1967            if arg_cor_ty.is_coroutine() {
1968                let span = self.def_span(def_id);
1969                let source_info = SourceInfo::outermost(span);
1970                // Even minimal, empty coroutine has 3 states (RESERVED_VARIANTS),
1971                // so variant_fields and variant_source_info should have 3 elements.
1972                let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1973                    iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1974                let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1975                    iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1976                let proxy_layout = CoroutineLayout {
1977                    field_tys: [].into(),
1978                    field_names: [].into(),
1979                    variant_fields,
1980                    variant_source_info,
1981                    storage_conflicts: BitMatrix::new(0, 0),
1982                };
1983                return Ok(self.arena.alloc(proxy_layout));
1984            } else {
1985                self.async_drop_coroutine_layout(def_id, args)
1986            }
1987        } else {
1988            self.ordinary_coroutine_layout(def_id, args)
1989        }
1990    }
1991
1992    /// If the given `DefId` is an associated item, returns the `DefId` and `DefKind` of the parent trait or impl.
1993    pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1994        if !self.def_kind(def_id).is_assoc() {
1995            return None;
1996        }
1997        let parent = self.parent(def_id);
1998        let def_kind = self.def_kind(parent);
1999        Some((parent, def_kind))
2000    }
2001
2002    /// Returns the trait item that is implemented by the given item `DefId`.
2003    pub fn trait_item_of(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2004        self.opt_associated_item(def_id.into_query_param())?.trait_item_def_id()
2005    }
2006
2007    /// If the given `DefId` is an associated item of a trait,
2008    /// returns the `DefId` of the trait; otherwise, returns `None`.
2009    pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
2010        match self.assoc_parent(def_id) {
2011            Some((id, DefKind::Trait)) => Some(id),
2012            _ => None,
2013        }
2014    }
2015
2016    pub fn impl_is_of_trait(self, def_id: impl IntoQueryParam<DefId>) -> bool {
2017        let def_id = def_id.into_query_param();
2018        let DefKind::Impl { of_trait } = self.def_kind(def_id) else {
2019            panic!("expected Impl for {def_id:?}");
2020        };
2021        of_trait
2022    }
2023
2024    /// If the given `DefId` is an associated item of an impl,
2025    /// returns the `DefId` of the impl; otherwise returns `None`.
2026    pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2027        match self.assoc_parent(def_id) {
2028            Some((id, DefKind::Impl { .. })) => Some(id),
2029            _ => None,
2030        }
2031    }
2032
2033    /// If the given `DefId` is an associated item of an inherent impl,
2034    /// returns the `DefId` of the impl; otherwise, returns `None`.
2035    pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2036        match self.assoc_parent(def_id) {
2037            Some((id, DefKind::Impl { of_trait: false })) => Some(id),
2038            _ => None,
2039        }
2040    }
2041
2042    /// If the given `DefId` is an associated item of a trait impl,
2043    /// returns the `DefId` of the impl; otherwise, returns `None`.
2044    pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2045        match self.assoc_parent(def_id) {
2046            Some((id, DefKind::Impl { of_trait: true })) => Some(id),
2047            _ => None,
2048        }
2049    }
2050
2051    pub fn impl_polarity(self, def_id: impl IntoQueryParam<DefId>) -> ty::ImplPolarity {
2052        self.impl_trait_header(def_id).polarity
2053    }
2054
2055    /// Given an `impl_id`, return the trait it implements.
2056    pub fn impl_trait_ref(
2057        self,
2058        def_id: impl IntoQueryParam<DefId>,
2059    ) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
2060        self.impl_trait_header(def_id).trait_ref
2061    }
2062
2063    /// Given an `impl_id`, return the trait it implements.
2064    /// Returns `None` if it is an inherent impl.
2065    pub fn impl_opt_trait_ref(
2066        self,
2067        def_id: impl IntoQueryParam<DefId>,
2068    ) -> Option<ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>> {
2069        let def_id = def_id.into_query_param();
2070        self.impl_is_of_trait(def_id).then(|| self.impl_trait_ref(def_id))
2071    }
2072
2073    /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2074    pub fn impl_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> DefId {
2075        self.impl_trait_ref(def_id).skip_binder().def_id
2076    }
2077
2078    /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2079    /// Returns `None` if it is an inherent impl.
2080    pub fn impl_opt_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2081        let def_id = def_id.into_query_param();
2082        self.impl_is_of_trait(def_id).then(|| self.impl_trait_id(def_id))
2083    }
2084
2085    pub fn is_exportable(self, def_id: DefId) -> bool {
2086        self.exportable_items(def_id.krate).contains(&def_id)
2087    }
2088
2089    /// Check if the given `DefId` is `#\[automatically_derived\]`, *and*
2090    /// whether it was produced by expanding a builtin derive macro.
2091    pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2092        if self.is_automatically_derived(def_id)
2093            && let Some(def_id) = def_id.as_local()
2094            && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2095            && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2096            && find_attr!(
2097                self.get_all_attrs(outer.macro_def_id.unwrap()),
2098                AttributeKind::RustcBuiltinMacro { .. }
2099            )
2100        {
2101            true
2102        } else {
2103            false
2104        }
2105    }
2106
2107    /// Check if the given `DefId` is `#\[automatically_derived\]`.
2108    pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2109        find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
2110    }
2111
2112    /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2113    /// with the name of the crate containing the impl.
2114    pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2115        if let Some(impl_def_id) = impl_def_id.as_local() {
2116            Ok(self.def_span(impl_def_id))
2117        } else {
2118            Err(self.crate_name(impl_def_id.krate))
2119        }
2120    }
2121
2122    /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2123    /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2124    /// definition's parent/scope to perform comparison.
2125    pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2126        // We could use `Ident::eq` here, but we deliberately don't. The identifier
2127        // comparison fails frequently, and we want to avoid the expensive
2128        // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2129        use_ident.name == def_ident.name
2130            && use_ident
2131                .span
2132                .ctxt()
2133                .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2134    }
2135
2136    pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2137        ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2138        ident
2139    }
2140
2141    // FIXME(vincenzopalazzo): move the HirId to a LocalDefId
2142    pub fn adjust_ident_and_get_scope(
2143        self,
2144        mut ident: Ident,
2145        scope: DefId,
2146        block: hir::HirId,
2147    ) -> (Ident, DefId) {
2148        let scope = ident
2149            .span
2150            .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2151            .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2152            .unwrap_or_else(|| self.parent_module(block).to_def_id());
2153        (ident, scope)
2154    }
2155
2156    /// Checks whether this is a `const fn`. Returns `false` for non-functions.
2157    ///
2158    /// Even if this returns `true`, constness may still be unstable!
2159    #[inline]
2160    pub fn is_const_fn(self, def_id: DefId) -> bool {
2161        matches!(
2162            self.def_kind(def_id),
2163            DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2164        ) && self.constness(def_id) == hir::Constness::Const
2165    }
2166
2167    /// Whether this item is conditionally constant for the purposes of the
2168    /// effects implementation.
2169    ///
2170    /// This roughly corresponds to all const functions and other callable
2171    /// items, along with const impls and traits, and associated types within
2172    /// those impls and traits.
2173    pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2174        let def_id: DefId = def_id.into();
2175        match self.def_kind(def_id) {
2176            DefKind::Impl { of_trait: true } => {
2177                let header = self.impl_trait_header(def_id);
2178                header.constness == hir::Constness::Const
2179                    && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2180            }
2181            DefKind::Impl { of_trait: false } => self.constness(def_id) == hir::Constness::Const,
2182            DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2183                self.constness(def_id) == hir::Constness::Const
2184            }
2185            DefKind::TraitAlias | DefKind::Trait => self.is_const_trait(def_id),
2186            DefKind::AssocTy => {
2187                let parent_def_id = self.parent(def_id);
2188                match self.def_kind(parent_def_id) {
2189                    DefKind::Impl { of_trait: false } => false,
2190                    DefKind::Impl { of_trait: true } | DefKind::Trait => {
2191                        self.is_conditionally_const(parent_def_id)
2192                    }
2193                    _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2194                }
2195            }
2196            DefKind::AssocFn => {
2197                let parent_def_id = self.parent(def_id);
2198                match self.def_kind(parent_def_id) {
2199                    DefKind::Impl { of_trait: false } => {
2200                        self.constness(def_id) == hir::Constness::Const
2201                    }
2202                    DefKind::Impl { of_trait: true } | DefKind::Trait => {
2203                        self.is_conditionally_const(parent_def_id)
2204                    }
2205                    _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2206                }
2207            }
2208            DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2209                hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2210                hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2211                // FIXME(const_trait_impl): ATPITs could be conditionally const?
2212                hir::OpaqueTyOrigin::TyAlias { .. } => false,
2213            },
2214            DefKind::Closure => {
2215                // Closures and RPITs will eventually have const conditions
2216                // for `[const]` bounds.
2217                false
2218            }
2219            DefKind::Ctor(_, CtorKind::Const)
2220            | DefKind::Mod
2221            | DefKind::Struct
2222            | DefKind::Union
2223            | DefKind::Enum
2224            | DefKind::Variant
2225            | DefKind::TyAlias
2226            | DefKind::ForeignTy
2227            | DefKind::TyParam
2228            | DefKind::Const
2229            | DefKind::ConstParam
2230            | DefKind::Static { .. }
2231            | DefKind::AssocConst
2232            | DefKind::Macro(_)
2233            | DefKind::ExternCrate
2234            | DefKind::Use
2235            | DefKind::ForeignMod
2236            | DefKind::AnonConst
2237            | DefKind::InlineConst
2238            | DefKind::Field
2239            | DefKind::LifetimeParam
2240            | DefKind::GlobalAsm
2241            | DefKind::SyntheticCoroutineBody => false,
2242        }
2243    }
2244
2245    #[inline]
2246    pub fn is_const_trait(self, def_id: DefId) -> bool {
2247        self.trait_def(def_id).constness == hir::Constness::Const
2248    }
2249
2250    pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2251        if self.def_kind(def_id) != DefKind::AssocFn {
2252            return false;
2253        }
2254
2255        let Some(item) = self.opt_associated_item(def_id) else {
2256            return false;
2257        };
2258
2259        let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2260            return false;
2261        };
2262
2263        !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2264    }
2265}
2266
2267pub fn provide(providers: &mut Providers) {
2268    closure::provide(providers);
2269    context::provide(providers);
2270    erase_regions::provide(providers);
2271    inhabitedness::provide(providers);
2272    util::provide(providers);
2273    print::provide(providers);
2274    super::util::bug::provide(providers);
2275    *providers = Providers {
2276        trait_impls_of: trait_def::trait_impls_of_provider,
2277        incoherent_impls: trait_def::incoherent_impls_provider,
2278        trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2279        traits: trait_def::traits_provider,
2280        vtable_allocation: vtable::vtable_allocation_provider,
2281        ..*providers
2282    };
2283}
2284
2285/// A map for the local crate mapping each type to a vector of its
2286/// inherent impls. This is not meant to be used outside of coherence;
2287/// rather, you should request the vector for a specific type via
2288/// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2289/// (constructing this map requires touching the entire crate).
2290#[derive(Clone, Debug, Default, HashStable)]
2291pub struct CrateInherentImpls {
2292    pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2293    pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2294}
2295
2296#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2297pub struct SymbolName<'tcx> {
2298    /// `&str` gives a consistent ordering, which ensures reproducible builds.
2299    pub name: &'tcx str,
2300}
2301
2302impl<'tcx> SymbolName<'tcx> {
2303    pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2304        SymbolName { name: tcx.arena.alloc_str(name) }
2305    }
2306}
2307
2308impl<'tcx> fmt::Display for SymbolName<'tcx> {
2309    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2310        fmt::Display::fmt(&self.name, fmt)
2311    }
2312}
2313
2314impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2315    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2316        fmt::Display::fmt(&self.name, fmt)
2317    }
2318}
2319
2320/// The constituent parts of a type level constant of kind ADT or array.
2321#[derive(Copy, Clone, Debug, HashStable)]
2322pub struct DestructuredConst<'tcx> {
2323    pub variant: Option<VariantIdx>,
2324    pub fields: &'tcx [ty::Const<'tcx>],
2325}
2326
2327/// Generate TypeTree information for autodiff.
2328/// This function creates TypeTree metadata that describes the memory layout
2329/// of function parameters and return types for Enzyme autodiff.
2330pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
2331    // Check if TypeTrees are disabled via NoTT flag
2332    if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
2333        return FncTree { args: vec![], ret: TypeTree::new() };
2334    }
2335
2336    // Check if this is actually a function type
2337    if !fn_ty.is_fn() {
2338        return FncTree { args: vec![], ret: TypeTree::new() };
2339    }
2340
2341    // Get the function signature
2342    let fn_sig = fn_ty.fn_sig(tcx);
2343    let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
2344
2345    // Create TypeTrees for each input parameter
2346    let mut args = vec![];
2347    for ty in sig.inputs().iter() {
2348        let type_tree = typetree_from_ty(tcx, *ty);
2349        args.push(type_tree);
2350    }
2351
2352    // Create TypeTree for return type
2353    let ret = typetree_from_ty(tcx, sig.output());
2354
2355    FncTree { args, ret }
2356}
2357
2358/// Generate TypeTree for a specific type.
2359/// This function analyzes a Rust type and creates appropriate TypeTree metadata.
2360pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
2361    let mut visited = Vec::new();
2362    typetree_from_ty_inner(tcx, ty, 0, &mut visited)
2363}
2364
2365/// Maximum recursion depth for TypeTree generation to prevent stack overflow
2366/// from pathological deeply nested types. Combined with cycle detection.
2367const MAX_TYPETREE_DEPTH: usize = 6;
2368
2369/// Internal recursive function for TypeTree generation with cycle detection and depth limiting.
2370fn typetree_from_ty_inner<'tcx>(
2371    tcx: TyCtxt<'tcx>,
2372    ty: Ty<'tcx>,
2373    depth: usize,
2374    visited: &mut Vec<Ty<'tcx>>,
2375) -> TypeTree {
2376    if depth >= MAX_TYPETREE_DEPTH {
2377        trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
2378        return TypeTree::new();
2379    }
2380
2381    if visited.contains(&ty) {
2382        return TypeTree::new();
2383    }
2384
2385    visited.push(ty);
2386    let result = typetree_from_ty_impl(tcx, ty, depth, visited);
2387    visited.pop();
2388    result
2389}
2390
2391/// Implementation of TypeTree generation logic.
2392fn typetree_from_ty_impl<'tcx>(
2393    tcx: TyCtxt<'tcx>,
2394    ty: Ty<'tcx>,
2395    depth: usize,
2396    visited: &mut Vec<Ty<'tcx>>,
2397) -> TypeTree {
2398    typetree_from_ty_impl_inner(tcx, ty, depth, visited, false)
2399}
2400
2401/// Internal implementation with context about whether this is for a reference target.
2402fn typetree_from_ty_impl_inner<'tcx>(
2403    tcx: TyCtxt<'tcx>,
2404    ty: Ty<'tcx>,
2405    depth: usize,
2406    visited: &mut Vec<Ty<'tcx>>,
2407    is_reference_target: bool,
2408) -> TypeTree {
2409    if ty.is_scalar() {
2410        let (kind, size) = if ty.is_integral() || ty.is_char() || ty.is_bool() {
2411            (Kind::Integer, ty.primitive_size(tcx).bytes_usize())
2412        } else if ty.is_floating_point() {
2413            match ty {
2414                x if x == tcx.types.f16 => (Kind::Half, 2),
2415                x if x == tcx.types.f32 => (Kind::Float, 4),
2416                x if x == tcx.types.f64 => (Kind::Double, 8),
2417                x if x == tcx.types.f128 => (Kind::F128, 16),
2418                _ => (Kind::Integer, 0),
2419            }
2420        } else {
2421            (Kind::Integer, 0)
2422        };
2423
2424        // Use offset 0 for scalars that are direct targets of references (like &f64)
2425        // Use offset -1 for scalars used directly (like function return types)
2426        let offset = if is_reference_target && !ty.is_array() { 0 } else { -1 };
2427        return TypeTree(vec![Type { offset, size, kind, child: TypeTree::new() }]);
2428    }
2429
2430    if ty.is_ref() || ty.is_raw_ptr() || ty.is_box() {
2431        let Some(inner_ty) = ty.builtin_deref(true) else {
2432            return TypeTree::new();
2433        };
2434
2435        let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
2436        return TypeTree(vec![Type {
2437            offset: -1,
2438            size: tcx.data_layout.pointer_size().bytes_usize(),
2439            kind: Kind::Pointer,
2440            child,
2441        }]);
2442    }
2443
2444    if ty.is_array() {
2445        if let ty::Array(element_ty, len_const) = ty.kind() {
2446            let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
2447            if len == 0 {
2448                return TypeTree::new();
2449            }
2450            let element_tree =
2451                typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2452            let mut types = Vec::new();
2453            for elem_type in &element_tree.0 {
2454                types.push(Type {
2455                    offset: -1,
2456                    size: elem_type.size,
2457                    kind: elem_type.kind,
2458                    child: elem_type.child.clone(),
2459                });
2460            }
2461
2462            return TypeTree(types);
2463        }
2464    }
2465
2466    if ty.is_slice() {
2467        if let ty::Slice(element_ty) = ty.kind() {
2468            let element_tree =
2469                typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2470            return element_tree;
2471        }
2472    }
2473
2474    if let ty::Tuple(tuple_types) = ty.kind() {
2475        if tuple_types.is_empty() {
2476            return TypeTree::new();
2477        }
2478
2479        let mut types = Vec::new();
2480        let mut current_offset = 0;
2481
2482        for tuple_ty in tuple_types.iter() {
2483            let element_tree =
2484                typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
2485
2486            let element_layout = tcx
2487                .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
2488                .ok()
2489                .map(|layout| layout.size.bytes_usize())
2490                .unwrap_or(0);
2491
2492            for elem_type in &element_tree.0 {
2493                types.push(Type {
2494                    offset: if elem_type.offset == -1 {
2495                        current_offset as isize
2496                    } else {
2497                        current_offset as isize + elem_type.offset
2498                    },
2499                    size: elem_type.size,
2500                    kind: elem_type.kind,
2501                    child: elem_type.child.clone(),
2502                });
2503            }
2504
2505            current_offset += element_layout;
2506        }
2507
2508        return TypeTree(types);
2509    }
2510
2511    if let ty::Adt(adt_def, args) = ty.kind() {
2512        if adt_def.is_struct() {
2513            let struct_layout =
2514                tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
2515            if let Ok(layout) = struct_layout {
2516                let mut types = Vec::new();
2517
2518                for (field_idx, field_def) in adt_def.all_fields().enumerate() {
2519                    let field_ty = field_def.ty(tcx, args);
2520                    let field_tree =
2521                        typetree_from_ty_impl_inner(tcx, field_ty, depth + 1, visited, false);
2522
2523                    let field_offset = layout.fields.offset(field_idx).bytes_usize();
2524
2525                    for elem_type in &field_tree.0 {
2526                        types.push(Type {
2527                            offset: if elem_type.offset == -1 {
2528                                field_offset as isize
2529                            } else {
2530                                field_offset as isize + elem_type.offset
2531                            },
2532                            size: elem_type.size,
2533                            kind: elem_type.kind,
2534                            child: elem_type.child.clone(),
2535                        });
2536                    }
2537                }
2538
2539                return TypeTree(types);
2540            }
2541        }
2542    }
2543
2544    TypeTree::new()
2545}