1#![allow(rustc::usage_of_ty_tykind)]
13
14use std::assert_matches::assert_matches;
15use std::fmt::Debug;
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18use std::num::NonZero;
19use std::ptr::NonNull;
20use std::{fmt, iter, str};
21
22pub use adt::*;
23pub use assoc::*;
24pub use generic_args::{GenericArgKind, TermKind, *};
25pub use generics::*;
26pub use intrinsic::IntrinsicDef;
27use rustc_abi::{Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, VariantIdx};
28use rustc_ast::expand::StrippedCfgItem;
29use rustc_ast::node_id::NodeMap;
30pub use rustc_ast_ir::{Movability, Mutability, try_visit};
31use rustc_attr_data_structures::AttributeKind;
32use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
33use rustc_data_structures::intern::Interned;
34use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
35use rustc_data_structures::steal::Steal;
36use rustc_data_structures::unord::UnordMap;
37use rustc_errors::{Diag, ErrorGuaranteed};
38use rustc_hir::LangItem;
39use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
40use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
41use rustc_hir::definitions::DisambiguatorState;
42use rustc_index::IndexVec;
43use rustc_index::bit_set::BitMatrix;
44use rustc_macros::{
45 Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
46 extension,
47};
48use rustc_query_system::ich::StableHashingContext;
49use rustc_serialize::{Decodable, Encodable};
50use rustc_session::lint::LintBuffer;
51pub use rustc_session::lint::RegisteredTools;
52use rustc_span::hygiene::MacroKind;
53use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, kw, sym};
54pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
55pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
56#[allow(
57 hidden_glob_reexports,
58 rustc::usage_of_type_ir_inherent,
59 rustc::non_glob_import_of_type_ir_inherent
60)]
61use rustc_type_ir::inherent;
62pub use rustc_type_ir::relate::VarianceDiagInfo;
63pub use rustc_type_ir::solve::SizedTraitKind;
64pub use rustc_type_ir::*;
65#[allow(hidden_glob_reexports, unused_imports)]
66use rustc_type_ir::{InferCtxtLike, Interner};
67use tracing::{debug, instrument};
68pub use vtable::*;
69use {rustc_ast as ast, rustc_attr_data_structures as attr, rustc_hir as hir};
70
71pub use self::closure::{
72 BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
73 MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
74 UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
75 place_to_string_for_capture,
76};
77pub use self::consts::{
78 AnonConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr,
79 ExprKind, ScalarInt, UnevaluatedConst, ValTree, ValTreeKind, Value,
80};
81pub use self::context::{
82 CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt,
83 TyCtxtFeed, tls,
84};
85pub use self::fold::*;
86pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams};
87pub use self::list::{List, ListWithCachedTypeInfo};
88pub use self::opaque_types::OpaqueTypeKey;
89pub use self::parameterized::ParameterizedOverTcx;
90pub use self::pattern::{Pattern, PatternKind};
91pub use self::predicate::{
92 AliasTerm, Clause, ClauseKind, CoercePredicate, ExistentialPredicate,
93 ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef,
94 HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
95 PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
96 PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
97 PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
98 RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate,
99};
100pub use self::region::{
101 BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
102 RegionKind, RegionVid,
103};
104pub use self::rvalue_scopes::RvalueScopes;
105pub use self::sty::{
106 AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
107 CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
108 ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
109};
110pub use self::trait_def::TraitDef;
111pub use self::typeck_results::{
112 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
113 Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
114};
115pub use self::visit::*;
116use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
117use crate::metadata::ModChild;
118use crate::middle::privacy::EffectiveVisibilities;
119use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
120use crate::query::{IntoQueryParam, Providers};
121use crate::ty;
122use crate::ty::codec::{TyDecoder, TyEncoder};
123pub use crate::ty::diagnostics::*;
124use crate::ty::fast_reject::SimplifiedType;
125use crate::ty::layout::LayoutError;
126use crate::ty::util::Discr;
127use crate::ty::walk::TypeWalker;
128
129pub mod abstract_const;
130pub mod adjustment;
131pub mod cast;
132pub mod codec;
133pub mod error;
134pub mod fast_reject;
135pub mod inhabitedness;
136pub mod layout;
137pub mod normalize_erasing_regions;
138pub mod pattern;
139pub mod print;
140pub mod relate;
141pub mod significant_drop_order;
142pub mod trait_def;
143pub mod util;
144pub mod vtable;
145
146mod adt;
147mod assoc;
148mod closure;
149mod consts;
150mod context;
151mod diagnostics;
152mod elaborate_impl;
153mod erase_regions;
154mod fold;
155mod generic_args;
156mod generics;
157mod impls_ty;
158mod instance;
159mod intrinsic;
160mod list;
161mod opaque_types;
162mod parameterized;
163mod predicate;
164mod region;
165mod rvalue_scopes;
166mod structural_impls;
167#[allow(hidden_glob_reexports)]
168mod sty;
169mod typeck_results;
170mod visit;
171
172pub struct ResolverOutputs {
175 pub global_ctxt: ResolverGlobalCtxt,
176 pub ast_lowering: ResolverAstLowering,
177}
178
179#[derive(Debug)]
180pub struct ResolverGlobalCtxt {
181 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
182 pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
184 pub effective_visibilities: EffectiveVisibilities,
185 pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
186 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
187 pub module_children: LocalDefIdMap<Vec<ModChild>>,
188 pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
189 pub main_def: Option<MainDefinition>,
190 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
191 pub proc_macros: Vec<LocalDefId>,
194 pub confused_type_with_std_module: FxIndexMap<Span, Span>,
197 pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
198 pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
199 pub all_macro_rules: FxHashSet<Symbol>,
200 pub stripped_cfg_items: Steal<Vec<StrippedCfgItem>>,
201}
202
203#[derive(Debug)]
206pub struct ResolverAstLowering {
207 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
208
209 pub partial_res_map: NodeMap<hir::def::PartialRes>,
211 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
213 pub label_res_map: NodeMap<ast::NodeId>,
215 pub lifetimes_res_map: NodeMap<LifetimeRes>,
217 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
219
220 pub next_node_id: ast::NodeId,
221
222 pub node_id_to_def_id: NodeMap<LocalDefId>,
223
224 pub disambiguator: DisambiguatorState,
225
226 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
227 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
229
230 pub lint_buffer: Steal<LintBuffer>,
232
233 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
235}
236
237#[derive(Debug)]
238pub struct DelegationFnSig {
239 pub header: ast::FnHeader,
240 pub param_count: usize,
241 pub has_self: bool,
242 pub c_variadic: bool,
243 pub target_feature: bool,
244}
245
246#[derive(Clone, Copy, Debug)]
247pub struct MainDefinition {
248 pub res: Res<ast::NodeId>,
249 pub is_import: bool,
250 pub span: Span,
251}
252
253impl MainDefinition {
254 pub fn opt_fn_def_id(self) -> Option<DefId> {
255 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
256 }
257}
258
259#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
263pub struct ImplHeader<'tcx> {
264 pub impl_def_id: DefId,
265 pub impl_args: ty::GenericArgsRef<'tcx>,
266 pub self_ty: Ty<'tcx>,
267 pub trait_ref: Option<TraitRef<'tcx>>,
268 pub predicates: Vec<Predicate<'tcx>>,
269}
270
271#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
272pub struct ImplTraitHeader<'tcx> {
273 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
274 pub polarity: ImplPolarity,
275 pub safety: hir::Safety,
276 pub constness: hir::Constness,
277}
278
279#[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable)]
280pub enum ImplSubject<'tcx> {
281 Trait(TraitRef<'tcx>),
282 Inherent(Ty<'tcx>),
283}
284
285#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
286#[derive(TypeFoldable, TypeVisitable)]
287pub enum Asyncness {
288 Yes,
289 No,
290}
291
292impl Asyncness {
293 pub fn is_async(self) -> bool {
294 matches!(self, Asyncness::Yes)
295 }
296}
297
298#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
299pub enum Visibility<Id = LocalDefId> {
300 Public,
302 Restricted(Id),
304}
305
306impl Visibility {
307 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
308 match self {
309 ty::Visibility::Restricted(restricted_id) => {
310 if restricted_id.is_top_level_module() {
311 "pub(crate)".to_string()
312 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
313 "pub(self)".to_string()
314 } else {
315 format!(
316 "pub(in crate{})",
317 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
318 )
319 }
320 }
321 ty::Visibility::Public => "pub".to_string(),
322 }
323 }
324}
325
326#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
327#[derive(TypeFoldable, TypeVisitable)]
328pub struct ClosureSizeProfileData<'tcx> {
329 pub before_feature_tys: Ty<'tcx>,
331 pub after_feature_tys: Ty<'tcx>,
333}
334
335impl TyCtxt<'_> {
336 #[inline]
337 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
338 self.def_key(id).parent.map(|index| DefId { index, ..id })
339 }
340
341 #[inline]
342 #[track_caller]
343 pub fn parent(self, id: DefId) -> DefId {
344 match self.opt_parent(id) {
345 Some(id) => id,
346 None => bug!("{id:?} doesn't have a parent"),
348 }
349 }
350
351 #[inline]
352 #[track_caller]
353 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
354 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
355 }
356
357 #[inline]
358 #[track_caller]
359 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
360 self.parent(id.into().to_def_id()).expect_local()
361 }
362
363 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
364 if descendant.krate != ancestor.krate {
365 return false;
366 }
367
368 while descendant != ancestor {
369 match self.opt_parent(descendant) {
370 Some(parent) => descendant = parent,
371 None => return false,
372 }
373 }
374 true
375 }
376}
377
378impl<Id> Visibility<Id> {
379 pub fn is_public(self) -> bool {
380 matches!(self, Visibility::Public)
381 }
382
383 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
384 match self {
385 Visibility::Public => Visibility::Public,
386 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
387 }
388 }
389}
390
391impl<Id: Into<DefId>> Visibility<Id> {
392 pub fn to_def_id(self) -> Visibility<DefId> {
393 self.map_id(Into::into)
394 }
395
396 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
398 match self {
399 Visibility::Public => true,
401 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
402 }
403 }
404
405 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
407 match vis {
408 Visibility::Public => self.is_public(),
409 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
410 }
411 }
412}
413
414impl Visibility<DefId> {
415 pub fn expect_local(self) -> Visibility {
416 self.map_id(|id| id.expect_local())
417 }
418
419 pub fn is_visible_locally(self) -> bool {
421 match self {
422 Visibility::Public => true,
423 Visibility::Restricted(def_id) => def_id.is_local(),
424 }
425 }
426}
427
428#[derive(HashStable, Debug)]
435pub struct CrateVariancesMap<'tcx> {
436 pub variances: DefIdMap<&'tcx [ty::Variance]>,
440}
441
442#[derive(Copy, Clone, PartialEq, Eq, Hash)]
445pub struct CReaderCacheKey {
446 pub cnum: Option<CrateNum>,
447 pub pos: usize,
448}
449
450#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
452#[rustc_diagnostic_item = "Ty"]
453#[rustc_pass_by_value]
454pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
455
456impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
457 type Kind = TyKind<'tcx>;
458
459 fn kind(self) -> TyKind<'tcx> {
460 *self.kind()
461 }
462}
463
464impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
465 fn flags(&self) -> TypeFlags {
466 self.0.flags
467 }
468
469 fn outer_exclusive_binder(&self) -> DebruijnIndex {
470 self.0.outer_exclusive_binder
471 }
472}
473
474impl EarlyParamRegion {
475 pub fn has_name(&self) -> bool {
478 self.name != kw::UnderscoreLifetime
479 }
480}
481
482#[derive(HashStable, Debug)]
489pub struct CratePredicatesMap<'tcx> {
490 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
494}
495
496#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
497pub struct Term<'tcx> {
498 ptr: NonNull<()>,
499 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
500}
501
502impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
503
504impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
505 type Kind = TermKind<'tcx>;
506
507 fn kind(self) -> Self::Kind {
508 self.kind()
509 }
510}
511
512unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
513 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
514{
515}
516unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
517 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
518{
519}
520unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
521unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
522
523impl Debug for Term<'_> {
524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525 match self.kind() {
526 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
527 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
528 }
529 }
530}
531
532impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
533 fn from(ty: Ty<'tcx>) -> Self {
534 TermKind::Ty(ty).pack()
535 }
536}
537
538impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
539 fn from(c: Const<'tcx>) -> Self {
540 TermKind::Const(c).pack()
541 }
542}
543
544impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
545 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
546 self.kind().hash_stable(hcx, hasher);
547 }
548}
549
550impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
551 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
552 self,
553 folder: &mut F,
554 ) -> Result<Self, F::Error> {
555 match self.kind() {
556 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
557 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
558 }
559 }
560
561 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
562 match self.kind() {
563 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
564 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
565 }
566 }
567}
568
569impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
570 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
571 match self.kind() {
572 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
573 ty::TermKind::Const(ct) => ct.visit_with(visitor),
574 }
575 }
576}
577
578impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
579 fn encode(&self, e: &mut E) {
580 self.kind().encode(e)
581 }
582}
583
584impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
585 fn decode(d: &mut D) -> Self {
586 let res: TermKind<'tcx> = Decodable::decode(d);
587 res.pack()
588 }
589}
590
591impl<'tcx> Term<'tcx> {
592 #[inline]
593 pub fn kind(self) -> TermKind<'tcx> {
594 let ptr =
595 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
596 unsafe {
600 match self.ptr.addr().get() & TAG_MASK {
601 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
602 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
603 ))),
604 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
605 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
606 ))),
607 _ => core::intrinsics::unreachable(),
608 }
609 }
610 }
611
612 pub fn as_type(&self) -> Option<Ty<'tcx>> {
613 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
614 }
615
616 pub fn expect_type(&self) -> Ty<'tcx> {
617 self.as_type().expect("expected a type, but found a const")
618 }
619
620 pub fn as_const(&self) -> Option<Const<'tcx>> {
621 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
622 }
623
624 pub fn expect_const(&self) -> Const<'tcx> {
625 self.as_const().expect("expected a const, but found a type")
626 }
627
628 pub fn into_arg(self) -> GenericArg<'tcx> {
629 match self.kind() {
630 TermKind::Ty(ty) => ty.into(),
631 TermKind::Const(c) => c.into(),
632 }
633 }
634
635 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
636 match self.kind() {
637 TermKind::Ty(ty) => match *ty.kind() {
638 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
639 _ => None,
640 },
641 TermKind::Const(ct) => match ct.kind() {
642 ConstKind::Unevaluated(uv) => Some(uv.into()),
643 _ => None,
644 },
645 }
646 }
647
648 pub fn is_infer(&self) -> bool {
649 match self.kind() {
650 TermKind::Ty(ty) => ty.is_ty_var(),
651 TermKind::Const(ct) => ct.is_ct_infer(),
652 }
653 }
654
655 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
656 match self.kind() {
657 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
658 TermKind::Const(ct) => ct.is_trivially_wf(),
659 }
660 }
661
662 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
673 TypeWalker::new(self.into())
674 }
675}
676
677const TAG_MASK: usize = 0b11;
678const TYPE_TAG: usize = 0b00;
679const CONST_TAG: usize = 0b01;
680
681#[extension(pub trait TermKindPackExt<'tcx>)]
682impl<'tcx> TermKind<'tcx> {
683 #[inline]
684 fn pack(self) -> Term<'tcx> {
685 let (tag, ptr) = match self {
686 TermKind::Ty(ty) => {
687 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
689 (TYPE_TAG, NonNull::from(ty.0.0).cast())
690 }
691 TermKind::Const(ct) => {
692 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
694 (CONST_TAG, NonNull::from(ct.0.0).cast())
695 }
696 };
697
698 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
699 }
700}
701
702#[derive(Copy, Clone, PartialEq, Eq, Debug)]
703pub enum ParamTerm {
704 Ty(ParamTy),
705 Const(ParamConst),
706}
707
708impl ParamTerm {
709 pub fn index(self) -> usize {
710 match self {
711 ParamTerm::Ty(ty) => ty.index as usize,
712 ParamTerm::Const(ct) => ct.index as usize,
713 }
714 }
715}
716
717#[derive(Copy, Clone, Eq, PartialEq, Debug)]
718pub enum TermVid {
719 Ty(ty::TyVid),
720 Const(ty::ConstVid),
721}
722
723impl From<ty::TyVid> for TermVid {
724 fn from(value: ty::TyVid) -> Self {
725 TermVid::Ty(value)
726 }
727}
728
729impl From<ty::ConstVid> for TermVid {
730 fn from(value: ty::ConstVid) -> Self {
731 TermVid::Const(value)
732 }
733}
734
735#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
755pub struct InstantiatedPredicates<'tcx> {
756 pub predicates: Vec<Clause<'tcx>>,
757 pub spans: Vec<Span>,
758}
759
760impl<'tcx> InstantiatedPredicates<'tcx> {
761 pub fn empty() -> InstantiatedPredicates<'tcx> {
762 InstantiatedPredicates { predicates: vec![], spans: vec![] }
763 }
764
765 pub fn is_empty(&self) -> bool {
766 self.predicates.is_empty()
767 }
768
769 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
770 self.into_iter()
771 }
772}
773
774impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
775 type Item = (Clause<'tcx>, Span);
776
777 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
778
779 fn into_iter(self) -> Self::IntoIter {
780 debug_assert_eq!(self.predicates.len(), self.spans.len());
781 std::iter::zip(self.predicates, self.spans)
782 }
783}
784
785impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
786 type Item = (Clause<'tcx>, Span);
787
788 type IntoIter = std::iter::Zip<
789 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
790 std::iter::Copied<std::slice::Iter<'a, Span>>,
791 >;
792
793 fn into_iter(self) -> Self::IntoIter {
794 debug_assert_eq!(self.predicates.len(), self.spans.len());
795 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
796 }
797}
798
799#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
800pub struct OpaqueHiddenType<'tcx> {
801 pub span: Span,
815
816 pub ty: Ty<'tcx>,
829}
830
831#[derive(Debug, Clone, Copy)]
833pub enum DefiningScopeKind {
834 HirTypeck,
839 MirBorrowck,
840}
841
842impl<'tcx> OpaqueHiddenType<'tcx> {
843 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> OpaqueHiddenType<'tcx> {
844 OpaqueHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
845 }
846
847 pub fn build_mismatch_error(
848 &self,
849 other: &Self,
850 tcx: TyCtxt<'tcx>,
851 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
852 (self.ty, other.ty).error_reported()?;
853 let sub_diag = if self.span == other.span {
855 TypeMismatchReason::ConflictType { span: self.span }
856 } else {
857 TypeMismatchReason::PreviousUse { span: self.span }
858 };
859 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
860 self_ty: self.ty,
861 other_ty: other.ty,
862 other_span: other.span,
863 sub: sub_diag,
864 }))
865 }
866
867 #[instrument(level = "debug", skip(tcx), ret)]
868 pub fn remap_generic_params_to_declaration_params(
869 self,
870 opaque_type_key: OpaqueTypeKey<'tcx>,
871 tcx: TyCtxt<'tcx>,
872 defining_scope_kind: DefiningScopeKind,
873 ) -> Self {
874 let OpaqueTypeKey { def_id, args } = opaque_type_key;
875
876 let id_args = GenericArgs::identity_for_item(tcx, def_id);
883 debug!(?id_args);
884
885 let map = args.iter().zip(id_args).collect();
889 debug!("map = {:#?}", map);
890
891 let this = match defining_scope_kind {
896 DefiningScopeKind::HirTypeck => tcx.erase_regions(self),
897 DefiningScopeKind::MirBorrowck => self,
898 };
899 let result = this.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
900 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
901 assert_eq!(result.ty, tcx.erase_regions(result.ty));
902 }
903 result
904 }
905}
906
907#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
912#[derive(HashStable, TyEncodable, TyDecodable)]
913pub struct Placeholder<T> {
914 pub universe: UniverseIndex,
915 pub bound: T,
916}
917
918pub type PlaceholderRegion = Placeholder<BoundRegion>;
919
920impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion {
921 type Bound = BoundRegion;
922
923 fn universe(self) -> UniverseIndex {
924 self.universe
925 }
926
927 fn var(self) -> BoundVar {
928 self.bound.var
929 }
930
931 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
932 Placeholder { universe: ui, ..self }
933 }
934
935 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
936 Placeholder { universe: ui, bound }
937 }
938
939 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
940 Placeholder { universe: ui, bound: BoundRegion { var, kind: BoundRegionKind::Anon } }
941 }
942}
943
944pub type PlaceholderType = Placeholder<BoundTy>;
945
946impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType {
947 type Bound = BoundTy;
948
949 fn universe(self) -> UniverseIndex {
950 self.universe
951 }
952
953 fn var(self) -> BoundVar {
954 self.bound.var
955 }
956
957 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
958 Placeholder { universe: ui, ..self }
959 }
960
961 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
962 Placeholder { universe: ui, bound }
963 }
964
965 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
966 Placeholder { universe: ui, bound: BoundTy { var, kind: BoundTyKind::Anon } }
967 }
968}
969
970#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
971#[derive(TyEncodable, TyDecodable)]
972pub struct BoundConst<'tcx> {
973 pub var: BoundVar,
974 pub ty: Ty<'tcx>,
975}
976
977pub type PlaceholderConst = Placeholder<BoundVar>;
978
979impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst {
980 type Bound = BoundVar;
981
982 fn universe(self) -> UniverseIndex {
983 self.universe
984 }
985
986 fn var(self) -> BoundVar {
987 self.bound
988 }
989
990 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
991 Placeholder { universe: ui, ..self }
992 }
993
994 fn new(ui: UniverseIndex, bound: BoundVar) -> Self {
995 Placeholder { universe: ui, bound }
996 }
997
998 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
999 Placeholder { universe: ui, bound: var }
1000 }
1001}
1002
1003pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
1004
1005impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
1006 fn flags(&self) -> TypeFlags {
1007 (**self).flags()
1008 }
1009
1010 fn outer_exclusive_binder(&self) -> DebruijnIndex {
1011 (**self).outer_exclusive_binder()
1012 }
1013}
1014
1015#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1021#[derive(HashStable, TypeVisitable, TypeFoldable)]
1022pub struct ParamEnv<'tcx> {
1023 caller_bounds: Clauses<'tcx>,
1029}
1030
1031impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1032 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
1033 self.caller_bounds()
1034 }
1035}
1036
1037impl<'tcx> ParamEnv<'tcx> {
1038 #[inline]
1045 pub fn empty() -> Self {
1046 Self::new(ListWithCachedTypeInfo::empty())
1047 }
1048
1049 #[inline]
1050 pub fn caller_bounds(self) -> Clauses<'tcx> {
1051 self.caller_bounds
1052 }
1053
1054 #[inline]
1056 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1057 ParamEnv { caller_bounds }
1058 }
1059
1060 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1062 ParamEnvAnd { param_env: self, value }
1063 }
1064}
1065
1066#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1067#[derive(HashStable)]
1068pub struct ParamEnvAnd<'tcx, T> {
1069 pub param_env: ParamEnv<'tcx>,
1070 pub value: T,
1071}
1072
1073impl<'tcx, T> ParamEnvAnd<'tcx, T> {
1074 pub fn into_parts(self) -> (ParamEnv<'tcx>, T) {
1075 (self.param_env, self.value)
1076 }
1077}
1078
1079#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1090#[derive(TypeVisitable, TypeFoldable)]
1091pub struct TypingEnv<'tcx> {
1092 pub typing_mode: TypingMode<'tcx>,
1093 pub param_env: ParamEnv<'tcx>,
1094}
1095
1096impl<'tcx> TypingEnv<'tcx> {
1097 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1105 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1106 }
1107
1108 pub fn non_body_analysis(
1114 tcx: TyCtxt<'tcx>,
1115 def_id: impl IntoQueryParam<DefId>,
1116 ) -> TypingEnv<'tcx> {
1117 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1118 }
1119
1120 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1121 tcx.typing_env_normalized_for_post_analysis(def_id)
1122 }
1123
1124 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1127 let TypingEnv { typing_mode, param_env } = self;
1128 if let TypingMode::PostAnalysis = typing_mode {
1129 return self;
1130 }
1131
1132 let param_env = if tcx.next_trait_solver_globally() {
1135 param_env
1136 } else {
1137 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1138 };
1139 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1140 }
1141
1142 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1147 where
1148 T: TypeVisitable<TyCtxt<'tcx>>,
1149 {
1150 PseudoCanonicalInput { typing_env: self, value }
1159 }
1160}
1161
1162#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1172#[derive(HashStable, TypeVisitable, TypeFoldable)]
1173pub struct PseudoCanonicalInput<'tcx, T> {
1174 pub typing_env: TypingEnv<'tcx>,
1175 pub value: T,
1176}
1177
1178#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1179pub struct Destructor {
1180 pub did: DefId,
1182}
1183
1184#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1186pub struct AsyncDestructor {
1187 pub impl_did: DefId,
1189}
1190
1191#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1192pub struct VariantFlags(u8);
1193bitflags::bitflags! {
1194 impl VariantFlags: u8 {
1195 const NO_VARIANT_FLAGS = 0;
1196 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1198 }
1199}
1200rustc_data_structures::external_bitflags_debug! { VariantFlags }
1201
1202#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1204pub struct VariantDef {
1205 pub def_id: DefId,
1208 pub ctor: Option<(CtorKind, DefId)>,
1211 pub name: Symbol,
1213 pub discr: VariantDiscr,
1215 pub fields: IndexVec<FieldIdx, FieldDef>,
1217 tainted: Option<ErrorGuaranteed>,
1219 flags: VariantFlags,
1221}
1222
1223impl VariantDef {
1224 #[instrument(level = "debug")]
1241 pub fn new(
1242 name: Symbol,
1243 variant_did: Option<DefId>,
1244 ctor: Option<(CtorKind, DefId)>,
1245 discr: VariantDiscr,
1246 fields: IndexVec<FieldIdx, FieldDef>,
1247 parent_did: DefId,
1248 recover_tainted: Option<ErrorGuaranteed>,
1249 is_field_list_non_exhaustive: bool,
1250 ) -> Self {
1251 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1252 if is_field_list_non_exhaustive {
1253 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1254 }
1255
1256 VariantDef {
1257 def_id: variant_did.unwrap_or(parent_did),
1258 ctor,
1259 name,
1260 discr,
1261 fields,
1262 flags,
1263 tainted: recover_tainted,
1264 }
1265 }
1266
1267 #[inline]
1273 pub fn is_field_list_non_exhaustive(&self) -> bool {
1274 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1275 }
1276
1277 #[inline]
1280 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1281 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1282 }
1283
1284 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1286 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1287 }
1288
1289 #[inline]
1291 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1292 self.tainted.map_or(Ok(()), Err)
1293 }
1294
1295 #[inline]
1296 pub fn ctor_kind(&self) -> Option<CtorKind> {
1297 self.ctor.map(|(kind, _)| kind)
1298 }
1299
1300 #[inline]
1301 pub fn ctor_def_id(&self) -> Option<DefId> {
1302 self.ctor.map(|(_, def_id)| def_id)
1303 }
1304
1305 #[inline]
1309 pub fn single_field(&self) -> &FieldDef {
1310 assert!(self.fields.len() == 1);
1311
1312 &self.fields[FieldIdx::ZERO]
1313 }
1314
1315 #[inline]
1317 pub fn tail_opt(&self) -> Option<&FieldDef> {
1318 self.fields.raw.last()
1319 }
1320
1321 #[inline]
1327 pub fn tail(&self) -> &FieldDef {
1328 self.tail_opt().expect("expected unsized ADT to have a tail field")
1329 }
1330
1331 pub fn has_unsafe_fields(&self) -> bool {
1333 self.fields.iter().any(|x| x.safety.is_unsafe())
1334 }
1335}
1336
1337impl PartialEq for VariantDef {
1338 #[inline]
1339 fn eq(&self, other: &Self) -> bool {
1340 let Self {
1348 def_id: lhs_def_id,
1349 ctor: _,
1350 name: _,
1351 discr: _,
1352 fields: _,
1353 flags: _,
1354 tainted: _,
1355 } = &self;
1356 let Self {
1357 def_id: rhs_def_id,
1358 ctor: _,
1359 name: _,
1360 discr: _,
1361 fields: _,
1362 flags: _,
1363 tainted: _,
1364 } = other;
1365
1366 let res = lhs_def_id == rhs_def_id;
1367
1368 if cfg!(debug_assertions) && res {
1370 let deep = self.ctor == other.ctor
1371 && self.name == other.name
1372 && self.discr == other.discr
1373 && self.fields == other.fields
1374 && self.flags == other.flags;
1375 assert!(deep, "VariantDef for the same def-id has differing data");
1376 }
1377
1378 res
1379 }
1380}
1381
1382impl Eq for VariantDef {}
1383
1384impl Hash for VariantDef {
1385 #[inline]
1386 fn hash<H: Hasher>(&self, s: &mut H) {
1387 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1395 def_id.hash(s)
1396 }
1397}
1398
1399#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1400pub enum VariantDiscr {
1401 Explicit(DefId),
1404
1405 Relative(u32),
1410}
1411
1412#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1413pub struct FieldDef {
1414 pub did: DefId,
1415 pub name: Symbol,
1416 pub vis: Visibility<DefId>,
1417 pub safety: hir::Safety,
1418 pub value: Option<DefId>,
1419}
1420
1421impl PartialEq for FieldDef {
1422 #[inline]
1423 fn eq(&self, other: &Self) -> bool {
1424 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1432
1433 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1434
1435 let res = lhs_did == rhs_did;
1436
1437 if cfg!(debug_assertions) && res {
1439 let deep =
1440 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1441 assert!(deep, "FieldDef for the same def-id has differing data");
1442 }
1443
1444 res
1445 }
1446}
1447
1448impl Eq for FieldDef {}
1449
1450impl Hash for FieldDef {
1451 #[inline]
1452 fn hash<H: Hasher>(&self, s: &mut H) {
1453 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1461
1462 did.hash(s)
1463 }
1464}
1465
1466impl<'tcx> FieldDef {
1467 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1470 tcx.type_of(self.did).instantiate(tcx, args)
1471 }
1472
1473 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1475 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1476 }
1477}
1478
1479#[derive(Debug, PartialEq, Eq)]
1480pub enum ImplOverlapKind {
1481 Permitted {
1483 marker: bool,
1485 },
1486}
1487
1488#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1491pub enum ImplTraitInTraitData {
1492 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1493 Impl { fn_def_id: DefId },
1494}
1495
1496impl<'tcx> TyCtxt<'tcx> {
1497 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1498 self.typeck(self.hir_body_owner_def_id(body))
1499 }
1500
1501 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1502 self.associated_items(id)
1503 .in_definition_order()
1504 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1505 }
1506
1507 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1508 let mut flags = ReprFlags::empty();
1509 let mut size = None;
1510 let mut max_align: Option<Align> = None;
1511 let mut min_pack: Option<Align> = None;
1512
1513 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1516
1517 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1521 field_shuffle_seed ^= user_seed;
1522 }
1523
1524 if let Some(reprs) = attr::find_attr!(self.get_all_attrs(did), AttributeKind::Repr(r) => r)
1525 {
1526 for (r, _) in reprs {
1527 flags.insert(match *r {
1528 attr::ReprRust => ReprFlags::empty(),
1529 attr::ReprC => ReprFlags::IS_C,
1530 attr::ReprPacked(pack) => {
1531 min_pack = Some(if let Some(min_pack) = min_pack {
1532 min_pack.min(pack)
1533 } else {
1534 pack
1535 });
1536 ReprFlags::empty()
1537 }
1538 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1539 attr::ReprSimd => ReprFlags::IS_SIMD,
1540 attr::ReprInt(i) => {
1541 size = Some(match i {
1542 attr::IntType::SignedInt(x) => match x {
1543 ast::IntTy::Isize => IntegerType::Pointer(true),
1544 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1545 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1546 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1547 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1548 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1549 },
1550 attr::IntType::UnsignedInt(x) => match x {
1551 ast::UintTy::Usize => IntegerType::Pointer(false),
1552 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1553 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1554 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1555 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1556 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1557 },
1558 });
1559 ReprFlags::empty()
1560 }
1561 attr::ReprAlign(align) => {
1562 max_align = max_align.max(Some(align));
1563 ReprFlags::empty()
1564 }
1565 attr::ReprEmpty => {
1566 ReprFlags::empty()
1568 }
1569 });
1570 }
1571 }
1572
1573 if self.sess.opts.unstable_opts.randomize_layout {
1576 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1577 }
1578
1579 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1582
1583 if is_box {
1585 flags.insert(ReprFlags::IS_LINEAR);
1586 }
1587
1588 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1589 }
1590
1591 pub fn opt_item_name(self, def_id: DefId) -> Option<Symbol> {
1593 if let Some(cnum) = def_id.as_crate_root() {
1594 Some(self.crate_name(cnum))
1595 } else {
1596 let def_key = self.def_key(def_id);
1597 match def_key.disambiguated_data.data {
1598 rustc_hir::definitions::DefPathData::Ctor => self
1600 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1601 _ => def_key.get_opt_name(),
1602 }
1603 }
1604 }
1605
1606 pub fn item_name(self, id: DefId) -> Symbol {
1613 self.opt_item_name(id).unwrap_or_else(|| {
1614 bug!("item_name: no name for {:?}", self.def_path(id));
1615 })
1616 }
1617
1618 pub fn opt_item_ident(self, def_id: DefId) -> Option<Ident> {
1622 let def = self.opt_item_name(def_id)?;
1623 let span = self
1624 .def_ident_span(def_id)
1625 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1626 Some(Ident::new(def, span))
1627 }
1628
1629 pub fn item_ident(self, def_id: DefId) -> Ident {
1633 self.opt_item_ident(def_id).unwrap_or_else(|| {
1634 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1635 })
1636 }
1637
1638 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1639 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1640 Some(self.associated_item(def_id))
1641 } else {
1642 None
1643 }
1644 }
1645
1646 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1650 if let DefKind::AssocTy = self.def_kind(def_id)
1651 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1652 self.associated_item(def_id).kind
1653 {
1654 Some(rpitit_info)
1655 } else {
1656 None
1657 }
1658 }
1659
1660 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1661 variant.fields.iter_enumerated().find_map(|(i, field)| {
1662 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1663 })
1664 }
1665
1666 #[instrument(level = "debug", skip(self), ret)]
1669 pub fn impls_are_allowed_to_overlap(
1670 self,
1671 def_id1: DefId,
1672 def_id2: DefId,
1673 ) -> Option<ImplOverlapKind> {
1674 let impl1 = self.impl_trait_header(def_id1).unwrap();
1675 let impl2 = self.impl_trait_header(def_id2).unwrap();
1676
1677 let trait_ref1 = impl1.trait_ref.skip_binder();
1678 let trait_ref2 = impl2.trait_ref.skip_binder();
1679
1680 if trait_ref1.references_error() || trait_ref2.references_error() {
1683 return Some(ImplOverlapKind::Permitted { marker: false });
1684 }
1685
1686 match (impl1.polarity, impl2.polarity) {
1687 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1688 return Some(ImplOverlapKind::Permitted { marker: false });
1690 }
1691 (ImplPolarity::Positive, ImplPolarity::Negative)
1692 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1693 return None;
1695 }
1696 (ImplPolarity::Positive, ImplPolarity::Positive)
1697 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1698 };
1699
1700 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1701 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1702
1703 if is_marker_overlap {
1704 return Some(ImplOverlapKind::Permitted { marker: true });
1705 }
1706
1707 None
1708 }
1709
1710 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1713 match res {
1714 Res::Def(DefKind::Variant, did) => {
1715 let enum_did = self.parent(did);
1716 self.adt_def(enum_did).variant_with_id(did)
1717 }
1718 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1719 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1720 let variant_did = self.parent(variant_ctor_did);
1721 let enum_did = self.parent(variant_did);
1722 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1723 }
1724 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1725 let struct_did = self.parent(ctor_did);
1726 self.adt_def(struct_did).non_enum_variant()
1727 }
1728 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1729 }
1730 }
1731
1732 #[instrument(skip(self), level = "debug")]
1734 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1735 match instance {
1736 ty::InstanceKind::Item(def) => {
1737 debug!("calling def_kind on def: {:?}", def);
1738 let def_kind = self.def_kind(def);
1739 debug!("returned from def_kind: {:?}", def_kind);
1740 match def_kind {
1741 DefKind::Const
1742 | DefKind::Static { .. }
1743 | DefKind::AssocConst
1744 | DefKind::Ctor(..)
1745 | DefKind::AnonConst
1746 | DefKind::InlineConst => self.mir_for_ctfe(def),
1747 _ => self.optimized_mir(def),
1750 }
1751 }
1752 ty::InstanceKind::VTableShim(..)
1753 | ty::InstanceKind::ReifyShim(..)
1754 | ty::InstanceKind::Intrinsic(..)
1755 | ty::InstanceKind::FnPtrShim(..)
1756 | ty::InstanceKind::Virtual(..)
1757 | ty::InstanceKind::ClosureOnceShim { .. }
1758 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1759 | ty::InstanceKind::FutureDropPollShim(..)
1760 | ty::InstanceKind::DropGlue(..)
1761 | ty::InstanceKind::CloneShim(..)
1762 | ty::InstanceKind::ThreadLocalShim(..)
1763 | ty::InstanceKind::FnPtrAddrShim(..)
1764 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1765 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1766 }
1767 }
1768
1769 pub fn get_attrs_unchecked(self, did: DefId) -> &'tcx [hir::Attribute] {
1771 if let Some(did) = did.as_local() {
1772 self.hir_attrs(self.local_def_id_to_hir_id(did))
1773 } else {
1774 self.attrs_for_def(did)
1775 }
1776 }
1777
1778 pub fn get_attrs(
1780 self,
1781 did: impl Into<DefId>,
1782 attr: Symbol,
1783 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1784 self.get_all_attrs(did).filter(move |a: &&hir::Attribute| a.has_name(attr))
1785 }
1786
1787 pub fn get_all_attrs(
1791 self,
1792 did: impl Into<DefId>,
1793 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1794 let did: DefId = did.into();
1795 if let Some(did) = did.as_local() {
1796 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter()
1797 } else {
1798 self.attrs_for_def(did).iter()
1799 }
1800 }
1801
1802 pub fn get_diagnostic_attr(
1811 self,
1812 did: impl Into<DefId>,
1813 attr: Symbol,
1814 ) -> Option<&'tcx hir::Attribute> {
1815 let did: DefId = did.into();
1816 if did.as_local().is_some() {
1817 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1819 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1820 } else {
1821 None
1822 }
1823 } else {
1824 debug_assert!(rustc_feature::encode_cross_crate(attr));
1827 self.attrs_for_def(did)
1828 .iter()
1829 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1830 }
1831 }
1832
1833 pub fn get_attrs_by_path(
1834 self,
1835 did: DefId,
1836 attr: &[Symbol],
1837 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1838 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1839 if let Some(did) = did.as_local() {
1840 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1841 } else {
1842 self.attrs_for_def(did).iter().filter(filter_fn)
1843 }
1844 }
1845
1846 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1847 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1848 let did: DefId = did.into();
1849 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1850 } else {
1851 self.get_attrs(did, attr).next()
1852 }
1853 }
1854
1855 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1857 self.get_attrs(did, attr).next().is_some()
1858 }
1859
1860 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1862 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1863 }
1864
1865 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1867 self.trait_def(trait_def_id).has_auto_impl
1868 }
1869
1870 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1873 self.trait_def(trait_def_id).is_coinductive
1874 }
1875
1876 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1878 self.def_kind(trait_def_id) == DefKind::TraitAlias
1879 }
1880
1881 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1883 self.arena.alloc(err)
1884 }
1885
1886 fn ordinary_coroutine_layout(
1892 self,
1893 def_id: DefId,
1894 args: GenericArgsRef<'tcx>,
1895 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1896 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1897 let mir = self.optimized_mir(def_id);
1898 let ty = || Ty::new_coroutine(self, def_id, args);
1899 if coroutine_kind_ty.is_unit() {
1901 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1902 } else {
1903 let ty::Coroutine(_, identity_args) =
1906 *self.type_of(def_id).instantiate_identity().kind()
1907 else {
1908 unreachable!();
1909 };
1910 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1911 if identity_kind_ty == coroutine_kind_ty {
1914 mir.coroutine_layout_raw()
1915 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1916 } else {
1917 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1918 assert_matches!(
1919 identity_kind_ty.to_opt_closure_kind(),
1920 Some(ClosureKind::Fn | ClosureKind::FnMut)
1921 );
1922 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1923 .coroutine_layout_raw()
1924 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1925 }
1926 }
1927 }
1928
1929 fn async_drop_coroutine_layout(
1933 self,
1934 def_id: DefId,
1935 args: GenericArgsRef<'tcx>,
1936 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1937 let ty = || Ty::new_coroutine(self, def_id, args);
1938 if args[0].has_placeholders() || args[0].has_non_region_param() {
1939 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1940 }
1941 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1942 self.mir_shims(instance)
1943 .coroutine_layout_raw()
1944 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1945 }
1946
1947 pub fn coroutine_layout(
1950 self,
1951 def_id: DefId,
1952 args: GenericArgsRef<'tcx>,
1953 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1954 if self.is_async_drop_in_place_coroutine(def_id) {
1955 let arg_cor_ty = args.first().unwrap().expect_ty();
1959 if arg_cor_ty.is_coroutine() {
1960 let span = self.def_span(def_id);
1961 let source_info = SourceInfo::outermost(span);
1962 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1965 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1966 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1967 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1968 let proxy_layout = CoroutineLayout {
1969 field_tys: [].into(),
1970 field_names: [].into(),
1971 variant_fields,
1972 variant_source_info,
1973 storage_conflicts: BitMatrix::new(0, 0),
1974 };
1975 return Ok(self.arena.alloc(proxy_layout));
1976 } else {
1977 self.async_drop_coroutine_layout(def_id, args)
1978 }
1979 } else {
1980 self.ordinary_coroutine_layout(def_id, args)
1981 }
1982 }
1983
1984 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1987 self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
1988 }
1989
1990 pub fn trait_of_item(self, def_id: DefId) -> Option<DefId> {
1994 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1995 let parent = self.parent(def_id);
1996 if let DefKind::Trait | DefKind::TraitAlias = self.def_kind(parent) {
1997 return Some(parent);
1998 }
1999 }
2000 None
2001 }
2002
2003 pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
2006 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
2007 let parent = self.parent(def_id);
2008 if let DefKind::Impl { .. } = self.def_kind(parent) {
2009 return Some(parent);
2010 }
2011 }
2012 None
2013 }
2014
2015 pub fn is_exportable(self, def_id: DefId) -> bool {
2016 self.exportable_items(def_id.krate).contains(&def_id)
2017 }
2018
2019 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2022 if self.is_automatically_derived(def_id)
2023 && let Some(def_id) = def_id.as_local()
2024 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2025 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2026 && self.has_attr(outer.macro_def_id.unwrap(), sym::rustc_builtin_macro)
2027 {
2028 true
2029 } else {
2030 false
2031 }
2032 }
2033
2034 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2036 self.has_attr(def_id, sym::automatically_derived)
2037 }
2038
2039 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2042 if let Some(impl_def_id) = impl_def_id.as_local() {
2043 Ok(self.def_span(impl_def_id))
2044 } else {
2045 Err(self.crate_name(impl_def_id.krate))
2046 }
2047 }
2048
2049 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2053 use_ident.name == def_ident.name
2057 && use_ident
2058 .span
2059 .ctxt()
2060 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2061 }
2062
2063 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2064 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2065 ident
2066 }
2067
2068 pub fn adjust_ident_and_get_scope(
2070 self,
2071 mut ident: Ident,
2072 scope: DefId,
2073 block: hir::HirId,
2074 ) -> (Ident, DefId) {
2075 let scope = ident
2076 .span
2077 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2078 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2079 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2080 (ident, scope)
2081 }
2082
2083 #[inline]
2087 pub fn is_const_fn(self, def_id: DefId) -> bool {
2088 matches!(
2089 self.def_kind(def_id),
2090 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2091 ) && self.constness(def_id) == hir::Constness::Const
2092 }
2093
2094 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2101 let def_id: DefId = def_id.into();
2102 match self.def_kind(def_id) {
2103 DefKind::Impl { of_trait: true } => {
2104 let header = self.impl_trait_header(def_id).unwrap();
2105 header.constness == hir::Constness::Const
2106 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2107 }
2108 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2109 self.constness(def_id) == hir::Constness::Const
2110 }
2111 DefKind::Trait => self.is_const_trait(def_id),
2112 DefKind::AssocTy => {
2113 let parent_def_id = self.parent(def_id);
2114 match self.def_kind(parent_def_id) {
2115 DefKind::Impl { of_trait: false } => false,
2116 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2117 self.is_conditionally_const(parent_def_id)
2118 }
2119 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2120 }
2121 }
2122 DefKind::AssocFn => {
2123 let parent_def_id = self.parent(def_id);
2124 match self.def_kind(parent_def_id) {
2125 DefKind::Impl { of_trait: false } => {
2126 self.constness(def_id) == hir::Constness::Const
2127 }
2128 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2129 self.is_conditionally_const(parent_def_id)
2130 }
2131 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2132 }
2133 }
2134 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2135 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2136 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2137 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2139 },
2140 DefKind::Closure => {
2141 false
2144 }
2145 DefKind::Ctor(_, CtorKind::Const)
2146 | DefKind::Impl { of_trait: false }
2147 | DefKind::Mod
2148 | DefKind::Struct
2149 | DefKind::Union
2150 | DefKind::Enum
2151 | DefKind::Variant
2152 | DefKind::TyAlias
2153 | DefKind::ForeignTy
2154 | DefKind::TraitAlias
2155 | DefKind::TyParam
2156 | DefKind::Const
2157 | DefKind::ConstParam
2158 | DefKind::Static { .. }
2159 | DefKind::AssocConst
2160 | DefKind::Macro(_)
2161 | DefKind::ExternCrate
2162 | DefKind::Use
2163 | DefKind::ForeignMod
2164 | DefKind::AnonConst
2165 | DefKind::InlineConst
2166 | DefKind::Field
2167 | DefKind::LifetimeParam
2168 | DefKind::GlobalAsm
2169 | DefKind::SyntheticCoroutineBody => false,
2170 }
2171 }
2172
2173 #[inline]
2174 pub fn is_const_trait(self, def_id: DefId) -> bool {
2175 self.trait_def(def_id).constness == hir::Constness::Const
2176 }
2177
2178 #[inline]
2179 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2180 matches!(self.trait_of_item(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2181 }
2182
2183 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2184 if self.def_kind(def_id) != DefKind::AssocFn {
2185 return false;
2186 }
2187
2188 let Some(item) = self.opt_associated_item(def_id) else {
2189 return false;
2190 };
2191 if item.container != ty::AssocItemContainer::Impl {
2192 return false;
2193 }
2194
2195 let Some(trait_item_def_id) = item.trait_item_def_id else {
2196 return false;
2197 };
2198
2199 return !self
2200 .associated_types_for_impl_traits_in_associated_fn(trait_item_def_id)
2201 .is_empty();
2202 }
2203}
2204
2205pub fn int_ty(ity: ast::IntTy) -> IntTy {
2206 match ity {
2207 ast::IntTy::Isize => IntTy::Isize,
2208 ast::IntTy::I8 => IntTy::I8,
2209 ast::IntTy::I16 => IntTy::I16,
2210 ast::IntTy::I32 => IntTy::I32,
2211 ast::IntTy::I64 => IntTy::I64,
2212 ast::IntTy::I128 => IntTy::I128,
2213 }
2214}
2215
2216pub fn uint_ty(uty: ast::UintTy) -> UintTy {
2217 match uty {
2218 ast::UintTy::Usize => UintTy::Usize,
2219 ast::UintTy::U8 => UintTy::U8,
2220 ast::UintTy::U16 => UintTy::U16,
2221 ast::UintTy::U32 => UintTy::U32,
2222 ast::UintTy::U64 => UintTy::U64,
2223 ast::UintTy::U128 => UintTy::U128,
2224 }
2225}
2226
2227pub fn float_ty(fty: ast::FloatTy) -> FloatTy {
2228 match fty {
2229 ast::FloatTy::F16 => FloatTy::F16,
2230 ast::FloatTy::F32 => FloatTy::F32,
2231 ast::FloatTy::F64 => FloatTy::F64,
2232 ast::FloatTy::F128 => FloatTy::F128,
2233 }
2234}
2235
2236pub fn ast_int_ty(ity: IntTy) -> ast::IntTy {
2237 match ity {
2238 IntTy::Isize => ast::IntTy::Isize,
2239 IntTy::I8 => ast::IntTy::I8,
2240 IntTy::I16 => ast::IntTy::I16,
2241 IntTy::I32 => ast::IntTy::I32,
2242 IntTy::I64 => ast::IntTy::I64,
2243 IntTy::I128 => ast::IntTy::I128,
2244 }
2245}
2246
2247pub fn ast_uint_ty(uty: UintTy) -> ast::UintTy {
2248 match uty {
2249 UintTy::Usize => ast::UintTy::Usize,
2250 UintTy::U8 => ast::UintTy::U8,
2251 UintTy::U16 => ast::UintTy::U16,
2252 UintTy::U32 => ast::UintTy::U32,
2253 UintTy::U64 => ast::UintTy::U64,
2254 UintTy::U128 => ast::UintTy::U128,
2255 }
2256}
2257
2258pub fn provide(providers: &mut Providers) {
2259 closure::provide(providers);
2260 context::provide(providers);
2261 erase_regions::provide(providers);
2262 inhabitedness::provide(providers);
2263 util::provide(providers);
2264 print::provide(providers);
2265 super::util::bug::provide(providers);
2266 *providers = Providers {
2267 trait_impls_of: trait_def::trait_impls_of_provider,
2268 incoherent_impls: trait_def::incoherent_impls_provider,
2269 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2270 traits: trait_def::traits_provider,
2271 vtable_allocation: vtable::vtable_allocation_provider,
2272 ..*providers
2273 };
2274}
2275
2276#[derive(Clone, Debug, Default, HashStable)]
2282pub struct CrateInherentImpls {
2283 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2284 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2285}
2286
2287#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2288pub struct SymbolName<'tcx> {
2289 pub name: &'tcx str,
2291}
2292
2293impl<'tcx> SymbolName<'tcx> {
2294 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2295 SymbolName { name: tcx.arena.alloc_str(name) }
2296 }
2297}
2298
2299impl<'tcx> fmt::Display for SymbolName<'tcx> {
2300 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2301 fmt::Display::fmt(&self.name, fmt)
2302 }
2303}
2304
2305impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2306 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2307 fmt::Display::fmt(&self.name, fmt)
2308 }
2309}
2310
2311#[derive(Debug, Default, Copy, Clone)]
2312pub struct InferVarInfo {
2313 pub self_in_trait: bool,
2319 pub output: bool,
2322}
2323
2324#[derive(Copy, Clone, Debug, HashStable)]
2326pub struct DestructuredConst<'tcx> {
2327 pub variant: Option<VariantIdx>,
2328 pub fields: &'tcx [ty::Const<'tcx>],
2329}
2330
2331#[cfg(target_pointer_width = "64")]
2333mod size_asserts {
2334 use rustc_data_structures::static_assert_size;
2335
2336 use super::*;
2337 static_assert_size!(PredicateKind<'_>, 32);
2339 static_assert_size!(WithCachedTypeInfo<TyKind<'_>>, 48);
2340 }