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