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