rustc_middle/ty/
mod.rs

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