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