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::{
28 Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, ScalableElt, VariantIdx,
29};
30use rustc_ast::AttrVec;
31use rustc_ast::expand::typetree::{FncTree, Kind, Type, TypeTree};
32use rustc_ast::node_id::NodeMap;
33pub use rustc_ast_ir::{Movability, Mutability, try_visit};
34use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
35use rustc_data_structures::intern::Interned;
36use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
37use rustc_data_structures::steal::Steal;
38use rustc_data_structures::unord::{UnordMap, UnordSet};
39use rustc_errors::{Diag, ErrorGuaranteed, LintBuffer};
40use rustc_hir::attrs::{AttributeKind, StrippedCfgItem};
41use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
42use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
43use rustc_hir::{LangItem, attrs as attr, find_attr};
44use rustc_index::IndexVec;
45use rustc_index::bit_set::BitMatrix;
46use rustc_macros::{
47 BlobDecodable, Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable,
48 TypeVisitable, extension,
49};
50use rustc_query_system::ich::StableHashingContext;
51use rustc_serialize::{Decodable, Encodable};
52pub use rustc_session::lint::RegisteredTools;
53use rustc_span::hygiene::MacroKind;
54use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, sym};
55pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
56pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
57#[allow(
58 hidden_glob_reexports,
59 rustc::usage_of_type_ir_inherent,
60 rustc::non_glob_import_of_type_ir_inherent
61)]
62use rustc_type_ir::inherent;
63pub use rustc_type_ir::relate::VarianceDiagInfo;
64pub use rustc_type_ir::solve::{CandidatePreferenceMode, SizedTraitKind};
65pub use rustc_type_ir::*;
66#[allow(hidden_glob_reexports, unused_imports)]
67use rustc_type_ir::{InferCtxtLike, Interner};
68use tracing::{debug, instrument, trace};
69pub use vtable::*;
70use {rustc_ast as ast, rustc_hir as hir};
71
72pub use self::closure::{
73 BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
74 MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
75 UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
76 place_to_string_for_capture,
77};
78pub use self::consts::{
79 AnonConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr,
80 ExprKind, ScalarInt, SimdAlign, UnevaluatedConst, ValTree, ValTreeKindExt, Value,
81};
82pub use self::context::{
83 CtxtInterners, CurrentGcx, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, tls,
84};
85pub use self::fold::*;
86pub use self::instance::{Instance, InstanceKind, ReifyReason, UnusedGenericParams};
87pub use self::list::{List, ListWithCachedTypeInfo};
88pub use self::opaque_types::OpaqueTypeKey;
89pub use self::pattern::{Pattern, PatternKind};
90pub use self::predicate::{
91 AliasTerm, ArgOutlivesPredicate, 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::sty::{
104 AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
105 CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
106 ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
107};
108pub use self::trait_def::TraitDef;
109pub use self::typeck_results::{
110 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
111 Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
112};
113use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
114use crate::metadata::{AmbigModChild, ModChild};
115use crate::middle::privacy::EffectiveVisibilities;
116use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
117use crate::query::{IntoQueryParam, Providers};
118use crate::ty;
119use crate::ty::codec::{TyDecoder, TyEncoder};
120pub use crate::ty::diagnostics::*;
121use crate::ty::fast_reject::SimplifiedType;
122use crate::ty::layout::LayoutError;
123use crate::ty::util::Discr;
124use crate::ty::walk::TypeWalker;
125
126pub mod abstract_const;
127pub mod adjustment;
128pub mod cast;
129pub mod codec;
130pub mod error;
131pub mod fast_reject;
132pub mod inhabitedness;
133pub mod layout;
134pub mod normalize_erasing_regions;
135pub mod offload_meta;
136pub mod pattern;
137pub mod print;
138pub mod relate;
139pub mod significant_drop_order;
140pub mod trait_def;
141pub mod util;
142pub mod vtable;
143
144mod adt;
145mod assoc;
146mod closure;
147mod consts;
148mod context;
149mod diagnostics;
150mod elaborate_impl;
151mod erase_regions;
152mod fold;
153mod generic_args;
154mod generics;
155mod impls_ty;
156mod instance;
157mod intrinsic;
158mod list;
159mod opaque_types;
160mod predicate;
161mod region;
162mod structural_impls;
163#[allow(hidden_glob_reexports)]
164mod sty;
165mod typeck_results;
166mod visit;
167
168#[derive(Debug, HashStable)]
171pub struct ResolverGlobalCtxt {
172 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
173 pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
175 pub effective_visibilities: EffectiveVisibilities,
176 pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
177 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
178 pub module_children: LocalDefIdMap<Vec<ModChild>>,
179 pub ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,
180 pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
181 pub main_def: Option<MainDefinition>,
182 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
183 pub proc_macros: Vec<LocalDefId>,
186 pub confused_type_with_std_module: FxIndexMap<Span, Span>,
189 pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
190 pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
191 pub all_macro_rules: UnordSet<Symbol>,
192 pub stripped_cfg_items: Vec<StrippedCfgItem>,
193}
194
195#[derive(Debug)]
198pub struct ResolverAstLowering {
199 pub partial_res_map: NodeMap<hir::def::PartialRes>,
201 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
203 pub label_res_map: NodeMap<ast::NodeId>,
205 pub lifetimes_res_map: NodeMap<LifetimeRes>,
207 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
209
210 pub next_node_id: ast::NodeId,
211
212 pub node_id_to_def_id: NodeMap<LocalDefId>,
213
214 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
215 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
217
218 pub lint_buffer: Steal<LintBuffer>,
220
221 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
223 pub delegation_sig_resolution_nodes: LocalDefIdMap<ast::NodeId>,
226}
227
228bitflags::bitflags! {
229 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
230 pub struct DelegationFnSigAttrs: u8 {
231 const TARGET_FEATURE = 1 << 0;
232 const MUST_USE = 1 << 1;
233 }
234}
235
236pub const DELEGATION_INHERIT_ATTRS_START: DelegationFnSigAttrs = DelegationFnSigAttrs::MUST_USE;
237
238#[derive(Debug)]
239pub struct DelegationFnSig {
240 pub header: ast::FnHeader,
241 pub param_count: usize,
242 pub has_self: bool,
243 pub c_variadic: bool,
244 pub attrs_flags: DelegationFnSigAttrs,
245 pub to_inherit_attrs: AttrVec,
246}
247
248#[derive(Clone, Copy, Debug, HashStable)]
249pub struct MainDefinition {
250 pub res: Res<ast::NodeId>,
251 pub is_import: bool,
252 pub span: Span,
253}
254
255impl MainDefinition {
256 pub fn opt_fn_def_id(self) -> Option<DefId> {
257 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
258 }
259}
260
261#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
262pub struct ImplTraitHeader<'tcx> {
263 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
264 pub polarity: ImplPolarity,
265 pub safety: hir::Safety,
266 pub constness: hir::Constness,
267}
268
269#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
270#[derive(TypeFoldable, TypeVisitable, Default)]
271pub enum Asyncness {
272 Yes,
273 #[default]
274 No,
275}
276
277impl Asyncness {
278 pub fn is_async(self) -> bool {
279 matches!(self, Asyncness::Yes)
280 }
281}
282
283#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, BlobDecodable, HashStable)]
284pub enum Visibility<Id = LocalDefId> {
285 Public,
287 Restricted(Id),
289}
290
291impl Visibility {
292 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
293 match self {
294 ty::Visibility::Restricted(restricted_id) => {
295 if restricted_id.is_top_level_module() {
296 "pub(crate)".to_string()
297 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
298 "pub(self)".to_string()
299 } else {
300 format!(
301 "pub(in crate{})",
302 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
303 )
304 }
305 }
306 ty::Visibility::Public => "pub".to_string(),
307 }
308 }
309}
310
311#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
312#[derive(TypeFoldable, TypeVisitable)]
313pub struct ClosureSizeProfileData<'tcx> {
314 pub before_feature_tys: Ty<'tcx>,
316 pub after_feature_tys: Ty<'tcx>,
318}
319
320impl TyCtxt<'_> {
321 #[inline]
322 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
323 self.def_key(id).parent.map(|index| DefId { index, ..id })
324 }
325
326 #[inline]
327 #[track_caller]
328 pub fn parent(self, id: DefId) -> DefId {
329 match self.opt_parent(id) {
330 Some(id) => id,
331 None => bug!("{id:?} doesn't have a parent"),
333 }
334 }
335
336 #[inline]
337 #[track_caller]
338 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
339 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
340 }
341
342 #[inline]
343 #[track_caller]
344 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
345 self.parent(id.into().to_def_id()).expect_local()
346 }
347
348 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
349 if descendant.krate != ancestor.krate {
350 return false;
351 }
352
353 while descendant != ancestor {
354 match self.opt_parent(descendant) {
355 Some(parent) => descendant = parent,
356 None => return false,
357 }
358 }
359 true
360 }
361}
362
363impl<Id> Visibility<Id> {
364 pub fn is_public(self) -> bool {
365 matches!(self, Visibility::Public)
366 }
367
368 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
369 match self {
370 Visibility::Public => Visibility::Public,
371 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
372 }
373 }
374}
375
376impl<Id: Into<DefId>> Visibility<Id> {
377 pub fn to_def_id(self) -> Visibility<DefId> {
378 self.map_id(Into::into)
379 }
380
381 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
383 match self {
384 Visibility::Public => true,
386 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
387 }
388 }
389
390 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
392 match vis {
393 Visibility::Public => self.is_public(),
394 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
395 }
396 }
397}
398
399impl Visibility<DefId> {
400 pub fn expect_local(self) -> Visibility {
401 self.map_id(|id| id.expect_local())
402 }
403
404 pub fn is_visible_locally(self) -> bool {
406 match self {
407 Visibility::Public => true,
408 Visibility::Restricted(def_id) => def_id.is_local(),
409 }
410 }
411}
412
413#[derive(HashStable, Debug)]
420pub struct CrateVariancesMap<'tcx> {
421 pub variances: DefIdMap<&'tcx [ty::Variance]>,
425}
426
427#[derive(Copy, Clone, PartialEq, Eq, Hash)]
430pub struct CReaderCacheKey {
431 pub cnum: Option<CrateNum>,
432 pub pos: usize,
433}
434
435#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
437#[rustc_diagnostic_item = "Ty"]
438#[rustc_pass_by_value]
439pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
440
441impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
442 type Kind = TyKind<'tcx>;
443
444 fn kind(self) -> TyKind<'tcx> {
445 *self.kind()
446 }
447}
448
449impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
450 fn flags(&self) -> TypeFlags {
451 self.0.flags
452 }
453
454 fn outer_exclusive_binder(&self) -> DebruijnIndex {
455 self.0.outer_exclusive_binder
456 }
457}
458
459#[derive(HashStable, Debug)]
466pub struct CratePredicatesMap<'tcx> {
467 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
471}
472
473#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
474pub struct Term<'tcx> {
475 ptr: NonNull<()>,
476 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
477}
478
479impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
480
481impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
482 type Kind = TermKind<'tcx>;
483
484 fn kind(self) -> Self::Kind {
485 self.kind()
486 }
487}
488
489unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
490 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
491{
492}
493unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
494 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
495{
496}
497unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
498unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
499
500impl Debug for Term<'_> {
501 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502 match self.kind() {
503 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
504 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
505 }
506 }
507}
508
509impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
510 fn from(ty: Ty<'tcx>) -> Self {
511 TermKind::Ty(ty).pack()
512 }
513}
514
515impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
516 fn from(c: Const<'tcx>) -> Self {
517 TermKind::Const(c).pack()
518 }
519}
520
521impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
522 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
523 self.kind().hash_stable(hcx, hasher);
524 }
525}
526
527impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
528 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
529 self,
530 folder: &mut F,
531 ) -> Result<Self, F::Error> {
532 match self.kind() {
533 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
534 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
535 }
536 }
537
538 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
539 match self.kind() {
540 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
541 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
542 }
543 }
544}
545
546impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
547 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
548 match self.kind() {
549 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
550 ty::TermKind::Const(ct) => ct.visit_with(visitor),
551 }
552 }
553}
554
555impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
556 fn encode(&self, e: &mut E) {
557 self.kind().encode(e)
558 }
559}
560
561impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
562 fn decode(d: &mut D) -> Self {
563 let res: TermKind<'tcx> = Decodable::decode(d);
564 res.pack()
565 }
566}
567
568impl<'tcx> Term<'tcx> {
569 #[inline]
570 pub fn kind(self) -> TermKind<'tcx> {
571 let ptr =
572 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
573 unsafe {
577 match self.ptr.addr().get() & TAG_MASK {
578 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
579 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
580 ))),
581 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
582 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
583 ))),
584 _ => core::intrinsics::unreachable(),
585 }
586 }
587 }
588
589 pub fn as_type(&self) -> Option<Ty<'tcx>> {
590 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
591 }
592
593 pub fn expect_type(&self) -> Ty<'tcx> {
594 self.as_type().expect("expected a type, but found a const")
595 }
596
597 pub fn as_const(&self) -> Option<Const<'tcx>> {
598 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
599 }
600
601 pub fn expect_const(&self) -> Const<'tcx> {
602 self.as_const().expect("expected a const, but found a type")
603 }
604
605 pub fn into_arg(self) -> GenericArg<'tcx> {
606 match self.kind() {
607 TermKind::Ty(ty) => ty.into(),
608 TermKind::Const(c) => c.into(),
609 }
610 }
611
612 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
613 match self.kind() {
614 TermKind::Ty(ty) => match *ty.kind() {
615 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
616 _ => None,
617 },
618 TermKind::Const(ct) => match ct.kind() {
619 ConstKind::Unevaluated(uv) => Some(uv.into()),
620 _ => None,
621 },
622 }
623 }
624
625 pub fn is_infer(&self) -> bool {
626 match self.kind() {
627 TermKind::Ty(ty) => ty.is_ty_var(),
628 TermKind::Const(ct) => ct.is_ct_infer(),
629 }
630 }
631
632 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
633 match self.kind() {
634 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
635 TermKind::Const(ct) => ct.is_trivially_wf(),
636 }
637 }
638
639 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
650 TypeWalker::new(self.into())
651 }
652}
653
654const TAG_MASK: usize = 0b11;
655const TYPE_TAG: usize = 0b00;
656const CONST_TAG: usize = 0b01;
657
658#[extension(pub trait TermKindPackExt<'tcx>)]
659impl<'tcx> TermKind<'tcx> {
660 #[inline]
661 fn pack(self) -> Term<'tcx> {
662 let (tag, ptr) = match self {
663 TermKind::Ty(ty) => {
664 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
666 (TYPE_TAG, NonNull::from(ty.0.0).cast())
667 }
668 TermKind::Const(ct) => {
669 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
671 (CONST_TAG, NonNull::from(ct.0.0).cast())
672 }
673 };
674
675 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
676 }
677}
678
679#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
699pub struct InstantiatedPredicates<'tcx> {
700 pub predicates: Vec<Clause<'tcx>>,
701 pub spans: Vec<Span>,
702}
703
704impl<'tcx> InstantiatedPredicates<'tcx> {
705 pub fn empty() -> InstantiatedPredicates<'tcx> {
706 InstantiatedPredicates { predicates: vec![], spans: vec![] }
707 }
708
709 pub fn is_empty(&self) -> bool {
710 self.predicates.is_empty()
711 }
712
713 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
714 self.into_iter()
715 }
716}
717
718impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
719 type Item = (Clause<'tcx>, Span);
720
721 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
722
723 fn into_iter(self) -> Self::IntoIter {
724 debug_assert_eq!(self.predicates.len(), self.spans.len());
725 std::iter::zip(self.predicates, self.spans)
726 }
727}
728
729impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
730 type Item = (Clause<'tcx>, Span);
731
732 type IntoIter = std::iter::Zip<
733 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
734 std::iter::Copied<std::slice::Iter<'a, Span>>,
735 >;
736
737 fn into_iter(self) -> Self::IntoIter {
738 debug_assert_eq!(self.predicates.len(), self.spans.len());
739 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
740 }
741}
742
743#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
744pub struct ProvisionalHiddenType<'tcx> {
745 pub span: Span,
759
760 pub ty: Ty<'tcx>,
773}
774
775#[derive(Debug, Clone, Copy)]
777pub enum DefiningScopeKind {
778 HirTypeck,
783 MirBorrowck,
784}
785
786impl<'tcx> ProvisionalHiddenType<'tcx> {
787 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> ProvisionalHiddenType<'tcx> {
788 ProvisionalHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
789 }
790
791 pub fn build_mismatch_error(
792 &self,
793 other: &Self,
794 tcx: TyCtxt<'tcx>,
795 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
796 (self.ty, other.ty).error_reported()?;
797 let sub_diag = if self.span == other.span {
799 TypeMismatchReason::ConflictType { span: self.span }
800 } else {
801 TypeMismatchReason::PreviousUse { span: self.span }
802 };
803 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
804 self_ty: self.ty,
805 other_ty: other.ty,
806 other_span: other.span,
807 sub: sub_diag,
808 }))
809 }
810
811 #[instrument(level = "debug", skip(tcx), ret)]
812 pub fn remap_generic_params_to_declaration_params(
813 self,
814 opaque_type_key: OpaqueTypeKey<'tcx>,
815 tcx: TyCtxt<'tcx>,
816 defining_scope_kind: DefiningScopeKind,
817 ) -> DefinitionSiteHiddenType<'tcx> {
818 let OpaqueTypeKey { def_id, args } = opaque_type_key;
819
820 let id_args = GenericArgs::identity_for_item(tcx, def_id);
827 debug!(?id_args);
828
829 let map = args.iter().zip(id_args).collect();
833 debug!("map = {:#?}", map);
834
835 let ty = match defining_scope_kind {
841 DefiningScopeKind::HirTypeck => {
842 fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
843 }
844 DefiningScopeKind::MirBorrowck => self.ty,
845 };
846 let result_ty = ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
847 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
848 assert_eq!(result_ty, fold_regions(tcx, result_ty, |_, _| tcx.lifetimes.re_erased));
849 }
850 DefinitionSiteHiddenType { span: self.span, ty: ty::EarlyBinder::bind(result_ty) }
851 }
852}
853
854#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
855pub struct DefinitionSiteHiddenType<'tcx> {
856 pub span: Span,
869
870 pub ty: ty::EarlyBinder<'tcx, Ty<'tcx>>,
872}
873
874impl<'tcx> DefinitionSiteHiddenType<'tcx> {
875 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> DefinitionSiteHiddenType<'tcx> {
876 DefinitionSiteHiddenType {
877 span: DUMMY_SP,
878 ty: ty::EarlyBinder::bind(Ty::new_error(tcx, guar)),
879 }
880 }
881
882 pub fn build_mismatch_error(
883 &self,
884 other: &Self,
885 tcx: TyCtxt<'tcx>,
886 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
887 let self_ty = self.ty.instantiate_identity();
888 let other_ty = other.ty.instantiate_identity();
889 (self_ty, other_ty).error_reported()?;
890 let sub_diag = if self.span == other.span {
892 TypeMismatchReason::ConflictType { span: self.span }
893 } else {
894 TypeMismatchReason::PreviousUse { span: self.span }
895 };
896 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
897 self_ty,
898 other_ty,
899 other_span: other.span,
900 sub: sub_diag,
901 }))
902 }
903}
904
905pub type PlaceholderRegion<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundRegion>;
906
907impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion<'tcx> {
908 type Bound = BoundRegion;
909
910 fn universe(self) -> UniverseIndex {
911 self.universe
912 }
913
914 fn var(self) -> BoundVar {
915 self.bound.var
916 }
917
918 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
919 ty::Placeholder::new(ui, self.bound)
920 }
921
922 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
923 ty::Placeholder::new(ui, bound)
924 }
925
926 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
927 ty::Placeholder::new(ui, BoundRegion { var, kind: BoundRegionKind::Anon })
928 }
929}
930
931pub type PlaceholderType<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundTy>;
932
933impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType<'tcx> {
934 type Bound = BoundTy;
935
936 fn universe(self) -> UniverseIndex {
937 self.universe
938 }
939
940 fn var(self) -> BoundVar {
941 self.bound.var
942 }
943
944 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
945 ty::Placeholder::new(ui, self.bound)
946 }
947
948 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
949 ty::Placeholder::new(ui, bound)
950 }
951
952 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
953 ty::Placeholder::new(ui, BoundTy { var, kind: BoundTyKind::Anon })
954 }
955}
956
957#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
958#[derive(TyEncodable, TyDecodable)]
959pub struct BoundConst {
960 pub var: BoundVar,
961}
962
963impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
964 fn var(self) -> BoundVar {
965 self.var
966 }
967
968 fn assert_eq(self, var: ty::BoundVariableKind) {
969 var.expect_const()
970 }
971}
972
973pub type PlaceholderConst<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundConst>;
974
975impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst<'tcx> {
976 type Bound = BoundConst;
977
978 fn universe(self) -> UniverseIndex {
979 self.universe
980 }
981
982 fn var(self) -> BoundVar {
983 self.bound.var
984 }
985
986 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
987 ty::Placeholder::new(ui, self.bound)
988 }
989
990 fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
991 ty::Placeholder::new(ui, bound)
992 }
993
994 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
995 ty::Placeholder::new(ui, BoundConst { var })
996 }
997}
998
999pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
1000
1001impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
1002 fn flags(&self) -> TypeFlags {
1003 (**self).flags()
1004 }
1005
1006 fn outer_exclusive_binder(&self) -> DebruijnIndex {
1007 (**self).outer_exclusive_binder()
1008 }
1009}
1010
1011#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1017#[derive(HashStable, TypeVisitable, TypeFoldable)]
1018pub struct ParamEnv<'tcx> {
1019 caller_bounds: Clauses<'tcx>,
1025}
1026
1027impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1028 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
1029 self.caller_bounds()
1030 }
1031}
1032
1033impl<'tcx> ParamEnv<'tcx> {
1034 #[inline]
1041 pub fn empty() -> Self {
1042 Self::new(ListWithCachedTypeInfo::empty())
1043 }
1044
1045 #[inline]
1046 pub fn caller_bounds(self) -> Clauses<'tcx> {
1047 self.caller_bounds
1048 }
1049
1050 #[inline]
1052 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1053 ParamEnv { caller_bounds }
1054 }
1055
1056 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1058 ParamEnvAnd { param_env: self, value }
1059 }
1060}
1061
1062#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1063#[derive(HashStable)]
1064pub struct ParamEnvAnd<'tcx, T> {
1065 pub param_env: ParamEnv<'tcx>,
1066 pub value: T,
1067}
1068
1069#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1080#[derive(TypeVisitable, TypeFoldable)]
1081pub struct TypingEnv<'tcx> {
1082 #[type_foldable(identity)]
1083 #[type_visitable(ignore)]
1084 pub typing_mode: TypingMode<'tcx>,
1085 pub param_env: ParamEnv<'tcx>,
1086}
1087
1088impl<'tcx> TypingEnv<'tcx> {
1089 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1097 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1098 }
1099
1100 pub fn non_body_analysis(
1106 tcx: TyCtxt<'tcx>,
1107 def_id: impl IntoQueryParam<DefId>,
1108 ) -> TypingEnv<'tcx> {
1109 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1110 }
1111
1112 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1113 tcx.typing_env_normalized_for_post_analysis(def_id)
1114 }
1115
1116 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1119 let TypingEnv { typing_mode, param_env } = self;
1120 if let TypingMode::PostAnalysis = typing_mode {
1121 return self;
1122 }
1123
1124 let param_env = if tcx.next_trait_solver_globally() {
1127 param_env
1128 } else {
1129 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1130 };
1131 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1132 }
1133
1134 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1139 where
1140 T: TypeVisitable<TyCtxt<'tcx>>,
1141 {
1142 PseudoCanonicalInput { typing_env: self, value }
1155 }
1156}
1157
1158#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1168#[derive(HashStable, TypeVisitable, TypeFoldable)]
1169pub struct PseudoCanonicalInput<'tcx, T> {
1170 pub typing_env: TypingEnv<'tcx>,
1171 pub value: T,
1172}
1173
1174#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1175pub struct Destructor {
1176 pub did: DefId,
1178}
1179
1180#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1182pub struct AsyncDestructor {
1183 pub impl_did: DefId,
1185}
1186
1187#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1188pub struct VariantFlags(u8);
1189bitflags::bitflags! {
1190 impl VariantFlags: u8 {
1191 const NO_VARIANT_FLAGS = 0;
1192 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1194 }
1195}
1196rustc_data_structures::external_bitflags_debug! { VariantFlags }
1197
1198#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1200pub struct VariantDef {
1201 pub def_id: DefId,
1204 pub ctor: Option<(CtorKind, DefId)>,
1207 pub name: Symbol,
1209 pub discr: VariantDiscr,
1211 pub fields: IndexVec<FieldIdx, FieldDef>,
1213 tainted: Option<ErrorGuaranteed>,
1215 flags: VariantFlags,
1217}
1218
1219impl VariantDef {
1220 #[instrument(level = "debug")]
1237 pub fn new(
1238 name: Symbol,
1239 variant_did: Option<DefId>,
1240 ctor: Option<(CtorKind, DefId)>,
1241 discr: VariantDiscr,
1242 fields: IndexVec<FieldIdx, FieldDef>,
1243 parent_did: DefId,
1244 recover_tainted: Option<ErrorGuaranteed>,
1245 is_field_list_non_exhaustive: bool,
1246 ) -> Self {
1247 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1248 if is_field_list_non_exhaustive {
1249 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1250 }
1251
1252 VariantDef {
1253 def_id: variant_did.unwrap_or(parent_did),
1254 ctor,
1255 name,
1256 discr,
1257 fields,
1258 flags,
1259 tainted: recover_tainted,
1260 }
1261 }
1262
1263 #[inline]
1269 pub fn is_field_list_non_exhaustive(&self) -> bool {
1270 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1271 }
1272
1273 #[inline]
1276 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1277 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1278 }
1279
1280 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1282 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1283 }
1284
1285 #[inline]
1287 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1288 self.tainted.map_or(Ok(()), Err)
1289 }
1290
1291 #[inline]
1292 pub fn ctor_kind(&self) -> Option<CtorKind> {
1293 self.ctor.map(|(kind, _)| kind)
1294 }
1295
1296 #[inline]
1297 pub fn ctor_def_id(&self) -> Option<DefId> {
1298 self.ctor.map(|(_, def_id)| def_id)
1299 }
1300
1301 #[inline]
1305 pub fn single_field(&self) -> &FieldDef {
1306 assert!(self.fields.len() == 1);
1307
1308 &self.fields[FieldIdx::ZERO]
1309 }
1310
1311 #[inline]
1313 pub fn tail_opt(&self) -> Option<&FieldDef> {
1314 self.fields.raw.last()
1315 }
1316
1317 #[inline]
1323 pub fn tail(&self) -> &FieldDef {
1324 self.tail_opt().expect("expected unsized ADT to have a tail field")
1325 }
1326
1327 pub fn has_unsafe_fields(&self) -> bool {
1329 self.fields.iter().any(|x| x.safety.is_unsafe())
1330 }
1331}
1332
1333impl PartialEq for VariantDef {
1334 #[inline]
1335 fn eq(&self, other: &Self) -> bool {
1336 let Self {
1344 def_id: lhs_def_id,
1345 ctor: _,
1346 name: _,
1347 discr: _,
1348 fields: _,
1349 flags: _,
1350 tainted: _,
1351 } = &self;
1352 let Self {
1353 def_id: rhs_def_id,
1354 ctor: _,
1355 name: _,
1356 discr: _,
1357 fields: _,
1358 flags: _,
1359 tainted: _,
1360 } = other;
1361
1362 let res = lhs_def_id == rhs_def_id;
1363
1364 if cfg!(debug_assertions) && res {
1366 let deep = self.ctor == other.ctor
1367 && self.name == other.name
1368 && self.discr == other.discr
1369 && self.fields == other.fields
1370 && self.flags == other.flags;
1371 assert!(deep, "VariantDef for the same def-id has differing data");
1372 }
1373
1374 res
1375 }
1376}
1377
1378impl Eq for VariantDef {}
1379
1380impl Hash for VariantDef {
1381 #[inline]
1382 fn hash<H: Hasher>(&self, s: &mut H) {
1383 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1391 def_id.hash(s)
1392 }
1393}
1394
1395#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1396pub enum VariantDiscr {
1397 Explicit(DefId),
1400
1401 Relative(u32),
1406}
1407
1408#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1409pub struct FieldDef {
1410 pub did: DefId,
1411 pub name: Symbol,
1412 pub vis: Visibility<DefId>,
1413 pub safety: hir::Safety,
1414 pub value: Option<DefId>,
1415}
1416
1417impl PartialEq for FieldDef {
1418 #[inline]
1419 fn eq(&self, other: &Self) -> bool {
1420 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1428
1429 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1430
1431 let res = lhs_did == rhs_did;
1432
1433 if cfg!(debug_assertions) && res {
1435 let deep =
1436 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1437 assert!(deep, "FieldDef for the same def-id has differing data");
1438 }
1439
1440 res
1441 }
1442}
1443
1444impl Eq for FieldDef {}
1445
1446impl Hash for FieldDef {
1447 #[inline]
1448 fn hash<H: Hasher>(&self, s: &mut H) {
1449 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1457
1458 did.hash(s)
1459 }
1460}
1461
1462impl<'tcx> FieldDef {
1463 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1466 tcx.type_of(self.did).instantiate(tcx, args)
1467 }
1468
1469 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1471 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1472 }
1473}
1474
1475#[derive(Debug, PartialEq, Eq)]
1476pub enum ImplOverlapKind {
1477 Permitted {
1479 marker: bool,
1481 },
1482}
1483
1484#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1487pub enum ImplTraitInTraitData {
1488 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1489 Impl { fn_def_id: DefId },
1490}
1491
1492impl<'tcx> TyCtxt<'tcx> {
1493 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1494 self.typeck(self.hir_body_owner_def_id(body))
1495 }
1496
1497 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1498 self.associated_items(id)
1499 .in_definition_order()
1500 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1501 }
1502
1503 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1504 let mut flags = ReprFlags::empty();
1505 let mut size = None;
1506 let mut max_align: Option<Align> = None;
1507 let mut min_pack: Option<Align> = None;
1508
1509 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1512
1513 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1517 field_shuffle_seed ^= user_seed;
1518 }
1519
1520 let attributes = self.get_all_attrs(did);
1521 let elt = find_attr!(
1522 attributes,
1523 AttributeKind::RustcScalableVector { element_count, .. } => element_count
1524 )
1525 .map(|elt| match elt {
1526 Some(n) => ScalableElt::ElementCount(*n),
1527 None => ScalableElt::Container,
1528 });
1529 if elt.is_some() {
1530 flags.insert(ReprFlags::IS_SCALABLE);
1531 }
1532 if let Some(reprs) = find_attr!(attributes, AttributeKind::Repr { reprs, .. } => reprs) {
1533 for (r, _) in reprs {
1534 flags.insert(match *r {
1535 attr::ReprRust => ReprFlags::empty(),
1536 attr::ReprC => ReprFlags::IS_C,
1537 attr::ReprPacked(pack) => {
1538 min_pack = Some(if let Some(min_pack) = min_pack {
1539 min_pack.min(pack)
1540 } else {
1541 pack
1542 });
1543 ReprFlags::empty()
1544 }
1545 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1546 attr::ReprSimd => ReprFlags::IS_SIMD,
1547 attr::ReprInt(i) => {
1548 size = Some(match i {
1549 attr::IntType::SignedInt(x) => match x {
1550 ast::IntTy::Isize => IntegerType::Pointer(true),
1551 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1552 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1553 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1554 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1555 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1556 },
1557 attr::IntType::UnsignedInt(x) => match x {
1558 ast::UintTy::Usize => IntegerType::Pointer(false),
1559 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1560 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1561 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1562 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1563 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1564 },
1565 });
1566 ReprFlags::empty()
1567 }
1568 attr::ReprAlign(align) => {
1569 max_align = max_align.max(Some(align));
1570 ReprFlags::empty()
1571 }
1572 });
1573 }
1574 }
1575
1576 if self.sess.opts.unstable_opts.randomize_layout {
1579 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1580 }
1581
1582 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1585
1586 if is_box {
1588 flags.insert(ReprFlags::IS_LINEAR);
1589 }
1590
1591 if find_attr!(attributes, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) {
1593 flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1594 }
1595
1596 ReprOptions {
1597 int: size,
1598 align: max_align,
1599 pack: min_pack,
1600 flags,
1601 field_shuffle_seed,
1602 scalable: elt,
1603 }
1604 }
1605
1606 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1608 let def_id = def_id.into_query_param();
1609 if let Some(cnum) = def_id.as_crate_root() {
1610 Some(self.crate_name(cnum))
1611 } else {
1612 let def_key = self.def_key(def_id);
1613 match def_key.disambiguated_data.data {
1614 rustc_hir::definitions::DefPathData::Ctor => self
1616 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1617 _ => def_key.get_opt_name(),
1618 }
1619 }
1620 }
1621
1622 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1629 let id = id.into_query_param();
1630 self.opt_item_name(id).unwrap_or_else(|| {
1631 bug!("item_name: no name for {:?}", self.def_path(id));
1632 })
1633 }
1634
1635 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1639 let def_id = def_id.into_query_param();
1640 let def = self.opt_item_name(def_id)?;
1641 let span = self
1642 .def_ident_span(def_id)
1643 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1644 Some(Ident::new(def, span))
1645 }
1646
1647 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1651 let def_id = def_id.into_query_param();
1652 self.opt_item_ident(def_id).unwrap_or_else(|| {
1653 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1654 })
1655 }
1656
1657 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1658 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1659 Some(self.associated_item(def_id))
1660 } else {
1661 None
1662 }
1663 }
1664
1665 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1669 if let DefKind::AssocTy = self.def_kind(def_id)
1670 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1671 self.associated_item(def_id).kind
1672 {
1673 Some(rpitit_info)
1674 } else {
1675 None
1676 }
1677 }
1678
1679 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1680 variant.fields.iter_enumerated().find_map(|(i, field)| {
1681 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1682 })
1683 }
1684
1685 #[instrument(level = "debug", skip(self), ret)]
1688 pub fn impls_are_allowed_to_overlap(
1689 self,
1690 def_id1: DefId,
1691 def_id2: DefId,
1692 ) -> Option<ImplOverlapKind> {
1693 let impl1 = self.impl_trait_header(def_id1);
1694 let impl2 = self.impl_trait_header(def_id2);
1695
1696 let trait_ref1 = impl1.trait_ref.skip_binder();
1697 let trait_ref2 = impl2.trait_ref.skip_binder();
1698
1699 if trait_ref1.references_error() || trait_ref2.references_error() {
1702 return Some(ImplOverlapKind::Permitted { marker: false });
1703 }
1704
1705 match (impl1.polarity, impl2.polarity) {
1706 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1707 return Some(ImplOverlapKind::Permitted { marker: false });
1709 }
1710 (ImplPolarity::Positive, ImplPolarity::Negative)
1711 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1712 return None;
1714 }
1715 (ImplPolarity::Positive, ImplPolarity::Positive)
1716 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1717 };
1718
1719 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1720 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1721
1722 if is_marker_overlap {
1723 return Some(ImplOverlapKind::Permitted { marker: true });
1724 }
1725
1726 None
1727 }
1728
1729 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1732 match res {
1733 Res::Def(DefKind::Variant, did) => {
1734 let enum_did = self.parent(did);
1735 self.adt_def(enum_did).variant_with_id(did)
1736 }
1737 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1738 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1739 let variant_did = self.parent(variant_ctor_did);
1740 let enum_did = self.parent(variant_did);
1741 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1742 }
1743 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1744 let struct_did = self.parent(ctor_did);
1745 self.adt_def(struct_did).non_enum_variant()
1746 }
1747 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1748 }
1749 }
1750
1751 #[instrument(skip(self), level = "debug")]
1753 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1754 match instance {
1755 ty::InstanceKind::Item(def) => {
1756 debug!("calling def_kind on def: {:?}", def);
1757 let def_kind = self.def_kind(def);
1758 debug!("returned from def_kind: {:?}", def_kind);
1759 match def_kind {
1760 DefKind::Const
1761 | DefKind::Static { .. }
1762 | DefKind::AssocConst
1763 | DefKind::Ctor(..)
1764 | DefKind::AnonConst
1765 | DefKind::InlineConst => self.mir_for_ctfe(def),
1766 _ => self.optimized_mir(def),
1769 }
1770 }
1771 ty::InstanceKind::VTableShim(..)
1772 | ty::InstanceKind::ReifyShim(..)
1773 | ty::InstanceKind::Intrinsic(..)
1774 | ty::InstanceKind::FnPtrShim(..)
1775 | ty::InstanceKind::Virtual(..)
1776 | ty::InstanceKind::ClosureOnceShim { .. }
1777 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1778 | ty::InstanceKind::FutureDropPollShim(..)
1779 | ty::InstanceKind::DropGlue(..)
1780 | ty::InstanceKind::CloneShim(..)
1781 | ty::InstanceKind::ThreadLocalShim(..)
1782 | ty::InstanceKind::FnPtrAddrShim(..)
1783 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1784 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1785 }
1786 }
1787
1788 pub fn get_attrs(
1790 self,
1791 did: impl Into<DefId>,
1792 attr: Symbol,
1793 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1794 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1795 }
1796
1797 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1802 let did: DefId = did.into();
1803 if let Some(did) = did.as_local() {
1804 self.hir_attrs(self.local_def_id_to_hir_id(did))
1805 } else {
1806 self.attrs_for_def(did)
1807 }
1808 }
1809
1810 pub fn get_diagnostic_attr(
1819 self,
1820 did: impl Into<DefId>,
1821 attr: Symbol,
1822 ) -> Option<&'tcx hir::Attribute> {
1823 let did: DefId = did.into();
1824 if did.as_local().is_some() {
1825 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1827 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1828 } else {
1829 None
1830 }
1831 } else {
1832 debug_assert!(rustc_feature::encode_cross_crate(attr));
1835 self.attrs_for_def(did)
1836 .iter()
1837 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1838 }
1839 }
1840
1841 pub fn get_attrs_by_path(
1842 self,
1843 did: DefId,
1844 attr: &[Symbol],
1845 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1846 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1847 if let Some(did) = did.as_local() {
1848 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1849 } else {
1850 self.attrs_for_def(did).iter().filter(filter_fn)
1851 }
1852 }
1853
1854 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1855 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1856 let did: DefId = did.into();
1857 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1858 } else {
1859 self.get_attrs(did, attr).next()
1860 }
1861 }
1862
1863 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1865 self.get_attrs(did, attr).next().is_some()
1866 }
1867
1868 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1870 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1871 }
1872
1873 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1875 self.trait_def(trait_def_id).has_auto_impl
1876 }
1877
1878 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1881 self.trait_def(trait_def_id).is_coinductive
1882 }
1883
1884 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1886 self.def_kind(trait_def_id) == DefKind::TraitAlias
1887 }
1888
1889 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1891 self.arena.alloc(err)
1892 }
1893
1894 fn ordinary_coroutine_layout(
1900 self,
1901 def_id: DefId,
1902 args: GenericArgsRef<'tcx>,
1903 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1904 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1905 let mir = self.optimized_mir(def_id);
1906 let ty = || Ty::new_coroutine(self, def_id, args);
1907 if coroutine_kind_ty.is_unit() {
1909 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1910 } else {
1911 let ty::Coroutine(_, identity_args) =
1914 *self.type_of(def_id).instantiate_identity().kind()
1915 else {
1916 unreachable!();
1917 };
1918 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1919 if identity_kind_ty == coroutine_kind_ty {
1922 mir.coroutine_layout_raw()
1923 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1924 } else {
1925 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1926 assert_matches!(
1927 identity_kind_ty.to_opt_closure_kind(),
1928 Some(ClosureKind::Fn | ClosureKind::FnMut)
1929 );
1930 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1931 .coroutine_layout_raw()
1932 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1933 }
1934 }
1935 }
1936
1937 fn async_drop_coroutine_layout(
1941 self,
1942 def_id: DefId,
1943 args: GenericArgsRef<'tcx>,
1944 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1945 let ty = || Ty::new_coroutine(self, def_id, args);
1946 if args[0].has_placeholders() || args[0].has_non_region_param() {
1947 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1948 }
1949 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1950 self.mir_shims(instance)
1951 .coroutine_layout_raw()
1952 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1953 }
1954
1955 pub fn coroutine_layout(
1958 self,
1959 def_id: DefId,
1960 args: GenericArgsRef<'tcx>,
1961 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1962 if self.is_async_drop_in_place_coroutine(def_id) {
1963 let arg_cor_ty = args.first().unwrap().expect_ty();
1967 if arg_cor_ty.is_coroutine() {
1968 let span = self.def_span(def_id);
1969 let source_info = SourceInfo::outermost(span);
1970 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1973 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1974 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1975 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1976 let proxy_layout = CoroutineLayout {
1977 field_tys: [].into(),
1978 field_names: [].into(),
1979 variant_fields,
1980 variant_source_info,
1981 storage_conflicts: BitMatrix::new(0, 0),
1982 };
1983 return Ok(self.arena.alloc(proxy_layout));
1984 } else {
1985 self.async_drop_coroutine_layout(def_id, args)
1986 }
1987 } else {
1988 self.ordinary_coroutine_layout(def_id, args)
1989 }
1990 }
1991
1992 pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1994 if !self.def_kind(def_id).is_assoc() {
1995 return None;
1996 }
1997 let parent = self.parent(def_id);
1998 let def_kind = self.def_kind(parent);
1999 Some((parent, def_kind))
2000 }
2001
2002 pub fn trait_item_of(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2004 self.opt_associated_item(def_id.into_query_param())?.trait_item_def_id()
2005 }
2006
2007 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
2010 match self.assoc_parent(def_id) {
2011 Some((id, DefKind::Trait)) => Some(id),
2012 _ => None,
2013 }
2014 }
2015
2016 pub fn impl_is_of_trait(self, def_id: impl IntoQueryParam<DefId>) -> bool {
2017 let def_id = def_id.into_query_param();
2018 let DefKind::Impl { of_trait } = self.def_kind(def_id) else {
2019 panic!("expected Impl for {def_id:?}");
2020 };
2021 of_trait
2022 }
2023
2024 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2027 match self.assoc_parent(def_id) {
2028 Some((id, DefKind::Impl { .. })) => Some(id),
2029 _ => None,
2030 }
2031 }
2032
2033 pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2036 match self.assoc_parent(def_id) {
2037 Some((id, DefKind::Impl { of_trait: false })) => Some(id),
2038 _ => None,
2039 }
2040 }
2041
2042 pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2045 match self.assoc_parent(def_id) {
2046 Some((id, DefKind::Impl { of_trait: true })) => Some(id),
2047 _ => None,
2048 }
2049 }
2050
2051 pub fn impl_polarity(self, def_id: impl IntoQueryParam<DefId>) -> ty::ImplPolarity {
2052 self.impl_trait_header(def_id).polarity
2053 }
2054
2055 pub fn impl_trait_ref(
2057 self,
2058 def_id: impl IntoQueryParam<DefId>,
2059 ) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
2060 self.impl_trait_header(def_id).trait_ref
2061 }
2062
2063 pub fn impl_opt_trait_ref(
2066 self,
2067 def_id: impl IntoQueryParam<DefId>,
2068 ) -> Option<ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>> {
2069 let def_id = def_id.into_query_param();
2070 self.impl_is_of_trait(def_id).then(|| self.impl_trait_ref(def_id))
2071 }
2072
2073 pub fn impl_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> DefId {
2075 self.impl_trait_ref(def_id).skip_binder().def_id
2076 }
2077
2078 pub fn impl_opt_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2081 let def_id = def_id.into_query_param();
2082 self.impl_is_of_trait(def_id).then(|| self.impl_trait_id(def_id))
2083 }
2084
2085 pub fn is_exportable(self, def_id: DefId) -> bool {
2086 self.exportable_items(def_id.krate).contains(&def_id)
2087 }
2088
2089 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2092 if self.is_automatically_derived(def_id)
2093 && let Some(def_id) = def_id.as_local()
2094 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2095 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2096 && find_attr!(
2097 self.get_all_attrs(outer.macro_def_id.unwrap()),
2098 AttributeKind::RustcBuiltinMacro { .. }
2099 )
2100 {
2101 true
2102 } else {
2103 false
2104 }
2105 }
2106
2107 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2109 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
2110 }
2111
2112 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2115 if let Some(impl_def_id) = impl_def_id.as_local() {
2116 Ok(self.def_span(impl_def_id))
2117 } else {
2118 Err(self.crate_name(impl_def_id.krate))
2119 }
2120 }
2121
2122 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2126 use_ident.name == def_ident.name
2130 && use_ident
2131 .span
2132 .ctxt()
2133 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2134 }
2135
2136 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2137 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2138 ident
2139 }
2140
2141 pub fn adjust_ident_and_get_scope(
2143 self,
2144 mut ident: Ident,
2145 scope: DefId,
2146 block: hir::HirId,
2147 ) -> (Ident, DefId) {
2148 let scope = ident
2149 .span
2150 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2151 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2152 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2153 (ident, scope)
2154 }
2155
2156 #[inline]
2160 pub fn is_const_fn(self, def_id: DefId) -> bool {
2161 matches!(
2162 self.def_kind(def_id),
2163 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2164 ) && self.constness(def_id) == hir::Constness::Const
2165 }
2166
2167 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2174 let def_id: DefId = def_id.into();
2175 match self.def_kind(def_id) {
2176 DefKind::Impl { of_trait: true } => {
2177 let header = self.impl_trait_header(def_id);
2178 header.constness == hir::Constness::Const
2179 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2180 }
2181 DefKind::Impl { of_trait: false } => self.constness(def_id) == hir::Constness::Const,
2182 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2183 self.constness(def_id) == hir::Constness::Const
2184 }
2185 DefKind::TraitAlias | DefKind::Trait => self.is_const_trait(def_id),
2186 DefKind::AssocTy => {
2187 let parent_def_id = self.parent(def_id);
2188 match self.def_kind(parent_def_id) {
2189 DefKind::Impl { of_trait: false } => false,
2190 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2191 self.is_conditionally_const(parent_def_id)
2192 }
2193 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2194 }
2195 }
2196 DefKind::AssocFn => {
2197 let parent_def_id = self.parent(def_id);
2198 match self.def_kind(parent_def_id) {
2199 DefKind::Impl { of_trait: false } => {
2200 self.constness(def_id) == hir::Constness::Const
2201 }
2202 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2203 self.is_conditionally_const(parent_def_id)
2204 }
2205 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2206 }
2207 }
2208 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2209 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2210 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2211 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2213 },
2214 DefKind::Closure => {
2215 false
2218 }
2219 DefKind::Ctor(_, CtorKind::Const)
2220 | DefKind::Mod
2221 | DefKind::Struct
2222 | DefKind::Union
2223 | DefKind::Enum
2224 | DefKind::Variant
2225 | DefKind::TyAlias
2226 | DefKind::ForeignTy
2227 | DefKind::TyParam
2228 | DefKind::Const
2229 | DefKind::ConstParam
2230 | DefKind::Static { .. }
2231 | DefKind::AssocConst
2232 | DefKind::Macro(_)
2233 | DefKind::ExternCrate
2234 | DefKind::Use
2235 | DefKind::ForeignMod
2236 | DefKind::AnonConst
2237 | DefKind::InlineConst
2238 | DefKind::Field
2239 | DefKind::LifetimeParam
2240 | DefKind::GlobalAsm
2241 | DefKind::SyntheticCoroutineBody => false,
2242 }
2243 }
2244
2245 #[inline]
2246 pub fn is_const_trait(self, def_id: DefId) -> bool {
2247 self.trait_def(def_id).constness == hir::Constness::Const
2248 }
2249
2250 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2251 if self.def_kind(def_id) != DefKind::AssocFn {
2252 return false;
2253 }
2254
2255 let Some(item) = self.opt_associated_item(def_id) else {
2256 return false;
2257 };
2258
2259 let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2260 return false;
2261 };
2262
2263 !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2264 }
2265}
2266
2267pub fn provide(providers: &mut Providers) {
2268 closure::provide(providers);
2269 context::provide(providers);
2270 erase_regions::provide(providers);
2271 inhabitedness::provide(providers);
2272 util::provide(providers);
2273 print::provide(providers);
2274 super::util::bug::provide(providers);
2275 *providers = Providers {
2276 trait_impls_of: trait_def::trait_impls_of_provider,
2277 incoherent_impls: trait_def::incoherent_impls_provider,
2278 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2279 traits: trait_def::traits_provider,
2280 vtable_allocation: vtable::vtable_allocation_provider,
2281 ..*providers
2282 };
2283}
2284
2285#[derive(Clone, Debug, Default, HashStable)]
2291pub struct CrateInherentImpls {
2292 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2293 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2294}
2295
2296#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2297pub struct SymbolName<'tcx> {
2298 pub name: &'tcx str,
2300}
2301
2302impl<'tcx> SymbolName<'tcx> {
2303 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2304 SymbolName { name: tcx.arena.alloc_str(name) }
2305 }
2306}
2307
2308impl<'tcx> fmt::Display for SymbolName<'tcx> {
2309 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2310 fmt::Display::fmt(&self.name, fmt)
2311 }
2312}
2313
2314impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2315 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2316 fmt::Display::fmt(&self.name, fmt)
2317 }
2318}
2319
2320#[derive(Copy, Clone, Debug, HashStable)]
2322pub struct DestructuredConst<'tcx> {
2323 pub variant: Option<VariantIdx>,
2324 pub fields: &'tcx [ty::Const<'tcx>],
2325}
2326
2327pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
2331 if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
2333 return FncTree { args: vec![], ret: TypeTree::new() };
2334 }
2335
2336 if !fn_ty.is_fn() {
2338 return FncTree { args: vec![], ret: TypeTree::new() };
2339 }
2340
2341 let fn_sig = fn_ty.fn_sig(tcx);
2343 let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
2344
2345 let mut args = vec![];
2347 for ty in sig.inputs().iter() {
2348 let type_tree = typetree_from_ty(tcx, *ty);
2349 args.push(type_tree);
2350 }
2351
2352 let ret = typetree_from_ty(tcx, sig.output());
2354
2355 FncTree { args, ret }
2356}
2357
2358pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
2361 let mut visited = Vec::new();
2362 typetree_from_ty_inner(tcx, ty, 0, &mut visited)
2363}
2364
2365const MAX_TYPETREE_DEPTH: usize = 6;
2368
2369fn typetree_from_ty_inner<'tcx>(
2371 tcx: TyCtxt<'tcx>,
2372 ty: Ty<'tcx>,
2373 depth: usize,
2374 visited: &mut Vec<Ty<'tcx>>,
2375) -> TypeTree {
2376 if depth >= MAX_TYPETREE_DEPTH {
2377 trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
2378 return TypeTree::new();
2379 }
2380
2381 if visited.contains(&ty) {
2382 return TypeTree::new();
2383 }
2384
2385 visited.push(ty);
2386 let result = typetree_from_ty_impl(tcx, ty, depth, visited);
2387 visited.pop();
2388 result
2389}
2390
2391fn typetree_from_ty_impl<'tcx>(
2393 tcx: TyCtxt<'tcx>,
2394 ty: Ty<'tcx>,
2395 depth: usize,
2396 visited: &mut Vec<Ty<'tcx>>,
2397) -> TypeTree {
2398 typetree_from_ty_impl_inner(tcx, ty, depth, visited, false)
2399}
2400
2401fn typetree_from_ty_impl_inner<'tcx>(
2403 tcx: TyCtxt<'tcx>,
2404 ty: Ty<'tcx>,
2405 depth: usize,
2406 visited: &mut Vec<Ty<'tcx>>,
2407 is_reference_target: bool,
2408) -> TypeTree {
2409 if ty.is_scalar() {
2410 let (kind, size) = if ty.is_integral() || ty.is_char() || ty.is_bool() {
2411 (Kind::Integer, ty.primitive_size(tcx).bytes_usize())
2412 } else if ty.is_floating_point() {
2413 match ty {
2414 x if x == tcx.types.f16 => (Kind::Half, 2),
2415 x if x == tcx.types.f32 => (Kind::Float, 4),
2416 x if x == tcx.types.f64 => (Kind::Double, 8),
2417 x if x == tcx.types.f128 => (Kind::F128, 16),
2418 _ => (Kind::Integer, 0),
2419 }
2420 } else {
2421 (Kind::Integer, 0)
2422 };
2423
2424 let offset = if is_reference_target && !ty.is_array() { 0 } else { -1 };
2427 return TypeTree(vec![Type { offset, size, kind, child: TypeTree::new() }]);
2428 }
2429
2430 if ty.is_ref() || ty.is_raw_ptr() || ty.is_box() {
2431 let Some(inner_ty) = ty.builtin_deref(true) else {
2432 return TypeTree::new();
2433 };
2434
2435 let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
2436 return TypeTree(vec![Type {
2437 offset: -1,
2438 size: tcx.data_layout.pointer_size().bytes_usize(),
2439 kind: Kind::Pointer,
2440 child,
2441 }]);
2442 }
2443
2444 if ty.is_array() {
2445 if let ty::Array(element_ty, len_const) = ty.kind() {
2446 let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
2447 if len == 0 {
2448 return TypeTree::new();
2449 }
2450 let element_tree =
2451 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2452 let mut types = Vec::new();
2453 for elem_type in &element_tree.0 {
2454 types.push(Type {
2455 offset: -1,
2456 size: elem_type.size,
2457 kind: elem_type.kind,
2458 child: elem_type.child.clone(),
2459 });
2460 }
2461
2462 return TypeTree(types);
2463 }
2464 }
2465
2466 if ty.is_slice() {
2467 if let ty::Slice(element_ty) = ty.kind() {
2468 let element_tree =
2469 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2470 return element_tree;
2471 }
2472 }
2473
2474 if let ty::Tuple(tuple_types) = ty.kind() {
2475 if tuple_types.is_empty() {
2476 return TypeTree::new();
2477 }
2478
2479 let mut types = Vec::new();
2480 let mut current_offset = 0;
2481
2482 for tuple_ty in tuple_types.iter() {
2483 let element_tree =
2484 typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
2485
2486 let element_layout = tcx
2487 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
2488 .ok()
2489 .map(|layout| layout.size.bytes_usize())
2490 .unwrap_or(0);
2491
2492 for elem_type in &element_tree.0 {
2493 types.push(Type {
2494 offset: if elem_type.offset == -1 {
2495 current_offset as isize
2496 } else {
2497 current_offset as isize + elem_type.offset
2498 },
2499 size: elem_type.size,
2500 kind: elem_type.kind,
2501 child: elem_type.child.clone(),
2502 });
2503 }
2504
2505 current_offset += element_layout;
2506 }
2507
2508 return TypeTree(types);
2509 }
2510
2511 if let ty::Adt(adt_def, args) = ty.kind() {
2512 if adt_def.is_struct() {
2513 let struct_layout =
2514 tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
2515 if let Ok(layout) = struct_layout {
2516 let mut types = Vec::new();
2517
2518 for (field_idx, field_def) in adt_def.all_fields().enumerate() {
2519 let field_ty = field_def.ty(tcx, args);
2520 let field_tree =
2521 typetree_from_ty_impl_inner(tcx, field_ty, depth + 1, visited, false);
2522
2523 let field_offset = layout.fields.offset(field_idx).bytes_usize();
2524
2525 for elem_type in &field_tree.0 {
2526 types.push(Type {
2527 offset: if elem_type.offset == -1 {
2528 field_offset as isize
2529 } else {
2530 field_offset as isize + elem_type.offset
2531 },
2532 size: elem_type.size,
2533 kind: elem_type.kind,
2534 child: elem_type.child.clone(),
2535 });
2536 }
2537 }
2538
2539 return TypeTree(types);
2540 }
2541 }
2542 }
2543
2544 TypeTree::new()
2545}