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::definitions::DisambiguatorState;
41use rustc_hir::{LangItem, attrs as attr, find_attr};
42use rustc_index::IndexVec;
43use rustc_index::bit_set::BitMatrix;
44use rustc_macros::{
45 Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
46 extension,
47};
48use rustc_query_system::ich::StableHashingContext;
49use rustc_serialize::{Decodable, Encodable};
50pub use rustc_session::lint::RegisteredTools;
51use rustc_span::hygiene::MacroKind;
52use rustc_span::{DUMMY_SP, ExpnId, ExpnKind, Ident, Span, Symbol, sym};
53pub use rustc_type_ir::data_structures::{DelayedMap, DelayedSet};
54pub use rustc_type_ir::fast_reject::DeepRejectCtxt;
55#[allow(
56 hidden_glob_reexports,
57 rustc::usage_of_type_ir_inherent,
58 rustc::non_glob_import_of_type_ir_inherent
59)]
60use rustc_type_ir::inherent;
61pub use rustc_type_ir::relate::VarianceDiagInfo;
62pub use rustc_type_ir::solve::SizedTraitKind;
63pub use rustc_type_ir::*;
64#[allow(hidden_glob_reexports, unused_imports)]
65use rustc_type_ir::{InferCtxtLike, Interner};
66use tracing::{debug, instrument, trace};
67pub use vtable::*;
68use {rustc_ast as ast, rustc_hir as hir};
69
70pub use self::closure::{
71 BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo,
72 MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId,
73 UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture,
74 place_to_string_for_capture,
75};
76pub use self::consts::{
77 AnonConstKind, AtomicOrdering, Const, ConstInt, ConstKind, ConstToValTreeResult, Expr,
78 ExprKind, ScalarInt, UnevaluatedConst, ValTree, ValTreeKind, Value,
79};
80pub use self::context::{
81 CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt,
82 TyCtxtFeed, tls,
83};
84pub use self::fold::*;
85pub use self::instance::{Instance, InstanceKind, ReifyReason, UnusedGenericParams};
86pub use self::list::{List, ListWithCachedTypeInfo};
87pub use self::opaque_types::OpaqueTypeKey;
88pub use self::pattern::{Pattern, PatternKind};
89pub use self::predicate::{
90 AliasTerm, ArgOutlivesPredicate, Clause, ClauseKind, CoercePredicate, ExistentialPredicate,
91 ExistentialPredicateStableCmpExt, ExistentialProjection, ExistentialTraitRef,
92 HostEffectPredicate, NormalizesTo, OutlivesPredicate, PolyCoercePredicate,
93 PolyExistentialPredicate, PolyExistentialProjection, PolyExistentialTraitRef,
94 PolyProjectionPredicate, PolyRegionOutlivesPredicate, PolySubtypePredicate, PolyTraitPredicate,
95 PolyTraitRef, PolyTypeOutlivesPredicate, Predicate, PredicateKind, ProjectionPredicate,
96 RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate,
97};
98pub use self::region::{
99 BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region,
100 RegionKind, RegionVid,
101};
102pub use self::rvalue_scopes::RvalueScopes;
103pub use self::sty::{
104 AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig,
105 CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst,
106 ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs,
107};
108pub use self::trait_def::TraitDef;
109pub use self::typeck_results::{
110 CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity,
111 Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind,
112};
113use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason};
114use crate::metadata::ModChild;
115use crate::middle::privacy::EffectiveVisibilities;
116use crate::mir::{Body, CoroutineLayout, CoroutineSavedLocal, SourceInfo};
117use crate::query::{IntoQueryParam, Providers};
118use crate::ty;
119use crate::ty::codec::{TyDecoder, TyEncoder};
120pub use crate::ty::diagnostics::*;
121use crate::ty::fast_reject::SimplifiedType;
122use crate::ty::layout::LayoutError;
123use crate::ty::util::Discr;
124use crate::ty::walk::TypeWalker;
125
126pub mod abstract_const;
127pub mod adjustment;
128pub mod cast;
129pub mod codec;
130pub mod error;
131pub mod fast_reject;
132pub mod inhabitedness;
133pub mod layout;
134pub mod normalize_erasing_regions;
135pub mod pattern;
136pub mod print;
137pub mod relate;
138pub mod significant_drop_order;
139pub mod trait_def;
140pub mod util;
141pub mod vtable;
142
143mod adt;
144mod assoc;
145mod closure;
146mod consts;
147mod context;
148mod diagnostics;
149mod elaborate_impl;
150mod erase_regions;
151mod fold;
152mod generic_args;
153mod generics;
154mod impls_ty;
155mod instance;
156mod intrinsic;
157mod list;
158mod opaque_types;
159mod predicate;
160mod region;
161mod rvalue_scopes;
162mod structural_impls;
163#[allow(hidden_glob_reexports)]
164mod sty;
165mod typeck_results;
166mod visit;
167
168#[derive(Debug, HashStable)]
171pub struct ResolverGlobalCtxt {
172 pub visibilities_for_hashing: Vec<(LocalDefId, Visibility)>,
173 pub expn_that_defined: UnordMap<LocalDefId, ExpnId>,
175 pub effective_visibilities: EffectiveVisibilities,
176 pub extern_crate_map: UnordMap<LocalDefId, CrateNum>,
177 pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
178 pub module_children: LocalDefIdMap<Vec<ModChild>>,
179 pub glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
180 pub main_def: Option<MainDefinition>,
181 pub trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
182 pub proc_macros: Vec<LocalDefId>,
185 pub confused_type_with_std_module: FxIndexMap<Span, Span>,
188 pub doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
189 pub doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
190 pub all_macro_rules: UnordSet<Symbol>,
191 pub stripped_cfg_items: Vec<StrippedCfgItem>,
192}
193
194#[derive(Debug)]
197pub struct ResolverAstLowering {
198 pub legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
199
200 pub partial_res_map: NodeMap<hir::def::PartialRes>,
202 pub import_res_map: NodeMap<hir::def::PerNS<Option<Res<ast::NodeId>>>>,
204 pub label_res_map: NodeMap<ast::NodeId>,
206 pub lifetimes_res_map: NodeMap<LifetimeRes>,
208 pub extra_lifetime_params_map: NodeMap<Vec<(Ident, ast::NodeId, LifetimeRes)>>,
210
211 pub next_node_id: ast::NodeId,
212
213 pub node_id_to_def_id: NodeMap<LocalDefId>,
214
215 pub disambiguator: DisambiguatorState,
216
217 pub trait_map: NodeMap<Vec<hir::TraitCandidate>>,
218 pub lifetime_elision_allowed: FxHashSet<ast::NodeId>,
220
221 pub lint_buffer: Steal<LintBuffer>,
223
224 pub delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
226}
227
228#[derive(Debug)]
229pub struct DelegationFnSig {
230 pub header: ast::FnHeader,
231 pub param_count: usize,
232 pub has_self: bool,
233 pub c_variadic: bool,
234 pub target_feature: bool,
235}
236
237#[derive(Clone, Copy, Debug, HashStable)]
238pub struct MainDefinition {
239 pub res: Res<ast::NodeId>,
240 pub is_import: bool,
241 pub span: Span,
242}
243
244impl MainDefinition {
245 pub fn opt_fn_def_id(self) -> Option<DefId> {
246 if let Res::Def(DefKind::Fn, def_id) = self.res { Some(def_id) } else { None }
247 }
248}
249
250#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
251pub struct ImplTraitHeader<'tcx> {
252 pub trait_ref: ty::EarlyBinder<'tcx, ty::TraitRef<'tcx>>,
253 pub polarity: ImplPolarity,
254 pub safety: hir::Safety,
255 pub constness: hir::Constness,
256}
257
258#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable, Debug)]
259#[derive(TypeFoldable, TypeVisitable)]
260pub enum Asyncness {
261 Yes,
262 No,
263}
264
265impl Asyncness {
266 pub fn is_async(self) -> bool {
267 matches!(self, Asyncness::Yes)
268 }
269}
270
271#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, Decodable, HashStable)]
272pub enum Visibility<Id = LocalDefId> {
273 Public,
275 Restricted(Id),
277}
278
279impl Visibility {
280 pub fn to_string(self, def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
281 match self {
282 ty::Visibility::Restricted(restricted_id) => {
283 if restricted_id.is_top_level_module() {
284 "pub(crate)".to_string()
285 } else if restricted_id == tcx.parent_module_from_def_id(def_id).to_local_def_id() {
286 "pub(self)".to_string()
287 } else {
288 format!(
289 "pub(in crate{})",
290 tcx.def_path(restricted_id.to_def_id()).to_string_no_crate_verbose()
291 )
292 }
293 }
294 ty::Visibility::Public => "pub".to_string(),
295 }
296 }
297}
298
299#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
300#[derive(TypeFoldable, TypeVisitable)]
301pub struct ClosureSizeProfileData<'tcx> {
302 pub before_feature_tys: Ty<'tcx>,
304 pub after_feature_tys: Ty<'tcx>,
306}
307
308impl TyCtxt<'_> {
309 #[inline]
310 pub fn opt_parent(self, id: DefId) -> Option<DefId> {
311 self.def_key(id).parent.map(|index| DefId { index, ..id })
312 }
313
314 #[inline]
315 #[track_caller]
316 pub fn parent(self, id: DefId) -> DefId {
317 match self.opt_parent(id) {
318 Some(id) => id,
319 None => bug!("{id:?} doesn't have a parent"),
321 }
322 }
323
324 #[inline]
325 #[track_caller]
326 pub fn opt_local_parent(self, id: LocalDefId) -> Option<LocalDefId> {
327 self.opt_parent(id.to_def_id()).map(DefId::expect_local)
328 }
329
330 #[inline]
331 #[track_caller]
332 pub fn local_parent(self, id: impl Into<LocalDefId>) -> LocalDefId {
333 self.parent(id.into().to_def_id()).expect_local()
334 }
335
336 pub fn is_descendant_of(self, mut descendant: DefId, ancestor: DefId) -> bool {
337 if descendant.krate != ancestor.krate {
338 return false;
339 }
340
341 while descendant != ancestor {
342 match self.opt_parent(descendant) {
343 Some(parent) => descendant = parent,
344 None => return false,
345 }
346 }
347 true
348 }
349}
350
351impl<Id> Visibility<Id> {
352 pub fn is_public(self) -> bool {
353 matches!(self, Visibility::Public)
354 }
355
356 pub fn map_id<OutId>(self, f: impl FnOnce(Id) -> OutId) -> Visibility<OutId> {
357 match self {
358 Visibility::Public => Visibility::Public,
359 Visibility::Restricted(id) => Visibility::Restricted(f(id)),
360 }
361 }
362}
363
364impl<Id: Into<DefId>> Visibility<Id> {
365 pub fn to_def_id(self) -> Visibility<DefId> {
366 self.map_id(Into::into)
367 }
368
369 pub fn is_accessible_from(self, module: impl Into<DefId>, tcx: TyCtxt<'_>) -> bool {
371 match self {
372 Visibility::Public => true,
374 Visibility::Restricted(id) => tcx.is_descendant_of(module.into(), id.into()),
375 }
376 }
377
378 pub fn is_at_least(self, vis: Visibility<impl Into<DefId>>, tcx: TyCtxt<'_>) -> bool {
380 match vis {
381 Visibility::Public => self.is_public(),
382 Visibility::Restricted(id) => self.is_accessible_from(id, tcx),
383 }
384 }
385}
386
387impl Visibility<DefId> {
388 pub fn expect_local(self) -> Visibility {
389 self.map_id(|id| id.expect_local())
390 }
391
392 pub fn is_visible_locally(self) -> bool {
394 match self {
395 Visibility::Public => true,
396 Visibility::Restricted(def_id) => def_id.is_local(),
397 }
398 }
399}
400
401#[derive(HashStable, Debug)]
408pub struct CrateVariancesMap<'tcx> {
409 pub variances: DefIdMap<&'tcx [ty::Variance]>,
413}
414
415#[derive(Copy, Clone, PartialEq, Eq, Hash)]
418pub struct CReaderCacheKey {
419 pub cnum: Option<CrateNum>,
420 pub pos: usize,
421}
422
423#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)]
425#[rustc_diagnostic_item = "Ty"]
426#[rustc_pass_by_value]
427pub struct Ty<'tcx>(Interned<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>);
428
429impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> {
430 type Kind = TyKind<'tcx>;
431
432 fn kind(self) -> TyKind<'tcx> {
433 *self.kind()
434 }
435}
436
437impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> {
438 fn flags(&self) -> TypeFlags {
439 self.0.flags
440 }
441
442 fn outer_exclusive_binder(&self) -> DebruijnIndex {
443 self.0.outer_exclusive_binder
444 }
445}
446
447#[derive(HashStable, Debug)]
454pub struct CratePredicatesMap<'tcx> {
455 pub predicates: DefIdMap<&'tcx [(Clause<'tcx>, Span)]>,
459}
460
461#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
462pub struct Term<'tcx> {
463 ptr: NonNull<()>,
464 marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>,
465}
466
467impl<'tcx> rustc_type_ir::inherent::Term<TyCtxt<'tcx>> for Term<'tcx> {}
468
469impl<'tcx> rustc_type_ir::inherent::IntoKind for Term<'tcx> {
470 type Kind = TermKind<'tcx>;
471
472 fn kind(self) -> Self::Kind {
473 self.kind()
474 }
475}
476
477unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where
478 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend
479{
480}
481unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where
482 &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync
483{
484}
485unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {}
486unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {}
487
488impl Debug for Term<'_> {
489 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490 match self.kind() {
491 TermKind::Ty(ty) => write!(f, "Term::Ty({ty:?})"),
492 TermKind::Const(ct) => write!(f, "Term::Const({ct:?})"),
493 }
494 }
495}
496
497impl<'tcx> From<Ty<'tcx>> for Term<'tcx> {
498 fn from(ty: Ty<'tcx>) -> Self {
499 TermKind::Ty(ty).pack()
500 }
501}
502
503impl<'tcx> From<Const<'tcx>> for Term<'tcx> {
504 fn from(c: Const<'tcx>) -> Self {
505 TermKind::Const(c).pack()
506 }
507}
508
509impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for Term<'tcx> {
510 fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
511 self.kind().hash_stable(hcx, hasher);
512 }
513}
514
515impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for Term<'tcx> {
516 fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>(
517 self,
518 folder: &mut F,
519 ) -> Result<Self, F::Error> {
520 match self.kind() {
521 ty::TermKind::Ty(ty) => ty.try_fold_with(folder).map(Into::into),
522 ty::TermKind::Const(ct) => ct.try_fold_with(folder).map(Into::into),
523 }
524 }
525
526 fn fold_with<F: TypeFolder<TyCtxt<'tcx>>>(self, folder: &mut F) -> Self {
527 match self.kind() {
528 ty::TermKind::Ty(ty) => ty.fold_with(folder).into(),
529 ty::TermKind::Const(ct) => ct.fold_with(folder).into(),
530 }
531 }
532}
533
534impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> {
535 fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> V::Result {
536 match self.kind() {
537 ty::TermKind::Ty(ty) => ty.visit_with(visitor),
538 ty::TermKind::Const(ct) => ct.visit_with(visitor),
539 }
540 }
541}
542
543impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> {
544 fn encode(&self, e: &mut E) {
545 self.kind().encode(e)
546 }
547}
548
549impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> {
550 fn decode(d: &mut D) -> Self {
551 let res: TermKind<'tcx> = Decodable::decode(d);
552 res.pack()
553 }
554}
555
556impl<'tcx> Term<'tcx> {
557 #[inline]
558 pub fn kind(self) -> TermKind<'tcx> {
559 let ptr =
560 unsafe { self.ptr.map_addr(|addr| NonZero::new_unchecked(addr.get() & !TAG_MASK)) };
561 unsafe {
565 match self.ptr.addr().get() & TAG_MASK {
566 TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked(
567 ptr.cast::<WithCachedTypeInfo<ty::TyKind<'tcx>>>().as_ref(),
568 ))),
569 CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked(
570 ptr.cast::<WithCachedTypeInfo<ty::ConstKind<'tcx>>>().as_ref(),
571 ))),
572 _ => core::intrinsics::unreachable(),
573 }
574 }
575 }
576
577 pub fn as_type(&self) -> Option<Ty<'tcx>> {
578 if let TermKind::Ty(ty) = self.kind() { Some(ty) } else { None }
579 }
580
581 pub fn expect_type(&self) -> Ty<'tcx> {
582 self.as_type().expect("expected a type, but found a const")
583 }
584
585 pub fn as_const(&self) -> Option<Const<'tcx>> {
586 if let TermKind::Const(c) = self.kind() { Some(c) } else { None }
587 }
588
589 pub fn expect_const(&self) -> Const<'tcx> {
590 self.as_const().expect("expected a const, but found a type")
591 }
592
593 pub fn into_arg(self) -> GenericArg<'tcx> {
594 match self.kind() {
595 TermKind::Ty(ty) => ty.into(),
596 TermKind::Const(c) => c.into(),
597 }
598 }
599
600 pub fn to_alias_term(self) -> Option<AliasTerm<'tcx>> {
601 match self.kind() {
602 TermKind::Ty(ty) => match *ty.kind() {
603 ty::Alias(_kind, alias_ty) => Some(alias_ty.into()),
604 _ => None,
605 },
606 TermKind::Const(ct) => match ct.kind() {
607 ConstKind::Unevaluated(uv) => Some(uv.into()),
608 _ => None,
609 },
610 }
611 }
612
613 pub fn is_infer(&self) -> bool {
614 match self.kind() {
615 TermKind::Ty(ty) => ty.is_ty_var(),
616 TermKind::Const(ct) => ct.is_ct_infer(),
617 }
618 }
619
620 pub fn is_trivially_wf(&self, tcx: TyCtxt<'tcx>) -> bool {
621 match self.kind() {
622 TermKind::Ty(ty) => ty.is_trivially_wf(tcx),
623 TermKind::Const(ct) => ct.is_trivially_wf(),
624 }
625 }
626
627 pub fn walk(self) -> TypeWalker<TyCtxt<'tcx>> {
638 TypeWalker::new(self.into())
639 }
640}
641
642const TAG_MASK: usize = 0b11;
643const TYPE_TAG: usize = 0b00;
644const CONST_TAG: usize = 0b01;
645
646#[extension(pub trait TermKindPackExt<'tcx>)]
647impl<'tcx> TermKind<'tcx> {
648 #[inline]
649 fn pack(self) -> Term<'tcx> {
650 let (tag, ptr) = match self {
651 TermKind::Ty(ty) => {
652 assert_eq!(align_of_val(&*ty.0.0) & TAG_MASK, 0);
654 (TYPE_TAG, NonNull::from(ty.0.0).cast())
655 }
656 TermKind::Const(ct) => {
657 assert_eq!(align_of_val(&*ct.0.0) & TAG_MASK, 0);
659 (CONST_TAG, NonNull::from(ct.0.0).cast())
660 }
661 };
662
663 Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData }
664 }
665}
666
667#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
687pub struct InstantiatedPredicates<'tcx> {
688 pub predicates: Vec<Clause<'tcx>>,
689 pub spans: Vec<Span>,
690}
691
692impl<'tcx> InstantiatedPredicates<'tcx> {
693 pub fn empty() -> InstantiatedPredicates<'tcx> {
694 InstantiatedPredicates { predicates: vec![], spans: vec![] }
695 }
696
697 pub fn is_empty(&self) -> bool {
698 self.predicates.is_empty()
699 }
700
701 pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
702 self.into_iter()
703 }
704}
705
706impl<'tcx> IntoIterator for InstantiatedPredicates<'tcx> {
707 type Item = (Clause<'tcx>, Span);
708
709 type IntoIter = std::iter::Zip<std::vec::IntoIter<Clause<'tcx>>, std::vec::IntoIter<Span>>;
710
711 fn into_iter(self) -> Self::IntoIter {
712 debug_assert_eq!(self.predicates.len(), self.spans.len());
713 std::iter::zip(self.predicates, self.spans)
714 }
715}
716
717impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> {
718 type Item = (Clause<'tcx>, Span);
719
720 type IntoIter = std::iter::Zip<
721 std::iter::Copied<std::slice::Iter<'a, Clause<'tcx>>>,
722 std::iter::Copied<std::slice::Iter<'a, Span>>,
723 >;
724
725 fn into_iter(self) -> Self::IntoIter {
726 debug_assert_eq!(self.predicates.len(), self.spans.len());
727 std::iter::zip(self.predicates.iter().copied(), self.spans.iter().copied())
728 }
729}
730
731#[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
732pub struct OpaqueHiddenType<'tcx> {
733 pub span: Span,
747
748 pub ty: Ty<'tcx>,
761}
762
763#[derive(Debug, Clone, Copy)]
765pub enum DefiningScopeKind {
766 HirTypeck,
771 MirBorrowck,
772}
773
774impl<'tcx> OpaqueHiddenType<'tcx> {
775 pub fn new_error(tcx: TyCtxt<'tcx>, guar: ErrorGuaranteed) -> OpaqueHiddenType<'tcx> {
776 OpaqueHiddenType { span: DUMMY_SP, ty: Ty::new_error(tcx, guar) }
777 }
778
779 pub fn build_mismatch_error(
780 &self,
781 other: &Self,
782 tcx: TyCtxt<'tcx>,
783 ) -> Result<Diag<'tcx>, ErrorGuaranteed> {
784 (self.ty, other.ty).error_reported()?;
785 let sub_diag = if self.span == other.span {
787 TypeMismatchReason::ConflictType { span: self.span }
788 } else {
789 TypeMismatchReason::PreviousUse { span: self.span }
790 };
791 Ok(tcx.dcx().create_err(OpaqueHiddenTypeMismatch {
792 self_ty: self.ty,
793 other_ty: other.ty,
794 other_span: other.span,
795 sub: sub_diag,
796 }))
797 }
798
799 #[instrument(level = "debug", skip(tcx), ret)]
800 pub fn remap_generic_params_to_declaration_params(
801 self,
802 opaque_type_key: OpaqueTypeKey<'tcx>,
803 tcx: TyCtxt<'tcx>,
804 defining_scope_kind: DefiningScopeKind,
805 ) -> Self {
806 let OpaqueTypeKey { def_id, args } = opaque_type_key;
807
808 let id_args = GenericArgs::identity_for_item(tcx, def_id);
815 debug!(?id_args);
816
817 let map = args.iter().zip(id_args).collect();
821 debug!("map = {:#?}", map);
822
823 let this = match defining_scope_kind {
829 DefiningScopeKind::HirTypeck => fold_regions(tcx, self, |_, _| tcx.lifetimes.re_erased),
830 DefiningScopeKind::MirBorrowck => self,
831 };
832 let result = this.fold_with(&mut opaque_types::ReverseMapper::new(tcx, map, self.span));
833 if cfg!(debug_assertions) && matches!(defining_scope_kind, DefiningScopeKind::HirTypeck) {
834 assert_eq!(result.ty, fold_regions(tcx, result.ty, |_, _| tcx.lifetimes.re_erased));
835 }
836 result
837 }
838}
839
840#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
845#[derive(HashStable, TyEncodable, TyDecodable)]
846pub struct Placeholder<T> {
847 pub universe: UniverseIndex,
848 pub bound: T,
849}
850
851pub type PlaceholderRegion = Placeholder<BoundRegion>;
852
853impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderRegion {
854 type Bound = BoundRegion;
855
856 fn universe(self) -> UniverseIndex {
857 self.universe
858 }
859
860 fn var(self) -> BoundVar {
861 self.bound.var
862 }
863
864 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
865 Placeholder { universe: ui, ..self }
866 }
867
868 fn new(ui: UniverseIndex, bound: BoundRegion) -> Self {
869 Placeholder { universe: ui, bound }
870 }
871
872 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
873 Placeholder { universe: ui, bound: BoundRegion { var, kind: BoundRegionKind::Anon } }
874 }
875}
876
877pub type PlaceholderType = Placeholder<BoundTy>;
878
879impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderType {
880 type Bound = BoundTy;
881
882 fn universe(self) -> UniverseIndex {
883 self.universe
884 }
885
886 fn var(self) -> BoundVar {
887 self.bound.var
888 }
889
890 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
891 Placeholder { universe: ui, ..self }
892 }
893
894 fn new(ui: UniverseIndex, bound: BoundTy) -> Self {
895 Placeholder { universe: ui, bound }
896 }
897
898 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
899 Placeholder { universe: ui, bound: BoundTy { var, kind: BoundTyKind::Anon } }
900 }
901}
902
903#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
904#[derive(TyEncodable, TyDecodable)]
905pub struct BoundConst {
906 pub var: BoundVar,
907}
908
909impl<'tcx> rustc_type_ir::inherent::BoundVarLike<TyCtxt<'tcx>> for BoundConst {
910 fn var(self) -> BoundVar {
911 self.var
912 }
913
914 fn assert_eq(self, var: ty::BoundVariableKind) {
915 var.expect_const()
916 }
917}
918
919pub type PlaceholderConst = Placeholder<BoundConst>;
920
921impl<'tcx> rustc_type_ir::inherent::PlaceholderLike<TyCtxt<'tcx>> for PlaceholderConst {
922 type Bound = BoundConst;
923
924 fn universe(self) -> UniverseIndex {
925 self.universe
926 }
927
928 fn var(self) -> BoundVar {
929 self.bound.var
930 }
931
932 fn with_updated_universe(self, ui: UniverseIndex) -> Self {
933 Placeholder { universe: ui, ..self }
934 }
935
936 fn new(ui: UniverseIndex, bound: BoundConst) -> Self {
937 Placeholder { universe: ui, bound }
938 }
939
940 fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self {
941 Placeholder { universe: ui, bound: BoundConst { var } }
942 }
943}
944
945pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>;
946
947impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> {
948 fn flags(&self) -> TypeFlags {
949 (**self).flags()
950 }
951
952 fn outer_exclusive_binder(&self) -> DebruijnIndex {
953 (**self).outer_exclusive_binder()
954 }
955}
956
957#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
963#[derive(HashStable, TypeVisitable, TypeFoldable)]
964pub struct ParamEnv<'tcx> {
965 caller_bounds: Clauses<'tcx>,
971}
972
973impl<'tcx> rustc_type_ir::inherent::ParamEnv<TyCtxt<'tcx>> for ParamEnv<'tcx> {
974 fn caller_bounds(self) -> impl inherent::SliceLike<Item = ty::Clause<'tcx>> {
975 self.caller_bounds()
976 }
977}
978
979impl<'tcx> ParamEnv<'tcx> {
980 #[inline]
987 pub fn empty() -> Self {
988 Self::new(ListWithCachedTypeInfo::empty())
989 }
990
991 #[inline]
992 pub fn caller_bounds(self) -> Clauses<'tcx> {
993 self.caller_bounds
994 }
995
996 #[inline]
998 pub fn new(caller_bounds: Clauses<'tcx>) -> Self {
999 ParamEnv { caller_bounds }
1000 }
1001
1002 pub fn and<T: TypeVisitable<TyCtxt<'tcx>>>(self, value: T) -> ParamEnvAnd<'tcx, T> {
1004 ParamEnvAnd { param_env: self, value }
1005 }
1006}
1007
1008#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TypeFoldable, TypeVisitable)]
1009#[derive(HashStable)]
1010pub struct ParamEnvAnd<'tcx, T> {
1011 pub param_env: ParamEnv<'tcx>,
1012 pub value: T,
1013}
1014
1015#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
1026#[derive(TypeVisitable, TypeFoldable)]
1027pub struct TypingEnv<'tcx> {
1028 #[type_foldable(identity)]
1029 #[type_visitable(ignore)]
1030 pub typing_mode: TypingMode<'tcx>,
1031 pub param_env: ParamEnv<'tcx>,
1032}
1033
1034impl<'tcx> TypingEnv<'tcx> {
1035 pub fn fully_monomorphized() -> TypingEnv<'tcx> {
1043 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env: ParamEnv::empty() }
1044 }
1045
1046 pub fn non_body_analysis(
1052 tcx: TyCtxt<'tcx>,
1053 def_id: impl IntoQueryParam<DefId>,
1054 ) -> TypingEnv<'tcx> {
1055 TypingEnv { typing_mode: TypingMode::non_body_analysis(), param_env: tcx.param_env(def_id) }
1056 }
1057
1058 pub fn post_analysis(tcx: TyCtxt<'tcx>, def_id: impl IntoQueryParam<DefId>) -> TypingEnv<'tcx> {
1059 tcx.typing_env_normalized_for_post_analysis(def_id)
1060 }
1061
1062 pub fn with_post_analysis_normalized(self, tcx: TyCtxt<'tcx>) -> TypingEnv<'tcx> {
1065 let TypingEnv { typing_mode, param_env } = self;
1066 if let TypingMode::PostAnalysis = typing_mode {
1067 return self;
1068 }
1069
1070 let param_env = if tcx.next_trait_solver_globally() {
1073 param_env
1074 } else {
1075 ParamEnv::new(tcx.reveal_opaque_types_in_bounds(param_env.caller_bounds()))
1076 };
1077 TypingEnv { typing_mode: TypingMode::PostAnalysis, param_env }
1078 }
1079
1080 pub fn as_query_input<T>(self, value: T) -> PseudoCanonicalInput<'tcx, T>
1085 where
1086 T: TypeVisitable<TyCtxt<'tcx>>,
1087 {
1088 PseudoCanonicalInput { typing_env: self, value }
1101 }
1102}
1103
1104#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1114#[derive(HashStable, TypeVisitable, TypeFoldable)]
1115pub struct PseudoCanonicalInput<'tcx, T> {
1116 pub typing_env: TypingEnv<'tcx>,
1117 pub value: T,
1118}
1119
1120#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1121pub struct Destructor {
1122 pub did: DefId,
1124}
1125
1126#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)]
1128pub struct AsyncDestructor {
1129 pub impl_did: DefId,
1131}
1132
1133#[derive(Clone, Copy, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
1134pub struct VariantFlags(u8);
1135bitflags::bitflags! {
1136 impl VariantFlags: u8 {
1137 const NO_VARIANT_FLAGS = 0;
1138 const IS_FIELD_LIST_NON_EXHAUSTIVE = 1 << 0;
1140 }
1141}
1142rustc_data_structures::external_bitflags_debug! { VariantFlags }
1143
1144#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1146pub struct VariantDef {
1147 pub def_id: DefId,
1150 pub ctor: Option<(CtorKind, DefId)>,
1153 pub name: Symbol,
1155 pub discr: VariantDiscr,
1157 pub fields: IndexVec<FieldIdx, FieldDef>,
1159 tainted: Option<ErrorGuaranteed>,
1161 flags: VariantFlags,
1163}
1164
1165impl VariantDef {
1166 #[instrument(level = "debug")]
1183 pub fn new(
1184 name: Symbol,
1185 variant_did: Option<DefId>,
1186 ctor: Option<(CtorKind, DefId)>,
1187 discr: VariantDiscr,
1188 fields: IndexVec<FieldIdx, FieldDef>,
1189 parent_did: DefId,
1190 recover_tainted: Option<ErrorGuaranteed>,
1191 is_field_list_non_exhaustive: bool,
1192 ) -> Self {
1193 let mut flags = VariantFlags::NO_VARIANT_FLAGS;
1194 if is_field_list_non_exhaustive {
1195 flags |= VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE;
1196 }
1197
1198 VariantDef {
1199 def_id: variant_did.unwrap_or(parent_did),
1200 ctor,
1201 name,
1202 discr,
1203 fields,
1204 flags,
1205 tainted: recover_tainted,
1206 }
1207 }
1208
1209 #[inline]
1215 pub fn is_field_list_non_exhaustive(&self) -> bool {
1216 self.flags.intersects(VariantFlags::IS_FIELD_LIST_NON_EXHAUSTIVE)
1217 }
1218
1219 #[inline]
1222 pub fn field_list_has_applicable_non_exhaustive(&self) -> bool {
1223 self.is_field_list_non_exhaustive() && !self.def_id.is_local()
1224 }
1225
1226 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1228 Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
1229 }
1230
1231 #[inline]
1233 pub fn has_errors(&self) -> Result<(), ErrorGuaranteed> {
1234 self.tainted.map_or(Ok(()), Err)
1235 }
1236
1237 #[inline]
1238 pub fn ctor_kind(&self) -> Option<CtorKind> {
1239 self.ctor.map(|(kind, _)| kind)
1240 }
1241
1242 #[inline]
1243 pub fn ctor_def_id(&self) -> Option<DefId> {
1244 self.ctor.map(|(_, def_id)| def_id)
1245 }
1246
1247 #[inline]
1251 pub fn single_field(&self) -> &FieldDef {
1252 assert!(self.fields.len() == 1);
1253
1254 &self.fields[FieldIdx::ZERO]
1255 }
1256
1257 #[inline]
1259 pub fn tail_opt(&self) -> Option<&FieldDef> {
1260 self.fields.raw.last()
1261 }
1262
1263 #[inline]
1269 pub fn tail(&self) -> &FieldDef {
1270 self.tail_opt().expect("expected unsized ADT to have a tail field")
1271 }
1272
1273 pub fn has_unsafe_fields(&self) -> bool {
1275 self.fields.iter().any(|x| x.safety.is_unsafe())
1276 }
1277}
1278
1279impl PartialEq for VariantDef {
1280 #[inline]
1281 fn eq(&self, other: &Self) -> bool {
1282 let Self {
1290 def_id: lhs_def_id,
1291 ctor: _,
1292 name: _,
1293 discr: _,
1294 fields: _,
1295 flags: _,
1296 tainted: _,
1297 } = &self;
1298 let Self {
1299 def_id: rhs_def_id,
1300 ctor: _,
1301 name: _,
1302 discr: _,
1303 fields: _,
1304 flags: _,
1305 tainted: _,
1306 } = other;
1307
1308 let res = lhs_def_id == rhs_def_id;
1309
1310 if cfg!(debug_assertions) && res {
1312 let deep = self.ctor == other.ctor
1313 && self.name == other.name
1314 && self.discr == other.discr
1315 && self.fields == other.fields
1316 && self.flags == other.flags;
1317 assert!(deep, "VariantDef for the same def-id has differing data");
1318 }
1319
1320 res
1321 }
1322}
1323
1324impl Eq for VariantDef {}
1325
1326impl Hash for VariantDef {
1327 #[inline]
1328 fn hash<H: Hasher>(&self, s: &mut H) {
1329 let Self { def_id, ctor: _, name: _, discr: _, fields: _, flags: _, tainted: _ } = &self;
1337 def_id.hash(s)
1338 }
1339}
1340
1341#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
1342pub enum VariantDiscr {
1343 Explicit(DefId),
1346
1347 Relative(u32),
1352}
1353
1354#[derive(Debug, HashStable, TyEncodable, TyDecodable)]
1355pub struct FieldDef {
1356 pub did: DefId,
1357 pub name: Symbol,
1358 pub vis: Visibility<DefId>,
1359 pub safety: hir::Safety,
1360 pub value: Option<DefId>,
1361}
1362
1363impl PartialEq for FieldDef {
1364 #[inline]
1365 fn eq(&self, other: &Self) -> bool {
1366 let Self { did: lhs_did, name: _, vis: _, safety: _, value: _ } = &self;
1374
1375 let Self { did: rhs_did, name: _, vis: _, safety: _, value: _ } = other;
1376
1377 let res = lhs_did == rhs_did;
1378
1379 if cfg!(debug_assertions) && res {
1381 let deep =
1382 self.name == other.name && self.vis == other.vis && self.safety == other.safety;
1383 assert!(deep, "FieldDef for the same def-id has differing data");
1384 }
1385
1386 res
1387 }
1388}
1389
1390impl Eq for FieldDef {}
1391
1392impl Hash for FieldDef {
1393 #[inline]
1394 fn hash<H: Hasher>(&self, s: &mut H) {
1395 let Self { did, name: _, vis: _, safety: _, value: _ } = &self;
1403
1404 did.hash(s)
1405 }
1406}
1407
1408impl<'tcx> FieldDef {
1409 pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
1412 tcx.type_of(self.did).instantiate(tcx, args)
1413 }
1414
1415 pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
1417 Ident::new(self.name, tcx.def_ident_span(self.did).unwrap())
1418 }
1419}
1420
1421#[derive(Debug, PartialEq, Eq)]
1422pub enum ImplOverlapKind {
1423 Permitted {
1425 marker: bool,
1427 },
1428}
1429
1430#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable, HashStable)]
1433pub enum ImplTraitInTraitData {
1434 Trait { fn_def_id: DefId, opaque_def_id: DefId },
1435 Impl { fn_def_id: DefId },
1436}
1437
1438impl<'tcx> TyCtxt<'tcx> {
1439 pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> {
1440 self.typeck(self.hir_body_owner_def_id(body))
1441 }
1442
1443 pub fn provided_trait_methods(self, id: DefId) -> impl 'tcx + Iterator<Item = &'tcx AssocItem> {
1444 self.associated_items(id)
1445 .in_definition_order()
1446 .filter(move |item| item.is_fn() && item.defaultness(self).has_value())
1447 }
1448
1449 pub fn repr_options_of_def(self, did: LocalDefId) -> ReprOptions {
1450 let mut flags = ReprFlags::empty();
1451 let mut size = None;
1452 let mut max_align: Option<Align> = None;
1453 let mut min_pack: Option<Align> = None;
1454
1455 let mut field_shuffle_seed = self.def_path_hash(did.to_def_id()).0.to_smaller_hash();
1458
1459 if let Some(user_seed) = self.sess.opts.unstable_opts.layout_seed {
1463 field_shuffle_seed ^= user_seed;
1464 }
1465
1466 if let Some(reprs) =
1467 find_attr!(self.get_all_attrs(did), AttributeKind::Repr { reprs, .. } => reprs)
1468 {
1469 for (r, _) in reprs {
1470 flags.insert(match *r {
1471 attr::ReprRust => ReprFlags::empty(),
1472 attr::ReprC => ReprFlags::IS_C,
1473 attr::ReprPacked(pack) => {
1474 min_pack = Some(if let Some(min_pack) = min_pack {
1475 min_pack.min(pack)
1476 } else {
1477 pack
1478 });
1479 ReprFlags::empty()
1480 }
1481 attr::ReprTransparent => ReprFlags::IS_TRANSPARENT,
1482 attr::ReprSimd => ReprFlags::IS_SIMD,
1483 attr::ReprInt(i) => {
1484 size = Some(match i {
1485 attr::IntType::SignedInt(x) => match x {
1486 ast::IntTy::Isize => IntegerType::Pointer(true),
1487 ast::IntTy::I8 => IntegerType::Fixed(Integer::I8, true),
1488 ast::IntTy::I16 => IntegerType::Fixed(Integer::I16, true),
1489 ast::IntTy::I32 => IntegerType::Fixed(Integer::I32, true),
1490 ast::IntTy::I64 => IntegerType::Fixed(Integer::I64, true),
1491 ast::IntTy::I128 => IntegerType::Fixed(Integer::I128, true),
1492 },
1493 attr::IntType::UnsignedInt(x) => match x {
1494 ast::UintTy::Usize => IntegerType::Pointer(false),
1495 ast::UintTy::U8 => IntegerType::Fixed(Integer::I8, false),
1496 ast::UintTy::U16 => IntegerType::Fixed(Integer::I16, false),
1497 ast::UintTy::U32 => IntegerType::Fixed(Integer::I32, false),
1498 ast::UintTy::U64 => IntegerType::Fixed(Integer::I64, false),
1499 ast::UintTy::U128 => IntegerType::Fixed(Integer::I128, false),
1500 },
1501 });
1502 ReprFlags::empty()
1503 }
1504 attr::ReprAlign(align) => {
1505 max_align = max_align.max(Some(align));
1506 ReprFlags::empty()
1507 }
1508 });
1509 }
1510 }
1511
1512 if self.sess.opts.unstable_opts.randomize_layout {
1515 flags.insert(ReprFlags::RANDOMIZE_LAYOUT);
1516 }
1517
1518 let is_box = self.is_lang_item(did.to_def_id(), LangItem::OwnedBox);
1521
1522 if is_box {
1524 flags.insert(ReprFlags::IS_LINEAR);
1525 }
1526
1527 ReprOptions { int: size, align: max_align, pack: min_pack, flags, field_shuffle_seed }
1528 }
1529
1530 pub fn opt_item_name(self, def_id: impl IntoQueryParam<DefId>) -> Option<Symbol> {
1532 let def_id = def_id.into_query_param();
1533 if let Some(cnum) = def_id.as_crate_root() {
1534 Some(self.crate_name(cnum))
1535 } else {
1536 let def_key = self.def_key(def_id);
1537 match def_key.disambiguated_data.data {
1538 rustc_hir::definitions::DefPathData::Ctor => self
1540 .opt_item_name(DefId { krate: def_id.krate, index: def_key.parent.unwrap() }),
1541 _ => def_key.get_opt_name(),
1542 }
1543 }
1544 }
1545
1546 pub fn item_name(self, id: impl IntoQueryParam<DefId>) -> Symbol {
1553 let id = id.into_query_param();
1554 self.opt_item_name(id).unwrap_or_else(|| {
1555 bug!("item_name: no name for {:?}", self.def_path(id));
1556 })
1557 }
1558
1559 pub fn opt_item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Option<Ident> {
1563 let def_id = def_id.into_query_param();
1564 let def = self.opt_item_name(def_id)?;
1565 let span = self
1566 .def_ident_span(def_id)
1567 .unwrap_or_else(|| bug!("missing ident span for {def_id:?}"));
1568 Some(Ident::new(def, span))
1569 }
1570
1571 pub fn item_ident(self, def_id: impl IntoQueryParam<DefId>) -> Ident {
1575 let def_id = def_id.into_query_param();
1576 self.opt_item_ident(def_id).unwrap_or_else(|| {
1577 bug!("item_ident: no name for {:?}", self.def_path(def_id));
1578 })
1579 }
1580
1581 pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
1582 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = self.def_kind(def_id) {
1583 Some(self.associated_item(def_id))
1584 } else {
1585 None
1586 }
1587 }
1588
1589 pub fn opt_rpitit_info(self, def_id: DefId) -> Option<ImplTraitInTraitData> {
1593 if let DefKind::AssocTy = self.def_kind(def_id)
1594 && let AssocKind::Type { data: AssocTypeData::Rpitit(rpitit_info) } =
1595 self.associated_item(def_id).kind
1596 {
1597 Some(rpitit_info)
1598 } else {
1599 None
1600 }
1601 }
1602
1603 pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<FieldIdx> {
1604 variant.fields.iter_enumerated().find_map(|(i, field)| {
1605 self.hygienic_eq(ident, field.ident(self), variant.def_id).then_some(i)
1606 })
1607 }
1608
1609 #[instrument(level = "debug", skip(self), ret)]
1612 pub fn impls_are_allowed_to_overlap(
1613 self,
1614 def_id1: DefId,
1615 def_id2: DefId,
1616 ) -> Option<ImplOverlapKind> {
1617 let impl1 = self.impl_trait_header(def_id1).unwrap();
1618 let impl2 = self.impl_trait_header(def_id2).unwrap();
1619
1620 let trait_ref1 = impl1.trait_ref.skip_binder();
1621 let trait_ref2 = impl2.trait_ref.skip_binder();
1622
1623 if trait_ref1.references_error() || trait_ref2.references_error() {
1626 return Some(ImplOverlapKind::Permitted { marker: false });
1627 }
1628
1629 match (impl1.polarity, impl2.polarity) {
1630 (ImplPolarity::Reservation, _) | (_, ImplPolarity::Reservation) => {
1631 return Some(ImplOverlapKind::Permitted { marker: false });
1633 }
1634 (ImplPolarity::Positive, ImplPolarity::Negative)
1635 | (ImplPolarity::Negative, ImplPolarity::Positive) => {
1636 return None;
1638 }
1639 (ImplPolarity::Positive, ImplPolarity::Positive)
1640 | (ImplPolarity::Negative, ImplPolarity::Negative) => {}
1641 };
1642
1643 let is_marker_impl = |trait_ref: TraitRef<'_>| self.trait_def(trait_ref.def_id).is_marker;
1644 let is_marker_overlap = is_marker_impl(trait_ref1) && is_marker_impl(trait_ref2);
1645
1646 if is_marker_overlap {
1647 return Some(ImplOverlapKind::Permitted { marker: true });
1648 }
1649
1650 None
1651 }
1652
1653 pub fn expect_variant_res(self, res: Res) -> &'tcx VariantDef {
1656 match res {
1657 Res::Def(DefKind::Variant, did) => {
1658 let enum_did = self.parent(did);
1659 self.adt_def(enum_did).variant_with_id(did)
1660 }
1661 Res::Def(DefKind::Struct | DefKind::Union, did) => self.adt_def(did).non_enum_variant(),
1662 Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_did) => {
1663 let variant_did = self.parent(variant_ctor_did);
1664 let enum_did = self.parent(variant_did);
1665 self.adt_def(enum_did).variant_with_ctor_id(variant_ctor_did)
1666 }
1667 Res::Def(DefKind::Ctor(CtorOf::Struct, ..), ctor_did) => {
1668 let struct_did = self.parent(ctor_did);
1669 self.adt_def(struct_did).non_enum_variant()
1670 }
1671 _ => bug!("expect_variant_res used with unexpected res {:?}", res),
1672 }
1673 }
1674
1675 #[instrument(skip(self), level = "debug")]
1677 pub fn instance_mir(self, instance: ty::InstanceKind<'tcx>) -> &'tcx Body<'tcx> {
1678 match instance {
1679 ty::InstanceKind::Item(def) => {
1680 debug!("calling def_kind on def: {:?}", def);
1681 let def_kind = self.def_kind(def);
1682 debug!("returned from def_kind: {:?}", def_kind);
1683 match def_kind {
1684 DefKind::Const
1685 | DefKind::Static { .. }
1686 | DefKind::AssocConst
1687 | DefKind::Ctor(..)
1688 | DefKind::AnonConst
1689 | DefKind::InlineConst => self.mir_for_ctfe(def),
1690 _ => self.optimized_mir(def),
1693 }
1694 }
1695 ty::InstanceKind::VTableShim(..)
1696 | ty::InstanceKind::ReifyShim(..)
1697 | ty::InstanceKind::Intrinsic(..)
1698 | ty::InstanceKind::FnPtrShim(..)
1699 | ty::InstanceKind::Virtual(..)
1700 | ty::InstanceKind::ClosureOnceShim { .. }
1701 | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1702 | ty::InstanceKind::FutureDropPollShim(..)
1703 | ty::InstanceKind::DropGlue(..)
1704 | ty::InstanceKind::CloneShim(..)
1705 | ty::InstanceKind::ThreadLocalShim(..)
1706 | ty::InstanceKind::FnPtrAddrShim(..)
1707 | ty::InstanceKind::AsyncDropGlueCtorShim(..)
1708 | ty::InstanceKind::AsyncDropGlue(..) => self.mir_shims(instance),
1709 }
1710 }
1711
1712 pub fn get_attrs(
1714 self,
1715 did: impl Into<DefId>,
1716 attr: Symbol,
1717 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1718 self.get_all_attrs(did).iter().filter(move |a: &&hir::Attribute| a.has_name(attr))
1719 }
1720
1721 pub fn get_all_attrs(self, did: impl Into<DefId>) -> &'tcx [hir::Attribute] {
1726 let did: DefId = did.into();
1727 if let Some(did) = did.as_local() {
1728 self.hir_attrs(self.local_def_id_to_hir_id(did))
1729 } else {
1730 self.attrs_for_def(did)
1731 }
1732 }
1733
1734 pub fn get_diagnostic_attr(
1743 self,
1744 did: impl Into<DefId>,
1745 attr: Symbol,
1746 ) -> Option<&'tcx hir::Attribute> {
1747 let did: DefId = did.into();
1748 if did.as_local().is_some() {
1749 if rustc_feature::is_stable_diagnostic_attribute(attr, self.features()) {
1751 self.get_attrs_by_path(did, &[sym::diagnostic, sym::do_not_recommend]).next()
1752 } else {
1753 None
1754 }
1755 } else {
1756 debug_assert!(rustc_feature::encode_cross_crate(attr));
1759 self.attrs_for_def(did)
1760 .iter()
1761 .find(|a| matches!(a.path().as_ref(), [sym::diagnostic, a] if *a == attr))
1762 }
1763 }
1764
1765 pub fn get_attrs_by_path(
1766 self,
1767 did: DefId,
1768 attr: &[Symbol],
1769 ) -> impl Iterator<Item = &'tcx hir::Attribute> {
1770 let filter_fn = move |a: &&hir::Attribute| a.path_matches(attr);
1771 if let Some(did) = did.as_local() {
1772 self.hir_attrs(self.local_def_id_to_hir_id(did)).iter().filter(filter_fn)
1773 } else {
1774 self.attrs_for_def(did).iter().filter(filter_fn)
1775 }
1776 }
1777
1778 pub fn get_attr(self, did: impl Into<DefId>, attr: Symbol) -> Option<&'tcx hir::Attribute> {
1779 if cfg!(debug_assertions) && !rustc_feature::is_valid_for_get_attr(attr) {
1780 let did: DefId = did.into();
1781 bug!("get_attr: unexpected called with DefId `{:?}`, attr `{:?}`", did, attr);
1782 } else {
1783 self.get_attrs(did, attr).next()
1784 }
1785 }
1786
1787 pub fn has_attr(self, did: impl Into<DefId>, attr: Symbol) -> bool {
1789 self.get_attrs(did, attr).next().is_some()
1790 }
1791
1792 pub fn has_attrs_with_path(self, did: impl Into<DefId>, attrs: &[Symbol]) -> bool {
1794 self.get_attrs_by_path(did.into(), attrs).next().is_some()
1795 }
1796
1797 pub fn trait_is_auto(self, trait_def_id: DefId) -> bool {
1799 self.trait_def(trait_def_id).has_auto_impl
1800 }
1801
1802 pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
1805 self.trait_def(trait_def_id).is_coinductive
1806 }
1807
1808 pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
1810 self.def_kind(trait_def_id) == DefKind::TraitAlias
1811 }
1812
1813 fn layout_error(self, err: LayoutError<'tcx>) -> &'tcx LayoutError<'tcx> {
1815 self.arena.alloc(err)
1816 }
1817
1818 fn ordinary_coroutine_layout(
1824 self,
1825 def_id: DefId,
1826 args: GenericArgsRef<'tcx>,
1827 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1828 let coroutine_kind_ty = args.as_coroutine().kind_ty();
1829 let mir = self.optimized_mir(def_id);
1830 let ty = || Ty::new_coroutine(self, def_id, args);
1831 if coroutine_kind_ty.is_unit() {
1833 mir.coroutine_layout_raw().ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1834 } else {
1835 let ty::Coroutine(_, identity_args) =
1838 *self.type_of(def_id).instantiate_identity().kind()
1839 else {
1840 unreachable!();
1841 };
1842 let identity_kind_ty = identity_args.as_coroutine().kind_ty();
1843 if identity_kind_ty == coroutine_kind_ty {
1846 mir.coroutine_layout_raw()
1847 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1848 } else {
1849 assert_matches!(coroutine_kind_ty.to_opt_closure_kind(), Some(ClosureKind::FnOnce));
1850 assert_matches!(
1851 identity_kind_ty.to_opt_closure_kind(),
1852 Some(ClosureKind::Fn | ClosureKind::FnMut)
1853 );
1854 self.optimized_mir(self.coroutine_by_move_body_def_id(def_id))
1855 .coroutine_layout_raw()
1856 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1857 }
1858 }
1859 }
1860
1861 fn async_drop_coroutine_layout(
1865 self,
1866 def_id: DefId,
1867 args: GenericArgsRef<'tcx>,
1868 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1869 let ty = || Ty::new_coroutine(self, def_id, args);
1870 if args[0].has_placeholders() || args[0].has_non_region_param() {
1871 return Err(self.layout_error(LayoutError::TooGeneric(ty())));
1872 }
1873 let instance = InstanceKind::AsyncDropGlue(def_id, Ty::new_coroutine(self, def_id, args));
1874 self.mir_shims(instance)
1875 .coroutine_layout_raw()
1876 .ok_or_else(|| self.layout_error(LayoutError::Unknown(ty())))
1877 }
1878
1879 pub fn coroutine_layout(
1882 self,
1883 def_id: DefId,
1884 args: GenericArgsRef<'tcx>,
1885 ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> {
1886 if self.is_async_drop_in_place_coroutine(def_id) {
1887 let arg_cor_ty = args.first().unwrap().expect_ty();
1891 if arg_cor_ty.is_coroutine() {
1892 let span = self.def_span(def_id);
1893 let source_info = SourceInfo::outermost(span);
1894 let variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
1897 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1898 let variant_source_info: IndexVec<VariantIdx, SourceInfo> =
1899 iter::repeat(source_info).take(CoroutineArgs::RESERVED_VARIANTS).collect();
1900 let proxy_layout = CoroutineLayout {
1901 field_tys: [].into(),
1902 field_names: [].into(),
1903 variant_fields,
1904 variant_source_info,
1905 storage_conflicts: BitMatrix::new(0, 0),
1906 };
1907 return Ok(self.arena.alloc(proxy_layout));
1908 } else {
1909 self.async_drop_coroutine_layout(def_id, args)
1910 }
1911 } else {
1912 self.ordinary_coroutine_layout(def_id, args)
1913 }
1914 }
1915
1916 pub fn trait_id_of_impl(self, def_id: DefId) -> Option<DefId> {
1919 self.impl_trait_ref(def_id).map(|tr| tr.skip_binder().def_id)
1920 }
1921
1922 pub fn assoc_parent(self, def_id: DefId) -> Option<(DefId, DefKind)> {
1924 if !self.def_kind(def_id).is_assoc() {
1925 return None;
1926 }
1927 let parent = self.parent(def_id);
1928 let def_kind = self.def_kind(parent);
1929 Some((parent, def_kind))
1930 }
1931
1932 pub fn trait_item_of(self, def_id: impl IntoQueryParam<DefId>) -> Option<DefId> {
1934 self.opt_associated_item(def_id.into_query_param())?.trait_item_def_id()
1935 }
1936
1937 pub fn trait_of_assoc(self, def_id: DefId) -> Option<DefId> {
1940 match self.assoc_parent(def_id) {
1941 Some((id, DefKind::Trait)) => Some(id),
1942 _ => None,
1943 }
1944 }
1945
1946 pub fn impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1949 match self.assoc_parent(def_id) {
1950 Some((id, DefKind::Impl { .. })) => Some(id),
1951 _ => None,
1952 }
1953 }
1954
1955 pub fn inherent_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1958 match self.assoc_parent(def_id) {
1959 Some((id, DefKind::Impl { of_trait: false })) => Some(id),
1960 _ => None,
1961 }
1962 }
1963
1964 pub fn trait_impl_of_assoc(self, def_id: DefId) -> Option<DefId> {
1967 match self.assoc_parent(def_id) {
1968 Some((id, DefKind::Impl { of_trait: true })) => Some(id),
1969 _ => None,
1970 }
1971 }
1972
1973 pub fn is_exportable(self, def_id: DefId) -> bool {
1974 self.exportable_items(def_id.krate).contains(&def_id)
1975 }
1976
1977 pub fn is_builtin_derived(self, def_id: DefId) -> bool {
1980 if self.is_automatically_derived(def_id)
1981 && let Some(def_id) = def_id.as_local()
1982 && let outer = self.def_span(def_id).ctxt().outer_expn_data()
1983 && matches!(outer.kind, ExpnKind::Macro(MacroKind::Derive, _))
1984 && find_attr!(
1985 self.get_all_attrs(outer.macro_def_id.unwrap()),
1986 AttributeKind::RustcBuiltinMacro { .. }
1987 )
1988 {
1989 true
1990 } else {
1991 false
1992 }
1993 }
1994
1995 pub fn is_automatically_derived(self, def_id: DefId) -> bool {
1997 find_attr!(self.get_all_attrs(def_id), AttributeKind::AutomaticallyDerived(..))
1998 }
1999
2000 pub fn span_of_impl(self, impl_def_id: DefId) -> Result<Span, Symbol> {
2003 if let Some(impl_def_id) = impl_def_id.as_local() {
2004 Ok(self.def_span(impl_def_id))
2005 } else {
2006 Err(self.crate_name(impl_def_id.krate))
2007 }
2008 }
2009
2010 pub fn hygienic_eq(self, use_ident: Ident, def_ident: Ident, def_parent_def_id: DefId) -> bool {
2014 use_ident.name == def_ident.name
2018 && use_ident
2019 .span
2020 .ctxt()
2021 .hygienic_eq(def_ident.span.ctxt(), self.expn_that_defined(def_parent_def_id))
2022 }
2023
2024 pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident {
2025 ident.span.normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope));
2026 ident
2027 }
2028
2029 pub fn adjust_ident_and_get_scope(
2031 self,
2032 mut ident: Ident,
2033 scope: DefId,
2034 block: hir::HirId,
2035 ) -> (Ident, DefId) {
2036 let scope = ident
2037 .span
2038 .normalize_to_macros_2_0_and_adjust(self.expn_that_defined(scope))
2039 .and_then(|actual_expansion| actual_expansion.expn_data().parent_module)
2040 .unwrap_or_else(|| self.parent_module(block).to_def_id());
2041 (ident, scope)
2042 }
2043
2044 #[inline]
2048 pub fn is_const_fn(self, def_id: DefId) -> bool {
2049 matches!(
2050 self.def_kind(def_id),
2051 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::Closure
2052 ) && self.constness(def_id) == hir::Constness::Const
2053 }
2054
2055 pub fn is_conditionally_const(self, def_id: impl Into<DefId>) -> bool {
2062 let def_id: DefId = def_id.into();
2063 match self.def_kind(def_id) {
2064 DefKind::Impl { of_trait: true } => {
2065 let header = self.impl_trait_header(def_id).unwrap();
2066 header.constness == hir::Constness::Const
2067 && self.is_const_trait(header.trait_ref.skip_binder().def_id)
2068 }
2069 DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) => {
2070 self.constness(def_id) == hir::Constness::Const
2071 }
2072 DefKind::Trait => self.is_const_trait(def_id),
2073 DefKind::AssocTy => {
2074 let parent_def_id = self.parent(def_id);
2075 match self.def_kind(parent_def_id) {
2076 DefKind::Impl { of_trait: false } => false,
2077 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2078 self.is_conditionally_const(parent_def_id)
2079 }
2080 _ => bug!("unexpected parent item of associated type: {parent_def_id:?}"),
2081 }
2082 }
2083 DefKind::AssocFn => {
2084 let parent_def_id = self.parent(def_id);
2085 match self.def_kind(parent_def_id) {
2086 DefKind::Impl { of_trait: false } => {
2087 self.constness(def_id) == hir::Constness::Const
2088 }
2089 DefKind::Impl { of_trait: true } | DefKind::Trait => {
2090 self.is_conditionally_const(parent_def_id)
2091 }
2092 _ => bug!("unexpected parent item of associated fn: {parent_def_id:?}"),
2093 }
2094 }
2095 DefKind::OpaqueTy => match self.opaque_ty_origin(def_id) {
2096 hir::OpaqueTyOrigin::FnReturn { parent, .. } => self.is_conditionally_const(parent),
2097 hir::OpaqueTyOrigin::AsyncFn { .. } => false,
2098 hir::OpaqueTyOrigin::TyAlias { .. } => false,
2100 },
2101 DefKind::Closure => {
2102 false
2105 }
2106 DefKind::Ctor(_, CtorKind::Const)
2107 | DefKind::Impl { of_trait: false }
2108 | DefKind::Mod
2109 | DefKind::Struct
2110 | DefKind::Union
2111 | DefKind::Enum
2112 | DefKind::Variant
2113 | DefKind::TyAlias
2114 | DefKind::ForeignTy
2115 | DefKind::TraitAlias
2116 | DefKind::TyParam
2117 | DefKind::Const
2118 | DefKind::ConstParam
2119 | DefKind::Static { .. }
2120 | DefKind::AssocConst
2121 | DefKind::Macro(_)
2122 | DefKind::ExternCrate
2123 | DefKind::Use
2124 | DefKind::ForeignMod
2125 | DefKind::AnonConst
2126 | DefKind::InlineConst
2127 | DefKind::Field
2128 | DefKind::LifetimeParam
2129 | DefKind::GlobalAsm
2130 | DefKind::SyntheticCoroutineBody => false,
2131 }
2132 }
2133
2134 #[inline]
2135 pub fn is_const_trait(self, def_id: DefId) -> bool {
2136 self.trait_def(def_id).constness == hir::Constness::Const
2137 }
2138
2139 #[inline]
2140 pub fn is_const_default_method(self, def_id: DefId) -> bool {
2141 matches!(self.trait_of_assoc(def_id), Some(trait_id) if self.is_const_trait(trait_id))
2142 }
2143
2144 pub fn impl_method_has_trait_impl_trait_tys(self, def_id: DefId) -> bool {
2145 if self.def_kind(def_id) != DefKind::AssocFn {
2146 return false;
2147 }
2148
2149 let Some(item) = self.opt_associated_item(def_id) else {
2150 return false;
2151 };
2152
2153 let AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container else {
2154 return false;
2155 };
2156
2157 !self.associated_types_for_impl_traits_in_associated_fn(trait_item_def_id).is_empty()
2158 }
2159}
2160
2161pub fn provide(providers: &mut Providers) {
2162 closure::provide(providers);
2163 context::provide(providers);
2164 erase_regions::provide(providers);
2165 inhabitedness::provide(providers);
2166 util::provide(providers);
2167 print::provide(providers);
2168 super::util::bug::provide(providers);
2169 *providers = Providers {
2170 trait_impls_of: trait_def::trait_impls_of_provider,
2171 incoherent_impls: trait_def::incoherent_impls_provider,
2172 trait_impls_in_crate: trait_def::trait_impls_in_crate_provider,
2173 traits: trait_def::traits_provider,
2174 vtable_allocation: vtable::vtable_allocation_provider,
2175 ..*providers
2176 };
2177}
2178
2179#[derive(Clone, Debug, Default, HashStable)]
2185pub struct CrateInherentImpls {
2186 pub inherent_impls: FxIndexMap<LocalDefId, Vec<DefId>>,
2187 pub incoherent_impls: FxIndexMap<SimplifiedType, Vec<LocalDefId>>,
2188}
2189
2190#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, HashStable)]
2191pub struct SymbolName<'tcx> {
2192 pub name: &'tcx str,
2194}
2195
2196impl<'tcx> SymbolName<'tcx> {
2197 pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2198 SymbolName { name: tcx.arena.alloc_str(name) }
2199 }
2200}
2201
2202impl<'tcx> fmt::Display for SymbolName<'tcx> {
2203 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2204 fmt::Display::fmt(&self.name, fmt)
2205 }
2206}
2207
2208impl<'tcx> fmt::Debug for SymbolName<'tcx> {
2209 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2210 fmt::Display::fmt(&self.name, fmt)
2211 }
2212}
2213
2214#[derive(Copy, Clone, Debug, HashStable)]
2216pub struct DestructuredConst<'tcx> {
2217 pub variant: Option<VariantIdx>,
2218 pub fields: &'tcx [ty::Const<'tcx>],
2219}
2220
2221pub fn fnc_typetrees<'tcx>(tcx: TyCtxt<'tcx>, fn_ty: Ty<'tcx>) -> FncTree {
2225 if tcx.sess.opts.unstable_opts.autodiff.contains(&rustc_session::config::AutoDiff::NoTT) {
2227 return FncTree { args: vec![], ret: TypeTree::new() };
2228 }
2229
2230 if !fn_ty.is_fn() {
2232 return FncTree { args: vec![], ret: TypeTree::new() };
2233 }
2234
2235 let fn_sig = fn_ty.fn_sig(tcx);
2237 let sig = tcx.instantiate_bound_regions_with_erased(fn_sig);
2238
2239 let mut args = vec![];
2241 for ty in sig.inputs().iter() {
2242 let type_tree = typetree_from_ty(tcx, *ty);
2243 args.push(type_tree);
2244 }
2245
2246 let ret = typetree_from_ty(tcx, sig.output());
2248
2249 FncTree { args, ret }
2250}
2251
2252pub fn typetree_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> TypeTree {
2255 let mut visited = Vec::new();
2256 typetree_from_ty_inner(tcx, ty, 0, &mut visited)
2257}
2258
2259const MAX_TYPETREE_DEPTH: usize = 6;
2262
2263fn typetree_from_ty_inner<'tcx>(
2265 tcx: TyCtxt<'tcx>,
2266 ty: Ty<'tcx>,
2267 depth: usize,
2268 visited: &mut Vec<Ty<'tcx>>,
2269) -> TypeTree {
2270 if depth >= MAX_TYPETREE_DEPTH {
2271 trace!("typetree depth limit {} reached for type: {}", MAX_TYPETREE_DEPTH, ty);
2272 return TypeTree::new();
2273 }
2274
2275 if visited.contains(&ty) {
2276 return TypeTree::new();
2277 }
2278
2279 visited.push(ty);
2280 let result = typetree_from_ty_impl(tcx, ty, depth, visited);
2281 visited.pop();
2282 result
2283}
2284
2285fn typetree_from_ty_impl<'tcx>(
2287 tcx: TyCtxt<'tcx>,
2288 ty: Ty<'tcx>,
2289 depth: usize,
2290 visited: &mut Vec<Ty<'tcx>>,
2291) -> TypeTree {
2292 typetree_from_ty_impl_inner(tcx, ty, depth, visited, false)
2293}
2294
2295fn typetree_from_ty_impl_inner<'tcx>(
2297 tcx: TyCtxt<'tcx>,
2298 ty: Ty<'tcx>,
2299 depth: usize,
2300 visited: &mut Vec<Ty<'tcx>>,
2301 is_reference_target: bool,
2302) -> TypeTree {
2303 if ty.is_scalar() {
2304 let (kind, size) = if ty.is_integral() || ty.is_char() || ty.is_bool() {
2305 (Kind::Integer, ty.primitive_size(tcx).bytes_usize())
2306 } else if ty.is_floating_point() {
2307 match ty {
2308 x if x == tcx.types.f16 => (Kind::Half, 2),
2309 x if x == tcx.types.f32 => (Kind::Float, 4),
2310 x if x == tcx.types.f64 => (Kind::Double, 8),
2311 x if x == tcx.types.f128 => (Kind::F128, 16),
2312 _ => (Kind::Integer, 0),
2313 }
2314 } else {
2315 (Kind::Integer, 0)
2316 };
2317
2318 let offset = if is_reference_target && !ty.is_array() { 0 } else { -1 };
2321 return TypeTree(vec![Type { offset, size, kind, child: TypeTree::new() }]);
2322 }
2323
2324 if ty.is_ref() || ty.is_raw_ptr() || ty.is_box() {
2325 let inner_ty = if let Some(inner) = ty.builtin_deref(true) {
2326 inner
2327 } else {
2328 return TypeTree::new();
2329 };
2330
2331 let child = typetree_from_ty_impl_inner(tcx, inner_ty, depth + 1, visited, true);
2332 return TypeTree(vec![Type {
2333 offset: -1,
2334 size: tcx.data_layout.pointer_size().bytes_usize(),
2335 kind: Kind::Pointer,
2336 child,
2337 }]);
2338 }
2339
2340 if ty.is_array() {
2341 if let ty::Array(element_ty, len_const) = ty.kind() {
2342 let len = len_const.try_to_target_usize(tcx).unwrap_or(0);
2343 if len == 0 {
2344 return TypeTree::new();
2345 }
2346 let element_tree =
2347 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2348 let mut types = Vec::new();
2349 for elem_type in &element_tree.0 {
2350 types.push(Type {
2351 offset: -1,
2352 size: elem_type.size,
2353 kind: elem_type.kind,
2354 child: elem_type.child.clone(),
2355 });
2356 }
2357
2358 return TypeTree(types);
2359 }
2360 }
2361
2362 if ty.is_slice() {
2363 if let ty::Slice(element_ty) = ty.kind() {
2364 let element_tree =
2365 typetree_from_ty_impl_inner(tcx, *element_ty, depth + 1, visited, false);
2366 return element_tree;
2367 }
2368 }
2369
2370 if let ty::Tuple(tuple_types) = ty.kind() {
2371 if tuple_types.is_empty() {
2372 return TypeTree::new();
2373 }
2374
2375 let mut types = Vec::new();
2376 let mut current_offset = 0;
2377
2378 for tuple_ty in tuple_types.iter() {
2379 let element_tree =
2380 typetree_from_ty_impl_inner(tcx, tuple_ty, depth + 1, visited, false);
2381
2382 let element_layout = tcx
2383 .layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(tuple_ty))
2384 .ok()
2385 .map(|layout| layout.size.bytes_usize())
2386 .unwrap_or(0);
2387
2388 for elem_type in &element_tree.0 {
2389 types.push(Type {
2390 offset: if elem_type.offset == -1 {
2391 current_offset as isize
2392 } else {
2393 current_offset as isize + elem_type.offset
2394 },
2395 size: elem_type.size,
2396 kind: elem_type.kind,
2397 child: elem_type.child.clone(),
2398 });
2399 }
2400
2401 current_offset += element_layout;
2402 }
2403
2404 return TypeTree(types);
2405 }
2406
2407 if let ty::Adt(adt_def, args) = ty.kind() {
2408 if adt_def.is_struct() {
2409 let struct_layout =
2410 tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty));
2411 if let Ok(layout) = struct_layout {
2412 let mut types = Vec::new();
2413
2414 for (field_idx, field_def) in adt_def.all_fields().enumerate() {
2415 let field_ty = field_def.ty(tcx, args);
2416 let field_tree =
2417 typetree_from_ty_impl_inner(tcx, field_ty, depth + 1, visited, false);
2418
2419 let field_offset = layout.fields.offset(field_idx).bytes_usize();
2420
2421 for elem_type in &field_tree.0 {
2422 types.push(Type {
2423 offset: if elem_type.offset == -1 {
2424 field_offset as isize
2425 } else {
2426 field_offset as isize + elem_type.offset
2427 },
2428 size: elem_type.size,
2429 kind: elem_type.kind,
2430 child: elem_type.child.clone(),
2431 });
2432 }
2433 }
2434
2435 return TypeTree(types);
2436 }
2437 }
2438 }
2439
2440 TypeTree::new()
2441}