rustc_middle/ty/
mod.rs

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