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