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