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