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