rustc_middle/ty/
mod.rs

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