1#![allow(rustc::usage_of_ty_tykind)]
13
14use std::assert_matches::assert_matches;
15use std::fmt::Debug;
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18use std::num::NonZero;
19use std::ptr::NonNull;
20use std::{fmt, iter, str};
21
22pub use adt::*;
23pub use assoc::*;
24pub use generic_args::{GenericArgKind, TermKind, *};
25pub use generics::*;
26pub use intrinsic::IntrinsicDef;
27use rustc_abi::{Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, VariantIdx};
28use rustc_ast::expand::typetree::{FncTree, Kind, Type, TypeTree};
29use rustc_ast::node_id::NodeMap;
30pub use rustc_ast_ir::{Movability, Mutability, try_visit};
31use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
32use rustc_data_structures::intern::Interned;
33use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
34use rustc_data_structures::steal::Steal;
35use rustc_data_structures::unord::{UnordMap, UnordSet};
36use rustc_errors::{Diag, ErrorGuaranteed, LintBuffer};
37use rustc_hir::attrs::{AttributeKind, StrippedCfgItem};
38use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
39use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
40use rustc_hir::{LangItem, attrs as attr, find_attr};
41use rustc_index::IndexVec;
42use rustc_index::bit_set::BitMatrix;
43use rustc_macros::{
44 Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
45 extension,
46};
47use rustc_query_system::ich::StableHashingContext;
48use rustc_serialize::{Decodable, Encodable};
49pub use rustc_session::lint::RegisteredTools;
50use rustc_span::hygiene::MacroKind;
51use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, sym};
52pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
53pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
54#[allow(
55 hidden_glob_reexports,
56 rustc::usage_of_type_ir_inherent,
57 rustc::non_glob_import_of_type_ir_inherent
58)]
59use rustc_type_ir::inherent;
60pub use rustc_type_ir::relate::VarianceDiagInfo;
61pub use rustc_type_ir::solve::{CandidatePreferenceMode, SizedTraitKind};
62pub use rustc_type_ir::*;
63#[allow(hidden_glob_reexports, unused_imports)]
64use rustc_type_ir::{InferCtxtLike, Interner};
65use tracing::{debug, instrument, trace};
66pub use vtable::*;
67use {rustc_ast as ast, rustc_hir as hir};
68
69pub use self::closure::{
70 BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
71 MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
72 UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
73 place_to_string_for_capture,
74};
75pub use self::consts::{
76 AnonConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr,
77 ExprKind, ScalarInt, SimdAlign, UnevaluatedConst, ValTree, ValTreeKind, Value,
78};
79pub use self::context::{
80 CtxtInterners, CurrentGcx, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, tls,
81};
82pub use self::fold::*;
83pub use self::instance::{Instance, InstanceKind, ReifyReason, UnusedGenericParams};
84pub use self::list::{List, ListWithCachedTypeInfo};
85pub use self::opaque_types::OpaqueTypeKey;
86pub use self::pattern::{Pattern, PatternKind};
87pub use self::predicate::{
88 AliasTerm, ArgOutlivesPredicate, Clause, ClauseKind, CoercePredicate, ExistentialPredicate,
89 ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef,
90 HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
91 PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
92 PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
93 PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
94 RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate,
95};
96pub use self::region::{
97 BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
98 RegionKind, RegionVid,
99};
100pub use self::sty::{
101 AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
102 CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
103 ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
104};
105pub use self::trait_def::TraitDef;
106pub use self::typeck_results::{
107 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
108 Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
109};
110use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
111use crate::metadata::ModChild;
112use crate::middle::privacy::EffectiveVisibilities;
113use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
114use crate::query::{IntoQueryParam, Providers};
115use crate::ty;
116use crate::ty::codec::{TyDecoder, TyEncoder};
117pub use crate::ty::diagnostics::*;
118use crate::ty::fast_reject::SimplifiedType;
119use crate::ty::layout::LayoutError;
120use crate::ty::util::Discr;
121use crate::ty::walk::TypeWalker;
122
123pub mod abstract_const;
124pub mod adjustment;
125pub mod cast;
126pub mod codec;
127pub mod error;
128pub mod fast_reject;
129pub mod inhabitedness;
130pub mod layout;
131pub mod normalize_erasing_regions;
132pub mod pattern;
133pub mod print;
134pub mod relate;
135pub mod significant_drop_order;
136pub mod trait_def;
137pub mod util;
138pub mod vtable;
139
140mod adt;
141mod assoc;
142mod closure;
143mod consts;
144mod context;
145mod diagnostics;
146mod elaborate_impl;
147mod erase_regions;
148mod fold;
149mod generic_args;
150mod generics;
151mod impls_ty;
152mod instance;
153mod intrinsic;
154mod list;
155mod opaque_types;
156mod predicate;
157mod region;
158mod structural_impls;
159#[allow(hidden_glob_reexports)]
160mod sty;
161mod typeck_results;
162mod visit;
163
164#[derive(Debug, HashStable)]
167pub struct ResolverGlobalCtxt {
168 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
169 pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
171 pub effective_visibilities: EffectiveVisibilities,
172 pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
173 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
174 pub module_children: LocalDefIdMap<Vec<ModChild>>,
175 pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
176 pub main_def: Option<MainDefinition>,
177 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
178 pub proc_macros: Vec<LocalDefId>,
181 pub confused_type_with_std_module: FxIndexMap<Span, Span>,
184 pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
185 pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
186 pub all_macro_rules: UnordSet<Symbol>,
187 pub stripped_cfg_items: Vec<StrippedCfgItem>,
188}
189
190#[derive(Debug)]
193pub struct ResolverAstLowering {
194 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
195
196 pub partial_res_map: NodeMap<hir::def::PartialRes>,
198 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
200 pub label_res_map: NodeMap<ast::NodeId>,
202 pub lifetimes_res_map: NodeMap<LifetimeRes>,
204 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
206
207 pub next_node_id: ast::NodeId,
208
209 pub node_id_to_def_id: NodeMap<LocalDefId>,
210
211 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
212 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
214
215 pub lint_buffer: Steal<LintBuffer>,
217
218 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
220}
221
222#[derive(Debug)]
223pub struct DelegationFnSig {
224 pub header: ast::FnHeader,
225 pub param_count: usize,
226 pub has_self: bool,
227 pub c_variadic: bool,
228 pub target_feature: bool,
229}
230
231#[derive(Clone, Copy, Debug, HashStable)]
232pub struct MainDefinition {
233 pub res: Res<ast::NodeId>,
234 pub is_import: bool,
235 pub span: Span,
236}
237
238impl MainDefinition {
239 pub fn opt_fn_def_id(self) -> Option<DefId> {
240 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
241 }
242}
243
244#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
245pub struct ImplTraitHeader<'tcx> {
246 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
247 pub polarity: ImplPolarity,
248 pub safety: hir::Safety,
249 pub constness: hir::Constness,
250}
251
252#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
253#[derive(TypeFoldable, TypeVisitable, Default)]
254pub enum Asyncness {
255 Yes,
256 #[default]
257 No,
258}
259
260impl Asyncness {
261 pub fn is_async(self) -> bool {
262 matches!(self, Asyncness::Yes)
263 }
264}
265
266#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
267pub enum Visibility<Id = LocalDefId> {
268 Public,
270 Restricted(Id),
272}
273
274impl Visibility {
275 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
276 match self {
277 ty::Visibility::Restricted(restricted_id) => {
278 if restricted_id.is_top_level_module() {
279 "pub(crate)".to_string()
280 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
281 "pub(self)".to_string()
282 } else {
283 format!(
284 "pub(in crate{})",
285 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
286 )
287 }
288 }
289 ty::Visibility::Public => "pub".to_string(),
290 }
291 }
292}
293
294#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
295#[derive(TypeFoldable, TypeVisitable)]
296pub struct ClosureSizeProfileData<'tcx> {
297 pub before_feature_tys: Ty<'tcx>,
299 pub after_feature_tys: Ty<'tcx>,
301}
302
303impl TyCtxt<'_> {
304 #[inline]
305 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
306 self.def_key(id).parent.map(|index| DefId { index, ..id })
307 }
308
309 #[inline]
310 #[track_caller]
311 pub fn parent(self, id: DefId) -> DefId {
312 match self.opt_parent(id) {
313 Some(id) => id,
314 None => bug!("{id:?} doesn't have a parent"),
316 }
317 }
318
319 #[inline]
320 #[track_caller]
321 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
322 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
323 }
324
325 #[inline]
326 #[track_caller]
327 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
328 self.parent(id.into().to_def_id()).expect_local()
329 }
330
331 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
332 if descendant.krate != ancestor.krate {
333 return false;
334 }
335
336 while descendant != ancestor {
337 match self.opt_parent(descendant) {
338 Some(parent) => descendant = parent,
339 None => return false,
340 }
341 }
342 true
343 }
344}
345
346impl<Id> Visibility<Id> {
347 pub fn is_public(self) -> bool {
348 matches!(self, Visibility::Public)
349 }
350
351 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
352 match self {
353 Visibility::Public => Visibility::Public,
354 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
355 }
356 }
357}
358
359impl<Id: Into<DefId>> Visibility<Id> {
360 pub fn to_def_id(self) -> Visibility<DefId> {
361 self.map_id(Into::into)
362 }
363
364 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
366 match self {
367 Visibility::Public => true,
369 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
370 }
371 }
372
373 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
375 match vis {
376 Visibility::Public => self.is_public(),
377 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
378 }
379 }
380}
381
382impl Visibility<DefId> {
383 pub fn expect_local(self) -> Visibility {
384 self.map_id(|id| id.expect_local())
385 }
386
387 pub fn is_visible_locally(self) -> bool {
389 match self {
390 Visibility::Public => true,
391 Visibility::Restricted(def_id) => def_id.is_local(),
392 }
393 }
394}
395
396#[derive(HashStable, Debug)]
403pub struct CrateVariancesMap<'tcx> {
404 pub variances: DefIdMap<&'tcx [ty::Variance]>,
408}
409
410#[derive(Copy, Clone, PartialEq, Eq, Hash)]
413pub struct CReaderCacheKey {
414 pub cnum: Option<CrateNum>,
415 pub pos: usize,
416}
417
418#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
420#[rustc_diagnostic_item = "Ty"]
421#[rustc_pass_by_value]
422pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
423
424impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
425 type Kind = TyKind<'tcx>;
426
427 fn kind(self) -> TyKind<'tcx> {
428 *self.kind()
429 }
430}
431
432impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
433 fn flags(&self) -> TypeFlags {
434 self.0.flags
435 }
436
437 fn outer_exclusive_binder(&self) -> DebruijnIndex {
438 self.0.outer_exclusive_binder
439 }
440}
441
442#[derive(HashStable, Debug)]
449pub struct CratePredicatesMap<'tcx> {
450 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
454}
455
456#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
457pub struct Term<'tcx> {
458 ptr: NonNull<()>,
459 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
460}
461
462impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
463
464impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
465 type Kind = TermKind<'tcx>;
466
467 fn kind(self) -> Self::Kind {
468 self.kind()
469 }
470}
471
472unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
473 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
474{
475}
476unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
477 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
478{
479}
480unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
481unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
482
483impl Debug for Term<'_> {
484 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485 match self.kind() {
486 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
487 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
488 }
489 }
490}
491
492impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
493 fn from(ty: Ty<'tcx>) -> Self {
494 TermKind::Ty(ty).pack()
495 }
496}
497
498impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
499 fn from(c: Const<'tcx>) -> Self {
500 TermKind::Const(c).pack()
501 }
502}
503
504impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
505 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
506 self.kind().hash_stable(hcx, hasher);
507 }
508}
509
510impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
511 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
512 self,
513 folder: &mut F,
514 ) -> Result<Self, F::Error> {
515 match self.kind() {
516 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
517 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
518 }
519 }
520
521 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
522 match self.kind() {
523 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
524 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
525 }
526 }
527}
528
529impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
530 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
531 match self.kind() {
532 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
533 ty::TermKind::Const(ct) => ct.visit_with(visitor),
534 }
535 }
536}
537
538impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
539 fn encode(&self, e: &mut E) {
540 self.kind().encode(e)
541 }
542}
543
544impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
545 fn decode(d: &mut D) -> Self {
546 let res: TermKind<'tcx> = Decodable::decode(d);
547 res.pack()
548 }
549}
550
551impl<'tcx> Term<'tcx> {
552 #[inline]
553 pub fn kind(self) -> TermKind<'tcx> {
554 let ptr =
555 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
556 unsafe {
560 match self.ptr.addr().get() & TAG_MASK {
561 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
562 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
563 ))),
564 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
565 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
566 ))),
567 _ => core::intrinsics::unreachable(),
568 }
569 }
570 }
571
572 pub fn as_type(&self) -> Option<Ty<'tcx>> {
573 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
574 }
575
576 pub fn expect_type(&self) -> Ty<'tcx> {
577 self.as_type().expect("expected a type, but found a const")
578 }
579
580 pub fn as_const(&self) -> Option<Const<'tcx>> {
581 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
582 }
583
584 pub fn expect_const(&self) -> Const<'tcx> {
585 self.as_const().expect("expected a const, but found a type")
586 }
587
588 pub fn into_arg(self) -> GenericArg<'tcx> {
589 match self.kind() {
590 TermKind::Ty(ty) => ty.into(),
591 TermKind::Const(c) => c.into(),
592 }
593 }
594
595 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
596 match self.kind() {
597 TermKind::Ty(ty) => match *ty.kind() {
598 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
599 _ => None,
600 },
601 TermKind::Const(ct) => match ct.kind() {
602 ConstKind::Unevaluated(uv) => Some(uv.into()),
603 _ => None,
604 },
605 }
606 }
607
608 pub fn is_infer(&self) -> bool {
609 match self.kind() {
610 TermKind::Ty(ty) => ty.is_ty_var(),
611 TermKind::Const(ct) => ct.is_ct_infer(),
612 }
613 }
614
615 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
616 match self.kind() {
617 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
618 TermKind::Const(ct) => ct.is_trivially_wf(),
619 }
620 }
621
622 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
633 TypeWalker::new(self.into())
634 }
635}
636
637const TAG_MASK: usize = 0b11;
638const TYPE_TAG: usize = 0b00;
639const CONST_TAG: usize = 0b01;
640
641#[extension(pub trait TermKindPackExt<'tcx>)]
642impl<'tcx> TermKind<'tcx> {
643 #[inline]
644 fn pack(self) -> Term<'tcx> {
645 let (tag, ptr) = match self {
646 TermKind::Ty(ty) => {
647 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
649 (TYPE_TAG, NonNull::from(ty.0.0).cast())
650 }
651 TermKind::Const(ct) => {
652 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
654 (CONST_TAG, NonNull::from(ct.0.0).cast())
655 }
656 };
657
658 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
659 }
660}
661
662#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
682pub struct InstantiatedPredicates<'tcx> {
683 pub predicates: Vec<Clause<'tcx>>,
684 pub spans: Vec<Span>,
685}
686
687impl<'tcx> InstantiatedPredicates<'tcx> {
688 pub fn empty() -> InstantiatedPredicates<'tcx> {
689 InstantiatedPredicates { predicates: vec![], spans: vec![] }
690 }
691
692 pub fn is_empty(&self) -> bool {
693 self.predicates.is_empty()
694 }
695
696 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
697 self.into_iter()
698 }
699}
700
701impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
702 type Item = (Clause<'tcx>, Span);
703
704 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
705
706 fn into_iter(self) -> Self::IntoIter {
707 debug_assert_eq!(self.predicates.len(), self.spans.len());
708 std::iter::zip(self.predicates, self.spans)
709 }
710}
711
712impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
713 type Item = (Clause<'tcx>, Span);
714
715 type IntoIter = std::iter::Zip<
716 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
717 std::iter::Copied<std::slice::Iter<'a, Span>>,
718 >;
719
720 fn into_iter(self) -> Self::IntoIter {
721 debug_assert_eq!(self.predicates.len(), self.spans.len());
722 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
723 }
724}
725
726#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
727pub struct ProvisionalHiddenType<'tcx> {
728 pub span: Span,
742
743 pub ty: Ty<'tcx>,
756}
757
758#[derive(Debug, Clone, Copy)]
760pub enum DefiningScopeKind {
761 HirTypeck,
766 MirBorrowck,
767}
768
769impl<'tcx> ProvisionalHiddenType<'tcx> {
770 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> ProvisionalHiddenType<'tcx> {
771 ProvisionalHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
772 }
773
774 pub fn build_mismatch_error(
775 &self,
776 other: &Self,
777 tcx: TyCtxt<'tcx>,
778 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
779 (self.ty, other.ty).error_reported()?;
780 let sub_diag = if self.span == other.span {
782 TypeMismatchReason::ConflictType { span: self.span }
783 } else {
784 TypeMismatchReason::PreviousUse { span: self.span }
785 };
786 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
787 self_ty: self.ty,
788 other_ty: other.ty,
789 other_span: other.span,
790 sub: sub_diag,
791 }))
792 }
793
794 #[instrument(level = "debug", skip(tcx), ret)]
795 pub fn remap_generic_params_to_declaration_params(
796 self,
797 opaque_type_key: OpaqueTypeKey<'tcx>,
798 tcx: TyCtxt<'tcx>,
799 defining_scope_kind: DefiningScopeKind,
800 ) -> DefinitionSiteHiddenType<'tcx> {
801 let OpaqueTypeKey { def_id, args } = opaque_type_key;
802
803 let id_args = GenericArgs::identity_for_item(tcx, def_id);
810 debug!(?id_args);
811
812 let map = args.iter().zip(id_args).collect();
816 debug!("map = {:#?}", map);
817
818 let ty = match defining_scope_kind {
824 DefiningScopeKind::HirTypeck => {
825 fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
826 }
827 DefiningScopeKind::MirBorrowck => self.ty,
828 };
829 let result_ty = ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
830 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
831 assert_eq!(result_ty, fold_regions(tcx, result_ty, |_, _| tcx.lifetimes.re_erased));
832 }
833 DefinitionSiteHiddenType { span: self.span, ty: ty::EarlyBinder::bind(result_ty) }
834 }
835}
836
837#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
838pub struct DefinitionSiteHiddenType<'tcx> {
839 pub span: Span,
852
853 pub ty: ty::EarlyBinder<'tcx, Ty<'tcx>>,
855}
856
857impl<'tcx> DefinitionSiteHiddenType<'tcx> {
858 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> DefinitionSiteHiddenType<'tcx> {
859 DefinitionSiteHiddenType {
860 span: DUMMY_SP,
861 ty: ty::EarlyBinder::bind(Ty::new_error(tcx, guar)),
862 }
863 }
864
865 pub fn build_mismatch_error(
866 &self,
867 other: &Self,
868 tcx: TyCtxt<'tcx>,
869 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
870 let self_ty = self.ty.instantiate_identity();
871 let other_ty = other.ty.instantiate_identity();
872 (self_ty, other_ty).error_reported()?;
873 let sub_diag = if self.span == other.span {
875 TypeMismatchReason::ConflictType { span: self.span }
876 } else {
877 TypeMismatchReason::PreviousUse { span: self.span }
878 };
879 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
880 self_ty,
881 other_ty,
882 other_span: other.span,
883 sub: sub_diag,
884 }))
885 }
886}
887
888#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
893#[derive(HashStable, TyEncodable, TyDecodable)]
894pub struct Placeholder<T> {
895 pub universe: UniverseIndex,
896 pub bound: T,
897}
898
899pub type PlaceholderRegion = Placeholder<BoundRegion>;
900
901impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion {
902 type Bound = BoundRegion;
903
904 fn universe(self) -> UniverseIndex {
905 self.universe
906 }
907
908 fn var(self) -> BoundVar {
909 self.bound.var
910 }
911
912 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
913 Placeholder { universe: ui, ..self }
914 }
915
916 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
917 Placeholder { universe: ui, bound }
918 }
919
920 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
921 Placeholder { universe: ui, bound: BoundRegion { var, kind: BoundRegionKind::Anon } }
922 }
923}
924
925pub type PlaceholderType = Placeholder<BoundTy>;
926
927impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType {
928 type Bound = BoundTy;
929
930 fn universe(self) -> UniverseIndex {
931 self.universe
932 }
933
934 fn var(self) -> BoundVar {
935 self.bound.var
936 }
937
938 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
939 Placeholder { universe: ui, ..self }
940 }
941
942 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
943 Placeholder { universe: ui, bound }
944 }
945
946 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
947 Placeholder { universe: ui, bound: BoundTy { var, kind: BoundTyKind::Anon } }
948 }
949}
950
951#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
952#[derive(TyEncodable, TyDecodable)]
953pub struct BoundConst {
954 pub var: BoundVar,
955}
956
957impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
958 fn var(self) -> BoundVar {
959 self.var
960 }
961
962 fn assert_eq(self, var: ty::BoundVariableKind) {
963 var.expect_const()
964 }
965}
966
967pub type PlaceholderConst = Placeholder<BoundConst>;
968
969impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst {
970 type Bound = BoundConst;
971
972 fn universe(self) -> UniverseIndex {
973 self.universe
974 }
975
976 fn var(self) -> BoundVar {
977 self.bound.var
978 }
979
980 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
981 Placeholder { universe: ui, ..self }
982 }
983
984 fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
985 Placeholder { universe: ui, bound }
986 }
987
988 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
989 Placeholder { universe: ui, bound: BoundConst { var } }
990 }
991}
992
993pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
994
995impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
996 fn flags(&self) -> TypeFlags {
997 (**self).flags()
998 }
999
1000 fn outer_exclusive_binder(&self) -> DebruijnIndex {
1001 (**self).outer_exclusive_binder()
1002 }
1003}
1004
1005#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1011#[derive(HashStable, TypeVisitable, TypeFoldable)]
1012pub struct ParamEnv<'tcx> {
1013 caller_bounds: Clauses<'tcx>,
1019}
1020
1021impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1022 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
1023 self.caller_bounds()
1024 }
1025}
1026
1027impl<'tcx> ParamEnv<'tcx> {
1028 #[inline]
1035 pub fn empty() -> Self {
1036 Self::new(ListWithCachedTypeInfo::empty())
1037 }
1038
1039 #[inline]
1040 pub fn caller_bounds(self) -> Clauses<'tcx> {
1041 self.caller_bounds
1042 }
1043
1044 #[inline]
1046 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1047 ParamEnv { caller_bounds }
1048 }
1049
1050 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1052 ParamEnvAnd { param_env: self, value }
1053 }
1054}
1055
1056#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1057#[derive(HashStable)]
1058pub struct ParamEnvAnd<'tcx, T> {
1059 pub param_env: ParamEnv<'tcx>,
1060 pub value: T,
1061}
1062
1063#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1074#[derive(TypeVisitable, TypeFoldable)]
1075pub struct TypingEnv<'tcx> {
1076 #[type_foldable(identity)]
1077 #[type_visitable(ignore)]
1078 pub typing_mode: TypingMode<'tcx>,
1079 pub param_env: ParamEnv<'tcx>,
1080}
1081
1082impl<'tcx> TypingEnv<'tcx> {
1083 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1091 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1092 }
1093
1094 pub fn non_body_analysis(
1100 tcx: TyCtxt<'tcx>,
1101 def_id: impl IntoQueryParam<DefId>,
1102 ) -> TypingEnv<'tcx> {
1103 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1104 }
1105
1106 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1107 tcx.typing_env_normalized_for_post_analysis(def_id)
1108 }
1109
1110 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1113 let TypingEnv { typing_mode, param_env } = self;
1114 if let TypingMode::PostAnalysis = typing_mode {
1115 return self;
1116 }
1117
1118 let param_env = if tcx.next_trait_solver_globally() {
1121 param_env
1122 } else {
1123 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1124 };
1125 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1126 }
1127
1128 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1133 where
1134 T: TypeVisitable<TyCtxt<'tcx>>,
1135 {
1136 PseudoCanonicalInput { typing_env: self, value }
1149 }
1150}
1151
1152#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1162#[derive(HashStable, TypeVisitable, TypeFoldable)]
1163pub struct PseudoCanonicalInput<'tcx, T> {
1164 pub typing_env: TypingEnv<'tcx>,
1165 pub value: T,
1166}
1167
1168#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1169pub struct Destructor {
1170 pub did: DefId,
1172}
1173
1174#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1176pub struct AsyncDestructor {
1177 pub impl_did: DefId,
1179}
1180
1181#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1182pub struct VariantFlags(u8);
1183bitflags::bitflags! {
1184 impl VariantFlags: u8 {
1185 const NO_VARIANT_FLAGS = 0;
1186 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1188 }
1189}
1190rustc_data_structures::external_bitflags_debug! { VariantFlags }
1191
1192#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1194pub struct VariantDef {
1195 pub def_id: DefId,
1198 pub ctor: Option<(CtorKind, DefId)>,
1201 pub name: Symbol,
1203 pub discr: VariantDiscr,
1205 pub fields: IndexVec<FieldIdx, FieldDef>,
1207 tainted: Option<ErrorGuaranteed>,
1209 flags: VariantFlags,
1211}
1212
1213impl VariantDef {
1214 #[instrument(level = "debug")]
1231 pub fn new(
1232 name: Symbol,
1233 variant_did: Option<DefId>,
1234 ctor: Option<(CtorKind, DefId)>,
1235 discr: VariantDiscr,
1236 fields: IndexVec<FieldIdx, FieldDef>,
1237 parent_did: DefId,
1238 recover_tainted: Option<ErrorGuaranteed>,
1239 is_field_list_non_exhaustive: bool,
1240 ) -> Self {
1241 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1242 if is_field_list_non_exhaustive {
1243 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1244 }
1245
1246 VariantDef {
1247 def_id: variant_did.unwrap_or(parent_did),
1248 ctor,
1249 name,
1250 discr,
1251 fields,
1252 flags,
1253 tainted: recover_tainted,
1254 }
1255 }
1256
1257 #[inline]
1263 pub fn is_field_list_non_exhaustive(&self) -> bool {
1264 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1265 }
1266
1267 #[inline]
1270 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1271 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1272 }
1273
1274 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1276 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1277 }
1278
1279 #[inline]
1281 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1282 self.tainted.map_or(Ok(()), Err)
1283 }
1284
1285 #[inline]
1286 pub fn ctor_kind(&self) -> Option<CtorKind> {
1287 self.ctor.map(|(kind, _)| kind)
1288 }
1289
1290 #[inline]
1291 pub fn ctor_def_id(&self) -> Option<DefId> {
1292 self.ctor.map(|(_, def_id)| def_id)
1293 }
1294
1295 #[inline]
1299 pub fn single_field(&self) -> &FieldDef {
1300 assert!(self.fields.len() == 1);
1301
1302 &self.fields[FieldIdx::ZERO]
1303 }
1304
1305 #[inline]
1307 pub fn tail_opt(&self) -> Option<&FieldDef> {
1308 self.fields.raw.last()
1309 }
1310
1311 #[inline]
1317 pub fn tail(&self) -> &FieldDef {
1318 self.tail_opt().expect("expected unsized ADT to have a tail field")
1319 }
1320
1321 pub fn has_unsafe_fields(&self) -> bool {
1323 self.fields.iter().any(|x| x.safety.is_unsafe())
1324 }
1325}
1326
1327impl PartialEq for VariantDef {
1328 #[inline]
1329 fn eq(&self, other: &Self) -> bool {
1330 let Self {
1338 def_id: lhs_def_id,
1339 ctor: _,
1340 name: _,
1341 discr: _,
1342 fields: _,
1343 flags: _,
1344 tainted: _,
1345 } = &self;
1346 let Self {
1347 def_id: rhs_def_id,
1348 ctor: _,
1349 name: _,
1350 discr: _,
1351 fields: _,
1352 flags: _,
1353 tainted: _,
1354 } = other;
1355
1356 let res = lhs_def_id == rhs_def_id;
1357
1358 if cfg!(debug_assertions) && res {
1360 let deep = self.ctor == other.ctor
1361 && self.name == other.name
1362 && self.discr == other.discr
1363 && self.fields == other.fields
1364 && self.flags == other.flags;
1365 assert!(deep, "VariantDef for the same def-id has differing data");
1366 }
1367
1368 res
1369 }
1370}
1371
1372impl Eq for VariantDef {}
1373
1374impl Hash for VariantDef {
1375 #[inline]
1376 fn hash<H: Hasher>(&self, s: &mut H) {
1377 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1385 def_id.hash(s)
1386 }
1387}
1388
1389#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1390pub enum VariantDiscr {
1391 Explicit(DefId),
1394
1395 Relative(u32),
1400}
1401
1402#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1403pub struct FieldDef {
1404 pub did: DefId,
1405 pub name: Symbol,
1406 pub vis: Visibility<DefId>,
1407 pub safety: hir::Safety,
1408 pub value: Option<DefId>,
1409}
1410
1411impl PartialEq for FieldDef {
1412 #[inline]
1413 fn eq(&self, other: &Self) -> bool {
1414 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1422
1423 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1424
1425 let res = lhs_did == rhs_did;
1426
1427 if cfg!(debug_assertions) && res {
1429 let deep =
1430 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1431 assert!(deep, "FieldDef for the same def-id has differing data");
1432 }
1433
1434 res
1435 }
1436}
1437
1438impl Eq for FieldDef {}
1439
1440impl Hash for FieldDef {
1441 #[inline]
1442 fn hash<H: Hasher>(&self, s: &mut H) {
1443 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1451
1452 did.hash(s)
1453 }
1454}
1455
1456impl<'tcx> FieldDef {
1457 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1460 tcx.type_of(self.did).instantiate(tcx, args)
1461 }
1462
1463 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1465 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1466 }
1467}
1468
1469#[derive(Debug, PartialEq, Eq)]
1470pub enum ImplOverlapKind {
1471 Permitted {
1473 marker: bool,
1475 },
1476}
1477
1478#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1481pub enum ImplTraitInTraitData {
1482 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1483 Impl { fn_def_id: DefId },
1484}
1485
1486impl<'tcx> TyCtxt<'tcx> {
1487 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1488 self.typeck(self.hir_body_owner_def_id(body))
1489 }
1490
1491 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1492 self.associated_items(id)
1493 .in_definition_order()
1494 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1495 }
1496
1497 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1498 let mut flags = ReprFlags::empty();
1499 let mut size = None;
1500 let mut max_align: Option<Align> = None;
1501 let mut min_pack: Option<Align> = None;
1502
1503 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1506
1507 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1511 field_shuffle_seed ^= user_seed;
1512 }
1513
1514 let attributes = self.get_all_attrs(did);
1515 if let Some(reprs) = find_attr!(attributes, AttributeKind::Repr { reprs, .. } => reprs) {
1516 for (r, _) in reprs {
1517 flags.insert(match *r {
1518 attr::ReprRust => ReprFlags::empty(),
1519 attr::ReprC => ReprFlags::IS_C,
1520 attr::ReprPacked(pack) => {
1521 min_pack = Some(if let Some(min_pack) = min_pack {
1522 min_pack.min(pack)
1523 } else {
1524 pack
1525 });
1526 ReprFlags::empty()
1527 }
1528 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1529 attr::ReprSimd => ReprFlags::IS_SIMD,
1530 attr::ReprInt(i) => {
1531 size = Some(match i {
1532 attr::IntType::SignedInt(x) => match x {
1533 ast::IntTy::Isize => IntegerType::Pointer(true),
1534 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1535 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1536 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1537 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1538 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1539 },
1540 attr::IntType::UnsignedInt(x) => match x {
1541 ast::UintTy::Usize => IntegerType::Pointer(false),
1542 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1543 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1544 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1545 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1546 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1547 },
1548 });
1549 ReprFlags::empty()
1550 }
1551 attr::ReprAlign(align) => {
1552 max_align = max_align.max(Some(align));
1553 ReprFlags::empty()
1554 }
1555 });
1556 }
1557 }
1558
1559 if self.sess.opts.unstable_opts.randomize_layout {
1562 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1563 }
1564
1565 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1568
1569 if is_box {
1571 flags.insert(ReprFlags::IS_LINEAR);
1572 }
1573
1574 if find_attr!(attributes, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) {
1576 flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1577 }
1578
1579 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1580 }
1581
1582 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1584 let def_id = def_id.into_query_param();
1585 if let Some(cnum) = def_id.as_crate_root() {
1586 Some(self.crate_name(cnum))
1587 } else {
1588 let def_key = self.def_key(def_id);
1589 match def_key.disambiguated_data.data {
1590 rustc_hir::definitions::DefPathData::Ctor => self
1592 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1593 _ => def_key.get_opt_name(),
1594 }
1595 }
1596 }
1597
1598 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1605 let id = id.into_query_param();
1606 self.opt_item_name(id).unwrap_or_else(|| {
1607 bug!("item_name: no name for {:?}", self.def_path(id));
1608 })
1609 }
1610
1611 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1615 let def_id = def_id.into_query_param();
1616 let def = self.opt_item_name(def_id)?;
1617 let span = self
1618 .def_ident_span(def_id)
1619 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1620 Some(Ident::new(def, span))
1621 }
1622
1623 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1627 let def_id = def_id.into_query_param();
1628 self.opt_item_ident(def_id).unwrap_or_else(|| {
1629 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1630 })
1631 }
1632
1633 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1634 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1635 Some(self.associated_item(def_id))
1636 } else {
1637 None
1638 }
1639 }
1640
1641 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1645 if let DefKind::AssocTy = self.def_kind(def_id)
1646 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1647 self.associated_item(def_id).kind
1648 {
1649 Some(rpitit_info)
1650 } else {
1651 None
1652 }
1653 }
1654
1655 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1656 variant.fields.iter_enumerated().find_map(|(i, field)| {
1657 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1658 })
1659 }
1660
1661 #[instrument(level = "debug", skip(self), ret)]
1664 pub fn impls_are_allowed_to_overlap(
1665 self,
1666 def_id1: DefId,
1667 def_id2: DefId,
1668 ) -> Option<ImplOverlapKind> {
1669 let impl1 = self.impl_trait_header(def_id1);
1670 let impl2 = self.impl_trait_header(def_id2);
1671
1672 let trait_ref1 = impl1.trait_ref.skip_binder();
1673 let trait_ref2 = impl2.trait_ref.skip_binder();
1674
1675 if trait_ref1.references_error() || trait_ref2.references_error() {
1678 return Some(ImplOverlapKind::Permitted { marker: false });
1679 }
1680
1681 match (impl1.polarity, impl2.polarity) {
1682 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1683 return Some(ImplOverlapKind::Permitted { marker: false });
1685 }
1686 (ImplPolarity::Positive, ImplPolarity::Negative)
1687 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1688 return None;
1690 }
1691 (ImplPolarity::Positive, ImplPolarity::Positive)
1692 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1693 };
1694
1695 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1696 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1697
1698 if is_marker_overlap {
1699 return Some(ImplOverlapKind::Permitted { marker: true });
1700 }
1701
1702 None
1703 }
1704
1705 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1708 match res {
1709 Res::Def(DefKind::Variant, did) => {
1710 let enum_did = self.parent(did);
1711 self.adt_def(enum_did).variant_with_id(did)
1712 }
1713 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1714 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1715 let variant_did = self.parent(variant_ctor_did);
1716 let enum_did = self.parent(variant_did);
1717 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1718 }
1719 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1720 let struct_did = self.parent(ctor_did);
1721 self.adt_def(struct_did).non_enum_variant()
1722 }
1723 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1724 }
1725 }
1726
1727 #[instrument(skip(self), level = "debug")]
1729 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1730 match instance {
1731 ty::InstanceKind::Item(def) => {
1732 debug!("calling def_kind on def: {:?}", def);
1733 let def_kind = self.def_kind(def);
1734 debug!("returned from def_kind: {:?}", def_kind);
1735 match def_kind {
1736 DefKind::Const
1737 | DefKind::Static { .. }
1738 | DefKind::AssocConst
1739 | DefKind::Ctor(..)
1740 | DefKind::AnonConst
1741 | DefKind::InlineConst => self.mir_for_ctfe(def),
1742 _ => self.optimized_mir(def),
1745 }
1746 }
1747 ty::InstanceKind::VTableShim(..)
1748 | ty::InstanceKind::ReifyShim(..)
1749 | ty::InstanceKind::Intrinsic(..)
1750 | ty::InstanceKind::FnPtrShim(..)
1751 | ty::InstanceKind::Virtual(..)
1752 | ty::InstanceKind::ClosureOnceShim { .. }
1753 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1754 | ty::InstanceKind::FutureDropPollShim(..)
1755 | ty::InstanceKind::DropGlue(..)
1756 | ty::InstanceKind::CloneShim(..)
1757 | ty::InstanceKind::ThreadLocalShim(..)
1758 | ty::InstanceKind::FnPtrAddrShim(..)
1759 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1760 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1761 }
1762 }
1763
1764 pub fn get_attrs(
1766 self,
1767 did: impl Into<DefId>,
1768 attr: Symbol,
1769 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1770 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1771 }
1772
1773 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1778 let did: DefId = did.into();
1779 if let Some(did) = did.as_local() {
1780 self.hir_attrs(self.local_def_id_to_hir_id(did))
1781 } else {
1782 self.attrs_for_def(did)
1783 }
1784 }
1785
1786 pub fn get_diagnostic_attr(
1795 self,
1796 did: impl Into<DefId>,
1797 attr: Symbol,
1798 ) -> Option<&'tcx hir::Attribute> {
1799 let did: DefId = did.into();
1800 if did.as_local().is_some() {
1801 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1803 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1804 } else {
1805 None
1806 }
1807 } else {
1808 debug_assert!(rustc_feature::encode_cross_crate(attr));
1811 self.attrs_for_def(did)
1812 .iter()
1813 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1814 }
1815 }
1816
1817 pub fn get_attrs_by_path(
1818 self,
1819 did: DefId,
1820 attr: &[Symbol],
1821 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1822 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1823 if let Some(did) = did.as_local() {
1824 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1825 } else {
1826 self.attrs_for_def(did).iter().filter(filter_fn)
1827 }
1828 }
1829
1830 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1831 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1832 let did: DefId = did.into();
1833 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1834 } else {
1835 self.get_attrs(did, attr).next()
1836 }
1837 }
1838
1839 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1841 self.get_attrs(did, attr).next().is_some()
1842 }
1843
1844 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1846 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1847 }
1848
1849 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1851 self.trait_def(trait_def_id).has_auto_impl
1852 }
1853
1854 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1857 self.trait_def(trait_def_id).is_coinductive
1858 }
1859
1860 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1862 self.def_kind(trait_def_id) == DefKind::TraitAlias
1863 }
1864
1865 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1867 self.arena.alloc(err)
1868 }
1869
1870 fn ordinary_coroutine_layout(
1876 self,
1877 def_id: DefId,
1878 args: GenericArgsRef<'tcx>,
1879 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1880 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1881 let mir = self.optimized_mir(def_id);
1882 let ty = || Ty::new_coroutine(self, def_id, args);
1883 if coroutine_kind_ty.is_unit() {
1885 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1886 } else {
1887 let ty::Coroutine(_, identity_args) =
1890 *self.type_of(def_id).instantiate_identity().kind()
1891 else {
1892 unreachable!();
1893 };
1894 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1895 if identity_kind_ty == coroutine_kind_ty {
1898 mir.coroutine_layout_raw()
1899 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1900 } else {
1901 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1902 assert_matches!(
1903 identity_kind_ty.to_opt_closure_kind(),
1904 Some(ClosureKind::Fn | ClosureKind::FnMut)
1905 );
1906 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1907 .coroutine_layout_raw()
1908 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1909 }
1910 }
1911 }
1912
1913 fn async_drop_coroutine_layout(
1917 self,
1918 def_id: DefId,
1919 args: GenericArgsRef<'tcx>,
1920 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1921 let ty = || Ty::new_coroutine(self, def_id, args);
1922 if args[0].has_placeholders() || args[0].has_non_region_param() {
1923 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1924 }
1925 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1926 self.mir_shims(instance)
1927 .coroutine_layout_raw()
1928 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1929 }
1930
1931 pub fn coroutine_layout(
1934 self,
1935 def_id: DefId,
1936 args: GenericArgsRef<'tcx>,
1937 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1938 if self.is_async_drop_in_place_coroutine(def_id) {
1939 let arg_cor_ty = args.first().unwrap().expect_ty();
1943 if arg_cor_ty.is_coroutine() {
1944 let span = self.def_span(def_id);
1945 let source_info = SourceInfo::outermost(span);
1946 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1949 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1950 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1951 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1952 let proxy_layout = CoroutineLayout {
1953 field_tys: [].into(),
1954 field_names: [].into(),
1955 variant_fields,
1956 variant_source_info,
1957 storage_conflicts: BitMatrix::new(0, 0),
1958 };
1959 return Ok(self.arena.alloc(proxy_layout));
1960 } else {
1961 self.async_drop_coroutine_layout(def_id, args)
1962 }
1963 } else {
1964 self.ordinary_coroutine_layout(def_id, args)
1965 }
1966 }
1967
1968 pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1970 if !self.def_kind(def_id).is_assoc() {
1971 return None;
1972 }
1973 let parent = self.parent(def_id);
1974 let def_kind = self.def_kind(parent);
1975 Some((parent, def_kind))
1976 }
1977
1978 pub fn trait_item_of(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
1980 self.opt_associated_item(def_id.into_query_param())?.trait_item_def_id()
1981 }
1982
1983 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
1986 match self.assoc_parent(def_id) {
1987 Some((id, DefKind::Trait)) => Some(id),
1988 _ => None,
1989 }
1990 }
1991
1992 pub fn impl_is_of_trait(self, def_id: impl IntoQueryParam<DefId>) -> bool {
1993 let def_id = def_id.into_query_param();
1994 let DefKind::Impl { of_trait } = self.def_kind(def_id) else {
1995 panic!("expected Impl for {def_id:?}");
1996 };
1997 of_trait
1998 }
1999
2000 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2003 match self.assoc_parent(def_id) {
2004 Some((id, DefKind::Impl { .. })) => Some(id),
2005 _ => None,
2006 }
2007 }
2008
2009 pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2012 match self.assoc_parent(def_id) {
2013 Some((id, DefKind::Impl { of_trait: false })) => Some(id),
2014 _ => None,
2015 }
2016 }
2017
2018 pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2021 match self.assoc_parent(def_id) {
2022 Some((id, DefKind::Impl { of_trait: true })) => Some(id),
2023 _ => None,
2024 }
2025 }
2026
2027 pub fn impl_polarity(self, def_id: impl IntoQueryParam<DefId>) -> ty::ImplPolarity {
2028 self.impl_trait_header(def_id).polarity
2029 }
2030
2031 pub fn impl_trait_ref(
2033 self,
2034 def_id: impl IntoQueryParam<DefId>,
2035 ) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
2036 self.impl_trait_header(def_id).trait_ref
2037 }
2038
2039 pub fn impl_opt_trait_ref(
2042 self,
2043 def_id: impl IntoQueryParam<DefId>,
2044 ) -> Option<ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>> {
2045 let def_id = def_id.into_query_param();
2046 self.impl_is_of_trait(def_id).then(|| self.impl_trait_ref(def_id))
2047 }
2048
2049 pub fn impl_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> DefId {
2051 self.impl_trait_ref(def_id).skip_binder().def_id
2052 }
2053
2054 pub fn impl_opt_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2057 let def_id = def_id.into_query_param();
2058 self.impl_is_of_trait(def_id).then(|| self.impl_trait_id(def_id))
2059 }
2060
2061 pub fn is_exportable(self, def_id: DefId) -> bool {
2062 self.exportable_items(def_id.krate).contains(&def_id)
2063 }
2064
2065 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2068 if self.is_automatically_derived(def_id)
2069 && let Some(def_id) = def_id.as_local()
2070 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2071 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2072 && find_attr!(
2073 self.get_all_attrs(outer.macro_def_id.unwrap()),
2074 AttributeKind::RustcBuiltinMacro { .. }
2075 )
2076 {
2077 true
2078 } else {
2079 false
2080 }
2081 }
2082
2083 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2085 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
2086 }
2087
2088 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2091 if let Some(impl_def_id) = impl_def_id.as_local() {
2092 Ok(self.def_span(impl_def_id))
2093 } else {
2094 Err(self.crate_name(impl_def_id.krate))
2095 }
2096 }
2097
2098 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2102 use_ident.name == def_ident.name
2106 && use_ident
2107 .span
2108 .ctxt()
2109 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2110 }
2111
2112 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2113 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2114 ident
2115 }
2116
2117 pub fn adjust_ident_and_get_scope(
2119 self,
2120 mut ident: Ident,
2121 scope: DefId,
2122 block: hir::HirId,
2123 ) -> (Ident, DefId) {
2124 let scope = ident
2125 .span
2126 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2127 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2128 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2129 (ident, scope)
2130 }
2131
2132 #[inline]
2136 pub fn is_const_fn(self, def_id: DefId) -> bool {
2137 matches!(
2138 self.def_kind(def_id),
2139 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2140 ) && self.constness(def_id) == hir::Constness::Const
2141 }
2142
2143 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2150 let def_id: DefId = def_id.into();
2151 match self.def_kind(def_id) {
2152 DefKind::Impl { of_trait: true } => {
2153 let header = self.impl_trait_header(def_id);
2154 header.constness == hir::Constness::Const
2155 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2156 }
2157 DefKind::Impl { of_trait: false } => self.constness(def_id) == hir::Constness::Const,
2158 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2159 self.constness(def_id) == hir::Constness::Const
2160 }
2161 DefKind::TraitAlias | DefKind::Trait => self.is_const_trait(def_id),
2162 DefKind::AssocTy => {
2163 let parent_def_id = self.parent(def_id);
2164 match self.def_kind(parent_def_id) {
2165 DefKind::Impl { of_trait: false } => false,
2166 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2167 self.is_conditionally_const(parent_def_id)
2168 }
2169 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2170 }
2171 }
2172 DefKind::AssocFn => {
2173 let parent_def_id = self.parent(def_id);
2174 match self.def_kind(parent_def_id) {
2175 DefKind::Impl { of_trait: false } => {
2176 self.constness(def_id) == hir::Constness::Const
2177 }
2178 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2179 self.is_conditionally_const(parent_def_id)
2180 }
2181 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2182 }
2183 }
2184 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2185 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2186 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2187 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2189 },
2190 DefKind::Closure => {
2191 false
2194 }
2195 DefKind::Ctor(_, CtorKind::Const)
2196 | DefKind::Mod
2197 | DefKind::Struct
2198 | DefKind::Union
2199 | DefKind::Enum
2200 | DefKind::Variant
2201 | DefKind::TyAlias
2202 | DefKind::ForeignTy
2203 | DefKind::TyParam
2204 | DefKind::Const
2205 | DefKind::ConstParam
2206 | DefKind::Static { .. }
2207 | DefKind::AssocConst
2208 | DefKind::Macro(_)
2209 | DefKind::ExternCrate
2210 | DefKind::Use
2211 | DefKind::ForeignMod
2212 | DefKind::AnonConst
2213 | DefKind::InlineConst
2214 | DefKind::Field
2215 | DefKind::LifetimeParam
2216 | DefKind::GlobalAsm
2217 | DefKind::SyntheticCoroutineBody => false,
2218 }
2219 }
2220
2221 #[inline]
2222 pub fn is_const_trait(self, def_id: DefId) -> bool {
2223 self.trait_def(def_id).constness == hir::Constness::Const
2224 }
2225
2226 #[inline]
2227 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2228 matches!(self.trait_of_assoc(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2229 }
2230
2231 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2232 if self.def_kind(def_id) != DefKind::AssocFn {
2233 return false;
2234 }
2235
2236 let Some(item) = self.opt_associated_item(def_id) else {
2237 return false;
2238 };
2239
2240 let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2241 return false;
2242 };
2243
2244 !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2245 }
2246}
2247
2248pub fn provide(providers: &mut Providers) {
2249 closure::provide(providers);
2250 context::provide(providers);
2251 erase_regions::provide(providers);
2252 inhabitedness::provide(providers);
2253 util::provide(providers);
2254 print::provide(providers);
2255 super::util::bug::provide(providers);
2256 *providers = Providers {
2257 trait_impls_of: trait_def::trait_impls_of_provider,
2258 incoherent_impls: trait_def::incoherent_impls_provider,
2259 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2260 traits: trait_def::traits_provider,
2261 vtable_allocation: vtable::vtable_allocation_provider,
2262 ..*providers
2263 };
2264}
2265
2266#[derive(Clone, Debug, Default, HashStable)]
2272pub struct CrateInherentImpls {
2273 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2274 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2275}
2276
2277#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2278pub struct SymbolName<'tcx> {
2279 pub name: &'tcx str,
2281}
2282
2283impl<'tcx> SymbolName<'tcx> {
2284 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2285 SymbolName { name: tcx.arena.alloc_str(name) }
2286 }
2287}
2288
2289impl<'tcx> fmt::Display for SymbolName<'tcx> {
2290 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2291 fmt::Display::fmt(&self.name, fmt)
2292 }
2293}
2294
2295impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2296 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2297 fmt::Display::fmt(&self.name, fmt)
2298 }
2299}
2300
2301#[derive(Copy, Clone, Debug, HashStable)]
2303pub struct DestructuredConst<'tcx> {
2304 pub variant: Option<VariantIdx>,
2305 pub fields: &'tcx [ty::Const<'tcx>],
2306}
2307
2308pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
2312 if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
2314 return FncTree { args: vec![], ret: TypeTree::new() };
2315 }
2316
2317 if !fn_ty.is_fn() {
2319 return FncTree { args: vec![], ret: TypeTree::new() };
2320 }
2321
2322 let fn_sig = fn_ty.fn_sig(tcx);
2324 let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
2325
2326 let mut args = vec![];
2328 for ty in sig.inputs().iter() {
2329 let type_tree = typetree_from_ty(tcx, *ty);
2330 args.push(type_tree);
2331 }
2332
2333 let ret = typetree_from_ty(tcx, sig.output());
2335
2336 FncTree { args, ret }
2337}
2338
2339pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
2342 let mut visited = Vec::new();
2343 typetree_from_ty_inner(tcx, ty, 0, &mut visited)
2344}
2345
2346const MAX_TYPETREE_DEPTH: usize = 6;
2349
2350fn typetree_from_ty_inner<'tcx>(
2352 tcx: TyCtxt<'tcx>,
2353 ty: Ty<'tcx>,
2354 depth: usize,
2355 visited: &mut Vec<Ty<'tcx>>,
2356) -> TypeTree {
2357 if depth >= MAX_TYPETREE_DEPTH {
2358 trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
2359 return TypeTree::new();
2360 }
2361
2362 if visited.contains(&ty) {
2363 return TypeTree::new();
2364 }
2365
2366 visited.push(ty);
2367 let result = typetree_from_ty_impl(tcx, ty, depth, visited);
2368 visited.pop();
2369 result
2370}
2371
2372fn typetree_from_ty_impl<'tcx>(
2374 tcx: TyCtxt<'tcx>,
2375 ty: Ty<'tcx>,
2376 depth: usize,
2377 visited: &mut Vec<Ty<'tcx>>,
2378) -> TypeTree {
2379 typetree_from_ty_impl_inner(tcx, ty, depth, visited, false)
2380}
2381
2382fn typetree_from_ty_impl_inner<'tcx>(
2384 tcx: TyCtxt<'tcx>,
2385 ty: Ty<'tcx>,
2386 depth: usize,
2387 visited: &mut Vec<Ty<'tcx>>,
2388 is_reference_target: bool,
2389) -> TypeTree {
2390 if ty.is_scalar() {
2391 let (kind, size) = if ty.is_integral() || ty.is_char() || ty.is_bool() {
2392 (Kind::Integer, ty.primitive_size(tcx).bytes_usize())
2393 } else if ty.is_floating_point() {
2394 match ty {
2395 x if x == tcx.types.f16 => (Kind::Half, 2),
2396 x if x == tcx.types.f32 => (Kind::Float, 4),
2397 x if x == tcx.types.f64 => (Kind::Double, 8),
2398 x if x == tcx.types.f128 => (Kind::F128, 16),
2399 _ => (Kind::Integer, 0),
2400 }
2401 } else {
2402 (Kind::Integer, 0)
2403 };
2404
2405 let offset = if is_reference_target && !ty.is_array() { 0 } else { -1 };
2408 return TypeTree(vec![Type { offset, size, kind, child: TypeTree::new() }]);
2409 }
2410
2411 if ty.is_ref() || ty.is_raw_ptr() || ty.is_box() {
2412 let inner_ty = if let Some(inner) = ty.builtin_deref(true) {
2413 inner
2414 } else {
2415 return TypeTree::new();
2416 };
2417
2418 let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
2419 return TypeTree(vec![Type {
2420 offset: -1,
2421 size: tcx.data_layout.pointer_size().bytes_usize(),
2422 kind: Kind::Pointer,
2423 child,
2424 }]);
2425 }
2426
2427 if ty.is_array() {
2428 if let ty::Array(element_ty, len_const) = ty.kind() {
2429 let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
2430 if len == 0 {
2431 return TypeTree::new();
2432 }
2433 let element_tree =
2434 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2435 let mut types = Vec::new();
2436 for elem_type in &element_tree.0 {
2437 types.push(Type {
2438 offset: -1,
2439 size: elem_type.size,
2440 kind: elem_type.kind,
2441 child: elem_type.child.clone(),
2442 });
2443 }
2444
2445 return TypeTree(types);
2446 }
2447 }
2448
2449 if ty.is_slice() {
2450 if let ty::Slice(element_ty) = ty.kind() {
2451 let element_tree =
2452 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2453 return element_tree;
2454 }
2455 }
2456
2457 if let ty::Tuple(tuple_types) = ty.kind() {
2458 if tuple_types.is_empty() {
2459 return TypeTree::new();
2460 }
2461
2462 let mut types = Vec::new();
2463 let mut current_offset = 0;
2464
2465 for tuple_ty in tuple_types.iter() {
2466 let element_tree =
2467 typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
2468
2469 let element_layout = tcx
2470 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
2471 .ok()
2472 .map(|layout| layout.size.bytes_usize())
2473 .unwrap_or(0);
2474
2475 for elem_type in &element_tree.0 {
2476 types.push(Type {
2477 offset: if elem_type.offset == -1 {
2478 current_offset as isize
2479 } else {
2480 current_offset as isize + elem_type.offset
2481 },
2482 size: elem_type.size,
2483 kind: elem_type.kind,
2484 child: elem_type.child.clone(),
2485 });
2486 }
2487
2488 current_offset += element_layout;
2489 }
2490
2491 return TypeTree(types);
2492 }
2493
2494 if let ty::Adt(adt_def, args) = ty.kind() {
2495 if adt_def.is_struct() {
2496 let struct_layout =
2497 tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
2498 if let Ok(layout) = struct_layout {
2499 let mut types = Vec::new();
2500
2501 for (field_idx, field_def) in adt_def.all_fields().enumerate() {
2502 let field_ty = field_def.ty(tcx, args);
2503 let field_tree =
2504 typetree_from_ty_impl_inner(tcx, field_ty, depth + 1, visited, false);
2505
2506 let field_offset = layout.fields.offset(field_idx).bytes_usize();
2507
2508 for elem_type in &field_tree.0 {
2509 types.push(Type {
2510 offset: if elem_type.offset == -1 {
2511 field_offset as isize
2512 } else {
2513 field_offset as isize + elem_type.offset
2514 },
2515 size: elem_type.size,
2516 kind: elem_type.kind,
2517 child: elem_type.child.clone(),
2518 });
2519 }
2520 }
2521
2522 return TypeTree(types);
2523 }
2524 }
2525 }
2526
2527 TypeTree::new()
2528}