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