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