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_infos: LocalDefIdMap<DelegationInfo>,
225}
226
227bitflags::bitflags! {
228 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
229 pub struct DelegationFnSigAttrs: u8 {
230 const TARGET_FEATURE = 1 << 0;
231 const MUST_USE = 1 << 1;
232 }
233}
234
235pub const DELEGATION_INHERIT_ATTRS_START: DelegationFnSigAttrs = DelegationFnSigAttrs::MUST_USE;
236
237#[derive(Debug)]
238pub struct DelegationInfo {
239 pub resolution_node: ast::NodeId,
242 pub attrs: DelegationAttrs,
243}
244
245#[derive(Debug)]
246pub struct DelegationAttrs {
247 pub flags: DelegationFnSigAttrs,
248 pub to_inherit: AttrVec,
249}
250
251#[derive(Debug)]
252pub struct DelegationFnSig {
253 pub header: ast::FnHeader,
254 pub param_count: usize,
255 pub has_self: bool,
256 pub c_variadic: bool,
257 pub attrs: DelegationAttrs,
258}
259
260#[derive(Clone, Copy, Debug, HashStable)]
261pub struct MainDefinition {
262 pub res: Res<ast::NodeId>,
263 pub is_import: bool,
264 pub span: Span,
265}
266
267impl MainDefinition {
268 pub fn opt_fn_def_id(self) -> Option<DefId> {
269 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
270 }
271}
272
273#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
274pub struct ImplTraitHeader<'tcx> {
275 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
276 pub polarity: ImplPolarity,
277 pub safety: hir::Safety,
278 pub constness: hir::Constness,
279}
280
281#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
282#[derive(TypeFoldable, TypeVisitable, Default)]
283pub enum Asyncness {
284 Yes,
285 #[default]
286 No,
287}
288
289impl Asyncness {
290 pub fn is_async(self) -> bool {
291 matches!(self, Asyncness::Yes)
292 }
293}
294
295#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, BlobDecodable, HashStable)]
296pub enum Visibility<Id = LocalDefId> {
297 Public,
299 Restricted(Id),
301}
302
303impl Visibility {
304 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
305 match self {
306 ty::Visibility::Restricted(restricted_id) => {
307 if restricted_id.is_top_level_module() {
308 "pub(crate)".to_string()
309 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
310 "pub(self)".to_string()
311 } else {
312 format!(
313 "pub(in crate{})",
314 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
315 )
316 }
317 }
318 ty::Visibility::Public => "pub".to_string(),
319 }
320 }
321}
322
323#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
324#[derive(TypeFoldable, TypeVisitable)]
325pub struct ClosureSizeProfileData<'tcx> {
326 pub before_feature_tys: Ty<'tcx>,
328 pub after_feature_tys: Ty<'tcx>,
330}
331
332impl TyCtxt<'_> {
333 #[inline]
334 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
335 self.def_key(id).parent.map(|index| DefId { index, ..id })
336 }
337
338 #[inline]
339 #[track_caller]
340 pub fn parent(self, id: DefId) -> DefId {
341 match self.opt_parent(id) {
342 Some(id) => id,
343 None => bug!("{id:?} doesn't have a parent"),
345 }
346 }
347
348 #[inline]
349 #[track_caller]
350 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
351 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
352 }
353
354 #[inline]
355 #[track_caller]
356 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
357 self.parent(id.into().to_def_id()).expect_local()
358 }
359
360 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
361 if descendant.krate != ancestor.krate {
362 return false;
363 }
364
365 while descendant != ancestor {
366 match self.opt_parent(descendant) {
367 Some(parent) => descendant = parent,
368 None => return false,
369 }
370 }
371 true
372 }
373}
374
375impl<Id> Visibility<Id> {
376 pub fn is_public(self) -> bool {
377 matches!(self, Visibility::Public)
378 }
379
380 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
381 match self {
382 Visibility::Public => Visibility::Public,
383 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
384 }
385 }
386}
387
388impl<Id: Into<DefId>> Visibility<Id> {
389 pub fn to_def_id(self) -> Visibility<DefId> {
390 self.map_id(Into::into)
391 }
392
393 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
395 match self {
396 Visibility::Public => true,
398 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
399 }
400 }
401
402 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
404 match vis {
405 Visibility::Public => self.is_public(),
406 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
407 }
408 }
409}
410
411impl Visibility<DefId> {
412 pub fn expect_local(self) -> Visibility {
413 self.map_id(|id| id.expect_local())
414 }
415
416 pub fn is_visible_locally(self) -> bool {
418 match self {
419 Visibility::Public => true,
420 Visibility::Restricted(def_id) => def_id.is_local(),
421 }
422 }
423}
424
425#[derive(HashStable, Debug)]
432pub struct CrateVariancesMap<'tcx> {
433 pub variances: DefIdMap<&'tcx [ty::Variance]>,
437}
438
439#[derive(Copy, Clone, PartialEq, Eq, Hash)]
442pub struct CReaderCacheKey {
443 pub cnum: Option<CrateNum>,
444 pub pos: usize,
445}
446
447#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
449#[rustc_diagnostic_item = "Ty"]
450#[rustc_pass_by_value]
451pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
452
453impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
454 type Kind = TyKind<'tcx>;
455
456 fn kind(self) -> TyKind<'tcx> {
457 *self.kind()
458 }
459}
460
461impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
462 fn flags(&self) -> TypeFlags {
463 self.0.flags
464 }
465
466 fn outer_exclusive_binder(&self) -> DebruijnIndex {
467 self.0.outer_exclusive_binder
468 }
469}
470
471#[derive(HashStable, Debug)]
478pub struct CratePredicatesMap<'tcx> {
479 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
483}
484
485#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
486pub struct Term<'tcx> {
487 ptr: NonNull<()>,
488 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
489}
490
491impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
492
493impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
494 type Kind = TermKind<'tcx>;
495
496 fn kind(self) -> Self::Kind {
497 self.kind()
498 }
499}
500
501unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
502 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
503{
504}
505unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
506 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
507{
508}
509unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
510unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
511
512impl Debug for Term<'_> {
513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 match self.kind() {
515 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
516 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
517 }
518 }
519}
520
521impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
522 fn from(ty: Ty<'tcx>) -> Self {
523 TermKind::Ty(ty).pack()
524 }
525}
526
527impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
528 fn from(c: Const<'tcx>) -> Self {
529 TermKind::Const(c).pack()
530 }
531}
532
533impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
534 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
535 self.kind().hash_stable(hcx, hasher);
536 }
537}
538
539impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
540 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
541 self,
542 folder: &mut F,
543 ) -> Result<Self, F::Error> {
544 match self.kind() {
545 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
546 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
547 }
548 }
549
550 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
551 match self.kind() {
552 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
553 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
554 }
555 }
556}
557
558impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
559 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
560 match self.kind() {
561 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
562 ty::TermKind::Const(ct) => ct.visit_with(visitor),
563 }
564 }
565}
566
567impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
568 fn encode(&self, e: &mut E) {
569 self.kind().encode(e)
570 }
571}
572
573impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
574 fn decode(d: &mut D) -> Self {
575 let res: TermKind<'tcx> = Decodable::decode(d);
576 res.pack()
577 }
578}
579
580impl<'tcx> Term<'tcx> {
581 #[inline]
582 pub fn kind(self) -> TermKind<'tcx> {
583 let ptr =
584 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
585 unsafe {
589 match self.ptr.addr().get() & TAG_MASK {
590 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
591 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
592 ))),
593 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
594 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
595 ))),
596 _ => core::intrinsics::unreachable(),
597 }
598 }
599 }
600
601 pub fn as_type(&self) -> Option<Ty<'tcx>> {
602 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
603 }
604
605 pub fn expect_type(&self) -> Ty<'tcx> {
606 self.as_type().expect("expected a type, but found a const")
607 }
608
609 pub fn as_const(&self) -> Option<Const<'tcx>> {
610 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
611 }
612
613 pub fn expect_const(&self) -> Const<'tcx> {
614 self.as_const().expect("expected a const, but found a type")
615 }
616
617 pub fn into_arg(self) -> GenericArg<'tcx> {
618 match self.kind() {
619 TermKind::Ty(ty) => ty.into(),
620 TermKind::Const(c) => c.into(),
621 }
622 }
623
624 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
625 match self.kind() {
626 TermKind::Ty(ty) => match *ty.kind() {
627 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
628 _ => None,
629 },
630 TermKind::Const(ct) => match ct.kind() {
631 ConstKind::Unevaluated(uv) => Some(uv.into()),
632 _ => None,
633 },
634 }
635 }
636
637 pub fn is_infer(&self) -> bool {
638 match self.kind() {
639 TermKind::Ty(ty) => ty.is_ty_var(),
640 TermKind::Const(ct) => ct.is_ct_infer(),
641 }
642 }
643
644 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
645 match self.kind() {
646 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
647 TermKind::Const(ct) => ct.is_trivially_wf(),
648 }
649 }
650
651 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
662 TypeWalker::new(self.into())
663 }
664}
665
666const TAG_MASK: usize = 0b11;
667const TYPE_TAG: usize = 0b00;
668const CONST_TAG: usize = 0b01;
669
670#[extension(pub trait TermKindPackExt<'tcx>)]
671impl<'tcx> TermKind<'tcx> {
672 #[inline]
673 fn pack(self) -> Term<'tcx> {
674 let (tag, ptr) = match self {
675 TermKind::Ty(ty) => {
676 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
678 (TYPE_TAG, NonNull::from(ty.0.0).cast())
679 }
680 TermKind::Const(ct) => {
681 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
683 (CONST_TAG, NonNull::from(ct.0.0).cast())
684 }
685 };
686
687 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
688 }
689}
690
691#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
711pub struct InstantiatedPredicates<'tcx> {
712 pub predicates: Vec<Clause<'tcx>>,
713 pub spans: Vec<Span>,
714}
715
716impl<'tcx> InstantiatedPredicates<'tcx> {
717 pub fn empty() -> InstantiatedPredicates<'tcx> {
718 InstantiatedPredicates { predicates: vec![], spans: vec![] }
719 }
720
721 pub fn is_empty(&self) -> bool {
722 self.predicates.is_empty()
723 }
724
725 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
726 self.into_iter()
727 }
728}
729
730impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
731 type Item = (Clause<'tcx>, Span);
732
733 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
734
735 fn into_iter(self) -> Self::IntoIter {
736 debug_assert_eq!(self.predicates.len(), self.spans.len());
737 std::iter::zip(self.predicates, self.spans)
738 }
739}
740
741impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
742 type Item = (Clause<'tcx>, Span);
743
744 type IntoIter = std::iter::Zip<
745 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
746 std::iter::Copied<std::slice::Iter<'a, Span>>,
747 >;
748
749 fn into_iter(self) -> Self::IntoIter {
750 debug_assert_eq!(self.predicates.len(), self.spans.len());
751 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
752 }
753}
754
755#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
756pub struct ProvisionalHiddenType<'tcx> {
757 pub span: Span,
771
772 pub ty: Ty<'tcx>,
785}
786
787#[derive(Debug, Clone, Copy)]
789pub enum DefiningScopeKind {
790 HirTypeck,
795 MirBorrowck,
796}
797
798impl<'tcx> ProvisionalHiddenType<'tcx> {
799 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> ProvisionalHiddenType<'tcx> {
800 ProvisionalHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
801 }
802
803 pub fn build_mismatch_error(
804 &self,
805 other: &Self,
806 tcx: TyCtxt<'tcx>,
807 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
808 (self.ty, other.ty).error_reported()?;
809 let sub_diag = if self.span == other.span {
811 TypeMismatchReason::ConflictType { span: self.span }
812 } else {
813 TypeMismatchReason::PreviousUse { span: self.span }
814 };
815 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
816 self_ty: self.ty,
817 other_ty: other.ty,
818 other_span: other.span,
819 sub: sub_diag,
820 }))
821 }
822
823 #[instrument(level = "debug", skip(tcx), ret)]
824 pub fn remap_generic_params_to_declaration_params(
825 self,
826 opaque_type_key: OpaqueTypeKey<'tcx>,
827 tcx: TyCtxt<'tcx>,
828 defining_scope_kind: DefiningScopeKind,
829 ) -> DefinitionSiteHiddenType<'tcx> {
830 let OpaqueTypeKey { def_id, args } = opaque_type_key;
831
832 let id_args = GenericArgs::identity_for_item(tcx, def_id);
839 debug!(?id_args);
840
841 let map = args.iter().zip(id_args).collect();
845 debug!("map = {:#?}", map);
846
847 let ty = match defining_scope_kind {
853 DefiningScopeKind::HirTypeck => {
854 fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
855 }
856 DefiningScopeKind::MirBorrowck => self.ty,
857 };
858 let result_ty = ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
859 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
860 assert_eq!(result_ty, fold_regions(tcx, result_ty, |_, _| tcx.lifetimes.re_erased));
861 }
862 DefinitionSiteHiddenType { span: self.span, ty: ty::EarlyBinder::bind(result_ty) }
863 }
864}
865
866#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
867pub struct DefinitionSiteHiddenType<'tcx> {
868 pub span: Span,
881
882 pub ty: ty::EarlyBinder<'tcx, Ty<'tcx>>,
884}
885
886impl<'tcx> DefinitionSiteHiddenType<'tcx> {
887 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> DefinitionSiteHiddenType<'tcx> {
888 DefinitionSiteHiddenType {
889 span: DUMMY_SP,
890 ty: ty::EarlyBinder::bind(Ty::new_error(tcx, guar)),
891 }
892 }
893
894 pub fn build_mismatch_error(
895 &self,
896 other: &Self,
897 tcx: TyCtxt<'tcx>,
898 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
899 let self_ty = self.ty.instantiate_identity();
900 let other_ty = other.ty.instantiate_identity();
901 (self_ty, other_ty).error_reported()?;
902 let sub_diag = if self.span == other.span {
904 TypeMismatchReason::ConflictType { span: self.span }
905 } else {
906 TypeMismatchReason::PreviousUse { span: self.span }
907 };
908 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
909 self_ty,
910 other_ty,
911 other_span: other.span,
912 sub: sub_diag,
913 }))
914 }
915}
916
917pub type PlaceholderRegion<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundRegion>;
918
919impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion<'tcx> {
920 type Bound = BoundRegion;
921
922 fn universe(self) -> UniverseIndex {
923 self.universe
924 }
925
926 fn var(self) -> BoundVar {
927 self.bound.var
928 }
929
930 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
931 ty::Placeholder::new(ui, self.bound)
932 }
933
934 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
935 ty::Placeholder::new(ui, bound)
936 }
937
938 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
939 ty::Placeholder::new(ui, BoundRegion { var, kind: BoundRegionKind::Anon })
940 }
941}
942
943pub type PlaceholderType<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundTy>;
944
945impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType<'tcx> {
946 type Bound = BoundTy;
947
948 fn universe(self) -> UniverseIndex {
949 self.universe
950 }
951
952 fn var(self) -> BoundVar {
953 self.bound.var
954 }
955
956 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
957 ty::Placeholder::new(ui, self.bound)
958 }
959
960 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
961 ty::Placeholder::new(ui, bound)
962 }
963
964 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
965 ty::Placeholder::new(ui, BoundTy { var, kind: BoundTyKind::Anon })
966 }
967}
968
969#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
970#[derive(TyEncodable, TyDecodable)]
971pub struct BoundConst {
972 pub var: BoundVar,
973}
974
975impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
976 fn var(self) -> BoundVar {
977 self.var
978 }
979
980 fn assert_eq(self, var: ty::BoundVariableKind) {
981 var.expect_const()
982 }
983}
984
985pub type PlaceholderConst<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundConst>;
986
987impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst<'tcx> {
988 type Bound = BoundConst;
989
990 fn universe(self) -> UniverseIndex {
991 self.universe
992 }
993
994 fn var(self) -> BoundVar {
995 self.bound.var
996 }
997
998 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
999 ty::Placeholder::new(ui, self.bound)
1000 }
1001
1002 fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
1003 ty::Placeholder::new(ui, bound)
1004 }
1005
1006 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
1007 ty::Placeholder::new(ui, BoundConst { var })
1008 }
1009}
1010
1011pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
1012
1013impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
1014 fn flags(&self) -> TypeFlags {
1015 (**self).flags()
1016 }
1017
1018 fn outer_exclusive_binder(&self) -> DebruijnIndex {
1019 (**self).outer_exclusive_binder()
1020 }
1021}
1022
1023#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1029#[derive(HashStable, TypeVisitable, TypeFoldable)]
1030pub struct ParamEnv<'tcx> {
1031 caller_bounds: Clauses<'tcx>,
1037}
1038
1039impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1040 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
1041 self.caller_bounds()
1042 }
1043}
1044
1045impl<'tcx> ParamEnv<'tcx> {
1046 #[inline]
1053 pub fn empty() -> Self {
1054 Self::new(ListWithCachedTypeInfo::empty())
1055 }
1056
1057 #[inline]
1058 pub fn caller_bounds(self) -> Clauses<'tcx> {
1059 self.caller_bounds
1060 }
1061
1062 #[inline]
1064 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1065 ParamEnv { caller_bounds }
1066 }
1067
1068 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1070 ParamEnvAnd { param_env: self, value }
1071 }
1072}
1073
1074#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1075#[derive(HashStable)]
1076pub struct ParamEnvAnd<'tcx, T> {
1077 pub param_env: ParamEnv<'tcx>,
1078 pub value: T,
1079}
1080
1081#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1092#[derive(TypeVisitable, TypeFoldable)]
1093pub struct TypingEnv<'tcx> {
1094 #[type_foldable(identity)]
1095 #[type_visitable(ignore)]
1096 pub typing_mode: TypingMode<'tcx>,
1097 pub param_env: ParamEnv<'tcx>,
1098}
1099
1100impl<'tcx> TypingEnv<'tcx> {
1101 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1109 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1110 }
1111
1112 pub fn non_body_analysis(
1118 tcx: TyCtxt<'tcx>,
1119 def_id: impl IntoQueryParam<DefId>,
1120 ) -> TypingEnv<'tcx> {
1121 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1122 }
1123
1124 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1125 tcx.typing_env_normalized_for_post_analysis(def_id)
1126 }
1127
1128 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1131 let TypingEnv { typing_mode, param_env } = self;
1132 if let TypingMode::PostAnalysis = typing_mode {
1133 return self;
1134 }
1135
1136 let param_env = if tcx.next_trait_solver_globally() {
1139 param_env
1140 } else {
1141 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1142 };
1143 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1144 }
1145
1146 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1151 where
1152 T: TypeVisitable<TyCtxt<'tcx>>,
1153 {
1154 PseudoCanonicalInput { typing_env: self, value }
1167 }
1168}
1169
1170#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1180#[derive(HashStable, TypeVisitable, TypeFoldable)]
1181pub struct PseudoCanonicalInput<'tcx, T> {
1182 pub typing_env: TypingEnv<'tcx>,
1183 pub value: T,
1184}
1185
1186#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1187pub struct Destructor {
1188 pub did: DefId,
1190}
1191
1192#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1194pub struct AsyncDestructor {
1195 pub impl_did: DefId,
1197}
1198
1199#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1200pub struct VariantFlags(u8);
1201bitflags::bitflags! {
1202 impl VariantFlags: u8 {
1203 const NO_VARIANT_FLAGS = 0;
1204 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1206 }
1207}
1208rustc_data_structures::external_bitflags_debug! { VariantFlags }
1209
1210#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1212pub struct VariantDef {
1213 pub def_id: DefId,
1216 pub ctor: Option<(CtorKind, DefId)>,
1219 pub name: Symbol,
1221 pub discr: VariantDiscr,
1223 pub fields: IndexVec<FieldIdx, FieldDef>,
1225 tainted: Option<ErrorGuaranteed>,
1227 flags: VariantFlags,
1229}
1230
1231impl VariantDef {
1232 #[instrument(level = "debug")]
1249 pub fn new(
1250 name: Symbol,
1251 variant_did: Option<DefId>,
1252 ctor: Option<(CtorKind, DefId)>,
1253 discr: VariantDiscr,
1254 fields: IndexVec<FieldIdx, FieldDef>,
1255 parent_did: DefId,
1256 recover_tainted: Option<ErrorGuaranteed>,
1257 is_field_list_non_exhaustive: bool,
1258 ) -> Self {
1259 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1260 if is_field_list_non_exhaustive {
1261 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1262 }
1263
1264 VariantDef {
1265 def_id: variant_did.unwrap_or(parent_did),
1266 ctor,
1267 name,
1268 discr,
1269 fields,
1270 flags,
1271 tainted: recover_tainted,
1272 }
1273 }
1274
1275 #[inline]
1281 pub fn is_field_list_non_exhaustive(&self) -> bool {
1282 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1283 }
1284
1285 #[inline]
1288 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1289 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1290 }
1291
1292 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1294 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1295 }
1296
1297 #[inline]
1299 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1300 self.tainted.map_or(Ok(()), Err)
1301 }
1302
1303 #[inline]
1304 pub fn ctor_kind(&self) -> Option<CtorKind> {
1305 self.ctor.map(|(kind, _)| kind)
1306 }
1307
1308 #[inline]
1309 pub fn ctor_def_id(&self) -> Option<DefId> {
1310 self.ctor.map(|(_, def_id)| def_id)
1311 }
1312
1313 #[inline]
1317 pub fn single_field(&self) -> &FieldDef {
1318 assert!(self.fields.len() == 1);
1319
1320 &self.fields[FieldIdx::ZERO]
1321 }
1322
1323 #[inline]
1325 pub fn tail_opt(&self) -> Option<&FieldDef> {
1326 self.fields.raw.last()
1327 }
1328
1329 #[inline]
1335 pub fn tail(&self) -> &FieldDef {
1336 self.tail_opt().expect("expected unsized ADT to have a tail field")
1337 }
1338
1339 pub fn has_unsafe_fields(&self) -> bool {
1341 self.fields.iter().any(|x| x.safety.is_unsafe())
1342 }
1343}
1344
1345impl PartialEq for VariantDef {
1346 #[inline]
1347 fn eq(&self, other: &Self) -> bool {
1348 let Self {
1356 def_id: lhs_def_id,
1357 ctor: _,
1358 name: _,
1359 discr: _,
1360 fields: _,
1361 flags: _,
1362 tainted: _,
1363 } = &self;
1364 let Self {
1365 def_id: rhs_def_id,
1366 ctor: _,
1367 name: _,
1368 discr: _,
1369 fields: _,
1370 flags: _,
1371 tainted: _,
1372 } = other;
1373
1374 let res = lhs_def_id == rhs_def_id;
1375
1376 if cfg!(debug_assertions) && res {
1378 let deep = self.ctor == other.ctor
1379 && self.name == other.name
1380 && self.discr == other.discr
1381 && self.fields == other.fields
1382 && self.flags == other.flags;
1383 assert!(deep, "VariantDef for the same def-id has differing data");
1384 }
1385
1386 res
1387 }
1388}
1389
1390impl Eq for VariantDef {}
1391
1392impl Hash for VariantDef {
1393 #[inline]
1394 fn hash<H: Hasher>(&self, s: &mut H) {
1395 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1403 def_id.hash(s)
1404 }
1405}
1406
1407#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1408pub enum VariantDiscr {
1409 Explicit(DefId),
1412
1413 Relative(u32),
1418}
1419
1420#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1421pub struct FieldDef {
1422 pub did: DefId,
1423 pub name: Symbol,
1424 pub vis: Visibility<DefId>,
1425 pub safety: hir::Safety,
1426 pub value: Option<DefId>,
1427}
1428
1429impl PartialEq for FieldDef {
1430 #[inline]
1431 fn eq(&self, other: &Self) -> bool {
1432 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1440
1441 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1442
1443 let res = lhs_did == rhs_did;
1444
1445 if cfg!(debug_assertions) && res {
1447 let deep =
1448 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1449 assert!(deep, "FieldDef for the same def-id has differing data");
1450 }
1451
1452 res
1453 }
1454}
1455
1456impl Eq for FieldDef {}
1457
1458impl Hash for FieldDef {
1459 #[inline]
1460 fn hash<H: Hasher>(&self, s: &mut H) {
1461 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1469
1470 did.hash(s)
1471 }
1472}
1473
1474impl<'tcx> FieldDef {
1475 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1478 tcx.type_of(self.did).instantiate(tcx, args)
1479 }
1480
1481 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1483 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1484 }
1485}
1486
1487#[derive(Debug, PartialEq, Eq)]
1488pub enum ImplOverlapKind {
1489 Permitted {
1491 marker: bool,
1493 },
1494}
1495
1496#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1499pub enum ImplTraitInTraitData {
1500 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1501 Impl { fn_def_id: DefId },
1502}
1503
1504impl<'tcx> TyCtxt<'tcx> {
1505 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1506 self.typeck(self.hir_body_owner_def_id(body))
1507 }
1508
1509 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1510 self.associated_items(id)
1511 .in_definition_order()
1512 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1513 }
1514
1515 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1516 let mut flags = ReprFlags::empty();
1517 let mut size = None;
1518 let mut max_align: Option<Align> = None;
1519 let mut min_pack: Option<Align> = None;
1520
1521 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1524
1525 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1529 field_shuffle_seed ^= user_seed;
1530 }
1531
1532 let attributes = self.get_all_attrs(did);
1533 let elt = find_attr!(
1534 attributes,
1535 AttributeKind::RustcScalableVector { element_count, .. } => element_count
1536 )
1537 .map(|elt| match elt {
1538 Some(n) => ScalableElt::ElementCount(*n),
1539 None => ScalableElt::Container,
1540 });
1541 if elt.is_some() {
1542 flags.insert(ReprFlags::IS_SCALABLE);
1543 }
1544 if let Some(reprs) = find_attr!(attributes, AttributeKind::Repr { reprs, .. } => reprs) {
1545 for (r, _) in reprs {
1546 flags.insert(match *r {
1547 attr::ReprRust => ReprFlags::empty(),
1548 attr::ReprC => ReprFlags::IS_C,
1549 attr::ReprPacked(pack) => {
1550 min_pack = Some(if let Some(min_pack) = min_pack {
1551 min_pack.min(pack)
1552 } else {
1553 pack
1554 });
1555 ReprFlags::empty()
1556 }
1557 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1558 attr::ReprSimd => ReprFlags::IS_SIMD,
1559 attr::ReprInt(i) => {
1560 size = Some(match i {
1561 attr::IntType::SignedInt(x) => match x {
1562 ast::IntTy::Isize => IntegerType::Pointer(true),
1563 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1564 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1565 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1566 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1567 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1568 },
1569 attr::IntType::UnsignedInt(x) => match x {
1570 ast::UintTy::Usize => IntegerType::Pointer(false),
1571 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1572 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1573 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1574 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1575 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1576 },
1577 });
1578 ReprFlags::empty()
1579 }
1580 attr::ReprAlign(align) => {
1581 max_align = max_align.max(Some(align));
1582 ReprFlags::empty()
1583 }
1584 });
1585 }
1586 }
1587
1588 if self.sess.opts.unstable_opts.randomize_layout {
1591 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1592 }
1593
1594 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1597
1598 if is_box {
1600 flags.insert(ReprFlags::IS_LINEAR);
1601 }
1602
1603 if find_attr!(attributes, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) {
1605 flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1606 }
1607
1608 ReprOptions {
1609 int: size,
1610 align: max_align,
1611 pack: min_pack,
1612 flags,
1613 field_shuffle_seed,
1614 scalable: elt,
1615 }
1616 }
1617
1618 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1620 let def_id = def_id.into_query_param();
1621 if let Some(cnum) = def_id.as_crate_root() {
1622 Some(self.crate_name(cnum))
1623 } else {
1624 let def_key = self.def_key(def_id);
1625 match def_key.disambiguated_data.data {
1626 rustc_hir::definitions::DefPathData::Ctor => self
1628 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1629 _ => def_key.get_opt_name(),
1630 }
1631 }
1632 }
1633
1634 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1641 let id = id.into_query_param();
1642 self.opt_item_name(id).unwrap_or_else(|| {
1643 bug!("item_name: no name for {:?}", self.def_path(id));
1644 })
1645 }
1646
1647 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1651 let def_id = def_id.into_query_param();
1652 let def = self.opt_item_name(def_id)?;
1653 let span = self
1654 .def_ident_span(def_id)
1655 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1656 Some(Ident::new(def, span))
1657 }
1658
1659 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1663 let def_id = def_id.into_query_param();
1664 self.opt_item_ident(def_id).unwrap_or_else(|| {
1665 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1666 })
1667 }
1668
1669 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1670 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1671 Some(self.associated_item(def_id))
1672 } else {
1673 None
1674 }
1675 }
1676
1677 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1681 if let DefKind::AssocTy = self.def_kind(def_id)
1682 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1683 self.associated_item(def_id).kind
1684 {
1685 Some(rpitit_info)
1686 } else {
1687 None
1688 }
1689 }
1690
1691 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1692 variant.fields.iter_enumerated().find_map(|(i, field)| {
1693 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1694 })
1695 }
1696
1697 #[instrument(level = "debug", skip(self), ret)]
1700 pub fn impls_are_allowed_to_overlap(
1701 self,
1702 def_id1: DefId,
1703 def_id2: DefId,
1704 ) -> Option<ImplOverlapKind> {
1705 let impl1 = self.impl_trait_header(def_id1);
1706 let impl2 = self.impl_trait_header(def_id2);
1707
1708 let trait_ref1 = impl1.trait_ref.skip_binder();
1709 let trait_ref2 = impl2.trait_ref.skip_binder();
1710
1711 if trait_ref1.references_error() || trait_ref2.references_error() {
1714 return Some(ImplOverlapKind::Permitted { marker: false });
1715 }
1716
1717 match (impl1.polarity, impl2.polarity) {
1718 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1719 return Some(ImplOverlapKind::Permitted { marker: false });
1721 }
1722 (ImplPolarity::Positive, ImplPolarity::Negative)
1723 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1724 return None;
1726 }
1727 (ImplPolarity::Positive, ImplPolarity::Positive)
1728 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1729 };
1730
1731 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1732 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1733
1734 if is_marker_overlap {
1735 return Some(ImplOverlapKind::Permitted { marker: true });
1736 }
1737
1738 None
1739 }
1740
1741 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1744 match res {
1745 Res::Def(DefKind::Variant, did) => {
1746 let enum_did = self.parent(did);
1747 self.adt_def(enum_did).variant_with_id(did)
1748 }
1749 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1750 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1751 let variant_did = self.parent(variant_ctor_did);
1752 let enum_did = self.parent(variant_did);
1753 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1754 }
1755 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1756 let struct_did = self.parent(ctor_did);
1757 self.adt_def(struct_did).non_enum_variant()
1758 }
1759 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1760 }
1761 }
1762
1763 #[instrument(skip(self), level = "debug")]
1765 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1766 match instance {
1767 ty::InstanceKind::Item(def) => {
1768 debug!("calling def_kind on def: {:?}", def);
1769 let def_kind = self.def_kind(def);
1770 debug!("returned from def_kind: {:?}", def_kind);
1771 match def_kind {
1772 DefKind::Const
1773 | DefKind::Static { .. }
1774 | DefKind::AssocConst
1775 | DefKind::Ctor(..)
1776 | DefKind::AnonConst
1777 | DefKind::InlineConst => self.mir_for_ctfe(def),
1778 _ => self.optimized_mir(def),
1781 }
1782 }
1783 ty::InstanceKind::VTableShim(..)
1784 | ty::InstanceKind::ReifyShim(..)
1785 | ty::InstanceKind::Intrinsic(..)
1786 | ty::InstanceKind::FnPtrShim(..)
1787 | ty::InstanceKind::Virtual(..)
1788 | ty::InstanceKind::ClosureOnceShim { .. }
1789 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1790 | ty::InstanceKind::FutureDropPollShim(..)
1791 | ty::InstanceKind::DropGlue(..)
1792 | ty::InstanceKind::CloneShim(..)
1793 | ty::InstanceKind::ThreadLocalShim(..)
1794 | ty::InstanceKind::FnPtrAddrShim(..)
1795 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1796 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1797 }
1798 }
1799
1800 pub fn get_attrs(
1802 self,
1803 did: impl Into<DefId>,
1804 attr: Symbol,
1805 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1806 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1807 }
1808
1809 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1814 let did: DefId = did.into();
1815 if let Some(did) = did.as_local() {
1816 self.hir_attrs(self.local_def_id_to_hir_id(did))
1817 } else {
1818 self.attrs_for_def(did)
1819 }
1820 }
1821
1822 pub fn get_diagnostic_attr(
1831 self,
1832 did: impl Into<DefId>,
1833 attr: Symbol,
1834 ) -> Option<&'tcx hir::Attribute> {
1835 let did: DefId = did.into();
1836 if did.as_local().is_some() {
1837 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1839 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1840 } else {
1841 None
1842 }
1843 } else {
1844 debug_assert!(rustc_feature::encode_cross_crate(attr));
1847 self.attrs_for_def(did)
1848 .iter()
1849 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1850 }
1851 }
1852
1853 pub fn get_attrs_by_path(
1854 self,
1855 did: DefId,
1856 attr: &[Symbol],
1857 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1858 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1859 if let Some(did) = did.as_local() {
1860 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1861 } else {
1862 self.attrs_for_def(did).iter().filter(filter_fn)
1863 }
1864 }
1865
1866 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1867 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1868 let did: DefId = did.into();
1869 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1870 } else {
1871 self.get_attrs(did, attr).next()
1872 }
1873 }
1874
1875 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1877 self.get_attrs(did, attr).next().is_some()
1878 }
1879
1880 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1882 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1883 }
1884
1885 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1887 self.trait_def(trait_def_id).has_auto_impl
1888 }
1889
1890 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1893 self.trait_def(trait_def_id).is_coinductive
1894 }
1895
1896 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1898 self.def_kind(trait_def_id) == DefKind::TraitAlias
1899 }
1900
1901 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1903 self.arena.alloc(err)
1904 }
1905
1906 fn ordinary_coroutine_layout(
1912 self,
1913 def_id: DefId,
1914 args: GenericArgsRef<'tcx>,
1915 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1916 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1917 let mir = self.optimized_mir(def_id);
1918 let ty = || Ty::new_coroutine(self, def_id, args);
1919 if coroutine_kind_ty.is_unit() {
1921 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1922 } else {
1923 let ty::Coroutine(_, identity_args) =
1926 *self.type_of(def_id).instantiate_identity().kind()
1927 else {
1928 unreachable!();
1929 };
1930 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1931 if identity_kind_ty == coroutine_kind_ty {
1934 mir.coroutine_layout_raw()
1935 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1936 } else {
1937 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1938 assert_matches!(
1939 identity_kind_ty.to_opt_closure_kind(),
1940 Some(ClosureKind::Fn | ClosureKind::FnMut)
1941 );
1942 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1943 .coroutine_layout_raw()
1944 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1945 }
1946 }
1947 }
1948
1949 fn async_drop_coroutine_layout(
1953 self,
1954 def_id: DefId,
1955 args: GenericArgsRef<'tcx>,
1956 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1957 let ty = || Ty::new_coroutine(self, def_id, args);
1958 if args[0].has_placeholders() || args[0].has_non_region_param() {
1959 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1960 }
1961 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1962 self.mir_shims(instance)
1963 .coroutine_layout_raw()
1964 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1965 }
1966
1967 pub fn coroutine_layout(
1970 self,
1971 def_id: DefId,
1972 args: GenericArgsRef<'tcx>,
1973 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1974 if self.is_async_drop_in_place_coroutine(def_id) {
1975 let arg_cor_ty = args.first().unwrap().expect_ty();
1979 if arg_cor_ty.is_coroutine() {
1980 let span = self.def_span(def_id);
1981 let source_info = SourceInfo::outermost(span);
1982 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1985 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1986 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1987 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1988 let proxy_layout = CoroutineLayout {
1989 field_tys: [].into(),
1990 field_names: [].into(),
1991 variant_fields,
1992 variant_source_info,
1993 storage_conflicts: BitMatrix::new(0, 0),
1994 };
1995 return Ok(self.arena.alloc(proxy_layout));
1996 } else {
1997 self.async_drop_coroutine_layout(def_id, args)
1998 }
1999 } else {
2000 self.ordinary_coroutine_layout(def_id, args)
2001 }
2002 }
2003
2004 pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
2006 if !self.def_kind(def_id).is_assoc() {
2007 return None;
2008 }
2009 let parent = self.parent(def_id);
2010 let def_kind = self.def_kind(parent);
2011 Some((parent, def_kind))
2012 }
2013
2014 pub fn trait_item_of(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2016 self.opt_associated_item(def_id.into_query_param())?.trait_item_def_id()
2017 }
2018
2019 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
2022 match self.assoc_parent(def_id) {
2023 Some((id, DefKind::Trait)) => Some(id),
2024 _ => None,
2025 }
2026 }
2027
2028 pub fn impl_is_of_trait(self, def_id: impl IntoQueryParam<DefId>) -> bool {
2029 let def_id = def_id.into_query_param();
2030 let DefKind::Impl { of_trait } = self.def_kind(def_id) else {
2031 panic!("expected Impl for {def_id:?}");
2032 };
2033 of_trait
2034 }
2035
2036 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2039 match self.assoc_parent(def_id) {
2040 Some((id, DefKind::Impl { .. })) => Some(id),
2041 _ => None,
2042 }
2043 }
2044
2045 pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2048 match self.assoc_parent(def_id) {
2049 Some((id, DefKind::Impl { of_trait: false })) => Some(id),
2050 _ => None,
2051 }
2052 }
2053
2054 pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2057 match self.assoc_parent(def_id) {
2058 Some((id, DefKind::Impl { of_trait: true })) => Some(id),
2059 _ => None,
2060 }
2061 }
2062
2063 pub fn impl_polarity(self, def_id: impl IntoQueryParam<DefId>) -> ty::ImplPolarity {
2064 self.impl_trait_header(def_id).polarity
2065 }
2066
2067 pub fn impl_trait_ref(
2069 self,
2070 def_id: impl IntoQueryParam<DefId>,
2071 ) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
2072 self.impl_trait_header(def_id).trait_ref
2073 }
2074
2075 pub fn impl_opt_trait_ref(
2078 self,
2079 def_id: impl IntoQueryParam<DefId>,
2080 ) -> Option<ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>> {
2081 let def_id = def_id.into_query_param();
2082 self.impl_is_of_trait(def_id).then(|| self.impl_trait_ref(def_id))
2083 }
2084
2085 pub fn impl_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> DefId {
2087 self.impl_trait_ref(def_id).skip_binder().def_id
2088 }
2089
2090 pub fn impl_opt_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2093 let def_id = def_id.into_query_param();
2094 self.impl_is_of_trait(def_id).then(|| self.impl_trait_id(def_id))
2095 }
2096
2097 pub fn is_exportable(self, def_id: DefId) -> bool {
2098 self.exportable_items(def_id.krate).contains(&def_id)
2099 }
2100
2101 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2104 if self.is_automatically_derived(def_id)
2105 && let Some(def_id) = def_id.as_local()
2106 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2107 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2108 && find_attr!(
2109 self.get_all_attrs(outer.macro_def_id.unwrap()),
2110 AttributeKind::RustcBuiltinMacro { .. }
2111 )
2112 {
2113 true
2114 } else {
2115 false
2116 }
2117 }
2118
2119 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2121 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
2122 }
2123
2124 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2127 if let Some(impl_def_id) = impl_def_id.as_local() {
2128 Ok(self.def_span(impl_def_id))
2129 } else {
2130 Err(self.crate_name(impl_def_id.krate))
2131 }
2132 }
2133
2134 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2138 use_ident.name == def_ident.name
2142 && use_ident
2143 .span
2144 .ctxt()
2145 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2146 }
2147
2148 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2149 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2150 ident
2151 }
2152
2153 pub fn adjust_ident_and_get_scope(
2155 self,
2156 mut ident: Ident,
2157 scope: DefId,
2158 block: hir::HirId,
2159 ) -> (Ident, DefId) {
2160 let scope = ident
2161 .span
2162 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2163 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2164 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2165 (ident, scope)
2166 }
2167
2168 #[inline]
2172 pub fn is_const_fn(self, def_id: DefId) -> bool {
2173 matches!(
2174 self.def_kind(def_id),
2175 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2176 ) && self.constness(def_id) == hir::Constness::Const
2177 }
2178
2179 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2186 let def_id: DefId = def_id.into();
2187 match self.def_kind(def_id) {
2188 DefKind::Impl { of_trait: true } => {
2189 let header = self.impl_trait_header(def_id);
2190 header.constness == hir::Constness::Const
2191 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2192 }
2193 DefKind::Impl { of_trait: false } => self.constness(def_id) == hir::Constness::Const,
2194 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2195 self.constness(def_id) == hir::Constness::Const
2196 }
2197 DefKind::TraitAlias | DefKind::Trait => self.is_const_trait(def_id),
2198 DefKind::AssocTy => {
2199 let parent_def_id = self.parent(def_id);
2200 match self.def_kind(parent_def_id) {
2201 DefKind::Impl { of_trait: false } => false,
2202 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2203 self.is_conditionally_const(parent_def_id)
2204 }
2205 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2206 }
2207 }
2208 DefKind::AssocFn => {
2209 let parent_def_id = self.parent(def_id);
2210 match self.def_kind(parent_def_id) {
2211 DefKind::Impl { of_trait: false } => {
2212 self.constness(def_id) == hir::Constness::Const
2213 }
2214 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2215 self.is_conditionally_const(parent_def_id)
2216 }
2217 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2218 }
2219 }
2220 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2221 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2222 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2223 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2225 },
2226 DefKind::Closure => {
2227 false
2230 }
2231 DefKind::Ctor(_, CtorKind::Const)
2232 | DefKind::Mod
2233 | DefKind::Struct
2234 | DefKind::Union
2235 | DefKind::Enum
2236 | DefKind::Variant
2237 | DefKind::TyAlias
2238 | DefKind::ForeignTy
2239 | DefKind::TyParam
2240 | DefKind::Const
2241 | DefKind::ConstParam
2242 | DefKind::Static { .. }
2243 | DefKind::AssocConst
2244 | DefKind::Macro(_)
2245 | DefKind::ExternCrate
2246 | DefKind::Use
2247 | DefKind::ForeignMod
2248 | DefKind::AnonConst
2249 | DefKind::InlineConst
2250 | DefKind::Field
2251 | DefKind::LifetimeParam
2252 | DefKind::GlobalAsm
2253 | DefKind::SyntheticCoroutineBody => false,
2254 }
2255 }
2256
2257 #[inline]
2258 pub fn is_const_trait(self, def_id: DefId) -> bool {
2259 self.trait_def(def_id).constness == hir::Constness::Const
2260 }
2261
2262 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2263 if self.def_kind(def_id) != DefKind::AssocFn {
2264 return false;
2265 }
2266
2267 let Some(item) = self.opt_associated_item(def_id) else {
2268 return false;
2269 };
2270
2271 let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2272 return false;
2273 };
2274
2275 !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2276 }
2277}
2278
2279pub fn provide(providers: &mut Providers) {
2280 closure::provide(providers);
2281 context::provide(providers);
2282 erase_regions::provide(providers);
2283 inhabitedness::provide(providers);
2284 util::provide(providers);
2285 print::provide(providers);
2286 super::util::bug::provide(providers);
2287 *providers = Providers {
2288 trait_impls_of: trait_def::trait_impls_of_provider,
2289 incoherent_impls: trait_def::incoherent_impls_provider,
2290 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2291 traits: trait_def::traits_provider,
2292 vtable_allocation: vtable::vtable_allocation_provider,
2293 ..*providers
2294 };
2295}
2296
2297#[derive(Clone, Debug, Default, HashStable)]
2303pub struct CrateInherentImpls {
2304 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2305 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2306}
2307
2308#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2309pub struct SymbolName<'tcx> {
2310 pub name: &'tcx str,
2312}
2313
2314impl<'tcx> SymbolName<'tcx> {
2315 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2316 SymbolName { name: tcx.arena.alloc_str(name) }
2317 }
2318}
2319
2320impl<'tcx> fmt::Display for SymbolName<'tcx> {
2321 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2322 fmt::Display::fmt(&self.name, fmt)
2323 }
2324}
2325
2326impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2327 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2328 fmt::Display::fmt(&self.name, fmt)
2329 }
2330}
2331
2332#[derive(Copy, Clone, Debug, HashStable)]
2334pub struct DestructuredConst<'tcx> {
2335 pub variant: Option<VariantIdx>,
2336 pub fields: &'tcx [ty::Const<'tcx>],
2337}
2338
2339pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
2343 if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
2345 return FncTree { args: vec![], ret: TypeTree::new() };
2346 }
2347
2348 if !fn_ty.is_fn() {
2350 return FncTree { args: vec![], ret: TypeTree::new() };
2351 }
2352
2353 let fn_sig = fn_ty.fn_sig(tcx);
2355 let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
2356
2357 let mut args = vec![];
2359 for ty in sig.inputs().iter() {
2360 let type_tree = typetree_from_ty(tcx, *ty);
2361 args.push(type_tree);
2362 }
2363
2364 let ret = typetree_from_ty(tcx, sig.output());
2366
2367 FncTree { args, ret }
2368}
2369
2370pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
2373 let mut visited = Vec::new();
2374 typetree_from_ty_inner(tcx, ty, 0, &mut visited)
2375}
2376
2377const MAX_TYPETREE_DEPTH: usize = 6;
2380
2381fn typetree_from_ty_inner<'tcx>(
2383 tcx: TyCtxt<'tcx>,
2384 ty: Ty<'tcx>,
2385 depth: usize,
2386 visited: &mut Vec<Ty<'tcx>>,
2387) -> TypeTree {
2388 if depth >= MAX_TYPETREE_DEPTH {
2389 trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
2390 return TypeTree::new();
2391 }
2392
2393 if visited.contains(&ty) {
2394 return TypeTree::new();
2395 }
2396
2397 visited.push(ty);
2398 let result = typetree_from_ty_impl(tcx, ty, depth, visited);
2399 visited.pop();
2400 result
2401}
2402
2403fn typetree_from_ty_impl<'tcx>(
2405 tcx: TyCtxt<'tcx>,
2406 ty: Ty<'tcx>,
2407 depth: usize,
2408 visited: &mut Vec<Ty<'tcx>>,
2409) -> TypeTree {
2410 typetree_from_ty_impl_inner(tcx, ty, depth, visited, false)
2411}
2412
2413fn typetree_from_ty_impl_inner<'tcx>(
2415 tcx: TyCtxt<'tcx>,
2416 ty: Ty<'tcx>,
2417 depth: usize,
2418 visited: &mut Vec<Ty<'tcx>>,
2419 is_reference_target: bool,
2420) -> TypeTree {
2421 if ty.is_scalar() {
2422 let (kind, size) = if ty.is_integral() || ty.is_char() || ty.is_bool() {
2423 (Kind::Integer, ty.primitive_size(tcx).bytes_usize())
2424 } else if ty.is_floating_point() {
2425 match ty {
2426 x if x == tcx.types.f16 => (Kind::Half, 2),
2427 x if x == tcx.types.f32 => (Kind::Float, 4),
2428 x if x == tcx.types.f64 => (Kind::Double, 8),
2429 x if x == tcx.types.f128 => (Kind::F128, 16),
2430 _ => (Kind::Integer, 0),
2431 }
2432 } else {
2433 (Kind::Integer, 0)
2434 };
2435
2436 let offset = if is_reference_target && !ty.is_array() { 0 } else { -1 };
2439 return TypeTree(vec![Type { offset, size, kind, child: TypeTree::new() }]);
2440 }
2441
2442 if ty.is_ref() || ty.is_raw_ptr() || ty.is_box() {
2443 let Some(inner_ty) = ty.builtin_deref(true) else {
2444 return TypeTree::new();
2445 };
2446
2447 let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
2448 return TypeTree(vec![Type {
2449 offset: -1,
2450 size: tcx.data_layout.pointer_size().bytes_usize(),
2451 kind: Kind::Pointer,
2452 child,
2453 }]);
2454 }
2455
2456 if ty.is_array() {
2457 if let ty::Array(element_ty, len_const) = ty.kind() {
2458 let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
2459 if len == 0 {
2460 return TypeTree::new();
2461 }
2462 let element_tree =
2463 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2464 let mut types = Vec::new();
2465 for elem_type in &element_tree.0 {
2466 types.push(Type {
2467 offset: -1,
2468 size: elem_type.size,
2469 kind: elem_type.kind,
2470 child: elem_type.child.clone(),
2471 });
2472 }
2473
2474 return TypeTree(types);
2475 }
2476 }
2477
2478 if ty.is_slice() {
2479 if let ty::Slice(element_ty) = ty.kind() {
2480 let element_tree =
2481 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2482 return element_tree;
2483 }
2484 }
2485
2486 if let ty::Tuple(tuple_types) = ty.kind() {
2487 if tuple_types.is_empty() {
2488 return TypeTree::new();
2489 }
2490
2491 let mut types = Vec::new();
2492 let mut current_offset = 0;
2493
2494 for tuple_ty in tuple_types.iter() {
2495 let element_tree =
2496 typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
2497
2498 let element_layout = tcx
2499 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
2500 .ok()
2501 .map(|layout| layout.size.bytes_usize())
2502 .unwrap_or(0);
2503
2504 for elem_type in &element_tree.0 {
2505 types.push(Type {
2506 offset: if elem_type.offset == -1 {
2507 current_offset as isize
2508 } else {
2509 current_offset as isize + elem_type.offset
2510 },
2511 size: elem_type.size,
2512 kind: elem_type.kind,
2513 child: elem_type.child.clone(),
2514 });
2515 }
2516
2517 current_offset += element_layout;
2518 }
2519
2520 return TypeTree(types);
2521 }
2522
2523 if let ty::Adt(adt_def, args) = ty.kind() {
2524 if adt_def.is_struct() {
2525 let struct_layout =
2526 tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
2527 if let Ok(layout) = struct_layout {
2528 let mut types = Vec::new();
2529
2530 for (field_idx, field_def) in adt_def.all_fields().enumerate() {
2531 let field_ty = field_def.ty(tcx, args);
2532 let field_tree =
2533 typetree_from_ty_impl_inner(tcx, field_ty, depth + 1, visited, false);
2534
2535 let field_offset = layout.fields.offset(field_idx).bytes_usize();
2536
2537 for elem_type in &field_tree.0 {
2538 types.push(Type {
2539 offset: if elem_type.offset == -1 {
2540 field_offset as isize
2541 } else {
2542 field_offset as isize + elem_type.offset
2543 },
2544 size: elem_type.size,
2545 kind: elem_type.kind,
2546 child: elem_type.child.clone(),
2547 });
2548 }
2549 }
2550
2551 return TypeTree(types);
2552 }
2553 }
2554 }
2555
2556 TypeTree::new()
2557}