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