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