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::{FxHashMap, 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, ValTreeKind, 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 legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
200 pub partial_res_map: NodeMap<hir::def::PartialRes>,
202 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
204 pub label_res_map: NodeMap<ast::NodeId>,
206 pub lifetimes_res_map: NodeMap<LifetimeRes>,
208 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
210
211 pub next_node_id: ast::NodeId,
212
213 pub node_id_to_def_id: NodeMap<LocalDefId>,
214
215 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
216 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
218
219 pub lint_buffer: Steal<LintBuffer>,
221
222 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
224}
225
226bitflags::bitflags! {
227 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
228 pub struct DelegationFnSigAttrs: u8 {
229 const TARGET_FEATURE = 1 << 0;
230 const MUST_USE = 1 << 1;
231 }
232}
233
234pub const DELEGATION_INHERIT_ATTRS_START: DelegationFnSigAttrs = DelegationFnSigAttrs::MUST_USE;
235
236#[derive(Debug)]
237pub struct DelegationFnSig {
238 pub header: ast::FnHeader,
239 pub param_count: usize,
240 pub has_self: bool,
241 pub c_variadic: bool,
242 pub attrs_flags: DelegationFnSigAttrs,
243 pub to_inherit_attrs: AttrVec,
244}
245
246#[derive(Clone, Copy, Debug, HashStable)]
247pub struct MainDefinition {
248 pub res: Res<ast::NodeId>,
249 pub is_import: bool,
250 pub span: Span,
251}
252
253impl MainDefinition {
254 pub fn opt_fn_def_id(self) -> Option<DefId> {
255 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
256 }
257}
258
259#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
260pub struct ImplTraitHeader<'tcx> {
261 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
262 pub polarity: ImplPolarity,
263 pub safety: hir::Safety,
264 pub constness: hir::Constness,
265}
266
267#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
268#[derive(TypeFoldable, TypeVisitable, Default)]
269pub enum Asyncness {
270 Yes,
271 #[default]
272 No,
273}
274
275impl Asyncness {
276 pub fn is_async(self) -> bool {
277 matches!(self, Asyncness::Yes)
278 }
279}
280
281#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, BlobDecodable, HashStable)]
282pub enum Visibility<Id = LocalDefId> {
283 Public,
285 Restricted(Id),
287}
288
289impl Visibility {
290 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
291 match self {
292 ty::Visibility::Restricted(restricted_id) => {
293 if restricted_id.is_top_level_module() {
294 "pub(crate)".to_string()
295 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
296 "pub(self)".to_string()
297 } else {
298 format!(
299 "pub(in crate{})",
300 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
301 )
302 }
303 }
304 ty::Visibility::Public => "pub".to_string(),
305 }
306 }
307}
308
309#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
310#[derive(TypeFoldable, TypeVisitable)]
311pub struct ClosureSizeProfileData<'tcx> {
312 pub before_feature_tys: Ty<'tcx>,
314 pub after_feature_tys: Ty<'tcx>,
316}
317
318impl TyCtxt<'_> {
319 #[inline]
320 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
321 self.def_key(id).parent.map(|index| DefId { index, ..id })
322 }
323
324 #[inline]
325 #[track_caller]
326 pub fn parent(self, id: DefId) -> DefId {
327 match self.opt_parent(id) {
328 Some(id) => id,
329 None => bug!("{id:?} doesn't have a parent"),
331 }
332 }
333
334 #[inline]
335 #[track_caller]
336 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
337 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
338 }
339
340 #[inline]
341 #[track_caller]
342 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
343 self.parent(id.into().to_def_id()).expect_local()
344 }
345
346 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
347 if descendant.krate != ancestor.krate {
348 return false;
349 }
350
351 while descendant != ancestor {
352 match self.opt_parent(descendant) {
353 Some(parent) => descendant = parent,
354 None => return false,
355 }
356 }
357 true
358 }
359}
360
361impl<Id> Visibility<Id> {
362 pub fn is_public(self) -> bool {
363 matches!(self, Visibility::Public)
364 }
365
366 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
367 match self {
368 Visibility::Public => Visibility::Public,
369 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
370 }
371 }
372}
373
374impl<Id: Into<DefId>> Visibility<Id> {
375 pub fn to_def_id(self) -> Visibility<DefId> {
376 self.map_id(Into::into)
377 }
378
379 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
381 match self {
382 Visibility::Public => true,
384 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
385 }
386 }
387
388 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
390 match vis {
391 Visibility::Public => self.is_public(),
392 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
393 }
394 }
395}
396
397impl Visibility<DefId> {
398 pub fn expect_local(self) -> Visibility {
399 self.map_id(|id| id.expect_local())
400 }
401
402 pub fn is_visible_locally(self) -> bool {
404 match self {
405 Visibility::Public => true,
406 Visibility::Restricted(def_id) => def_id.is_local(),
407 }
408 }
409}
410
411#[derive(HashStable, Debug)]
418pub struct CrateVariancesMap<'tcx> {
419 pub variances: DefIdMap<&'tcx [ty::Variance]>,
423}
424
425#[derive(Copy, Clone, PartialEq, Eq, Hash)]
428pub struct CReaderCacheKey {
429 pub cnum: Option<CrateNum>,
430 pub pos: usize,
431}
432
433#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
435#[rustc_diagnostic_item = "Ty"]
436#[rustc_pass_by_value]
437pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
438
439impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
440 type Kind = TyKind<'tcx>;
441
442 fn kind(self) -> TyKind<'tcx> {
443 *self.kind()
444 }
445}
446
447impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
448 fn flags(&self) -> TypeFlags {
449 self.0.flags
450 }
451
452 fn outer_exclusive_binder(&self) -> DebruijnIndex {
453 self.0.outer_exclusive_binder
454 }
455}
456
457#[derive(HashStable, Debug)]
464pub struct CratePredicatesMap<'tcx> {
465 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
469}
470
471#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
472pub struct Term<'tcx> {
473 ptr: NonNull<()>,
474 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
475}
476
477impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
478
479impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
480 type Kind = TermKind<'tcx>;
481
482 fn kind(self) -> Self::Kind {
483 self.kind()
484 }
485}
486
487unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
488 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
489{
490}
491unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
492 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
493{
494}
495unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
496unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
497
498impl Debug for Term<'_> {
499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 match self.kind() {
501 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
502 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
503 }
504 }
505}
506
507impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
508 fn from(ty: Ty<'tcx>) -> Self {
509 TermKind::Ty(ty).pack()
510 }
511}
512
513impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
514 fn from(c: Const<'tcx>) -> Self {
515 TermKind::Const(c).pack()
516 }
517}
518
519impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
520 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
521 self.kind().hash_stable(hcx, hasher);
522 }
523}
524
525impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
526 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
527 self,
528 folder: &mut F,
529 ) -> Result<Self, F::Error> {
530 match self.kind() {
531 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
532 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
533 }
534 }
535
536 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
537 match self.kind() {
538 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
539 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
540 }
541 }
542}
543
544impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
545 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
546 match self.kind() {
547 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
548 ty::TermKind::Const(ct) => ct.visit_with(visitor),
549 }
550 }
551}
552
553impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
554 fn encode(&self, e: &mut E) {
555 self.kind().encode(e)
556 }
557}
558
559impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
560 fn decode(d: &mut D) -> Self {
561 let res: TermKind<'tcx> = Decodable::decode(d);
562 res.pack()
563 }
564}
565
566impl<'tcx> Term<'tcx> {
567 #[inline]
568 pub fn kind(self) -> TermKind<'tcx> {
569 let ptr =
570 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
571 unsafe {
575 match self.ptr.addr().get() & TAG_MASK {
576 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
577 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
578 ))),
579 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
580 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
581 ))),
582 _ => core::intrinsics::unreachable(),
583 }
584 }
585 }
586
587 pub fn as_type(&self) -> Option<Ty<'tcx>> {
588 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
589 }
590
591 pub fn expect_type(&self) -> Ty<'tcx> {
592 self.as_type().expect("expected a type, but found a const")
593 }
594
595 pub fn as_const(&self) -> Option<Const<'tcx>> {
596 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
597 }
598
599 pub fn expect_const(&self) -> Const<'tcx> {
600 self.as_const().expect("expected a const, but found a type")
601 }
602
603 pub fn into_arg(self) -> GenericArg<'tcx> {
604 match self.kind() {
605 TermKind::Ty(ty) => ty.into(),
606 TermKind::Const(c) => c.into(),
607 }
608 }
609
610 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
611 match self.kind() {
612 TermKind::Ty(ty) => match *ty.kind() {
613 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
614 _ => None,
615 },
616 TermKind::Const(ct) => match ct.kind() {
617 ConstKind::Unevaluated(uv) => Some(uv.into()),
618 _ => None,
619 },
620 }
621 }
622
623 pub fn is_infer(&self) -> bool {
624 match self.kind() {
625 TermKind::Ty(ty) => ty.is_ty_var(),
626 TermKind::Const(ct) => ct.is_ct_infer(),
627 }
628 }
629
630 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
631 match self.kind() {
632 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
633 TermKind::Const(ct) => ct.is_trivially_wf(),
634 }
635 }
636
637 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
648 TypeWalker::new(self.into())
649 }
650}
651
652const TAG_MASK: usize = 0b11;
653const TYPE_TAG: usize = 0b00;
654const CONST_TAG: usize = 0b01;
655
656#[extension(pub trait TermKindPackExt<'tcx>)]
657impl<'tcx> TermKind<'tcx> {
658 #[inline]
659 fn pack(self) -> Term<'tcx> {
660 let (tag, ptr) = match self {
661 TermKind::Ty(ty) => {
662 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
664 (TYPE_TAG, NonNull::from(ty.0.0).cast())
665 }
666 TermKind::Const(ct) => {
667 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
669 (CONST_TAG, NonNull::from(ct.0.0).cast())
670 }
671 };
672
673 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
674 }
675}
676
677#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
697pub struct InstantiatedPredicates<'tcx> {
698 pub predicates: Vec<Clause<'tcx>>,
699 pub spans: Vec<Span>,
700}
701
702impl<'tcx> InstantiatedPredicates<'tcx> {
703 pub fn empty() -> InstantiatedPredicates<'tcx> {
704 InstantiatedPredicates { predicates: vec![], spans: vec![] }
705 }
706
707 pub fn is_empty(&self) -> bool {
708 self.predicates.is_empty()
709 }
710
711 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
712 self.into_iter()
713 }
714}
715
716impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
717 type Item = (Clause<'tcx>, Span);
718
719 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
720
721 fn into_iter(self) -> Self::IntoIter {
722 debug_assert_eq!(self.predicates.len(), self.spans.len());
723 std::iter::zip(self.predicates, self.spans)
724 }
725}
726
727impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
728 type Item = (Clause<'tcx>, Span);
729
730 type IntoIter = std::iter::Zip<
731 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
732 std::iter::Copied<std::slice::Iter<'a, Span>>,
733 >;
734
735 fn into_iter(self) -> Self::IntoIter {
736 debug_assert_eq!(self.predicates.len(), self.spans.len());
737 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
738 }
739}
740
741#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
742pub struct ProvisionalHiddenType<'tcx> {
743 pub span: Span,
757
758 pub ty: Ty<'tcx>,
771}
772
773#[derive(Debug, Clone, Copy)]
775pub enum DefiningScopeKind {
776 HirTypeck,
781 MirBorrowck,
782}
783
784impl<'tcx> ProvisionalHiddenType<'tcx> {
785 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> ProvisionalHiddenType<'tcx> {
786 ProvisionalHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
787 }
788
789 pub fn build_mismatch_error(
790 &self,
791 other: &Self,
792 tcx: TyCtxt<'tcx>,
793 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
794 (self.ty, other.ty).error_reported()?;
795 let sub_diag = if self.span == other.span {
797 TypeMismatchReason::ConflictType { span: self.span }
798 } else {
799 TypeMismatchReason::PreviousUse { span: self.span }
800 };
801 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
802 self_ty: self.ty,
803 other_ty: other.ty,
804 other_span: other.span,
805 sub: sub_diag,
806 }))
807 }
808
809 #[instrument(level = "debug", skip(tcx), ret)]
810 pub fn remap_generic_params_to_declaration_params(
811 self,
812 opaque_type_key: OpaqueTypeKey<'tcx>,
813 tcx: TyCtxt<'tcx>,
814 defining_scope_kind: DefiningScopeKind,
815 ) -> DefinitionSiteHiddenType<'tcx> {
816 let OpaqueTypeKey { def_id, args } = opaque_type_key;
817
818 let id_args = GenericArgs::identity_for_item(tcx, def_id);
825 debug!(?id_args);
826
827 let map = args.iter().zip(id_args).collect();
831 debug!("map = {:#?}", map);
832
833 let ty = match defining_scope_kind {
839 DefiningScopeKind::HirTypeck => {
840 fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
841 }
842 DefiningScopeKind::MirBorrowck => self.ty,
843 };
844 let result_ty = ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
845 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
846 assert_eq!(result_ty, fold_regions(tcx, result_ty, |_, _| tcx.lifetimes.re_erased));
847 }
848 DefinitionSiteHiddenType { span: self.span, ty: ty::EarlyBinder::bind(result_ty) }
849 }
850}
851
852#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
853pub struct DefinitionSiteHiddenType<'tcx> {
854 pub span: Span,
867
868 pub ty: ty::EarlyBinder<'tcx, Ty<'tcx>>,
870}
871
872impl<'tcx> DefinitionSiteHiddenType<'tcx> {
873 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> DefinitionSiteHiddenType<'tcx> {
874 DefinitionSiteHiddenType {
875 span: DUMMY_SP,
876 ty: ty::EarlyBinder::bind(Ty::new_error(tcx, guar)),
877 }
878 }
879
880 pub fn build_mismatch_error(
881 &self,
882 other: &Self,
883 tcx: TyCtxt<'tcx>,
884 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
885 let self_ty = self.ty.instantiate_identity();
886 let other_ty = other.ty.instantiate_identity();
887 (self_ty, other_ty).error_reported()?;
888 let sub_diag = if self.span == other.span {
890 TypeMismatchReason::ConflictType { span: self.span }
891 } else {
892 TypeMismatchReason::PreviousUse { span: self.span }
893 };
894 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
895 self_ty,
896 other_ty,
897 other_span: other.span,
898 sub: sub_diag,
899 }))
900 }
901}
902
903pub type PlaceholderRegion<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundRegion>;
904
905impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion<'tcx> {
906 type Bound = BoundRegion;
907
908 fn universe(self) -> UniverseIndex {
909 self.universe
910 }
911
912 fn var(self) -> BoundVar {
913 self.bound.var
914 }
915
916 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
917 ty::Placeholder::new(ui, self.bound)
918 }
919
920 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
921 ty::Placeholder::new(ui, bound)
922 }
923
924 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
925 ty::Placeholder::new(ui, BoundRegion { var, kind: BoundRegionKind::Anon })
926 }
927}
928
929pub type PlaceholderType<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundTy>;
930
931impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType<'tcx> {
932 type Bound = BoundTy;
933
934 fn universe(self) -> UniverseIndex {
935 self.universe
936 }
937
938 fn var(self) -> BoundVar {
939 self.bound.var
940 }
941
942 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
943 ty::Placeholder::new(ui, self.bound)
944 }
945
946 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
947 ty::Placeholder::new(ui, bound)
948 }
949
950 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
951 ty::Placeholder::new(ui, BoundTy { var, kind: BoundTyKind::Anon })
952 }
953}
954
955#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
956#[derive(TyEncodable, TyDecodable)]
957pub struct BoundConst {
958 pub var: BoundVar,
959}
960
961impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
962 fn var(self) -> BoundVar {
963 self.var
964 }
965
966 fn assert_eq(self, var: ty::BoundVariableKind) {
967 var.expect_const()
968 }
969}
970
971pub type PlaceholderConst<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundConst>;
972
973impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst<'tcx> {
974 type Bound = BoundConst;
975
976 fn universe(self) -> UniverseIndex {
977 self.universe
978 }
979
980 fn var(self) -> BoundVar {
981 self.bound.var
982 }
983
984 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
985 ty::Placeholder::new(ui, self.bound)
986 }
987
988 fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
989 ty::Placeholder::new(ui, bound)
990 }
991
992 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
993 ty::Placeholder::new(ui, BoundConst { var })
994 }
995}
996
997pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
998
999impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
1000 fn flags(&self) -> TypeFlags {
1001 (**self).flags()
1002 }
1003
1004 fn outer_exclusive_binder(&self) -> DebruijnIndex {
1005 (**self).outer_exclusive_binder()
1006 }
1007}
1008
1009#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1015#[derive(HashStable, TypeVisitable, TypeFoldable)]
1016pub struct ParamEnv<'tcx> {
1017 caller_bounds: Clauses<'tcx>,
1023}
1024
1025impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1026 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
1027 self.caller_bounds()
1028 }
1029}
1030
1031impl<'tcx> ParamEnv<'tcx> {
1032 #[inline]
1039 pub fn empty() -> Self {
1040 Self::new(ListWithCachedTypeInfo::empty())
1041 }
1042
1043 #[inline]
1044 pub fn caller_bounds(self) -> Clauses<'tcx> {
1045 self.caller_bounds
1046 }
1047
1048 #[inline]
1050 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1051 ParamEnv { caller_bounds }
1052 }
1053
1054 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1056 ParamEnvAnd { param_env: self, value }
1057 }
1058}
1059
1060#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1061#[derive(HashStable)]
1062pub struct ParamEnvAnd<'tcx, T> {
1063 pub param_env: ParamEnv<'tcx>,
1064 pub value: T,
1065}
1066
1067#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1078#[derive(TypeVisitable, TypeFoldable)]
1079pub struct TypingEnv<'tcx> {
1080 #[type_foldable(identity)]
1081 #[type_visitable(ignore)]
1082 pub typing_mode: TypingMode<'tcx>,
1083 pub param_env: ParamEnv<'tcx>,
1084}
1085
1086impl<'tcx> TypingEnv<'tcx> {
1087 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1095 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1096 }
1097
1098 pub fn non_body_analysis(
1104 tcx: TyCtxt<'tcx>,
1105 def_id: impl IntoQueryParam<DefId>,
1106 ) -> TypingEnv<'tcx> {
1107 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1108 }
1109
1110 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1111 tcx.typing_env_normalized_for_post_analysis(def_id)
1112 }
1113
1114 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1117 let TypingEnv { typing_mode, param_env } = self;
1118 if let TypingMode::PostAnalysis = typing_mode {
1119 return self;
1120 }
1121
1122 let param_env = if tcx.next_trait_solver_globally() {
1125 param_env
1126 } else {
1127 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1128 };
1129 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1130 }
1131
1132 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1137 where
1138 T: TypeVisitable<TyCtxt<'tcx>>,
1139 {
1140 PseudoCanonicalInput { typing_env: self, value }
1153 }
1154}
1155
1156#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1166#[derive(HashStable, TypeVisitable, TypeFoldable)]
1167pub struct PseudoCanonicalInput<'tcx, T> {
1168 pub typing_env: TypingEnv<'tcx>,
1169 pub value: T,
1170}
1171
1172#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1173pub struct Destructor {
1174 pub did: DefId,
1176}
1177
1178#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1180pub struct AsyncDestructor {
1181 pub impl_did: DefId,
1183}
1184
1185#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1186pub struct VariantFlags(u8);
1187bitflags::bitflags! {
1188 impl VariantFlags: u8 {
1189 const NO_VARIANT_FLAGS = 0;
1190 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1192 }
1193}
1194rustc_data_structures::external_bitflags_debug! { VariantFlags }
1195
1196#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1198pub struct VariantDef {
1199 pub def_id: DefId,
1202 pub ctor: Option<(CtorKind, DefId)>,
1205 pub name: Symbol,
1207 pub discr: VariantDiscr,
1209 pub fields: IndexVec<FieldIdx, FieldDef>,
1211 tainted: Option<ErrorGuaranteed>,
1213 flags: VariantFlags,
1215}
1216
1217impl VariantDef {
1218 #[instrument(level = "debug")]
1235 pub fn new(
1236 name: Symbol,
1237 variant_did: Option<DefId>,
1238 ctor: Option<(CtorKind, DefId)>,
1239 discr: VariantDiscr,
1240 fields: IndexVec<FieldIdx, FieldDef>,
1241 parent_did: DefId,
1242 recover_tainted: Option<ErrorGuaranteed>,
1243 is_field_list_non_exhaustive: bool,
1244 ) -> Self {
1245 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1246 if is_field_list_non_exhaustive {
1247 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1248 }
1249
1250 VariantDef {
1251 def_id: variant_did.unwrap_or(parent_did),
1252 ctor,
1253 name,
1254 discr,
1255 fields,
1256 flags,
1257 tainted: recover_tainted,
1258 }
1259 }
1260
1261 #[inline]
1267 pub fn is_field_list_non_exhaustive(&self) -> bool {
1268 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1269 }
1270
1271 #[inline]
1274 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1275 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1276 }
1277
1278 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1280 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1281 }
1282
1283 #[inline]
1285 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1286 self.tainted.map_or(Ok(()), Err)
1287 }
1288
1289 #[inline]
1290 pub fn ctor_kind(&self) -> Option<CtorKind> {
1291 self.ctor.map(|(kind, _)| kind)
1292 }
1293
1294 #[inline]
1295 pub fn ctor_def_id(&self) -> Option<DefId> {
1296 self.ctor.map(|(_, def_id)| def_id)
1297 }
1298
1299 #[inline]
1303 pub fn single_field(&self) -> &FieldDef {
1304 assert!(self.fields.len() == 1);
1305
1306 &self.fields[FieldIdx::ZERO]
1307 }
1308
1309 #[inline]
1311 pub fn tail_opt(&self) -> Option<&FieldDef> {
1312 self.fields.raw.last()
1313 }
1314
1315 #[inline]
1321 pub fn tail(&self) -> &FieldDef {
1322 self.tail_opt().expect("expected unsized ADT to have a tail field")
1323 }
1324
1325 pub fn has_unsafe_fields(&self) -> bool {
1327 self.fields.iter().any(|x| x.safety.is_unsafe())
1328 }
1329}
1330
1331impl PartialEq for VariantDef {
1332 #[inline]
1333 fn eq(&self, other: &Self) -> bool {
1334 let Self {
1342 def_id: lhs_def_id,
1343 ctor: _,
1344 name: _,
1345 discr: _,
1346 fields: _,
1347 flags: _,
1348 tainted: _,
1349 } = &self;
1350 let Self {
1351 def_id: rhs_def_id,
1352 ctor: _,
1353 name: _,
1354 discr: _,
1355 fields: _,
1356 flags: _,
1357 tainted: _,
1358 } = other;
1359
1360 let res = lhs_def_id == rhs_def_id;
1361
1362 if cfg!(debug_assertions) && res {
1364 let deep = self.ctor == other.ctor
1365 && self.name == other.name
1366 && self.discr == other.discr
1367 && self.fields == other.fields
1368 && self.flags == other.flags;
1369 assert!(deep, "VariantDef for the same def-id has differing data");
1370 }
1371
1372 res
1373 }
1374}
1375
1376impl Eq for VariantDef {}
1377
1378impl Hash for VariantDef {
1379 #[inline]
1380 fn hash<H: Hasher>(&self, s: &mut H) {
1381 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1389 def_id.hash(s)
1390 }
1391}
1392
1393#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1394pub enum VariantDiscr {
1395 Explicit(DefId),
1398
1399 Relative(u32),
1404}
1405
1406#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1407pub struct FieldDef {
1408 pub did: DefId,
1409 pub name: Symbol,
1410 pub vis: Visibility<DefId>,
1411 pub safety: hir::Safety,
1412 pub value: Option<DefId>,
1413}
1414
1415impl PartialEq for FieldDef {
1416 #[inline]
1417 fn eq(&self, other: &Self) -> bool {
1418 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1426
1427 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1428
1429 let res = lhs_did == rhs_did;
1430
1431 if cfg!(debug_assertions) && res {
1433 let deep =
1434 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1435 assert!(deep, "FieldDef for the same def-id has differing data");
1436 }
1437
1438 res
1439 }
1440}
1441
1442impl Eq for FieldDef {}
1443
1444impl Hash for FieldDef {
1445 #[inline]
1446 fn hash<H: Hasher>(&self, s: &mut H) {
1447 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1455
1456 did.hash(s)
1457 }
1458}
1459
1460impl<'tcx> FieldDef {
1461 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1464 tcx.type_of(self.did).instantiate(tcx, args)
1465 }
1466
1467 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1469 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1470 }
1471}
1472
1473#[derive(Debug, PartialEq, Eq)]
1474pub enum ImplOverlapKind {
1475 Permitted {
1477 marker: bool,
1479 },
1480}
1481
1482#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1485pub enum ImplTraitInTraitData {
1486 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1487 Impl { fn_def_id: DefId },
1488}
1489
1490impl<'tcx> TyCtxt<'tcx> {
1491 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1492 self.typeck(self.hir_body_owner_def_id(body))
1493 }
1494
1495 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1496 self.associated_items(id)
1497 .in_definition_order()
1498 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1499 }
1500
1501 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1502 let mut flags = ReprFlags::empty();
1503 let mut size = None;
1504 let mut max_align: Option<Align> = None;
1505 let mut min_pack: Option<Align> = None;
1506
1507 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1510
1511 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1515 field_shuffle_seed ^= user_seed;
1516 }
1517
1518 let attributes = self.get_all_attrs(did);
1519 let elt = find_attr!(
1520 attributes,
1521 AttributeKind::RustcScalableVector { element_count, .. } => element_count
1522 )
1523 .map(|elt| match elt {
1524 Some(n) => ScalableElt::ElementCount(*n),
1525 None => ScalableElt::Container,
1526 });
1527 if elt.is_some() {
1528 flags.insert(ReprFlags::IS_SCALABLE);
1529 }
1530 if let Some(reprs) = find_attr!(attributes, AttributeKind::Repr { reprs, .. } => reprs) {
1531 for (r, _) in reprs {
1532 flags.insert(match *r {
1533 attr::ReprRust => ReprFlags::empty(),
1534 attr::ReprC => ReprFlags::IS_C,
1535 attr::ReprPacked(pack) => {
1536 min_pack = Some(if let Some(min_pack) = min_pack {
1537 min_pack.min(pack)
1538 } else {
1539 pack
1540 });
1541 ReprFlags::empty()
1542 }
1543 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1544 attr::ReprSimd => ReprFlags::IS_SIMD,
1545 attr::ReprInt(i) => {
1546 size = Some(match i {
1547 attr::IntType::SignedInt(x) => match x {
1548 ast::IntTy::Isize => IntegerType::Pointer(true),
1549 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1550 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1551 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1552 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1553 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1554 },
1555 attr::IntType::UnsignedInt(x) => match x {
1556 ast::UintTy::Usize => IntegerType::Pointer(false),
1557 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1558 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1559 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1560 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1561 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1562 },
1563 });
1564 ReprFlags::empty()
1565 }
1566 attr::ReprAlign(align) => {
1567 max_align = max_align.max(Some(align));
1568 ReprFlags::empty()
1569 }
1570 });
1571 }
1572 }
1573
1574 if self.sess.opts.unstable_opts.randomize_layout {
1577 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1578 }
1579
1580 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1583
1584 if is_box {
1586 flags.insert(ReprFlags::IS_LINEAR);
1587 }
1588
1589 if find_attr!(attributes, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) {
1591 flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1592 }
1593
1594 ReprOptions {
1595 int: size,
1596 align: max_align,
1597 pack: min_pack,
1598 flags,
1599 field_shuffle_seed,
1600 scalable: elt,
1601 }
1602 }
1603
1604 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1606 let def_id = def_id.into_query_param();
1607 if let Some(cnum) = def_id.as_crate_root() {
1608 Some(self.crate_name(cnum))
1609 } else {
1610 let def_key = self.def_key(def_id);
1611 match def_key.disambiguated_data.data {
1612 rustc_hir::definitions::DefPathData::Ctor => self
1614 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1615 _ => def_key.get_opt_name(),
1616 }
1617 }
1618 }
1619
1620 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1627 let id = id.into_query_param();
1628 self.opt_item_name(id).unwrap_or_else(|| {
1629 bug!("item_name: no name for {:?}", self.def_path(id));
1630 })
1631 }
1632
1633 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1637 let def_id = def_id.into_query_param();
1638 let def = self.opt_item_name(def_id)?;
1639 let span = self
1640 .def_ident_span(def_id)
1641 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1642 Some(Ident::new(def, span))
1643 }
1644
1645 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1649 let def_id = def_id.into_query_param();
1650 self.opt_item_ident(def_id).unwrap_or_else(|| {
1651 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1652 })
1653 }
1654
1655 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1656 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1657 Some(self.associated_item(def_id))
1658 } else {
1659 None
1660 }
1661 }
1662
1663 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1667 if let DefKind::AssocTy = self.def_kind(def_id)
1668 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1669 self.associated_item(def_id).kind
1670 {
1671 Some(rpitit_info)
1672 } else {
1673 None
1674 }
1675 }
1676
1677 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1678 variant.fields.iter_enumerated().find_map(|(i, field)| {
1679 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1680 })
1681 }
1682
1683 #[instrument(level = "debug", skip(self), ret)]
1686 pub fn impls_are_allowed_to_overlap(
1687 self,
1688 def_id1: DefId,
1689 def_id2: DefId,
1690 ) -> Option<ImplOverlapKind> {
1691 let impl1 = self.impl_trait_header(def_id1);
1692 let impl2 = self.impl_trait_header(def_id2);
1693
1694 let trait_ref1 = impl1.trait_ref.skip_binder();
1695 let trait_ref2 = impl2.trait_ref.skip_binder();
1696
1697 if trait_ref1.references_error() || trait_ref2.references_error() {
1700 return Some(ImplOverlapKind::Permitted { marker: false });
1701 }
1702
1703 match (impl1.polarity, impl2.polarity) {
1704 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1705 return Some(ImplOverlapKind::Permitted { marker: false });
1707 }
1708 (ImplPolarity::Positive, ImplPolarity::Negative)
1709 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1710 return None;
1712 }
1713 (ImplPolarity::Positive, ImplPolarity::Positive)
1714 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1715 };
1716
1717 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1718 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1719
1720 if is_marker_overlap {
1721 return Some(ImplOverlapKind::Permitted { marker: true });
1722 }
1723
1724 None
1725 }
1726
1727 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1730 match res {
1731 Res::Def(DefKind::Variant, did) => {
1732 let enum_did = self.parent(did);
1733 self.adt_def(enum_did).variant_with_id(did)
1734 }
1735 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1736 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1737 let variant_did = self.parent(variant_ctor_did);
1738 let enum_did = self.parent(variant_did);
1739 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1740 }
1741 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1742 let struct_did = self.parent(ctor_did);
1743 self.adt_def(struct_did).non_enum_variant()
1744 }
1745 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1746 }
1747 }
1748
1749 #[instrument(skip(self), level = "debug")]
1751 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1752 match instance {
1753 ty::InstanceKind::Item(def) => {
1754 debug!("calling def_kind on def: {:?}", def);
1755 let def_kind = self.def_kind(def);
1756 debug!("returned from def_kind: {:?}", def_kind);
1757 match def_kind {
1758 DefKind::Const
1759 | DefKind::Static { .. }
1760 | DefKind::AssocConst
1761 | DefKind::Ctor(..)
1762 | DefKind::AnonConst
1763 | DefKind::InlineConst => self.mir_for_ctfe(def),
1764 _ => self.optimized_mir(def),
1767 }
1768 }
1769 ty::InstanceKind::VTableShim(..)
1770 | ty::InstanceKind::ReifyShim(..)
1771 | ty::InstanceKind::Intrinsic(..)
1772 | ty::InstanceKind::FnPtrShim(..)
1773 | ty::InstanceKind::Virtual(..)
1774 | ty::InstanceKind::ClosureOnceShim { .. }
1775 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1776 | ty::InstanceKind::FutureDropPollShim(..)
1777 | ty::InstanceKind::DropGlue(..)
1778 | ty::InstanceKind::CloneShim(..)
1779 | ty::InstanceKind::ThreadLocalShim(..)
1780 | ty::InstanceKind::FnPtrAddrShim(..)
1781 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1782 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1783 }
1784 }
1785
1786 pub fn get_attrs(
1788 self,
1789 did: impl Into<DefId>,
1790 attr: Symbol,
1791 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1792 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1793 }
1794
1795 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1800 let did: DefId = did.into();
1801 if let Some(did) = did.as_local() {
1802 self.hir_attrs(self.local_def_id_to_hir_id(did))
1803 } else {
1804 self.attrs_for_def(did)
1805 }
1806 }
1807
1808 pub fn get_diagnostic_attr(
1817 self,
1818 did: impl Into<DefId>,
1819 attr: Symbol,
1820 ) -> Option<&'tcx hir::Attribute> {
1821 let did: DefId = did.into();
1822 if did.as_local().is_some() {
1823 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1825 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1826 } else {
1827 None
1828 }
1829 } else {
1830 debug_assert!(rustc_feature::encode_cross_crate(attr));
1833 self.attrs_for_def(did)
1834 .iter()
1835 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1836 }
1837 }
1838
1839 pub fn get_attrs_by_path(
1840 self,
1841 did: DefId,
1842 attr: &[Symbol],
1843 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1844 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1845 if let Some(did) = did.as_local() {
1846 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1847 } else {
1848 self.attrs_for_def(did).iter().filter(filter_fn)
1849 }
1850 }
1851
1852 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1853 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1854 let did: DefId = did.into();
1855 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1856 } else {
1857 self.get_attrs(did, attr).next()
1858 }
1859 }
1860
1861 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1863 self.get_attrs(did, attr).next().is_some()
1864 }
1865
1866 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1868 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1869 }
1870
1871 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1873 self.trait_def(trait_def_id).has_auto_impl
1874 }
1875
1876 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1879 self.trait_def(trait_def_id).is_coinductive
1880 }
1881
1882 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1884 self.def_kind(trait_def_id) == DefKind::TraitAlias
1885 }
1886
1887 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1889 self.arena.alloc(err)
1890 }
1891
1892 fn ordinary_coroutine_layout(
1898 self,
1899 def_id: DefId,
1900 args: GenericArgsRef<'tcx>,
1901 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1902 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1903 let mir = self.optimized_mir(def_id);
1904 let ty = || Ty::new_coroutine(self, def_id, args);
1905 if coroutine_kind_ty.is_unit() {
1907 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1908 } else {
1909 let ty::Coroutine(_, identity_args) =
1912 *self.type_of(def_id).instantiate_identity().kind()
1913 else {
1914 unreachable!();
1915 };
1916 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1917 if identity_kind_ty == coroutine_kind_ty {
1920 mir.coroutine_layout_raw()
1921 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1922 } else {
1923 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1924 assert_matches!(
1925 identity_kind_ty.to_opt_closure_kind(),
1926 Some(ClosureKind::Fn | ClosureKind::FnMut)
1927 );
1928 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1929 .coroutine_layout_raw()
1930 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1931 }
1932 }
1933 }
1934
1935 fn async_drop_coroutine_layout(
1939 self,
1940 def_id: DefId,
1941 args: GenericArgsRef<'tcx>,
1942 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1943 let ty = || Ty::new_coroutine(self, def_id, args);
1944 if args[0].has_placeholders() || args[0].has_non_region_param() {
1945 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1946 }
1947 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1948 self.mir_shims(instance)
1949 .coroutine_layout_raw()
1950 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1951 }
1952
1953 pub fn coroutine_layout(
1956 self,
1957 def_id: DefId,
1958 args: GenericArgsRef<'tcx>,
1959 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1960 if self.is_async_drop_in_place_coroutine(def_id) {
1961 let arg_cor_ty = args.first().unwrap().expect_ty();
1965 if arg_cor_ty.is_coroutine() {
1966 let span = self.def_span(def_id);
1967 let source_info = SourceInfo::outermost(span);
1968 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1971 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1972 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1973 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1974 let proxy_layout = CoroutineLayout {
1975 field_tys: [].into(),
1976 field_names: [].into(),
1977 variant_fields,
1978 variant_source_info,
1979 storage_conflicts: BitMatrix::new(0, 0),
1980 };
1981 return Ok(self.arena.alloc(proxy_layout));
1982 } else {
1983 self.async_drop_coroutine_layout(def_id, args)
1984 }
1985 } else {
1986 self.ordinary_coroutine_layout(def_id, args)
1987 }
1988 }
1989
1990 pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1992 if !self.def_kind(def_id).is_assoc() {
1993 return None;
1994 }
1995 let parent = self.parent(def_id);
1996 let def_kind = self.def_kind(parent);
1997 Some((parent, def_kind))
1998 }
1999
2000 pub fn trait_item_of(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2002 self.opt_associated_item(def_id.into_query_param())?.trait_item_def_id()
2003 }
2004
2005 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
2008 match self.assoc_parent(def_id) {
2009 Some((id, DefKind::Trait)) => Some(id),
2010 _ => None,
2011 }
2012 }
2013
2014 pub fn impl_is_of_trait(self, def_id: impl IntoQueryParam<DefId>) -> bool {
2015 let def_id = def_id.into_query_param();
2016 let DefKind::Impl { of_trait } = self.def_kind(def_id) else {
2017 panic!("expected Impl for {def_id:?}");
2018 };
2019 of_trait
2020 }
2021
2022 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2025 match self.assoc_parent(def_id) {
2026 Some((id, DefKind::Impl { .. })) => Some(id),
2027 _ => None,
2028 }
2029 }
2030
2031 pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2034 match self.assoc_parent(def_id) {
2035 Some((id, DefKind::Impl { of_trait: false })) => Some(id),
2036 _ => None,
2037 }
2038 }
2039
2040 pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2043 match self.assoc_parent(def_id) {
2044 Some((id, DefKind::Impl { of_trait: true })) => Some(id),
2045 _ => None,
2046 }
2047 }
2048
2049 pub fn impl_polarity(self, def_id: impl IntoQueryParam<DefId>) -> ty::ImplPolarity {
2050 self.impl_trait_header(def_id).polarity
2051 }
2052
2053 pub fn impl_trait_ref(
2055 self,
2056 def_id: impl IntoQueryParam<DefId>,
2057 ) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
2058 self.impl_trait_header(def_id).trait_ref
2059 }
2060
2061 pub fn impl_opt_trait_ref(
2064 self,
2065 def_id: impl IntoQueryParam<DefId>,
2066 ) -> Option<ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>> {
2067 let def_id = def_id.into_query_param();
2068 self.impl_is_of_trait(def_id).then(|| self.impl_trait_ref(def_id))
2069 }
2070
2071 pub fn impl_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> DefId {
2073 self.impl_trait_ref(def_id).skip_binder().def_id
2074 }
2075
2076 pub fn impl_opt_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2079 let def_id = def_id.into_query_param();
2080 self.impl_is_of_trait(def_id).then(|| self.impl_trait_id(def_id))
2081 }
2082
2083 pub fn is_exportable(self, def_id: DefId) -> bool {
2084 self.exportable_items(def_id.krate).contains(&def_id)
2085 }
2086
2087 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2090 if self.is_automatically_derived(def_id)
2091 && let Some(def_id) = def_id.as_local()
2092 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2093 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2094 && find_attr!(
2095 self.get_all_attrs(outer.macro_def_id.unwrap()),
2096 AttributeKind::RustcBuiltinMacro { .. }
2097 )
2098 {
2099 true
2100 } else {
2101 false
2102 }
2103 }
2104
2105 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2107 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
2108 }
2109
2110 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2113 if let Some(impl_def_id) = impl_def_id.as_local() {
2114 Ok(self.def_span(impl_def_id))
2115 } else {
2116 Err(self.crate_name(impl_def_id.krate))
2117 }
2118 }
2119
2120 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2124 use_ident.name == def_ident.name
2128 && use_ident
2129 .span
2130 .ctxt()
2131 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2132 }
2133
2134 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2135 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2136 ident
2137 }
2138
2139 pub fn adjust_ident_and_get_scope(
2141 self,
2142 mut ident: Ident,
2143 scope: DefId,
2144 block: hir::HirId,
2145 ) -> (Ident, DefId) {
2146 let scope = ident
2147 .span
2148 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2149 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2150 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2151 (ident, scope)
2152 }
2153
2154 #[inline]
2158 pub fn is_const_fn(self, def_id: DefId) -> bool {
2159 matches!(
2160 self.def_kind(def_id),
2161 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2162 ) && self.constness(def_id) == hir::Constness::Const
2163 }
2164
2165 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2172 let def_id: DefId = def_id.into();
2173 match self.def_kind(def_id) {
2174 DefKind::Impl { of_trait: true } => {
2175 let header = self.impl_trait_header(def_id);
2176 header.constness == hir::Constness::Const
2177 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2178 }
2179 DefKind::Impl { of_trait: false } => self.constness(def_id) == hir::Constness::Const,
2180 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2181 self.constness(def_id) == hir::Constness::Const
2182 }
2183 DefKind::TraitAlias | DefKind::Trait => self.is_const_trait(def_id),
2184 DefKind::AssocTy => {
2185 let parent_def_id = self.parent(def_id);
2186 match self.def_kind(parent_def_id) {
2187 DefKind::Impl { of_trait: false } => false,
2188 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2189 self.is_conditionally_const(parent_def_id)
2190 }
2191 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2192 }
2193 }
2194 DefKind::AssocFn => {
2195 let parent_def_id = self.parent(def_id);
2196 match self.def_kind(parent_def_id) {
2197 DefKind::Impl { of_trait: false } => {
2198 self.constness(def_id) == hir::Constness::Const
2199 }
2200 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2201 self.is_conditionally_const(parent_def_id)
2202 }
2203 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2204 }
2205 }
2206 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2207 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2208 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2209 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2211 },
2212 DefKind::Closure => {
2213 false
2216 }
2217 DefKind::Ctor(_, CtorKind::Const)
2218 | DefKind::Mod
2219 | DefKind::Struct
2220 | DefKind::Union
2221 | DefKind::Enum
2222 | DefKind::Variant
2223 | DefKind::TyAlias
2224 | DefKind::ForeignTy
2225 | DefKind::TyParam
2226 | DefKind::Const
2227 | DefKind::ConstParam
2228 | DefKind::Static { .. }
2229 | DefKind::AssocConst
2230 | DefKind::Macro(_)
2231 | DefKind::ExternCrate
2232 | DefKind::Use
2233 | DefKind::ForeignMod
2234 | DefKind::AnonConst
2235 | DefKind::InlineConst
2236 | DefKind::Field
2237 | DefKind::LifetimeParam
2238 | DefKind::GlobalAsm
2239 | DefKind::SyntheticCoroutineBody => false,
2240 }
2241 }
2242
2243 #[inline]
2244 pub fn is_const_trait(self, def_id: DefId) -> bool {
2245 self.trait_def(def_id).constness == hir::Constness::Const
2246 }
2247
2248 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2249 if self.def_kind(def_id) != DefKind::AssocFn {
2250 return false;
2251 }
2252
2253 let Some(item) = self.opt_associated_item(def_id) else {
2254 return false;
2255 };
2256
2257 let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2258 return false;
2259 };
2260
2261 !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2262 }
2263}
2264
2265pub fn provide(providers: &mut Providers) {
2266 closure::provide(providers);
2267 context::provide(providers);
2268 erase_regions::provide(providers);
2269 inhabitedness::provide(providers);
2270 util::provide(providers);
2271 print::provide(providers);
2272 super::util::bug::provide(providers);
2273 *providers = Providers {
2274 trait_impls_of: trait_def::trait_impls_of_provider,
2275 incoherent_impls: trait_def::incoherent_impls_provider,
2276 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2277 traits: trait_def::traits_provider,
2278 vtable_allocation: vtable::vtable_allocation_provider,
2279 ..*providers
2280 };
2281}
2282
2283#[derive(Clone, Debug, Default, HashStable)]
2289pub struct CrateInherentImpls {
2290 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2291 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2292}
2293
2294#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2295pub struct SymbolName<'tcx> {
2296 pub name: &'tcx str,
2298}
2299
2300impl<'tcx> SymbolName<'tcx> {
2301 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2302 SymbolName { name: tcx.arena.alloc_str(name) }
2303 }
2304}
2305
2306impl<'tcx> fmt::Display for SymbolName<'tcx> {
2307 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2308 fmt::Display::fmt(&self.name, fmt)
2309 }
2310}
2311
2312impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2313 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2314 fmt::Display::fmt(&self.name, fmt)
2315 }
2316}
2317
2318#[derive(Copy, Clone, Debug, HashStable)]
2320pub struct DestructuredConst<'tcx> {
2321 pub variant: Option<VariantIdx>,
2322 pub fields: &'tcx [ty::Const<'tcx>],
2323}
2324
2325pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
2329 if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
2331 return FncTree { args: vec![], ret: TypeTree::new() };
2332 }
2333
2334 if !fn_ty.is_fn() {
2336 return FncTree { args: vec![], ret: TypeTree::new() };
2337 }
2338
2339 let fn_sig = fn_ty.fn_sig(tcx);
2341 let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
2342
2343 let mut args = vec![];
2345 for ty in sig.inputs().iter() {
2346 let type_tree = typetree_from_ty(tcx, *ty);
2347 args.push(type_tree);
2348 }
2349
2350 let ret = typetree_from_ty(tcx, sig.output());
2352
2353 FncTree { args, ret }
2354}
2355
2356pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
2359 let mut visited = Vec::new();
2360 typetree_from_ty_inner(tcx, ty, 0, &mut visited)
2361}
2362
2363const MAX_TYPETREE_DEPTH: usize = 6;
2366
2367fn typetree_from_ty_inner<'tcx>(
2369 tcx: TyCtxt<'tcx>,
2370 ty: Ty<'tcx>,
2371 depth: usize,
2372 visited: &mut Vec<Ty<'tcx>>,
2373) -> TypeTree {
2374 if depth >= MAX_TYPETREE_DEPTH {
2375 trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
2376 return TypeTree::new();
2377 }
2378
2379 if visited.contains(&ty) {
2380 return TypeTree::new();
2381 }
2382
2383 visited.push(ty);
2384 let result = typetree_from_ty_impl(tcx, ty, depth, visited);
2385 visited.pop();
2386 result
2387}
2388
2389fn typetree_from_ty_impl<'tcx>(
2391 tcx: TyCtxt<'tcx>,
2392 ty: Ty<'tcx>,
2393 depth: usize,
2394 visited: &mut Vec<Ty<'tcx>>,
2395) -> TypeTree {
2396 typetree_from_ty_impl_inner(tcx, ty, depth, visited, false)
2397}
2398
2399fn typetree_from_ty_impl_inner<'tcx>(
2401 tcx: TyCtxt<'tcx>,
2402 ty: Ty<'tcx>,
2403 depth: usize,
2404 visited: &mut Vec<Ty<'tcx>>,
2405 is_reference_target: bool,
2406) -> TypeTree {
2407 if ty.is_scalar() {
2408 let (kind, size) = if ty.is_integral() || ty.is_char() || ty.is_bool() {
2409 (Kind::Integer, ty.primitive_size(tcx).bytes_usize())
2410 } else if ty.is_floating_point() {
2411 match ty {
2412 x if x == tcx.types.f16 => (Kind::Half, 2),
2413 x if x == tcx.types.f32 => (Kind::Float, 4),
2414 x if x == tcx.types.f64 => (Kind::Double, 8),
2415 x if x == tcx.types.f128 => (Kind::F128, 16),
2416 _ => (Kind::Integer, 0),
2417 }
2418 } else {
2419 (Kind::Integer, 0)
2420 };
2421
2422 let offset = if is_reference_target && !ty.is_array() { 0 } else { -1 };
2425 return TypeTree(vec![Type { offset, size, kind, child: TypeTree::new() }]);
2426 }
2427
2428 if ty.is_ref() || ty.is_raw_ptr() || ty.is_box() {
2429 let Some(inner_ty) = ty.builtin_deref(true) else {
2430 return TypeTree::new();
2431 };
2432
2433 let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
2434 return TypeTree(vec![Type {
2435 offset: -1,
2436 size: tcx.data_layout.pointer_size().bytes_usize(),
2437 kind: Kind::Pointer,
2438 child,
2439 }]);
2440 }
2441
2442 if ty.is_array() {
2443 if let ty::Array(element_ty, len_const) = ty.kind() {
2444 let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
2445 if len == 0 {
2446 return TypeTree::new();
2447 }
2448 let element_tree =
2449 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2450 let mut types = Vec::new();
2451 for elem_type in &element_tree.0 {
2452 types.push(Type {
2453 offset: -1,
2454 size: elem_type.size,
2455 kind: elem_type.kind,
2456 child: elem_type.child.clone(),
2457 });
2458 }
2459
2460 return TypeTree(types);
2461 }
2462 }
2463
2464 if ty.is_slice() {
2465 if let ty::Slice(element_ty) = ty.kind() {
2466 let element_tree =
2467 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2468 return element_tree;
2469 }
2470 }
2471
2472 if let ty::Tuple(tuple_types) = ty.kind() {
2473 if tuple_types.is_empty() {
2474 return TypeTree::new();
2475 }
2476
2477 let mut types = Vec::new();
2478 let mut current_offset = 0;
2479
2480 for tuple_ty in tuple_types.iter() {
2481 let element_tree =
2482 typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
2483
2484 let element_layout = tcx
2485 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
2486 .ok()
2487 .map(|layout| layout.size.bytes_usize())
2488 .unwrap_or(0);
2489
2490 for elem_type in &element_tree.0 {
2491 types.push(Type {
2492 offset: if elem_type.offset == -1 {
2493 current_offset as isize
2494 } else {
2495 current_offset as isize + elem_type.offset
2496 },
2497 size: elem_type.size,
2498 kind: elem_type.kind,
2499 child: elem_type.child.clone(),
2500 });
2501 }
2502
2503 current_offset += element_layout;
2504 }
2505
2506 return TypeTree(types);
2507 }
2508
2509 if let ty::Adt(adt_def, args) = ty.kind() {
2510 if adt_def.is_struct() {
2511 let struct_layout =
2512 tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
2513 if let Ok(layout) = struct_layout {
2514 let mut types = Vec::new();
2515
2516 for (field_idx, field_def) in adt_def.all_fields().enumerate() {
2517 let field_ty = field_def.ty(tcx, args);
2518 let field_tree =
2519 typetree_from_ty_impl_inner(tcx, field_ty, depth + 1, visited, false);
2520
2521 let field_offset = layout.fields.offset(field_idx).bytes_usize();
2522
2523 for elem_type in &field_tree.0 {
2524 types.push(Type {
2525 offset: if elem_type.offset == -1 {
2526 field_offset as isize
2527 } else {
2528 field_offset as isize + elem_type.offset
2529 },
2530 size: elem_type.size,
2531 kind: elem_type.kind,
2532 child: elem_type.child.clone(),
2533 });
2534 }
2535 }
2536
2537 return TypeTree(types);
2538 }
2539 }
2540 }
2541
2542 TypeTree::new()
2543}