rustc_middle/ty/
mod.rs

1//! Defines how the compiler represents types internally.
2//!
3//! Two important entities in this module are:
4//!
5//! - [`rustc_middle::ty::Ty`], used to represent the semantics of a type.
6//! - [`rustc_middle::ty::TyCtxt`], the central data structure in the compiler.
7//!
8//! For more information, see ["The `ty` module: representing types"] in the rustc-dev-guide.
9//!
10//! ["The `ty` module: representing types"]: https://rustc-dev-guide.rust-lang.org/ty.html
11
12#![allow(rustc::usage_of_ty_tykind)]
13
14use std::assert_matches::assert_matches;
15use std::fmt::Debug;
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18use std::num::NonZero;
19use std::ptr::NonNull;
20use std::{fmt, iter, str};
21
22pub use adt::*;
23pub use assoc::*;
24pub use generic_args::{GenericArgKind, TermKind, *};
25pub use generics::*;
26pub use intrinsic::IntrinsicDef;
27use rustc_abi::{Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, VariantIdx};
28use rustc_ast::expand::typetree::{FncTree, Kind, Type, TypeTree};
29use rustc_ast::node_id::NodeMap;
30pub use rustc_ast_ir::{Movability, Mutability, try_visit};
31use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
32use rustc_data_structures::intern::Interned;
33use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
34use rustc_data_structures::steal::Steal;
35use rustc_data_structures::unord::{UnordMap, UnordSet};
36use rustc_errors::{Diag, ErrorGuaranteed, LintBuffer};
37use rustc_hir::attrs::{AttributeKind, StrippedCfgItem};
38use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
39use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
40use rustc_hir::{LangItem, attrs as attr, find_attr};
41use rustc_index::IndexVec;
42use rustc_index::bit_set::BitMatrix;
43use rustc_macros::{
44    Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
45    extension,
46};
47use rustc_query_system::ich::StableHashingContext;
48use rustc_serialize::{Decodable, Encodable};
49pub use rustc_session::lint::RegisteredTools;
50use rustc_span::hygiene::MacroKind;
51use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, sym};
52pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
53pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
54#[allow(
55    hidden_glob_reexports,
56    rustc::usage_of_type_ir_inherent,
57    rustc::non_glob_import_of_type_ir_inherent
58)]
59use rustc_type_ir::inherent;
60pub use rustc_type_ir::relate::VarianceDiagInfo;
61pub use rustc_type_ir::solve::{CandidatePreferenceMode, SizedTraitKind};
62pub use rustc_type_ir::*;
63#[allow(hidden_glob_reexports, unused_imports)]
64use rustc_type_ir::{InferCtxtLike, Interner};
65use tracing::{debug, instrument, trace};
66pub use vtable::*;
67use {rustc_ast as ast, rustc_hir as hir};
68
69pub use self::closure::{
70    BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
71    MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
72    UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
73    place_to_string_for_capture,
74};
75pub use self::consts::{
76    AnonConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr,
77    ExprKind, ScalarInt, SimdAlign, UnevaluatedConst, ValTree, ValTreeKind, Value,
78};
79pub use self::context::{
80    CtxtInterners, CurrentGcx, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, tls,
81};
82pub use self::fold::*;
83pub use self::instance::{Instance, InstanceKind, ReifyReason, UnusedGenericParams};
84pub use self::list::{List, ListWithCachedTypeInfo};
85pub use self::opaque_types::OpaqueTypeKey;
86pub use self::pattern::{Pattern, PatternKind};
87pub use self::predicate::{
88    AliasTerm, ArgOutlivesPredicate, Clause, ClauseKind, CoercePredicate, ExistentialPredicate,
89    ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef,
90    HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
91    PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
92    PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
93    PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
94    RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate,
95};
96pub use self::region::{
97    BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
98    RegionKind, RegionVid,
99};
100pub use self::sty::{
101    AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
102    CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
103    ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
104};
105pub use self::trait_def::TraitDef;
106pub use self::typeck_results::{
107    CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
108    Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
109};
110use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
111use crate::metadata::ModChild;
112use crate::middle::privacy::EffectiveVisibilities;
113use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
114use crate::query::{IntoQueryParam, Providers};
115use crate::ty;
116use crate::ty::codec::{TyDecoder, TyEncoder};
117pub use crate::ty::diagnostics::*;
118use crate::ty::fast_reject::SimplifiedType;
119use crate::ty::layout::LayoutError;
120use crate::ty::util::Discr;
121use crate::ty::walk::TypeWalker;
122
123pub mod abstract_const;
124pub mod adjustment;
125pub mod cast;
126pub mod codec;
127pub mod error;
128pub mod fast_reject;
129pub mod inhabitedness;
130pub mod layout;
131pub mod normalize_erasing_regions;
132pub mod offload_meta;
133pub mod pattern;
134pub mod print;
135pub mod relate;
136pub mod significant_drop_order;
137pub mod trait_def;
138pub mod util;
139pub mod vtable;
140
141mod adt;
142mod assoc;
143mod closure;
144mod consts;
145mod context;
146mod diagnostics;
147mod elaborate_impl;
148mod erase_regions;
149mod fold;
150mod generic_args;
151mod generics;
152mod impls_ty;
153mod instance;
154mod intrinsic;
155mod list;
156mod opaque_types;
157mod predicate;
158mod region;
159mod structural_impls;
160#[allow(hidden_glob_reexports)]
161mod sty;
162mod typeck_results;
163mod visit;
164
165// Data types
166
167#[derive(Debug, HashStable)]
168pub struct ResolverGlobalCtxt {
169    pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
170    /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
171    pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
172    pub effective_visibilities: EffectiveVisibilities,
173    pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
174    pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
175    pub module_children: LocalDefIdMap<Vec<ModChild>>,
176    pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
177    pub main_def: Option<MainDefinition>,
178    pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
179    /// A list of proc macro LocalDefIds, written out in the order in which
180    /// they are declared in the static array generated by proc_macro_harness.
181    pub proc_macros: Vec<LocalDefId>,
182    /// Mapping from ident span to path span for paths that don't exist as written, but that
183    /// exist under `std`. For example, wrote `str::from_utf8` instead of `std::str::from_utf8`.
184    pub confused_type_with_std_module: FxIndexMap<Span, Span>,
185    pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
186    pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
187    pub all_macro_rules: UnordSet<Symbol>,
188    pub stripped_cfg_items: Vec<StrippedCfgItem>,
189}
190
191/// Resolutions that should only be used for lowering.
192/// This struct is meant to be consumed by lowering.
193#[derive(Debug)]
194pub struct ResolverAstLowering {
195    pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
196
197    /// Resolutions for nodes that have a single resolution.
198    pub partial_res_map: NodeMap<hir::def::PartialRes>,
199    /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
200    pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
201    /// Resolutions for labels (node IDs of their corresponding blocks or loops).
202    pub label_res_map: NodeMap<ast::NodeId>,
203    /// Resolutions for lifetimes.
204    pub lifetimes_res_map: NodeMap<LifetimeRes>,
205    /// Lifetime parameters that lowering will have to introduce.
206    pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
207
208    pub next_node_id: ast::NodeId,
209
210    pub node_id_to_def_id: NodeMap<LocalDefId>,
211
212    pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
213    /// List functions and methods for which lifetime elision was successful.
214    pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
215
216    /// Lints that were emitted by the resolver and early lints.
217    pub lint_buffer: Steal<LintBuffer>,
218
219    /// Information about functions signatures for delegation items expansion
220    pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
221}
222
223#[derive(Debug)]
224pub struct DelegationFnSig {
225    pub header: ast::FnHeader,
226    pub param_count: usize,
227    pub has_self: bool,
228    pub c_variadic: bool,
229    pub target_feature: bool,
230}
231
232#[derive(Clone, Copy, Debug, HashStable)]
233pub struct MainDefinition {
234    pub res: Res<ast::NodeId>,
235    pub is_import: bool,
236    pub span: Span,
237}
238
239impl MainDefinition {
240    pub fn opt_fn_def_id(self) -> Option<DefId> {
241        if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
242    }
243}
244
245#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
246pub struct ImplTraitHeader<'tcx> {
247    pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
248    pub polarity: ImplPolarity,
249    pub safety: hir::Safety,
250    pub constness: hir::Constness,
251}
252
253#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
254#[derive(TypeFoldable, TypeVisitable, Default)]
255pub enum Asyncness {
256    Yes,
257    #[default]
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        let attributes = self.get_all_attrs(did);
1516        if let Some(reprs) = find_attr!(attributes, AttributeKind::Repr { reprs, .. } => reprs) {
1517            for (r, _) in reprs {
1518                flags.insert(match *r {
1519                    attr::ReprRust => ReprFlags::empty(),
1520                    attr::ReprC => ReprFlags::IS_C,
1521                    attr::ReprPacked(pack) => {
1522                        min_pack = Some(if let Some(min_pack) = min_pack {
1523                            min_pack.min(pack)
1524                        } else {
1525                            pack
1526                        });
1527                        ReprFlags::empty()
1528                    }
1529                    attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1530                    attr::ReprSimd => ReprFlags::IS_SIMD,
1531                    attr::ReprInt(i) => {
1532                        size = Some(match i {
1533                            attr::IntType::SignedInt(x) => match x {
1534                                ast::IntTy::Isize => IntegerType::Pointer(true),
1535                                ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1536                                ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1537                                ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1538                                ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1539                                ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1540                            },
1541                            attr::IntType::UnsignedInt(x) => match x {
1542                                ast::UintTy::Usize => IntegerType::Pointer(false),
1543                                ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1544                                ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1545                                ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1546                                ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1547                                ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1548                            },
1549                        });
1550                        ReprFlags::empty()
1551                    }
1552                    attr::ReprAlign(align) => {
1553                        max_align = max_align.max(Some(align));
1554                        ReprFlags::empty()
1555                    }
1556                });
1557            }
1558        }
1559
1560        // If `-Z randomize-layout` was enabled for the type definition then we can
1561        // consider performing layout randomization
1562        if self.sess.opts.unstable_opts.randomize_layout {
1563            flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1564        }
1565
1566        // box is special, on the one hand the compiler assumes an ordered layout, with the pointer
1567        // always at offset zero. On the other hand we want scalar abi optimizations.
1568        let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1569
1570        // This is here instead of layout because the choice must make it into metadata.
1571        if is_box {
1572            flags.insert(ReprFlags::IS_LINEAR);
1573        }
1574
1575        // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details.
1576        if find_attr!(attributes, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) {
1577            flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1578        }
1579
1580        ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1581    }
1582
1583    /// Look up the name of a definition across crates. This does not look at HIR.
1584    pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1585        let def_id = def_id.into_query_param();
1586        if let Some(cnum) = def_id.as_crate_root() {
1587            Some(self.crate_name(cnum))
1588        } else {
1589            let def_key = self.def_key(def_id);
1590            match def_key.disambiguated_data.data {
1591                // The name of a constructor is that of its parent.
1592                rustc_hir::definitions::DefPathData::Ctor => self
1593                    .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1594                _ => def_key.get_opt_name(),
1595            }
1596        }
1597    }
1598
1599    /// Look up the name of a definition across crates. This does not look at HIR.
1600    ///
1601    /// This method will ICE if the corresponding item does not have a name. In these cases, use
1602    /// [`opt_item_name`] instead.
1603    ///
1604    /// [`opt_item_name`]: Self::opt_item_name
1605    pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1606        let id = id.into_query_param();
1607        self.opt_item_name(id).unwrap_or_else(|| {
1608            bug!("item_name: no name for {:?}", self.def_path(id));
1609        })
1610    }
1611
1612    /// Look up the name and span of a definition.
1613    ///
1614    /// See [`item_name`][Self::item_name] for more information.
1615    pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1616        let def_id = def_id.into_query_param();
1617        let def = self.opt_item_name(def_id)?;
1618        let span = self
1619            .def_ident_span(def_id)
1620            .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1621        Some(Ident::new(def, span))
1622    }
1623
1624    /// Look up the name and span of a definition.
1625    ///
1626    /// See [`item_name`][Self::item_name] for more information.
1627    pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1628        let def_id = def_id.into_query_param();
1629        self.opt_item_ident(def_id).unwrap_or_else(|| {
1630            bug!("item_ident: no name for {:?}", self.def_path(def_id));
1631        })
1632    }
1633
1634    pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1635        if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1636            Some(self.associated_item(def_id))
1637        } else {
1638            None
1639        }
1640    }
1641
1642    /// If the `def_id` is an associated type that was desugared from a
1643    /// return-position `impl Trait` from a trait, then provide the source info
1644    /// about where that RPITIT came from.
1645    pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1646        if let DefKind::AssocTy = self.def_kind(def_id)
1647            && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1648                self.associated_item(def_id).kind
1649        {
1650            Some(rpitit_info)
1651        } else {
1652            None
1653        }
1654    }
1655
1656    pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1657        variant.fields.iter_enumerated().find_map(|(i, field)| {
1658            self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1659        })
1660    }
1661
1662    /// Returns `Some` if the impls are the same polarity and the trait either
1663    /// has no items or is annotated `#[marker]` and prevents item overrides.
1664    #[instrument(level = "debug", skip(self), ret)]
1665    pub fn impls_are_allowed_to_overlap(
1666        self,
1667        def_id1: DefId,
1668        def_id2: DefId,
1669    ) -> Option<ImplOverlapKind> {
1670        let impl1 = self.impl_trait_header(def_id1);
1671        let impl2 = self.impl_trait_header(def_id2);
1672
1673        let trait_ref1 = impl1.trait_ref.skip_binder();
1674        let trait_ref2 = impl2.trait_ref.skip_binder();
1675
1676        // If either trait impl references an error, they're allowed to overlap,
1677        // as one of them essentially doesn't exist.
1678        if trait_ref1.references_error() || trait_ref2.references_error() {
1679            return Some(ImplOverlapKind::Permitted { marker: false });
1680        }
1681
1682        match (impl1.polarity, impl2.polarity) {
1683            (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1684                // `#[rustc_reservation_impl]` impls don't overlap with anything
1685                return Some(ImplOverlapKind::Permitted { marker: false });
1686            }
1687            (ImplPolarity::Positive, ImplPolarity::Negative)
1688            | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1689                // `impl AutoTrait for Type` + `impl !AutoTrait for Type`
1690                return None;
1691            }
1692            (ImplPolarity::Positive, ImplPolarity::Positive)
1693            | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1694        };
1695
1696        let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1697        let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1698
1699        if is_marker_overlap {
1700            return Some(ImplOverlapKind::Permitted { marker: true });
1701        }
1702
1703        None
1704    }
1705
1706    /// Returns `ty::VariantDef` if `res` refers to a struct,
1707    /// or variant or their constructors, panics otherwise.
1708    pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1709        match res {
1710            Res::Def(DefKind::Variant, did) => {
1711                let enum_did = self.parent(did);
1712                self.adt_def(enum_did).variant_with_id(did)
1713            }
1714            Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1715            Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1716                let variant_did = self.parent(variant_ctor_did);
1717                let enum_did = self.parent(variant_did);
1718                self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1719            }
1720            Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1721                let struct_did = self.parent(ctor_did);
1722                self.adt_def(struct_did).non_enum_variant()
1723            }
1724            _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1725        }
1726    }
1727
1728    /// Returns the possibly-auto-generated MIR of a [`ty::InstanceKind`].
1729    #[instrument(skip(self), level = "debug")]
1730    pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1731        match instance {
1732            ty::InstanceKind::Item(def) => {
1733                debug!("calling def_kind on def: {:?}", def);
1734                let def_kind = self.def_kind(def);
1735                debug!("returned from def_kind: {:?}", def_kind);
1736                match def_kind {
1737                    DefKind::Const
1738                    | DefKind::Static { .. }
1739                    | DefKind::AssocConst
1740                    | DefKind::Ctor(..)
1741                    | DefKind::AnonConst
1742                    | DefKind::InlineConst => self.mir_for_ctfe(def),
1743                    // If the caller wants `mir_for_ctfe` of a function they should not be using
1744                    // `instance_mir`, so we'll assume const fn also wants the optimized version.
1745                    _ => self.optimized_mir(def),
1746                }
1747            }
1748            ty::InstanceKind::VTableShim(..)
1749            | ty::InstanceKind::ReifyShim(..)
1750            | ty::InstanceKind::Intrinsic(..)
1751            | ty::InstanceKind::FnPtrShim(..)
1752            | ty::InstanceKind::Virtual(..)
1753            | ty::InstanceKind::ClosureOnceShim { .. }
1754            | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1755            | ty::InstanceKind::FutureDropPollShim(..)
1756            | ty::InstanceKind::DropGlue(..)
1757            | ty::InstanceKind::CloneShim(..)
1758            | ty::InstanceKind::ThreadLocalShim(..)
1759            | ty::InstanceKind::FnPtrAddrShim(..)
1760            | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1761            | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1762        }
1763    }
1764
1765    /// Gets all attributes with the given name.
1766    pub fn get_attrs(
1767        self,
1768        did: impl Into<DefId>,
1769        attr: Symbol,
1770    ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1771        self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1772    }
1773
1774    /// Gets all attributes.
1775    ///
1776    /// To see if an item has a specific attribute, you should use
1777    /// [`rustc_hir::find_attr!`] so you can use matching.
1778    pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1779        let did: DefId = did.into();
1780        if let Some(did) = did.as_local() {
1781            self.hir_attrs(self.local_def_id_to_hir_id(did))
1782        } else {
1783            self.attrs_for_def(did)
1784        }
1785    }
1786
1787    /// Get an attribute from the diagnostic attribute namespace
1788    ///
1789    /// This function requests an attribute with the following structure:
1790    ///
1791    /// `#[diagnostic::$attr]`
1792    ///
1793    /// This function performs feature checking, so if an attribute is returned
1794    /// it can be used by the consumer
1795    pub fn get_diagnostic_attr(
1796        self,
1797        did: impl Into<DefId>,
1798        attr: Symbol,
1799    ) -> Option<&'tcx hir::Attribute> {
1800        let did: DefId = did.into();
1801        if did.as_local().is_some() {
1802            // it's a crate local item, we need to check feature flags
1803            if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1804                self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1805            } else {
1806                None
1807            }
1808        } else {
1809            // we filter out unstable diagnostic attributes before
1810            // encoding attributes
1811            debug_assert!(rustc_feature::encode_cross_crate(attr));
1812            self.attrs_for_def(did)
1813                .iter()
1814                .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1815        }
1816    }
1817
1818    pub fn get_attrs_by_path(
1819        self,
1820        did: DefId,
1821        attr: &[Symbol],
1822    ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1823        let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1824        if let Some(did) = did.as_local() {
1825            self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1826        } else {
1827            self.attrs_for_def(did).iter().filter(filter_fn)
1828        }
1829    }
1830
1831    pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1832        if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1833            let did: DefId = did.into();
1834            bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1835        } else {
1836            self.get_attrs(did, attr).next()
1837        }
1838    }
1839
1840    /// Determines whether an item is annotated with an attribute.
1841    pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1842        self.get_attrs(did, attr).next().is_some()
1843    }
1844
1845    /// Determines whether an item is annotated with a multi-segment attribute
1846    pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1847        self.get_attrs_by_path(did.into(), attrs).next().is_some()
1848    }
1849
1850    /// Returns `true` if this is an `auto trait`.
1851    pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1852        self.trait_def(trait_def_id).has_auto_impl
1853    }
1854
1855    /// Returns `true` if this is coinductive, either because it is
1856    /// an auto trait or because it has the `#[rustc_coinductive]` attribute.
1857    pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1858        self.trait_def(trait_def_id).is_coinductive
1859    }
1860
1861    /// Returns `true` if this is a trait alias.
1862    pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1863        self.def_kind(trait_def_id) == DefKind::TraitAlias
1864    }
1865
1866    /// Arena-alloc of LayoutError for coroutine layout
1867    fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1868        self.arena.alloc(err)
1869    }
1870
1871    /// Returns layout of a non-async-drop coroutine. Layout might be unavailable if the
1872    /// coroutine is tainted by errors.
1873    ///
1874    /// Takes `coroutine_kind` which can be acquired from the `CoroutineArgs::kind_ty`,
1875    /// e.g. `args.as_coroutine().kind_ty()`.
1876    fn ordinary_coroutine_layout(
1877        self,
1878        def_id: DefId,
1879        args: GenericArgsRef<'tcx>,
1880    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1881        let coroutine_kind_ty = args.as_coroutine().kind_ty();
1882        let mir = self.optimized_mir(def_id);
1883        let ty = || Ty::new_coroutine(self, def_id, args);
1884        // Regular coroutine
1885        if coroutine_kind_ty.is_unit() {
1886            mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1887        } else {
1888            // If we have a `Coroutine` that comes from an coroutine-closure,
1889            // then it may be a by-move or by-ref body.
1890            let ty::Coroutine(_, identity_args) =
1891                *self.type_of(def_id).instantiate_identity().kind()
1892            else {
1893                unreachable!();
1894            };
1895            let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1896            // If the types differ, then we must be getting the by-move body of
1897            // a by-ref coroutine.
1898            if identity_kind_ty == coroutine_kind_ty {
1899                mir.coroutine_layout_raw()
1900                    .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1901            } else {
1902                assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1903                assert_matches!(
1904                    identity_kind_ty.to_opt_closure_kind(),
1905                    Some(ClosureKind::Fn | ClosureKind::FnMut)
1906                );
1907                self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1908                    .coroutine_layout_raw()
1909                    .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1910            }
1911        }
1912    }
1913
1914    /// Returns layout of a `async_drop_in_place::{closure}` coroutine
1915    ///   (returned from `async fn async_drop_in_place<T>(..)`).
1916    /// Layout might be unavailable if the coroutine is tainted by errors.
1917    fn async_drop_coroutine_layout(
1918        self,
1919        def_id: DefId,
1920        args: GenericArgsRef<'tcx>,
1921    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1922        let ty = || Ty::new_coroutine(self, def_id, args);
1923        if args[0].has_placeholders() || args[0].has_non_region_param() {
1924            return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1925        }
1926        let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1927        self.mir_shims(instance)
1928            .coroutine_layout_raw()
1929            .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1930    }
1931
1932    /// Returns layout of a coroutine. Layout might be unavailable if the
1933    /// coroutine is tainted by errors.
1934    pub fn coroutine_layout(
1935        self,
1936        def_id: DefId,
1937        args: GenericArgsRef<'tcx>,
1938    ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1939        if self.is_async_drop_in_place_coroutine(def_id) {
1940            // layout of `async_drop_in_place<T>::{closure}` in case,
1941            // when T is a coroutine, contains this internal coroutine's ptr in upvars
1942            // and doesn't require any locals. Here is an `empty coroutine's layout`
1943            let arg_cor_ty = args.first().unwrap().expect_ty();
1944            if arg_cor_ty.is_coroutine() {
1945                let span = self.def_span(def_id);
1946                let source_info = SourceInfo::outermost(span);
1947                // Even minimal, empty coroutine has 3 states (RESERVED_VARIANTS),
1948                // so variant_fields and variant_source_info should have 3 elements.
1949                let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1950                    iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1951                let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1952                    iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1953                let proxy_layout = CoroutineLayout {
1954                    field_tys: [].into(),
1955                    field_names: [].into(),
1956                    variant_fields,
1957                    variant_source_info,
1958                    storage_conflicts: BitMatrix::new(0, 0),
1959                };
1960                return Ok(self.arena.alloc(proxy_layout));
1961            } else {
1962                self.async_drop_coroutine_layout(def_id, args)
1963            }
1964        } else {
1965            self.ordinary_coroutine_layout(def_id, args)
1966        }
1967    }
1968
1969    /// If the given `DefId` is an associated item, returns the `DefId` and `DefKind` of the parent trait or impl.
1970    pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1971        if !self.def_kind(def_id).is_assoc() {
1972            return None;
1973        }
1974        let parent = self.parent(def_id);
1975        let def_kind = self.def_kind(parent);
1976        Some((parent, def_kind))
1977    }
1978
1979    /// Returns the trait item that is implemented by the given item `DefId`.
1980    pub fn trait_item_of(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
1981        self.opt_associated_item(def_id.into_query_param())?.trait_item_def_id()
1982    }
1983
1984    /// If the given `DefId` is an associated item of a trait,
1985    /// returns the `DefId` of the trait; otherwise, returns `None`.
1986    pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
1987        match self.assoc_parent(def_id) {
1988            Some((id, DefKind::Trait)) => Some(id),
1989            _ => None,
1990        }
1991    }
1992
1993    pub fn impl_is_of_trait(self, def_id: impl IntoQueryParam<DefId>) -> bool {
1994        let def_id = def_id.into_query_param();
1995        let DefKind::Impl { of_trait } = self.def_kind(def_id) else {
1996            panic!("expected Impl for {def_id:?}");
1997        };
1998        of_trait
1999    }
2000
2001    /// If the given `DefId` is an associated item of an impl,
2002    /// returns the `DefId` of the impl; otherwise returns `None`.
2003    pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2004        match self.assoc_parent(def_id) {
2005            Some((id, DefKind::Impl { .. })) => Some(id),
2006            _ => None,
2007        }
2008    }
2009
2010    /// If the given `DefId` is an associated item of an inherent impl,
2011    /// returns the `DefId` of the impl; otherwise, returns `None`.
2012    pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2013        match self.assoc_parent(def_id) {
2014            Some((id, DefKind::Impl { of_trait: false })) => Some(id),
2015            _ => None,
2016        }
2017    }
2018
2019    /// If the given `DefId` is an associated item of a trait impl,
2020    /// returns the `DefId` of the impl; otherwise, returns `None`.
2021    pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2022        match self.assoc_parent(def_id) {
2023            Some((id, DefKind::Impl { of_trait: true })) => Some(id),
2024            _ => None,
2025        }
2026    }
2027
2028    pub fn impl_polarity(self, def_id: impl IntoQueryParam<DefId>) -> ty::ImplPolarity {
2029        self.impl_trait_header(def_id).polarity
2030    }
2031
2032    /// Given an `impl_id`, return the trait it implements.
2033    pub fn impl_trait_ref(
2034        self,
2035        def_id: impl IntoQueryParam<DefId>,
2036    ) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
2037        self.impl_trait_header(def_id).trait_ref
2038    }
2039
2040    /// Given an `impl_id`, return the trait it implements.
2041    /// Returns `None` if it is an inherent impl.
2042    pub fn impl_opt_trait_ref(
2043        self,
2044        def_id: impl IntoQueryParam<DefId>,
2045    ) -> Option<ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>> {
2046        let def_id = def_id.into_query_param();
2047        self.impl_is_of_trait(def_id).then(|| self.impl_trait_ref(def_id))
2048    }
2049
2050    /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2051    pub fn impl_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> DefId {
2052        self.impl_trait_ref(def_id).skip_binder().def_id
2053    }
2054
2055    /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements.
2056    /// Returns `None` if it is an inherent impl.
2057    pub fn impl_opt_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2058        let def_id = def_id.into_query_param();
2059        self.impl_is_of_trait(def_id).then(|| self.impl_trait_id(def_id))
2060    }
2061
2062    pub fn is_exportable(self, def_id: DefId) -> bool {
2063        self.exportable_items(def_id.krate).contains(&def_id)
2064    }
2065
2066    /// Check if the given `DefId` is `#\[automatically_derived\]`, *and*
2067    /// whether it was produced by expanding a builtin derive macro.
2068    pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2069        if self.is_automatically_derived(def_id)
2070            && let Some(def_id) = def_id.as_local()
2071            && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2072            && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2073            && find_attr!(
2074                self.get_all_attrs(outer.macro_def_id.unwrap()),
2075                AttributeKind::RustcBuiltinMacro { .. }
2076            )
2077        {
2078            true
2079        } else {
2080            false
2081        }
2082    }
2083
2084    /// Check if the given `DefId` is `#\[automatically_derived\]`.
2085    pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2086        find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
2087    }
2088
2089    /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
2090    /// with the name of the crate containing the impl.
2091    pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2092        if let Some(impl_def_id) = impl_def_id.as_local() {
2093            Ok(self.def_span(impl_def_id))
2094        } else {
2095            Err(self.crate_name(impl_def_id.krate))
2096        }
2097    }
2098
2099    /// Hygienically compares a use-site name (`use_name`) for a field or an associated item with
2100    /// its supposed definition name (`def_name`). The method also needs `DefId` of the supposed
2101    /// definition's parent/scope to perform comparison.
2102    pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2103        // We could use `Ident::eq` here, but we deliberately don't. The identifier
2104        // comparison fails frequently, and we want to avoid the expensive
2105        // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible.
2106        use_ident.name == def_ident.name
2107            && use_ident
2108                .span
2109                .ctxt()
2110                .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2111    }
2112
2113    pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2114        ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2115        ident
2116    }
2117
2118    // FIXME(vincenzopalazzo): move the HirId to a LocalDefId
2119    pub fn adjust_ident_and_get_scope(
2120        self,
2121        mut ident: Ident,
2122        scope: DefId,
2123        block: hir::HirId,
2124    ) -> (Ident, DefId) {
2125        let scope = ident
2126            .span
2127            .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2128            .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2129            .unwrap_or_else(|| self.parent_module(block).to_def_id());
2130        (ident, scope)
2131    }
2132
2133    /// Checks whether this is a `const fn`. Returns `false` for non-functions.
2134    ///
2135    /// Even if this returns `true`, constness may still be unstable!
2136    #[inline]
2137    pub fn is_const_fn(self, def_id: DefId) -> bool {
2138        matches!(
2139            self.def_kind(def_id),
2140            DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2141        ) && self.constness(def_id) == hir::Constness::Const
2142    }
2143
2144    /// Whether this item is conditionally constant for the purposes of the
2145    /// effects implementation.
2146    ///
2147    /// This roughly corresponds to all const functions and other callable
2148    /// items, along with const impls and traits, and associated types within
2149    /// those impls and traits.
2150    pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2151        let def_id: DefId = def_id.into();
2152        match self.def_kind(def_id) {
2153            DefKind::Impl { of_trait: true } => {
2154                let header = self.impl_trait_header(def_id);
2155                header.constness == hir::Constness::Const
2156                    && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2157            }
2158            DefKind::Impl { of_trait: false } => self.constness(def_id) == hir::Constness::Const,
2159            DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2160                self.constness(def_id) == hir::Constness::Const
2161            }
2162            DefKind::TraitAlias | DefKind::Trait => self.is_const_trait(def_id),
2163            DefKind::AssocTy => {
2164                let parent_def_id = self.parent(def_id);
2165                match self.def_kind(parent_def_id) {
2166                    DefKind::Impl { of_trait: false } => false,
2167                    DefKind::Impl { of_trait: true } | DefKind::Trait => {
2168                        self.is_conditionally_const(parent_def_id)
2169                    }
2170                    _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2171                }
2172            }
2173            DefKind::AssocFn => {
2174                let parent_def_id = self.parent(def_id);
2175                match self.def_kind(parent_def_id) {
2176                    DefKind::Impl { of_trait: false } => {
2177                        self.constness(def_id) == hir::Constness::Const
2178                    }
2179                    DefKind::Impl { of_trait: true } | DefKind::Trait => {
2180                        self.is_conditionally_const(parent_def_id)
2181                    }
2182                    _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2183                }
2184            }
2185            DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2186                hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2187                hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2188                // FIXME(const_trait_impl): ATPITs could be conditionally const?
2189                hir::OpaqueTyOrigin::TyAlias { .. } => false,
2190            },
2191            DefKind::Closure => {
2192                // Closures and RPITs will eventually have const conditions
2193                // for `[const]` bounds.
2194                false
2195            }
2196            DefKind::Ctor(_, CtorKind::Const)
2197            | DefKind::Mod
2198            | DefKind::Struct
2199            | DefKind::Union
2200            | DefKind::Enum
2201            | DefKind::Variant
2202            | DefKind::TyAlias
2203            | DefKind::ForeignTy
2204            | DefKind::TyParam
2205            | DefKind::Const
2206            | DefKind::ConstParam
2207            | DefKind::Static { .. }
2208            | DefKind::AssocConst
2209            | DefKind::Macro(_)
2210            | DefKind::ExternCrate
2211            | DefKind::Use
2212            | DefKind::ForeignMod
2213            | DefKind::AnonConst
2214            | DefKind::InlineConst
2215            | DefKind::Field
2216            | DefKind::LifetimeParam
2217            | DefKind::GlobalAsm
2218            | DefKind::SyntheticCoroutineBody => false,
2219        }
2220    }
2221
2222    #[inline]
2223    pub fn is_const_trait(self, def_id: DefId) -> bool {
2224        self.trait_def(def_id).constness == hir::Constness::Const
2225    }
2226
2227    #[inline]
2228    pub fn is_const_default_method(self, def_id: DefId) -> bool {
2229        matches!(self.trait_of_assoc(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2230    }
2231
2232    pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2233        if self.def_kind(def_id) != DefKind::AssocFn {
2234            return false;
2235        }
2236
2237        let Some(item) = self.opt_associated_item(def_id) else {
2238            return false;
2239        };
2240
2241        let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2242            return false;
2243        };
2244
2245        !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2246    }
2247}
2248
2249pub fn provide(providers: &mut Providers) {
2250    closure::provide(providers);
2251    context::provide(providers);
2252    erase_regions::provide(providers);
2253    inhabitedness::provide(providers);
2254    util::provide(providers);
2255    print::provide(providers);
2256    super::util::bug::provide(providers);
2257    *providers = Providers {
2258        trait_impls_of: trait_def::trait_impls_of_provider,
2259        incoherent_impls: trait_def::incoherent_impls_provider,
2260        trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2261        traits: trait_def::traits_provider,
2262        vtable_allocation: vtable::vtable_allocation_provider,
2263        ..*providers
2264    };
2265}
2266
2267/// A map for the local crate mapping each type to a vector of its
2268/// inherent impls. This is not meant to be used outside of coherence;
2269/// rather, you should request the vector for a specific type via
2270/// `tcx.inherent_impls(def_id)` so as to minimize your dependencies
2271/// (constructing this map requires touching the entire crate).
2272#[derive(Clone, Debug, Default, HashStable)]
2273pub struct CrateInherentImpls {
2274    pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2275    pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2276}
2277
2278#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2279pub struct SymbolName<'tcx> {
2280    /// `&str` gives a consistent ordering, which ensures reproducible builds.
2281    pub name: &'tcx str,
2282}
2283
2284impl<'tcx> SymbolName<'tcx> {
2285    pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2286        SymbolName { name: tcx.arena.alloc_str(name) }
2287    }
2288}
2289
2290impl<'tcx> fmt::Display for SymbolName<'tcx> {
2291    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2292        fmt::Display::fmt(&self.name, fmt)
2293    }
2294}
2295
2296impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2297    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2298        fmt::Display::fmt(&self.name, fmt)
2299    }
2300}
2301
2302/// The constituent parts of a type level constant of kind ADT or array.
2303#[derive(Copy, Clone, Debug, HashStable)]
2304pub struct DestructuredConst<'tcx> {
2305    pub variant: Option<VariantIdx>,
2306    pub fields: &'tcx [ty::Const<'tcx>],
2307}
2308
2309/// Generate TypeTree information for autodiff.
2310/// This function creates TypeTree metadata that describes the memory layout
2311/// of function parameters and return types for Enzyme autodiff.
2312pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
2313    // Check if TypeTrees are disabled via NoTT flag
2314    if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
2315        return FncTree { args: vec![], ret: TypeTree::new() };
2316    }
2317
2318    // Check if this is actually a function type
2319    if !fn_ty.is_fn() {
2320        return FncTree { args: vec![], ret: TypeTree::new() };
2321    }
2322
2323    // Get the function signature
2324    let fn_sig = fn_ty.fn_sig(tcx);
2325    let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
2326
2327    // Create TypeTrees for each input parameter
2328    let mut args = vec![];
2329    for ty in sig.inputs().iter() {
2330        let type_tree = typetree_from_ty(tcx, *ty);
2331        args.push(type_tree);
2332    }
2333
2334    // Create TypeTree for return type
2335    let ret = typetree_from_ty(tcx, sig.output());
2336
2337    FncTree { args, ret }
2338}
2339
2340/// Generate TypeTree for a specific type.
2341/// This function analyzes a Rust type and creates appropriate TypeTree metadata.
2342pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
2343    let mut visited = Vec::new();
2344    typetree_from_ty_inner(tcx, ty, 0, &mut visited)
2345}
2346
2347/// Maximum recursion depth for TypeTree generation to prevent stack overflow
2348/// from pathological deeply nested types. Combined with cycle detection.
2349const MAX_TYPETREE_DEPTH: usize = 6;
2350
2351/// Internal recursive function for TypeTree generation with cycle detection and depth limiting.
2352fn typetree_from_ty_inner<'tcx>(
2353    tcx: TyCtxt<'tcx>,
2354    ty: Ty<'tcx>,
2355    depth: usize,
2356    visited: &mut Vec<Ty<'tcx>>,
2357) -> TypeTree {
2358    if depth >= MAX_TYPETREE_DEPTH {
2359        trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
2360        return TypeTree::new();
2361    }
2362
2363    if visited.contains(&ty) {
2364        return TypeTree::new();
2365    }
2366
2367    visited.push(ty);
2368    let result = typetree_from_ty_impl(tcx, ty, depth, visited);
2369    visited.pop();
2370    result
2371}
2372
2373/// Implementation of TypeTree generation logic.
2374fn typetree_from_ty_impl<'tcx>(
2375    tcx: TyCtxt<'tcx>,
2376    ty: Ty<'tcx>,
2377    depth: usize,
2378    visited: &mut Vec<Ty<'tcx>>,
2379) -> TypeTree {
2380    typetree_from_ty_impl_inner(tcx, ty, depth, visited, false)
2381}
2382
2383/// Internal implementation with context about whether this is for a reference target.
2384fn typetree_from_ty_impl_inner<'tcx>(
2385    tcx: TyCtxt<'tcx>,
2386    ty: Ty<'tcx>,
2387    depth: usize,
2388    visited: &mut Vec<Ty<'tcx>>,
2389    is_reference_target: bool,
2390) -> TypeTree {
2391    if ty.is_scalar() {
2392        let (kind, size) = if ty.is_integral() || ty.is_char() || ty.is_bool() {
2393            (Kind::Integer, ty.primitive_size(tcx).bytes_usize())
2394        } else if ty.is_floating_point() {
2395            match ty {
2396                x if x == tcx.types.f16 => (Kind::Half, 2),
2397                x if x == tcx.types.f32 => (Kind::Float, 4),
2398                x if x == tcx.types.f64 => (Kind::Double, 8),
2399                x if x == tcx.types.f128 => (Kind::F128, 16),
2400                _ => (Kind::Integer, 0),
2401            }
2402        } else {
2403            (Kind::Integer, 0)
2404        };
2405
2406        // Use offset 0 for scalars that are direct targets of references (like &f64)
2407        // Use offset -1 for scalars used directly (like function return types)
2408        let offset = if is_reference_target && !ty.is_array() { 0 } else { -1 };
2409        return TypeTree(vec![Type { offset, size, kind, child: TypeTree::new() }]);
2410    }
2411
2412    if ty.is_ref() || ty.is_raw_ptr() || ty.is_box() {
2413        let inner_ty = if let Some(inner) = ty.builtin_deref(true) {
2414            inner
2415        } else {
2416            return TypeTree::new();
2417        };
2418
2419        let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
2420        return TypeTree(vec![Type {
2421            offset: -1,
2422            size: tcx.data_layout.pointer_size().bytes_usize(),
2423            kind: Kind::Pointer,
2424            child,
2425        }]);
2426    }
2427
2428    if ty.is_array() {
2429        if let ty::Array(element_ty, len_const) = ty.kind() {
2430            let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
2431            if len == 0 {
2432                return TypeTree::new();
2433            }
2434            let element_tree =
2435                typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2436            let mut types = Vec::new();
2437            for elem_type in &element_tree.0 {
2438                types.push(Type {
2439                    offset: -1,
2440                    size: elem_type.size,
2441                    kind: elem_type.kind,
2442                    child: elem_type.child.clone(),
2443                });
2444            }
2445
2446            return TypeTree(types);
2447        }
2448    }
2449
2450    if ty.is_slice() {
2451        if let ty::Slice(element_ty) = ty.kind() {
2452            let element_tree =
2453                typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2454            return element_tree;
2455        }
2456    }
2457
2458    if let ty::Tuple(tuple_types) = ty.kind() {
2459        if tuple_types.is_empty() {
2460            return TypeTree::new();
2461        }
2462
2463        let mut types = Vec::new();
2464        let mut current_offset = 0;
2465
2466        for tuple_ty in tuple_types.iter() {
2467            let element_tree =
2468                typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
2469
2470            let element_layout = tcx
2471                .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
2472                .ok()
2473                .map(|layout| layout.size.bytes_usize())
2474                .unwrap_or(0);
2475
2476            for elem_type in &element_tree.0 {
2477                types.push(Type {
2478                    offset: if elem_type.offset == -1 {
2479                        current_offset as isize
2480                    } else {
2481                        current_offset as isize + elem_type.offset
2482                    },
2483                    size: elem_type.size,
2484                    kind: elem_type.kind,
2485                    child: elem_type.child.clone(),
2486                });
2487            }
2488
2489            current_offset += element_layout;
2490        }
2491
2492        return TypeTree(types);
2493    }
2494
2495    if let ty::Adt(adt_def, args) = ty.kind() {
2496        if adt_def.is_struct() {
2497            let struct_layout =
2498                tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
2499            if let Ok(layout) = struct_layout {
2500                let mut types = Vec::new();
2501
2502                for (field_idx, field_def) in adt_def.all_fields().enumerate() {
2503                    let field_ty = field_def.ty(tcx, args);
2504                    let field_tree =
2505                        typetree_from_ty_impl_inner(tcx, field_ty, depth + 1, visited, false);
2506
2507                    let field_offset = layout.fields.offset(field_idx).bytes_usize();
2508
2509                    for elem_type in &field_tree.0 {
2510                        types.push(Type {
2511                            offset: if elem_type.offset == -1 {
2512                                field_offset as isize
2513                            } else {
2514                                field_offset as isize + elem_type.offset
2515                            },
2516                            size: elem_type.size,
2517                            kind: elem_type.kind,
2518                            child: elem_type.child.clone(),
2519                        });
2520                    }
2521                }
2522
2523                return TypeTree(types);
2524            }
2525        }
2526    }
2527
2528    TypeTree::new()
2529}