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 BlobDecodable, Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable,
45 TypeVisitable, 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::{AmbigModChild, 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 offload_meta;
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 structural_impls;
160#[allow(hidden_glob_reexports)]
161mod sty;
162mod typeck_results;
163mod visit;
164
165#[derive(Debug, HashStable)]
168pub struct ResolverGlobalCtxt {
169 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
170 pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
172 pub effective_visibilities: EffectiveVisibilities,
173 pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
174 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
175 pub module_children: LocalDefIdMap<Vec<ModChild>>,
176 pub ambig_module_children: LocalDefIdMap<Vec<AmbigModChild>>,
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, Default)]
256pub enum Asyncness {
257 Yes,
258 #[default]
259 No,
260}
261
262impl Asyncness {
263 pub fn is_async(self) -> bool {
264 matches!(self, Asyncness::Yes)
265 }
266}
267
268#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, BlobDecodable, HashStable)]
269pub enum Visibility<Id = LocalDefId> {
270 Public,
272 Restricted(Id),
274}
275
276impl Visibility {
277 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
278 match self {
279 ty::Visibility::Restricted(restricted_id) => {
280 if restricted_id.is_top_level_module() {
281 "pub(crate)".to_string()
282 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
283 "pub(self)".to_string()
284 } else {
285 format!(
286 "pub(in crate{})",
287 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
288 )
289 }
290 }
291 ty::Visibility::Public => "pub".to_string(),
292 }
293 }
294}
295
296#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
297#[derive(TypeFoldable, TypeVisitable)]
298pub struct ClosureSizeProfileData<'tcx> {
299 pub before_feature_tys: Ty<'tcx>,
301 pub after_feature_tys: Ty<'tcx>,
303}
304
305impl TyCtxt<'_> {
306 #[inline]
307 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
308 self.def_key(id).parent.map(|index| DefId { index, ..id })
309 }
310
311 #[inline]
312 #[track_caller]
313 pub fn parent(self, id: DefId) -> DefId {
314 match self.opt_parent(id) {
315 Some(id) => id,
316 None => bug!("{id:?} doesn't have a parent"),
318 }
319 }
320
321 #[inline]
322 #[track_caller]
323 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
324 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
325 }
326
327 #[inline]
328 #[track_caller]
329 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
330 self.parent(id.into().to_def_id()).expect_local()
331 }
332
333 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
334 if descendant.krate != ancestor.krate {
335 return false;
336 }
337
338 while descendant != ancestor {
339 match self.opt_parent(descendant) {
340 Some(parent) => descendant = parent,
341 None => return false,
342 }
343 }
344 true
345 }
346}
347
348impl<Id> Visibility<Id> {
349 pub fn is_public(self) -> bool {
350 matches!(self, Visibility::Public)
351 }
352
353 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
354 match self {
355 Visibility::Public => Visibility::Public,
356 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
357 }
358 }
359}
360
361impl<Id: Into<DefId>> Visibility<Id> {
362 pub fn to_def_id(self) -> Visibility<DefId> {
363 self.map_id(Into::into)
364 }
365
366 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
368 match self {
369 Visibility::Public => true,
371 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
372 }
373 }
374
375 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
377 match vis {
378 Visibility::Public => self.is_public(),
379 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
380 }
381 }
382}
383
384impl Visibility<DefId> {
385 pub fn expect_local(self) -> Visibility {
386 self.map_id(|id| id.expect_local())
387 }
388
389 pub fn is_visible_locally(self) -> bool {
391 match self {
392 Visibility::Public => true,
393 Visibility::Restricted(def_id) => def_id.is_local(),
394 }
395 }
396}
397
398#[derive(HashStable, Debug)]
405pub struct CrateVariancesMap<'tcx> {
406 pub variances: DefIdMap<&'tcx [ty::Variance]>,
410}
411
412#[derive(Copy, Clone, PartialEq, Eq, Hash)]
415pub struct CReaderCacheKey {
416 pub cnum: Option<CrateNum>,
417 pub pos: usize,
418}
419
420#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
422#[rustc_diagnostic_item = "Ty"]
423#[rustc_pass_by_value]
424pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
425
426impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
427 type Kind = TyKind<'tcx>;
428
429 fn kind(self) -> TyKind<'tcx> {
430 *self.kind()
431 }
432}
433
434impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
435 fn flags(&self) -> TypeFlags {
436 self.0.flags
437 }
438
439 fn outer_exclusive_binder(&self) -> DebruijnIndex {
440 self.0.outer_exclusive_binder
441 }
442}
443
444#[derive(HashStable, Debug)]
451pub struct CratePredicatesMap<'tcx> {
452 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
456}
457
458#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
459pub struct Term<'tcx> {
460 ptr: NonNull<()>,
461 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
462}
463
464impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
465
466impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
467 type Kind = TermKind<'tcx>;
468
469 fn kind(self) -> Self::Kind {
470 self.kind()
471 }
472}
473
474unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
475 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
476{
477}
478unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
479 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
480{
481}
482unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
483unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
484
485impl Debug for Term<'_> {
486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487 match self.kind() {
488 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
489 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
490 }
491 }
492}
493
494impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
495 fn from(ty: Ty<'tcx>) -> Self {
496 TermKind::Ty(ty).pack()
497 }
498}
499
500impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
501 fn from(c: Const<'tcx>) -> Self {
502 TermKind::Const(c).pack()
503 }
504}
505
506impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
507 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
508 self.kind().hash_stable(hcx, hasher);
509 }
510}
511
512impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
513 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
514 self,
515 folder: &mut F,
516 ) -> Result<Self, F::Error> {
517 match self.kind() {
518 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
519 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
520 }
521 }
522
523 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
524 match self.kind() {
525 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
526 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
527 }
528 }
529}
530
531impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
532 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
533 match self.kind() {
534 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
535 ty::TermKind::Const(ct) => ct.visit_with(visitor),
536 }
537 }
538}
539
540impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
541 fn encode(&self, e: &mut E) {
542 self.kind().encode(e)
543 }
544}
545
546impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
547 fn decode(d: &mut D) -> Self {
548 let res: TermKind<'tcx> = Decodable::decode(d);
549 res.pack()
550 }
551}
552
553impl<'tcx> Term<'tcx> {
554 #[inline]
555 pub fn kind(self) -> TermKind<'tcx> {
556 let ptr =
557 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
558 unsafe {
562 match self.ptr.addr().get() & TAG_MASK {
563 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
564 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
565 ))),
566 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
567 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
568 ))),
569 _ => core::intrinsics::unreachable(),
570 }
571 }
572 }
573
574 pub fn as_type(&self) -> Option<Ty<'tcx>> {
575 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
576 }
577
578 pub fn expect_type(&self) -> Ty<'tcx> {
579 self.as_type().expect("expected a type, but found a const")
580 }
581
582 pub fn as_const(&self) -> Option<Const<'tcx>> {
583 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
584 }
585
586 pub fn expect_const(&self) -> Const<'tcx> {
587 self.as_const().expect("expected a const, but found a type")
588 }
589
590 pub fn into_arg(self) -> GenericArg<'tcx> {
591 match self.kind() {
592 TermKind::Ty(ty) => ty.into(),
593 TermKind::Const(c) => c.into(),
594 }
595 }
596
597 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
598 match self.kind() {
599 TermKind::Ty(ty) => match *ty.kind() {
600 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
601 _ => None,
602 },
603 TermKind::Const(ct) => match ct.kind() {
604 ConstKind::Unevaluated(uv) => Some(uv.into()),
605 _ => None,
606 },
607 }
608 }
609
610 pub fn is_infer(&self) -> bool {
611 match self.kind() {
612 TermKind::Ty(ty) => ty.is_ty_var(),
613 TermKind::Const(ct) => ct.is_ct_infer(),
614 }
615 }
616
617 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
618 match self.kind() {
619 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
620 TermKind::Const(ct) => ct.is_trivially_wf(),
621 }
622 }
623
624 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
635 TypeWalker::new(self.into())
636 }
637}
638
639const TAG_MASK: usize = 0b11;
640const TYPE_TAG: usize = 0b00;
641const CONST_TAG: usize = 0b01;
642
643#[extension(pub trait TermKindPackExt<'tcx>)]
644impl<'tcx> TermKind<'tcx> {
645 #[inline]
646 fn pack(self) -> Term<'tcx> {
647 let (tag, ptr) = match self {
648 TermKind::Ty(ty) => {
649 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
651 (TYPE_TAG, NonNull::from(ty.0.0).cast())
652 }
653 TermKind::Const(ct) => {
654 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
656 (CONST_TAG, NonNull::from(ct.0.0).cast())
657 }
658 };
659
660 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
661 }
662}
663
664#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
684pub struct InstantiatedPredicates<'tcx> {
685 pub predicates: Vec<Clause<'tcx>>,
686 pub spans: Vec<Span>,
687}
688
689impl<'tcx> InstantiatedPredicates<'tcx> {
690 pub fn empty() -> InstantiatedPredicates<'tcx> {
691 InstantiatedPredicates { predicates: vec![], spans: vec![] }
692 }
693
694 pub fn is_empty(&self) -> bool {
695 self.predicates.is_empty()
696 }
697
698 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
699 self.into_iter()
700 }
701}
702
703impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
704 type Item = (Clause<'tcx>, Span);
705
706 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
707
708 fn into_iter(self) -> Self::IntoIter {
709 debug_assert_eq!(self.predicates.len(), self.spans.len());
710 std::iter::zip(self.predicates, self.spans)
711 }
712}
713
714impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
715 type Item = (Clause<'tcx>, Span);
716
717 type IntoIter = std::iter::Zip<
718 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
719 std::iter::Copied<std::slice::Iter<'a, Span>>,
720 >;
721
722 fn into_iter(self) -> Self::IntoIter {
723 debug_assert_eq!(self.predicates.len(), self.spans.len());
724 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
725 }
726}
727
728#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
729pub struct ProvisionalHiddenType<'tcx> {
730 pub span: Span,
744
745 pub ty: Ty<'tcx>,
758}
759
760#[derive(Debug, Clone, Copy)]
762pub enum DefiningScopeKind {
763 HirTypeck,
768 MirBorrowck,
769}
770
771impl<'tcx> ProvisionalHiddenType<'tcx> {
772 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> ProvisionalHiddenType<'tcx> {
773 ProvisionalHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
774 }
775
776 pub fn build_mismatch_error(
777 &self,
778 other: &Self,
779 tcx: TyCtxt<'tcx>,
780 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
781 (self.ty, other.ty).error_reported()?;
782 let sub_diag = if self.span == other.span {
784 TypeMismatchReason::ConflictType { span: self.span }
785 } else {
786 TypeMismatchReason::PreviousUse { span: self.span }
787 };
788 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
789 self_ty: self.ty,
790 other_ty: other.ty,
791 other_span: other.span,
792 sub: sub_diag,
793 }))
794 }
795
796 #[instrument(level = "debug", skip(tcx), ret)]
797 pub fn remap_generic_params_to_declaration_params(
798 self,
799 opaque_type_key: OpaqueTypeKey<'tcx>,
800 tcx: TyCtxt<'tcx>,
801 defining_scope_kind: DefiningScopeKind,
802 ) -> DefinitionSiteHiddenType<'tcx> {
803 let OpaqueTypeKey { def_id, args } = opaque_type_key;
804
805 let id_args = GenericArgs::identity_for_item(tcx, def_id);
812 debug!(?id_args);
813
814 let map = args.iter().zip(id_args).collect();
818 debug!("map = {:#?}", map);
819
820 let ty = match defining_scope_kind {
826 DefiningScopeKind::HirTypeck => {
827 fold_regions(tcx, self.ty, |_, _| tcx.lifetimes.re_erased)
828 }
829 DefiningScopeKind::MirBorrowck => self.ty,
830 };
831 let result_ty = ty.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
832 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
833 assert_eq!(result_ty, fold_regions(tcx, result_ty, |_, _| tcx.lifetimes.re_erased));
834 }
835 DefinitionSiteHiddenType { span: self.span, ty: ty::EarlyBinder::bind(result_ty) }
836 }
837}
838
839#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
840pub struct DefinitionSiteHiddenType<'tcx> {
841 pub span: Span,
854
855 pub ty: ty::EarlyBinder<'tcx, Ty<'tcx>>,
857}
858
859impl<'tcx> DefinitionSiteHiddenType<'tcx> {
860 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> DefinitionSiteHiddenType<'tcx> {
861 DefinitionSiteHiddenType {
862 span: DUMMY_SP,
863 ty: ty::EarlyBinder::bind(Ty::new_error(tcx, guar)),
864 }
865 }
866
867 pub fn build_mismatch_error(
868 &self,
869 other: &Self,
870 tcx: TyCtxt<'tcx>,
871 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
872 let self_ty = self.ty.instantiate_identity();
873 let other_ty = other.ty.instantiate_identity();
874 (self_ty, other_ty).error_reported()?;
875 let sub_diag = if self.span == other.span {
877 TypeMismatchReason::ConflictType { span: self.span }
878 } else {
879 TypeMismatchReason::PreviousUse { span: self.span }
880 };
881 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
882 self_ty,
883 other_ty,
884 other_span: other.span,
885 sub: sub_diag,
886 }))
887 }
888}
889
890pub type PlaceholderRegion<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundRegion>;
891
892impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion<'tcx> {
893 type Bound = BoundRegion;
894
895 fn universe(self) -> UniverseIndex {
896 self.universe
897 }
898
899 fn var(self) -> BoundVar {
900 self.bound.var
901 }
902
903 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
904 ty::Placeholder::new(ui, self.bound)
905 }
906
907 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
908 ty::Placeholder::new(ui, bound)
909 }
910
911 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
912 ty::Placeholder::new(ui, BoundRegion { var, kind: BoundRegionKind::Anon })
913 }
914}
915
916pub type PlaceholderType<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundTy>;
917
918impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType<'tcx> {
919 type Bound = BoundTy;
920
921 fn universe(self) -> UniverseIndex {
922 self.universe
923 }
924
925 fn var(self) -> BoundVar {
926 self.bound.var
927 }
928
929 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
930 ty::Placeholder::new(ui, self.bound)
931 }
932
933 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
934 ty::Placeholder::new(ui, bound)
935 }
936
937 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
938 ty::Placeholder::new(ui, BoundTy { var, kind: BoundTyKind::Anon })
939 }
940}
941
942#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
943#[derive(TyEncodable, TyDecodable)]
944pub struct BoundConst {
945 pub var: BoundVar,
946}
947
948impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
949 fn var(self) -> BoundVar {
950 self.var
951 }
952
953 fn assert_eq(self, var: ty::BoundVariableKind) {
954 var.expect_const()
955 }
956}
957
958pub type PlaceholderConst<'tcx> = ty::Placeholder<TyCtxt<'tcx>, BoundConst>;
959
960impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst<'tcx> {
961 type Bound = BoundConst;
962
963 fn universe(self) -> UniverseIndex {
964 self.universe
965 }
966
967 fn var(self) -> BoundVar {
968 self.bound.var
969 }
970
971 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
972 ty::Placeholder::new(ui, self.bound)
973 }
974
975 fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
976 ty::Placeholder::new(ui, bound)
977 }
978
979 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
980 ty::Placeholder::new(ui, BoundConst { var })
981 }
982}
983
984pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
985
986impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
987 fn flags(&self) -> TypeFlags {
988 (**self).flags()
989 }
990
991 fn outer_exclusive_binder(&self) -> DebruijnIndex {
992 (**self).outer_exclusive_binder()
993 }
994}
995
996#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
1002#[derive(HashStable, TypeVisitable, TypeFoldable)]
1003pub struct ParamEnv<'tcx> {
1004 caller_bounds: Clauses<'tcx>,
1010}
1011
1012impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
1013 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
1014 self.caller_bounds()
1015 }
1016}
1017
1018impl<'tcx> ParamEnv<'tcx> {
1019 #[inline]
1026 pub fn empty() -> Self {
1027 Self::new(ListWithCachedTypeInfo::empty())
1028 }
1029
1030 #[inline]
1031 pub fn caller_bounds(self) -> Clauses<'tcx> {
1032 self.caller_bounds
1033 }
1034
1035 #[inline]
1037 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
1038 ParamEnv { caller_bounds }
1039 }
1040
1041 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1043 ParamEnvAnd { param_env: self, value }
1044 }
1045}
1046
1047#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1048#[derive(HashStable)]
1049pub struct ParamEnvAnd<'tcx, T> {
1050 pub param_env: ParamEnv<'tcx>,
1051 pub value: T,
1052}
1053
1054#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1065#[derive(TypeVisitable, TypeFoldable)]
1066pub struct TypingEnv<'tcx> {
1067 #[type_foldable(identity)]
1068 #[type_visitable(ignore)]
1069 pub typing_mode: TypingMode<'tcx>,
1070 pub param_env: ParamEnv<'tcx>,
1071}
1072
1073impl<'tcx> TypingEnv<'tcx> {
1074 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1082 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1083 }
1084
1085 pub fn non_body_analysis(
1091 tcx: TyCtxt<'tcx>,
1092 def_id: impl IntoQueryParam<DefId>,
1093 ) -> TypingEnv<'tcx> {
1094 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1095 }
1096
1097 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1098 tcx.typing_env_normalized_for_post_analysis(def_id)
1099 }
1100
1101 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1104 let TypingEnv { typing_mode, param_env } = self;
1105 if let TypingMode::PostAnalysis = typing_mode {
1106 return self;
1107 }
1108
1109 let param_env = if tcx.next_trait_solver_globally() {
1112 param_env
1113 } else {
1114 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1115 };
1116 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1117 }
1118
1119 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1124 where
1125 T: TypeVisitable<TyCtxt<'tcx>>,
1126 {
1127 PseudoCanonicalInput { typing_env: self, value }
1140 }
1141}
1142
1143#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1153#[derive(HashStable, TypeVisitable, TypeFoldable)]
1154pub struct PseudoCanonicalInput<'tcx, T> {
1155 pub typing_env: TypingEnv<'tcx>,
1156 pub value: T,
1157}
1158
1159#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1160pub struct Destructor {
1161 pub did: DefId,
1163}
1164
1165#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1167pub struct AsyncDestructor {
1168 pub impl_did: DefId,
1170}
1171
1172#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1173pub struct VariantFlags(u8);
1174bitflags::bitflags! {
1175 impl VariantFlags: u8 {
1176 const NO_VARIANT_FLAGS = 0;
1177 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1179 }
1180}
1181rustc_data_structures::external_bitflags_debug! { VariantFlags }
1182
1183#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1185pub struct VariantDef {
1186 pub def_id: DefId,
1189 pub ctor: Option<(CtorKind, DefId)>,
1192 pub name: Symbol,
1194 pub discr: VariantDiscr,
1196 pub fields: IndexVec<FieldIdx, FieldDef>,
1198 tainted: Option<ErrorGuaranteed>,
1200 flags: VariantFlags,
1202}
1203
1204impl VariantDef {
1205 #[instrument(level = "debug")]
1222 pub fn new(
1223 name: Symbol,
1224 variant_did: Option<DefId>,
1225 ctor: Option<(CtorKind, DefId)>,
1226 discr: VariantDiscr,
1227 fields: IndexVec<FieldIdx, FieldDef>,
1228 parent_did: DefId,
1229 recover_tainted: Option<ErrorGuaranteed>,
1230 is_field_list_non_exhaustive: bool,
1231 ) -> Self {
1232 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1233 if is_field_list_non_exhaustive {
1234 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1235 }
1236
1237 VariantDef {
1238 def_id: variant_did.unwrap_or(parent_did),
1239 ctor,
1240 name,
1241 discr,
1242 fields,
1243 flags,
1244 tainted: recover_tainted,
1245 }
1246 }
1247
1248 #[inline]
1254 pub fn is_field_list_non_exhaustive(&self) -> bool {
1255 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1256 }
1257
1258 #[inline]
1261 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1262 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1263 }
1264
1265 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1267 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1268 }
1269
1270 #[inline]
1272 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1273 self.tainted.map_or(Ok(()), Err)
1274 }
1275
1276 #[inline]
1277 pub fn ctor_kind(&self) -> Option<CtorKind> {
1278 self.ctor.map(|(kind, _)| kind)
1279 }
1280
1281 #[inline]
1282 pub fn ctor_def_id(&self) -> Option<DefId> {
1283 self.ctor.map(|(_, def_id)| def_id)
1284 }
1285
1286 #[inline]
1290 pub fn single_field(&self) -> &FieldDef {
1291 assert!(self.fields.len() == 1);
1292
1293 &self.fields[FieldIdx::ZERO]
1294 }
1295
1296 #[inline]
1298 pub fn tail_opt(&self) -> Option<&FieldDef> {
1299 self.fields.raw.last()
1300 }
1301
1302 #[inline]
1308 pub fn tail(&self) -> &FieldDef {
1309 self.tail_opt().expect("expected unsized ADT to have a tail field")
1310 }
1311
1312 pub fn has_unsafe_fields(&self) -> bool {
1314 self.fields.iter().any(|x| x.safety.is_unsafe())
1315 }
1316}
1317
1318impl PartialEq for VariantDef {
1319 #[inline]
1320 fn eq(&self, other: &Self) -> bool {
1321 let Self {
1329 def_id: lhs_def_id,
1330 ctor: _,
1331 name: _,
1332 discr: _,
1333 fields: _,
1334 flags: _,
1335 tainted: _,
1336 } = &self;
1337 let Self {
1338 def_id: rhs_def_id,
1339 ctor: _,
1340 name: _,
1341 discr: _,
1342 fields: _,
1343 flags: _,
1344 tainted: _,
1345 } = other;
1346
1347 let res = lhs_def_id == rhs_def_id;
1348
1349 if cfg!(debug_assertions) && res {
1351 let deep = self.ctor == other.ctor
1352 && self.name == other.name
1353 && self.discr == other.discr
1354 && self.fields == other.fields
1355 && self.flags == other.flags;
1356 assert!(deep, "VariantDef for the same def-id has differing data");
1357 }
1358
1359 res
1360 }
1361}
1362
1363impl Eq for VariantDef {}
1364
1365impl Hash for VariantDef {
1366 #[inline]
1367 fn hash<H: Hasher>(&self, s: &mut H) {
1368 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1376 def_id.hash(s)
1377 }
1378}
1379
1380#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1381pub enum VariantDiscr {
1382 Explicit(DefId),
1385
1386 Relative(u32),
1391}
1392
1393#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1394pub struct FieldDef {
1395 pub did: DefId,
1396 pub name: Symbol,
1397 pub vis: Visibility<DefId>,
1398 pub safety: hir::Safety,
1399 pub value: Option<DefId>,
1400}
1401
1402impl PartialEq for FieldDef {
1403 #[inline]
1404 fn eq(&self, other: &Self) -> bool {
1405 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1413
1414 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1415
1416 let res = lhs_did == rhs_did;
1417
1418 if cfg!(debug_assertions) && res {
1420 let deep =
1421 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1422 assert!(deep, "FieldDef for the same def-id has differing data");
1423 }
1424
1425 res
1426 }
1427}
1428
1429impl Eq for FieldDef {}
1430
1431impl Hash for FieldDef {
1432 #[inline]
1433 fn hash<H: Hasher>(&self, s: &mut H) {
1434 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1442
1443 did.hash(s)
1444 }
1445}
1446
1447impl<'tcx> FieldDef {
1448 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1451 tcx.type_of(self.did).instantiate(tcx, args)
1452 }
1453
1454 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1456 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1457 }
1458}
1459
1460#[derive(Debug, PartialEq, Eq)]
1461pub enum ImplOverlapKind {
1462 Permitted {
1464 marker: bool,
1466 },
1467}
1468
1469#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1472pub enum ImplTraitInTraitData {
1473 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1474 Impl { fn_def_id: DefId },
1475}
1476
1477impl<'tcx> TyCtxt<'tcx> {
1478 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1479 self.typeck(self.hir_body_owner_def_id(body))
1480 }
1481
1482 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1483 self.associated_items(id)
1484 .in_definition_order()
1485 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1486 }
1487
1488 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1489 let mut flags = ReprFlags::empty();
1490 let mut size = None;
1491 let mut max_align: Option<Align> = None;
1492 let mut min_pack: Option<Align> = None;
1493
1494 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1497
1498 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1502 field_shuffle_seed ^= user_seed;
1503 }
1504
1505 let attributes = self.get_all_attrs(did);
1506 if let Some(reprs) = find_attr!(attributes, AttributeKind::Repr { reprs, .. } => reprs) {
1507 for (r, _) in reprs {
1508 flags.insert(match *r {
1509 attr::ReprRust => ReprFlags::empty(),
1510 attr::ReprC => ReprFlags::IS_C,
1511 attr::ReprPacked(pack) => {
1512 min_pack = Some(if let Some(min_pack) = min_pack {
1513 min_pack.min(pack)
1514 } else {
1515 pack
1516 });
1517 ReprFlags::empty()
1518 }
1519 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1520 attr::ReprSimd => ReprFlags::IS_SIMD,
1521 attr::ReprInt(i) => {
1522 size = Some(match i {
1523 attr::IntType::SignedInt(x) => match x {
1524 ast::IntTy::Isize => IntegerType::Pointer(true),
1525 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1526 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1527 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1528 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1529 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1530 },
1531 attr::IntType::UnsignedInt(x) => match x {
1532 ast::UintTy::Usize => IntegerType::Pointer(false),
1533 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1534 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1535 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1536 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1537 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1538 },
1539 });
1540 ReprFlags::empty()
1541 }
1542 attr::ReprAlign(align) => {
1543 max_align = max_align.max(Some(align));
1544 ReprFlags::empty()
1545 }
1546 });
1547 }
1548 }
1549
1550 if self.sess.opts.unstable_opts.randomize_layout {
1553 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1554 }
1555
1556 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1559
1560 if is_box {
1562 flags.insert(ReprFlags::IS_LINEAR);
1563 }
1564
1565 if find_attr!(attributes, AttributeKind::RustcPassIndirectlyInNonRusticAbis(..)) {
1567 flags.insert(ReprFlags::PASS_INDIRECTLY_IN_NON_RUSTIC_ABIS);
1568 }
1569
1570 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1571 }
1572
1573 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1575 let def_id = def_id.into_query_param();
1576 if let Some(cnum) = def_id.as_crate_root() {
1577 Some(self.crate_name(cnum))
1578 } else {
1579 let def_key = self.def_key(def_id);
1580 match def_key.disambiguated_data.data {
1581 rustc_hir::definitions::DefPathData::Ctor => self
1583 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1584 _ => def_key.get_opt_name(),
1585 }
1586 }
1587 }
1588
1589 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1596 let id = id.into_query_param();
1597 self.opt_item_name(id).unwrap_or_else(|| {
1598 bug!("item_name: no name for {:?}", self.def_path(id));
1599 })
1600 }
1601
1602 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1606 let def_id = def_id.into_query_param();
1607 let def = self.opt_item_name(def_id)?;
1608 let span = self
1609 .def_ident_span(def_id)
1610 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1611 Some(Ident::new(def, span))
1612 }
1613
1614 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1618 let def_id = def_id.into_query_param();
1619 self.opt_item_ident(def_id).unwrap_or_else(|| {
1620 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1621 })
1622 }
1623
1624 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1625 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1626 Some(self.associated_item(def_id))
1627 } else {
1628 None
1629 }
1630 }
1631
1632 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1636 if let DefKind::AssocTy = self.def_kind(def_id)
1637 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1638 self.associated_item(def_id).kind
1639 {
1640 Some(rpitit_info)
1641 } else {
1642 None
1643 }
1644 }
1645
1646 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1647 variant.fields.iter_enumerated().find_map(|(i, field)| {
1648 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1649 })
1650 }
1651
1652 #[instrument(level = "debug", skip(self), ret)]
1655 pub fn impls_are_allowed_to_overlap(
1656 self,
1657 def_id1: DefId,
1658 def_id2: DefId,
1659 ) -> Option<ImplOverlapKind> {
1660 let impl1 = self.impl_trait_header(def_id1);
1661 let impl2 = self.impl_trait_header(def_id2);
1662
1663 let trait_ref1 = impl1.trait_ref.skip_binder();
1664 let trait_ref2 = impl2.trait_ref.skip_binder();
1665
1666 if trait_ref1.references_error() || trait_ref2.references_error() {
1669 return Some(ImplOverlapKind::Permitted { marker: false });
1670 }
1671
1672 match (impl1.polarity, impl2.polarity) {
1673 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1674 return Some(ImplOverlapKind::Permitted { marker: false });
1676 }
1677 (ImplPolarity::Positive, ImplPolarity::Negative)
1678 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1679 return None;
1681 }
1682 (ImplPolarity::Positive, ImplPolarity::Positive)
1683 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1684 };
1685
1686 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1687 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1688
1689 if is_marker_overlap {
1690 return Some(ImplOverlapKind::Permitted { marker: true });
1691 }
1692
1693 None
1694 }
1695
1696 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1699 match res {
1700 Res::Def(DefKind::Variant, did) => {
1701 let enum_did = self.parent(did);
1702 self.adt_def(enum_did).variant_with_id(did)
1703 }
1704 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1705 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1706 let variant_did = self.parent(variant_ctor_did);
1707 let enum_did = self.parent(variant_did);
1708 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1709 }
1710 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1711 let struct_did = self.parent(ctor_did);
1712 self.adt_def(struct_did).non_enum_variant()
1713 }
1714 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1715 }
1716 }
1717
1718 #[instrument(skip(self), level = "debug")]
1720 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1721 match instance {
1722 ty::InstanceKind::Item(def) => {
1723 debug!("calling def_kind on def: {:?}", def);
1724 let def_kind = self.def_kind(def);
1725 debug!("returned from def_kind: {:?}", def_kind);
1726 match def_kind {
1727 DefKind::Const
1728 | DefKind::Static { .. }
1729 | DefKind::AssocConst
1730 | DefKind::Ctor(..)
1731 | DefKind::AnonConst
1732 | DefKind::InlineConst => self.mir_for_ctfe(def),
1733 _ => self.optimized_mir(def),
1736 }
1737 }
1738 ty::InstanceKind::VTableShim(..)
1739 | ty::InstanceKind::ReifyShim(..)
1740 | ty::InstanceKind::Intrinsic(..)
1741 | ty::InstanceKind::FnPtrShim(..)
1742 | ty::InstanceKind::Virtual(..)
1743 | ty::InstanceKind::ClosureOnceShim { .. }
1744 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1745 | ty::InstanceKind::FutureDropPollShim(..)
1746 | ty::InstanceKind::DropGlue(..)
1747 | ty::InstanceKind::CloneShim(..)
1748 | ty::InstanceKind::ThreadLocalShim(..)
1749 | ty::InstanceKind::FnPtrAddrShim(..)
1750 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1751 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1752 }
1753 }
1754
1755 pub fn get_attrs(
1757 self,
1758 did: impl Into<DefId>,
1759 attr: Symbol,
1760 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1761 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1762 }
1763
1764 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1769 let did: DefId = did.into();
1770 if let Some(did) = did.as_local() {
1771 self.hir_attrs(self.local_def_id_to_hir_id(did))
1772 } else {
1773 self.attrs_for_def(did)
1774 }
1775 }
1776
1777 pub fn get_diagnostic_attr(
1786 self,
1787 did: impl Into<DefId>,
1788 attr: Symbol,
1789 ) -> Option<&'tcx hir::Attribute> {
1790 let did: DefId = did.into();
1791 if did.as_local().is_some() {
1792 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1794 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1795 } else {
1796 None
1797 }
1798 } else {
1799 debug_assert!(rustc_feature::encode_cross_crate(attr));
1802 self.attrs_for_def(did)
1803 .iter()
1804 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1805 }
1806 }
1807
1808 pub fn get_attrs_by_path(
1809 self,
1810 did: DefId,
1811 attr: &[Symbol],
1812 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1813 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1814 if let Some(did) = did.as_local() {
1815 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1816 } else {
1817 self.attrs_for_def(did).iter().filter(filter_fn)
1818 }
1819 }
1820
1821 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1822 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1823 let did: DefId = did.into();
1824 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1825 } else {
1826 self.get_attrs(did, attr).next()
1827 }
1828 }
1829
1830 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1832 self.get_attrs(did, attr).next().is_some()
1833 }
1834
1835 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1837 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1838 }
1839
1840 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1842 self.trait_def(trait_def_id).has_auto_impl
1843 }
1844
1845 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1848 self.trait_def(trait_def_id).is_coinductive
1849 }
1850
1851 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1853 self.def_kind(trait_def_id) == DefKind::TraitAlias
1854 }
1855
1856 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1858 self.arena.alloc(err)
1859 }
1860
1861 fn ordinary_coroutine_layout(
1867 self,
1868 def_id: DefId,
1869 args: GenericArgsRef<'tcx>,
1870 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1871 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1872 let mir = self.optimized_mir(def_id);
1873 let ty = || Ty::new_coroutine(self, def_id, args);
1874 if coroutine_kind_ty.is_unit() {
1876 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1877 } else {
1878 let ty::Coroutine(_, identity_args) =
1881 *self.type_of(def_id).instantiate_identity().kind()
1882 else {
1883 unreachable!();
1884 };
1885 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1886 if identity_kind_ty == coroutine_kind_ty {
1889 mir.coroutine_layout_raw()
1890 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1891 } else {
1892 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1893 assert_matches!(
1894 identity_kind_ty.to_opt_closure_kind(),
1895 Some(ClosureKind::Fn | ClosureKind::FnMut)
1896 );
1897 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1898 .coroutine_layout_raw()
1899 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1900 }
1901 }
1902 }
1903
1904 fn async_drop_coroutine_layout(
1908 self,
1909 def_id: DefId,
1910 args: GenericArgsRef<'tcx>,
1911 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1912 let ty = || Ty::new_coroutine(self, def_id, args);
1913 if args[0].has_placeholders() || args[0].has_non_region_param() {
1914 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1915 }
1916 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1917 self.mir_shims(instance)
1918 .coroutine_layout_raw()
1919 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1920 }
1921
1922 pub fn coroutine_layout(
1925 self,
1926 def_id: DefId,
1927 args: GenericArgsRef<'tcx>,
1928 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1929 if self.is_async_drop_in_place_coroutine(def_id) {
1930 let arg_cor_ty = args.first().unwrap().expect_ty();
1934 if arg_cor_ty.is_coroutine() {
1935 let span = self.def_span(def_id);
1936 let source_info = SourceInfo::outermost(span);
1937 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1940 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1941 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1942 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1943 let proxy_layout = CoroutineLayout {
1944 field_tys: [].into(),
1945 field_names: [].into(),
1946 variant_fields,
1947 variant_source_info,
1948 storage_conflicts: BitMatrix::new(0, 0),
1949 };
1950 return Ok(self.arena.alloc(proxy_layout));
1951 } else {
1952 self.async_drop_coroutine_layout(def_id, args)
1953 }
1954 } else {
1955 self.ordinary_coroutine_layout(def_id, args)
1956 }
1957 }
1958
1959 pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1961 if !self.def_kind(def_id).is_assoc() {
1962 return None;
1963 }
1964 let parent = self.parent(def_id);
1965 let def_kind = self.def_kind(parent);
1966 Some((parent, def_kind))
1967 }
1968
1969 pub fn trait_item_of(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
1971 self.opt_associated_item(def_id.into_query_param())?.trait_item_def_id()
1972 }
1973
1974 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
1977 match self.assoc_parent(def_id) {
1978 Some((id, DefKind::Trait)) => Some(id),
1979 _ => None,
1980 }
1981 }
1982
1983 pub fn impl_is_of_trait(self, def_id: impl IntoQueryParam<DefId>) -> bool {
1984 let def_id = def_id.into_query_param();
1985 let DefKind::Impl { of_trait } = self.def_kind(def_id) else {
1986 panic!("expected Impl for {def_id:?}");
1987 };
1988 of_trait
1989 }
1990
1991 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1994 match self.assoc_parent(def_id) {
1995 Some((id, DefKind::Impl { .. })) => Some(id),
1996 _ => None,
1997 }
1998 }
1999
2000 pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2003 match self.assoc_parent(def_id) {
2004 Some((id, DefKind::Impl { of_trait: false })) => Some(id),
2005 _ => None,
2006 }
2007 }
2008
2009 pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
2012 match self.assoc_parent(def_id) {
2013 Some((id, DefKind::Impl { of_trait: true })) => Some(id),
2014 _ => None,
2015 }
2016 }
2017
2018 pub fn impl_polarity(self, def_id: impl IntoQueryParam<DefId>) -> ty::ImplPolarity {
2019 self.impl_trait_header(def_id).polarity
2020 }
2021
2022 pub fn impl_trait_ref(
2024 self,
2025 def_id: impl IntoQueryParam<DefId>,
2026 ) -> ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>> {
2027 self.impl_trait_header(def_id).trait_ref
2028 }
2029
2030 pub fn impl_opt_trait_ref(
2033 self,
2034 def_id: impl IntoQueryParam<DefId>,
2035 ) -> Option<ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>> {
2036 let def_id = def_id.into_query_param();
2037 self.impl_is_of_trait(def_id).then(|| self.impl_trait_ref(def_id))
2038 }
2039
2040 pub fn impl_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> DefId {
2042 self.impl_trait_ref(def_id).skip_binder().def_id
2043 }
2044
2045 pub fn impl_opt_trait_id(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
2048 let def_id = def_id.into_query_param();
2049 self.impl_is_of_trait(def_id).then(|| self.impl_trait_id(def_id))
2050 }
2051
2052 pub fn is_exportable(self, def_id: DefId) -> bool {
2053 self.exportable_items(def_id.krate).contains(&def_id)
2054 }
2055
2056 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
2059 if self.is_automatically_derived(def_id)
2060 && let Some(def_id) = def_id.as_local()
2061 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
2062 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
2063 && find_attr!(
2064 self.get_all_attrs(outer.macro_def_id.unwrap()),
2065 AttributeKind::RustcBuiltinMacro { .. }
2066 )
2067 {
2068 true
2069 } else {
2070 false
2071 }
2072 }
2073
2074 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
2076 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
2077 }
2078
2079 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2082 if let Some(impl_def_id) = impl_def_id.as_local() {
2083 Ok(self.def_span(impl_def_id))
2084 } else {
2085 Err(self.crate_name(impl_def_id.krate))
2086 }
2087 }
2088
2089 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2093 use_ident.name == def_ident.name
2097 && use_ident
2098 .span
2099 .ctxt()
2100 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2101 }
2102
2103 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2104 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2105 ident
2106 }
2107
2108 pub fn adjust_ident_and_get_scope(
2110 self,
2111 mut ident: Ident,
2112 scope: DefId,
2113 block: hir::HirId,
2114 ) -> (Ident, DefId) {
2115 let scope = ident
2116 .span
2117 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2118 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2119 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2120 (ident, scope)
2121 }
2122
2123 #[inline]
2127 pub fn is_const_fn(self, def_id: DefId) -> bool {
2128 matches!(
2129 self.def_kind(def_id),
2130 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2131 ) && self.constness(def_id) == hir::Constness::Const
2132 }
2133
2134 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2141 let def_id: DefId = def_id.into();
2142 match self.def_kind(def_id) {
2143 DefKind::Impl { of_trait: true } => {
2144 let header = self.impl_trait_header(def_id);
2145 header.constness == hir::Constness::Const
2146 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2147 }
2148 DefKind::Impl { of_trait: false } => self.constness(def_id) == hir::Constness::Const,
2149 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2150 self.constness(def_id) == hir::Constness::Const
2151 }
2152 DefKind::TraitAlias | DefKind::Trait => self.is_const_trait(def_id),
2153 DefKind::AssocTy => {
2154 let parent_def_id = self.parent(def_id);
2155 match self.def_kind(parent_def_id) {
2156 DefKind::Impl { of_trait: false } => false,
2157 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2158 self.is_conditionally_const(parent_def_id)
2159 }
2160 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2161 }
2162 }
2163 DefKind::AssocFn => {
2164 let parent_def_id = self.parent(def_id);
2165 match self.def_kind(parent_def_id) {
2166 DefKind::Impl { of_trait: false } => {
2167 self.constness(def_id) == hir::Constness::Const
2168 }
2169 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2170 self.is_conditionally_const(parent_def_id)
2171 }
2172 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2173 }
2174 }
2175 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2176 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2177 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2178 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2180 },
2181 DefKind::Closure => {
2182 false
2185 }
2186 DefKind::Ctor(_, CtorKind::Const)
2187 | DefKind::Mod
2188 | DefKind::Struct
2189 | DefKind::Union
2190 | DefKind::Enum
2191 | DefKind::Variant
2192 | DefKind::TyAlias
2193 | DefKind::ForeignTy
2194 | DefKind::TyParam
2195 | DefKind::Const
2196 | DefKind::ConstParam
2197 | DefKind::Static { .. }
2198 | DefKind::AssocConst
2199 | DefKind::Macro(_)
2200 | DefKind::ExternCrate
2201 | DefKind::Use
2202 | DefKind::ForeignMod
2203 | DefKind::AnonConst
2204 | DefKind::InlineConst
2205 | DefKind::Field
2206 | DefKind::LifetimeParam
2207 | DefKind::GlobalAsm
2208 | DefKind::SyntheticCoroutineBody => false,
2209 }
2210 }
2211
2212 #[inline]
2213 pub fn is_const_trait(self, def_id: DefId) -> bool {
2214 self.trait_def(def_id).constness == hir::Constness::Const
2215 }
2216
2217 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2218 if self.def_kind(def_id) != DefKind::AssocFn {
2219 return false;
2220 }
2221
2222 let Some(item) = self.opt_associated_item(def_id) else {
2223 return false;
2224 };
2225
2226 let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2227 return false;
2228 };
2229
2230 !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2231 }
2232}
2233
2234pub fn provide(providers: &mut Providers) {
2235 closure::provide(providers);
2236 context::provide(providers);
2237 erase_regions::provide(providers);
2238 inhabitedness::provide(providers);
2239 util::provide(providers);
2240 print::provide(providers);
2241 super::util::bug::provide(providers);
2242 *providers = Providers {
2243 trait_impls_of: trait_def::trait_impls_of_provider,
2244 incoherent_impls: trait_def::incoherent_impls_provider,
2245 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2246 traits: trait_def::traits_provider,
2247 vtable_allocation: vtable::vtable_allocation_provider,
2248 ..*providers
2249 };
2250}
2251
2252#[derive(Clone, Debug, Default, HashStable)]
2258pub struct CrateInherentImpls {
2259 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2260 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2261}
2262
2263#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2264pub struct SymbolName<'tcx> {
2265 pub name: &'tcx str,
2267}
2268
2269impl<'tcx> SymbolName<'tcx> {
2270 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2271 SymbolName { name: tcx.arena.alloc_str(name) }
2272 }
2273}
2274
2275impl<'tcx> fmt::Display for SymbolName<'tcx> {
2276 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2277 fmt::Display::fmt(&self.name, fmt)
2278 }
2279}
2280
2281impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2282 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2283 fmt::Display::fmt(&self.name, fmt)
2284 }
2285}
2286
2287#[derive(Copy, Clone, Debug, HashStable)]
2289pub struct DestructuredConst<'tcx> {
2290 pub variant: Option<VariantIdx>,
2291 pub fields: &'tcx [ty::Const<'tcx>],
2292}
2293
2294pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
2298 if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
2300 return FncTree { args: vec![], ret: TypeTree::new() };
2301 }
2302
2303 if !fn_ty.is_fn() {
2305 return FncTree { args: vec![], ret: TypeTree::new() };
2306 }
2307
2308 let fn_sig = fn_ty.fn_sig(tcx);
2310 let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
2311
2312 let mut args = vec![];
2314 for ty in sig.inputs().iter() {
2315 let type_tree = typetree_from_ty(tcx, *ty);
2316 args.push(type_tree);
2317 }
2318
2319 let ret = typetree_from_ty(tcx, sig.output());
2321
2322 FncTree { args, ret }
2323}
2324
2325pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
2328 let mut visited = Vec::new();
2329 typetree_from_ty_inner(tcx, ty, 0, &mut visited)
2330}
2331
2332const MAX_TYPETREE_DEPTH: usize = 6;
2335
2336fn typetree_from_ty_inner<'tcx>(
2338 tcx: TyCtxt<'tcx>,
2339 ty: Ty<'tcx>,
2340 depth: usize,
2341 visited: &mut Vec<Ty<'tcx>>,
2342) -> TypeTree {
2343 if depth >= MAX_TYPETREE_DEPTH {
2344 trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
2345 return TypeTree::new();
2346 }
2347
2348 if visited.contains(&ty) {
2349 return TypeTree::new();
2350 }
2351
2352 visited.push(ty);
2353 let result = typetree_from_ty_impl(tcx, ty, depth, visited);
2354 visited.pop();
2355 result
2356}
2357
2358fn typetree_from_ty_impl<'tcx>(
2360 tcx: TyCtxt<'tcx>,
2361 ty: Ty<'tcx>,
2362 depth: usize,
2363 visited: &mut Vec<Ty<'tcx>>,
2364) -> TypeTree {
2365 typetree_from_ty_impl_inner(tcx, ty, depth, visited, false)
2366}
2367
2368fn typetree_from_ty_impl_inner<'tcx>(
2370 tcx: TyCtxt<'tcx>,
2371 ty: Ty<'tcx>,
2372 depth: usize,
2373 visited: &mut Vec<Ty<'tcx>>,
2374 is_reference_target: bool,
2375) -> TypeTree {
2376 if ty.is_scalar() {
2377 let (kind, size) = if ty.is_integral() || ty.is_char() || ty.is_bool() {
2378 (Kind::Integer, ty.primitive_size(tcx).bytes_usize())
2379 } else if ty.is_floating_point() {
2380 match ty {
2381 x if x == tcx.types.f16 => (Kind::Half, 2),
2382 x if x == tcx.types.f32 => (Kind::Float, 4),
2383 x if x == tcx.types.f64 => (Kind::Double, 8),
2384 x if x == tcx.types.f128 => (Kind::F128, 16),
2385 _ => (Kind::Integer, 0),
2386 }
2387 } else {
2388 (Kind::Integer, 0)
2389 };
2390
2391 let offset = if is_reference_target && !ty.is_array() { 0 } else { -1 };
2394 return TypeTree(vec![Type { offset, size, kind, child: TypeTree::new() }]);
2395 }
2396
2397 if ty.is_ref() || ty.is_raw_ptr() || ty.is_box() {
2398 let inner_ty = if let Some(inner) = ty.builtin_deref(true) {
2399 inner
2400 } else {
2401 return TypeTree::new();
2402 };
2403
2404 let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
2405 return TypeTree(vec![Type {
2406 offset: -1,
2407 size: tcx.data_layout.pointer_size().bytes_usize(),
2408 kind: Kind::Pointer,
2409 child,
2410 }]);
2411 }
2412
2413 if ty.is_array() {
2414 if let ty::Array(element_ty, len_const) = ty.kind() {
2415 let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
2416 if len == 0 {
2417 return TypeTree::new();
2418 }
2419 let element_tree =
2420 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2421 let mut types = Vec::new();
2422 for elem_type in &element_tree.0 {
2423 types.push(Type {
2424 offset: -1,
2425 size: elem_type.size,
2426 kind: elem_type.kind,
2427 child: elem_type.child.clone(),
2428 });
2429 }
2430
2431 return TypeTree(types);
2432 }
2433 }
2434
2435 if ty.is_slice() {
2436 if let ty::Slice(element_ty) = ty.kind() {
2437 let element_tree =
2438 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2439 return element_tree;
2440 }
2441 }
2442
2443 if let ty::Tuple(tuple_types) = ty.kind() {
2444 if tuple_types.is_empty() {
2445 return TypeTree::new();
2446 }
2447
2448 let mut types = Vec::new();
2449 let mut current_offset = 0;
2450
2451 for tuple_ty in tuple_types.iter() {
2452 let element_tree =
2453 typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
2454
2455 let element_layout = tcx
2456 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
2457 .ok()
2458 .map(|layout| layout.size.bytes_usize())
2459 .unwrap_or(0);
2460
2461 for elem_type in &element_tree.0 {
2462 types.push(Type {
2463 offset: if elem_type.offset == -1 {
2464 current_offset as isize
2465 } else {
2466 current_offset as isize + elem_type.offset
2467 },
2468 size: elem_type.size,
2469 kind: elem_type.kind,
2470 child: elem_type.child.clone(),
2471 });
2472 }
2473
2474 current_offset += element_layout;
2475 }
2476
2477 return TypeTree(types);
2478 }
2479
2480 if let ty::Adt(adt_def, args) = ty.kind() {
2481 if adt_def.is_struct() {
2482 let struct_layout =
2483 tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
2484 if let Ok(layout) = struct_layout {
2485 let mut types = Vec::new();
2486
2487 for (field_idx, field_def) in adt_def.all_fields().enumerate() {
2488 let field_ty = field_def.ty(tcx, args);
2489 let field_tree =
2490 typetree_from_ty_impl_inner(tcx, field_ty, depth + 1, visited, false);
2491
2492 let field_offset = layout.fields.offset(field_idx).bytes_usize();
2493
2494 for elem_type in &field_tree.0 {
2495 types.push(Type {
2496 offset: if elem_type.offset == -1 {
2497 field_offset as isize
2498 } else {
2499 field_offset as isize + elem_type.offset
2500 },
2501 size: elem_type.size,
2502 kind: elem_type.kind,
2503 child: elem_type.child.clone(),
2504 });
2505 }
2506 }
2507
2508 return TypeTree(types);
2509 }
2510 }
2511 }
2512
2513 TypeTree::new()
2514}