1use std::{fmt, iter};
4
5use rustc_abi::{Float, Integer, IntegerType, Size};
6use rustc_apfloat::Float as _;
7use rustc_ast::attr::AttributeExt;
8use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
10use rustc_data_structures::stack::ensure_sufficient_stack;
11use rustc_errors::ErrorGuaranteed;
12use rustc_hashes::Hash128;
13use rustc_hir as hir;
14use rustc_hir::attrs::AttributeKind;
15use rustc_hir::def::{CtorOf, DefKind, Res};
16use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
17use rustc_hir::limit::Limit;
18use rustc_index::bit_set::GrowableBitSet;
19use rustc_macros::{HashStable, TyDecodable, TyEncodable, extension};
20use rustc_span::sym;
21use rustc_type_ir::solve::SizedTraitKind;
22use smallvec::{SmallVec, smallvec};
23use tracing::{debug, instrument};
24
25use super::TypingEnv;
26use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
27use crate::mir;
28use crate::query::Providers;
29use crate::traits::ObligationCause;
30use crate::ty::layout::{FloatExt, IntegerExt};
31use crate::ty::{
32 self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
33 TypeFolder, TypeSuperFoldable, TypeVisitableExt, Upcast,
34};
35
36#[derive(Copy, Clone, Debug)]
37pub struct Discr<'tcx> {
38 pub val: u128,
40 pub ty: Ty<'tcx>,
41}
42
43#[derive(Copy, Clone, Debug, PartialEq, Eq)]
45pub enum CheckRegions {
46 No,
47 OnlyParam,
51 FromFunction,
55}
56
57#[derive(Copy, Clone, Debug)]
58pub enum NotUniqueParam<'tcx> {
59 DuplicateParam(ty::GenericArg<'tcx>),
60 NotParam(ty::GenericArg<'tcx>),
61}
62
63impl<'tcx> fmt::Display for Discr<'tcx> {
64 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match *self.ty.kind() {
66 ty::Int(ity) => {
67 let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
68 let x = self.val;
69 let x = size.sign_extend(x) as i128;
71 write!(fmt, "{x}")
72 }
73 _ => write!(fmt, "{}", self.val),
74 }
75 }
76}
77
78impl<'tcx> Discr<'tcx> {
79 pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
81 self.checked_add(tcx, 1).0
82 }
83 pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
84 let (size, signed) = self.ty.int_size_and_signed(tcx);
85 let (val, oflo) = if signed {
86 let min = size.signed_int_min();
87 let max = size.signed_int_max();
88 let val = size.sign_extend(self.val);
89 assert!(n < (i128::MAX as u128));
90 let n = n as i128;
91 let oflo = val > max - n;
92 let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
93 let val = val as u128;
95 let val = size.truncate(val);
96 (val, oflo)
97 } else {
98 let max = size.unsigned_int_max();
99 let val = self.val;
100 let oflo = val > max - n;
101 let val = if oflo { n - (max - val) - 1 } else { val + n };
102 (val, oflo)
103 };
104 (Self { val, ty: self.ty }, oflo)
105 }
106}
107
108#[extension(pub trait IntTypeExt)]
109impl IntegerType {
110 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
111 match self {
112 IntegerType::Pointer(true) => tcx.types.isize,
113 IntegerType::Pointer(false) => tcx.types.usize,
114 IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
115 }
116 }
117
118 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
119 Discr { val: 0, ty: self.to_ty(tcx) }
120 }
121
122 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
123 if let Some(val) = val {
124 assert_eq!(self.to_ty(tcx), val.ty);
125 let (new, oflo) = val.checked_add(tcx, 1);
126 if oflo { None } else { Some(new) }
127 } else {
128 Some(self.initial_discriminant(tcx))
129 }
130 }
131}
132
133impl<'tcx> TyCtxt<'tcx> {
134 pub fn type_id_hash(self, ty: Ty<'tcx>) -> Hash128 {
137 let ty = self.erase_and_anonymize_regions(ty);
140
141 self.with_stable_hashing_context(|mut hcx| {
142 let mut hasher = StableHasher::new();
143 hcx.while_hashing_spans(false, |hcx| ty.hash_stable(hcx, &mut hasher));
144 hasher.finish()
145 })
146 }
147
148 pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
149 match res {
150 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
151 Some(self.parent(self.parent(def_id)))
152 }
153 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
154 Some(self.parent(def_id))
155 }
156 Res::Def(
159 DefKind::Struct
160 | DefKind::Union
161 | DefKind::Enum
162 | DefKind::Trait
163 | DefKind::OpaqueTy
164 | DefKind::TyAlias
165 | DefKind::ForeignTy
166 | DefKind::TraitAlias
167 | DefKind::AssocTy
168 | DefKind::Fn
169 | DefKind::AssocFn
170 | DefKind::AssocConst
171 | DefKind::Impl { .. },
172 def_id,
173 ) => Some(def_id),
174 Res::Err => None,
175 _ => None,
176 }
177 }
178
179 pub fn type_is_copy_modulo_regions(
190 self,
191 typing_env: ty::TypingEnv<'tcx>,
192 ty: Ty<'tcx>,
193 ) -> bool {
194 ty.is_trivially_pure_clone_copy() || self.is_copy_raw(typing_env.as_query_input(ty))
195 }
196
197 pub fn type_is_use_cloned_modulo_regions(
202 self,
203 typing_env: ty::TypingEnv<'tcx>,
204 ty: Ty<'tcx>,
205 ) -> bool {
206 ty.is_trivially_pure_clone_copy() || self.is_use_cloned_raw(typing_env.as_query_input(ty))
207 }
208
209 pub fn struct_tail_for_codegen(
217 self,
218 ty: Ty<'tcx>,
219 typing_env: ty::TypingEnv<'tcx>,
220 ) -> Ty<'tcx> {
221 let tcx = self;
222 tcx.struct_tail_raw(
223 ty,
224 &ObligationCause::dummy(),
225 |ty| tcx.normalize_erasing_regions(typing_env, ty),
226 || {},
227 )
228 }
229
230 pub fn type_has_metadata(self, ty: Ty<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
232 if ty.is_sized(self, typing_env) {
233 return false;
234 }
235
236 let tail = self.struct_tail_for_codegen(ty, typing_env);
237 match tail.kind() {
238 ty::Foreign(..) => false,
239 ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
240 _ => bug!("unexpected unsized tail: {:?}", tail),
241 }
242 }
243
244 pub fn struct_tail_raw(
257 self,
258 mut ty: Ty<'tcx>,
259 cause: &ObligationCause<'tcx>,
260 mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
261 mut f: impl FnMut() -> (),
265 ) -> Ty<'tcx> {
266 let recursion_limit = self.recursion_limit();
267 for iteration in 0.. {
268 if !recursion_limit.value_within_limit(iteration) {
269 let suggested_limit = match recursion_limit {
270 Limit(0) => Limit(2),
271 limit => limit * 2,
272 };
273 let reported = self.dcx().emit_err(crate::error::RecursionLimitReached {
274 span: cause.span,
275 ty,
276 suggested_limit,
277 });
278 return Ty::new_error(self, reported);
279 }
280 match *ty.kind() {
281 ty::Adt(def, args) => {
282 if !def.is_struct() {
283 break;
284 }
285 match def.non_enum_variant().tail_opt() {
286 Some(field) => {
287 f();
288 ty = field.ty(self, args);
289 }
290 None => break,
291 }
292 }
293
294 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
295 f();
296 ty = last_ty;
297 }
298
299 ty::Tuple(_) => break,
300
301 ty::Pat(inner, _) => {
302 f();
303 ty = inner;
304 }
305
306 ty::Alias(..) => {
307 let normalized = normalize(ty);
308 if ty == normalized {
309 return ty;
310 } else {
311 ty = normalized;
312 }
313 }
314
315 _ => {
316 break;
317 }
318 }
319 }
320 ty
321 }
322
323 pub fn struct_lockstep_tails_for_codegen(
333 self,
334 source: Ty<'tcx>,
335 target: Ty<'tcx>,
336 typing_env: ty::TypingEnv<'tcx>,
337 ) -> (Ty<'tcx>, Ty<'tcx>) {
338 let tcx = self;
339 tcx.struct_lockstep_tails_raw(source, target, |ty| {
340 tcx.normalize_erasing_regions(typing_env, ty)
341 })
342 }
343
344 pub fn struct_lockstep_tails_raw(
353 self,
354 source: Ty<'tcx>,
355 target: Ty<'tcx>,
356 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
357 ) -> (Ty<'tcx>, Ty<'tcx>) {
358 let (mut a, mut b) = (source, target);
359 loop {
360 match (a.kind(), b.kind()) {
361 (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args))
362 if a_def == b_def && a_def.is_struct() =>
363 {
364 if let Some(f) = a_def.non_enum_variant().tail_opt() {
365 a = f.ty(self, a_args);
366 b = f.ty(self, b_args);
367 } else {
368 break;
369 }
370 }
371 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
372 if let Some(&a_last) = a_tys.last() {
373 a = a_last;
374 b = *b_tys.last().unwrap();
375 } else {
376 break;
377 }
378 }
379 (ty::Alias(..), _) | (_, ty::Alias(..)) => {
380 let a_norm = normalize(a);
385 let b_norm = normalize(b);
386 if a == a_norm && b == b_norm {
387 break;
388 } else {
389 a = a_norm;
390 b = b_norm;
391 }
392 }
393
394 _ => break,
395 }
396 }
397 (a, b)
398 }
399
400 pub fn calculate_dtor(
402 self,
403 adt_did: LocalDefId,
404 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
405 ) -> Option<ty::Destructor> {
406 let drop_trait = self.lang_items().drop_trait()?;
407 self.ensure_ok().coherent_trait(drop_trait).ok()?;
408
409 let mut dtor_candidate = None;
410 for &impl_did in self.local_trait_impls(drop_trait) {
412 let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
413 if adt_def.did() != adt_did.to_def_id() {
414 continue;
415 }
416
417 if validate(self, impl_did).is_err() {
418 continue;
420 }
421
422 let Some(item_id) = self.associated_item_def_ids(impl_did).first() else {
423 self.dcx()
424 .span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
425 continue;
426 };
427
428 if self.def_kind(item_id) != DefKind::AssocFn {
429 self.dcx().span_delayed_bug(self.def_span(item_id), "drop is not a function");
430 continue;
431 }
432
433 if let Some(old_item_id) = dtor_candidate {
434 self.dcx()
435 .struct_span_err(self.def_span(item_id), "multiple drop impls found")
436 .with_span_note(self.def_span(old_item_id), "other impl here")
437 .delay_as_bug();
438 }
439
440 dtor_candidate = Some(*item_id);
441 }
442
443 let did = dtor_candidate?;
444 Some(ty::Destructor { did })
445 }
446
447 pub fn calculate_async_dtor(
449 self,
450 adt_did: LocalDefId,
451 validate: impl Fn(Self, LocalDefId) -> Result<(), ErrorGuaranteed>,
452 ) -> Option<ty::AsyncDestructor> {
453 let async_drop_trait = self.lang_items().async_drop_trait()?;
454 self.ensure_ok().coherent_trait(async_drop_trait).ok()?;
455
456 let mut dtor_candidate = None;
457 for &impl_did in self.local_trait_impls(async_drop_trait) {
459 let Some(adt_def) = self.type_of(impl_did).skip_binder().ty_adt_def() else { continue };
460 if adt_def.did() != adt_did.to_def_id() {
461 continue;
462 }
463
464 if validate(self, impl_did).is_err() {
465 continue;
467 }
468
469 if let Some(old_impl_did) = dtor_candidate {
470 self.dcx()
471 .struct_span_err(self.def_span(impl_did), "multiple async drop impls found")
472 .with_span_note(self.def_span(old_impl_did), "other impl here")
473 .delay_as_bug();
474 }
475
476 dtor_candidate = Some(impl_did);
477 }
478
479 Some(ty::AsyncDestructor { impl_did: dtor_candidate?.into() })
480 }
481
482 pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
490 let dtor = match def.destructor(self) {
491 None => {
492 debug!("destructor_constraints({:?}) - no dtor", def.did());
493 return vec![];
494 }
495 Some(dtor) => dtor.did,
496 };
497
498 let impl_def_id = self.parent(dtor);
499 let impl_generics = self.generics_of(impl_def_id);
500
501 let impl_args = match *self.type_of(impl_def_id).instantiate_identity().kind() {
523 ty::Adt(def_, args) if def_ == def => args,
524 _ => span_bug!(self.def_span(impl_def_id), "expected ADT for self type of `Drop` impl"),
525 };
526
527 let item_args = ty::GenericArgs::identity_for_item(self, def.did());
528
529 let result = iter::zip(item_args, impl_args)
530 .filter(|&(_, arg)| {
531 match arg.kind() {
532 GenericArgKind::Lifetime(region) => match region.kind() {
533 ty::ReEarlyParam(ebr) => {
534 !impl_generics.region_param(ebr, self).pure_wrt_drop
535 }
536 _ => false,
538 },
539 GenericArgKind::Type(ty) => match *ty.kind() {
540 ty::Param(pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
541 _ => false,
543 },
544 GenericArgKind::Const(ct) => match ct.kind() {
545 ty::ConstKind::Param(pc) => {
546 !impl_generics.const_param(pc, self).pure_wrt_drop
547 }
548 _ => false,
550 },
551 }
552 })
553 .map(|(item_param, _)| item_param)
554 .collect();
555 debug!("destructor_constraint({:?}) = {:?}", def.did(), result);
556 result
557 }
558
559 pub fn uses_unique_generic_params(
561 self,
562 args: &[ty::GenericArg<'tcx>],
563 ignore_regions: CheckRegions,
564 ) -> Result<(), NotUniqueParam<'tcx>> {
565 let mut seen = GrowableBitSet::default();
566 let mut seen_late = FxHashSet::default();
567 for arg in args {
568 match arg.kind() {
569 GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
570 (CheckRegions::FromFunction, ty::ReBound(di, reg)) => {
571 if !seen_late.insert((di, reg)) {
572 return Err(NotUniqueParam::DuplicateParam(lt.into()));
573 }
574 }
575 (CheckRegions::OnlyParam | CheckRegions::FromFunction, ty::ReEarlyParam(p)) => {
576 if !seen.insert(p.index) {
577 return Err(NotUniqueParam::DuplicateParam(lt.into()));
578 }
579 }
580 (CheckRegions::OnlyParam | CheckRegions::FromFunction, _) => {
581 return Err(NotUniqueParam::NotParam(lt.into()));
582 }
583 (CheckRegions::No, _) => {}
584 },
585 GenericArgKind::Type(t) => match t.kind() {
586 ty::Param(p) => {
587 if !seen.insert(p.index) {
588 return Err(NotUniqueParam::DuplicateParam(t.into()));
589 }
590 }
591 _ => return Err(NotUniqueParam::NotParam(t.into())),
592 },
593 GenericArgKind::Const(c) => match c.kind() {
594 ty::ConstKind::Param(p) => {
595 if !seen.insert(p.index) {
596 return Err(NotUniqueParam::DuplicateParam(c.into()));
597 }
598 }
599 _ => return Err(NotUniqueParam::NotParam(c.into())),
600 },
601 }
602 }
603
604 Ok(())
605 }
606
607 pub fn is_closure_like(self, def_id: DefId) -> bool {
616 matches!(self.def_kind(def_id), DefKind::Closure)
617 }
618
619 pub fn is_typeck_child(self, def_id: DefId) -> bool {
622 self.def_kind(def_id).is_typeck_child()
623 }
624
625 pub fn is_trait(self, def_id: DefId) -> bool {
627 self.def_kind(def_id) == DefKind::Trait
628 }
629
630 pub fn is_trait_alias(self, def_id: DefId) -> bool {
633 self.def_kind(def_id) == DefKind::TraitAlias
634 }
635
636 pub fn is_constructor(self, def_id: DefId) -> bool {
639 matches!(self.def_kind(def_id), DefKind::Ctor(..))
640 }
641
642 pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
653 let mut def_id = def_id;
654 while self.is_typeck_child(def_id) {
655 def_id = self.parent(def_id);
656 }
657 def_id
658 }
659
660 pub fn closure_env_ty(
671 self,
672 closure_ty: Ty<'tcx>,
673 closure_kind: ty::ClosureKind,
674 env_region: ty::Region<'tcx>,
675 ) -> Ty<'tcx> {
676 match closure_kind {
677 ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
678 ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
679 ty::ClosureKind::FnOnce => closure_ty,
680 }
681 }
682
683 #[inline]
685 pub fn is_static(self, def_id: DefId) -> bool {
686 matches!(self.def_kind(def_id), DefKind::Static { .. })
687 }
688
689 #[inline]
690 pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
691 if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
692 Some(mutability)
693 } else {
694 None
695 }
696 }
697
698 pub fn is_thread_local_static(self, def_id: DefId) -> bool {
700 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
701 }
702
703 #[inline]
705 pub fn is_mutable_static(self, def_id: DefId) -> bool {
706 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
707 }
708
709 #[inline]
712 pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
713 !self.sess.target.dll_tls_export
714 && self.is_thread_local_static(def_id)
715 && !self.is_foreign_item(def_id)
716 }
717
718 pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
720 let static_ty = self.type_of(def_id).instantiate_identity();
721 if self.is_mutable_static(def_id) {
722 Ty::new_mut_ptr(self, static_ty)
723 } else if self.is_foreign_item(def_id) {
724 Ty::new_imm_ptr(self, static_ty)
725 } else {
726 Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
728 }
729 }
730
731 pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
733 let static_ty =
735 self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
736
737 if self.is_mutable_static(def_id) {
740 Ty::new_mut_ptr(self, static_ty)
741 } else if self.is_foreign_item(def_id) {
742 Ty::new_imm_ptr(self, static_ty)
743 } else {
744 Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
745 }
746 }
747
748 #[instrument(skip(self), level = "debug", ret)]
750 pub fn try_expand_impl_trait_type(
751 self,
752 def_id: DefId,
753 args: GenericArgsRef<'tcx>,
754 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
755 let mut visitor = OpaqueTypeExpander {
756 seen_opaque_tys: FxHashSet::default(),
757 expanded_cache: FxHashMap::default(),
758 primary_def_id: Some(def_id),
759 found_recursion: false,
760 found_any_recursion: false,
761 check_recursion: true,
762 tcx: self,
763 };
764
765 let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
766 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
767 }
768
769 pub fn def_descr(self, def_id: DefId) -> &'static str {
771 self.def_kind_descr(self.def_kind(def_id), def_id)
772 }
773
774 pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
776 match def_kind {
777 DefKind::AssocFn if self.associated_item(def_id).is_method() => "method",
778 DefKind::AssocTy if self.opt_rpitit_info(def_id).is_some() => "opaque type",
779 DefKind::Closure if let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
780 match coroutine_kind {
781 hir::CoroutineKind::Desugared(
782 hir::CoroutineDesugaring::Async,
783 hir::CoroutineSource::Fn,
784 ) => "async fn",
785 hir::CoroutineKind::Desugared(
786 hir::CoroutineDesugaring::Async,
787 hir::CoroutineSource::Block,
788 ) => "async block",
789 hir::CoroutineKind::Desugared(
790 hir::CoroutineDesugaring::Async,
791 hir::CoroutineSource::Closure,
792 ) => "async closure",
793 hir::CoroutineKind::Desugared(
794 hir::CoroutineDesugaring::AsyncGen,
795 hir::CoroutineSource::Fn,
796 ) => "async gen fn",
797 hir::CoroutineKind::Desugared(
798 hir::CoroutineDesugaring::AsyncGen,
799 hir::CoroutineSource::Block,
800 ) => "async gen block",
801 hir::CoroutineKind::Desugared(
802 hir::CoroutineDesugaring::AsyncGen,
803 hir::CoroutineSource::Closure,
804 ) => "async gen closure",
805 hir::CoroutineKind::Desugared(
806 hir::CoroutineDesugaring::Gen,
807 hir::CoroutineSource::Fn,
808 ) => "gen fn",
809 hir::CoroutineKind::Desugared(
810 hir::CoroutineDesugaring::Gen,
811 hir::CoroutineSource::Block,
812 ) => "gen block",
813 hir::CoroutineKind::Desugared(
814 hir::CoroutineDesugaring::Gen,
815 hir::CoroutineSource::Closure,
816 ) => "gen closure",
817 hir::CoroutineKind::Coroutine(_) => "coroutine",
818 }
819 }
820 _ => def_kind.descr(def_id),
821 }
822 }
823
824 pub fn def_descr_article(self, def_id: DefId) -> &'static str {
826 self.def_kind_descr_article(self.def_kind(def_id), def_id)
827 }
828
829 pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
831 match def_kind {
832 DefKind::AssocFn if self.associated_item(def_id).is_method() => "a",
833 DefKind::Closure if let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
834 match coroutine_kind {
835 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
836 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
837 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
838 hir::CoroutineKind::Coroutine(_) => "a",
839 }
840 }
841 _ => def_kind.article(),
842 }
843 }
844
845 pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
852 if self.features().enabled(sym::rustc_private) {
854 return true;
855 }
856
857 !self.is_private_dep(key)
864 || self.extern_crate(key).is_some_and(|e| e.is_direct())
868 }
869
870 pub fn expand_free_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
891 value.fold_with(&mut FreeAliasTypeExpander { tcx: self, depth: 0 })
892 }
893
894 pub fn peel_off_free_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
909 let ty::Alias(ty::Free, _) = ty.kind() else { return ty };
910
911 let limit = self.recursion_limit();
912 let mut depth = 0;
913
914 while let ty::Alias(ty::Free, alias) = ty.kind() {
915 if !limit.value_within_limit(depth) {
916 let guar = self.dcx().delayed_bug("overflow expanding free alias type");
917 return Ty::new_error(self, guar);
918 }
919
920 ty = self.type_of(alias.def_id).instantiate(self, alias.args);
921 depth += 1;
922 }
923
924 ty
925 }
926
927 pub fn opt_alias_variances(
930 self,
931 kind: impl Into<ty::AliasTermKind>,
932 def_id: DefId,
933 ) -> Option<&'tcx [ty::Variance]> {
934 match kind.into() {
935 ty::AliasTermKind::ProjectionTy => {
936 if self.is_impl_trait_in_trait(def_id) {
937 Some(self.variances_of(def_id))
938 } else {
939 None
940 }
941 }
942 ty::AliasTermKind::OpaqueTy => Some(self.variances_of(def_id)),
943 ty::AliasTermKind::InherentTy
944 | ty::AliasTermKind::InherentConst
945 | ty::AliasTermKind::FreeTy
946 | ty::AliasTermKind::FreeConst
947 | ty::AliasTermKind::UnevaluatedConst
948 | ty::AliasTermKind::ProjectionConst => None,
949 }
950 }
951}
952
953struct OpaqueTypeExpander<'tcx> {
954 seen_opaque_tys: FxHashSet<DefId>,
959 expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
962 primary_def_id: Option<DefId>,
963 found_recursion: bool,
964 found_any_recursion: bool,
965 check_recursion: bool,
969 tcx: TyCtxt<'tcx>,
970}
971
972impl<'tcx> OpaqueTypeExpander<'tcx> {
973 fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
974 if self.found_any_recursion {
975 return None;
976 }
977 let args = args.fold_with(self);
978 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
979 let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
980 Some(expanded_ty) => *expanded_ty,
981 None => {
982 let generic_ty = self.tcx.type_of(def_id);
983 let concrete_ty = generic_ty.instantiate(self.tcx, args);
984 let expanded_ty = self.fold_ty(concrete_ty);
985 self.expanded_cache.insert((def_id, args), expanded_ty);
986 expanded_ty
987 }
988 };
989 if self.check_recursion {
990 self.seen_opaque_tys.remove(&def_id);
991 }
992 Some(expanded_ty)
993 } else {
994 self.found_any_recursion = true;
997 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
998 None
999 }
1000 }
1001}
1002
1003impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
1004 fn cx(&self) -> TyCtxt<'tcx> {
1005 self.tcx
1006 }
1007
1008 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1009 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) = *t.kind() {
1010 self.expand_opaque_ty(def_id, args).unwrap_or(t)
1011 } else if t.has_opaque_types() {
1012 t.super_fold_with(self)
1013 } else {
1014 t
1015 }
1016 }
1017
1018 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1019 if let ty::PredicateKind::Clause(clause) = p.kind().skip_binder()
1020 && let ty::ClauseKind::Projection(projection_pred) = clause
1021 {
1022 p.kind()
1023 .rebind(ty::ProjectionPredicate {
1024 projection_term: projection_pred.projection_term.fold_with(self),
1025 term: projection_pred.term,
1031 })
1032 .upcast(self.tcx)
1033 } else {
1034 p.super_fold_with(self)
1035 }
1036 }
1037}
1038
1039struct FreeAliasTypeExpander<'tcx> {
1040 tcx: TyCtxt<'tcx>,
1041 depth: usize,
1042}
1043
1044impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FreeAliasTypeExpander<'tcx> {
1045 fn cx(&self) -> TyCtxt<'tcx> {
1046 self.tcx
1047 }
1048
1049 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1050 if !ty.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1051 return ty;
1052 }
1053 let ty::Alias(ty::Free, alias) = ty.kind() else {
1054 return ty.super_fold_with(self);
1055 };
1056 if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1057 let guar = self.tcx.dcx().delayed_bug("overflow expanding free alias type");
1058 return Ty::new_error(self.tcx, guar);
1059 }
1060
1061 self.depth += 1;
1062 let ty = ensure_sufficient_stack(|| {
1063 self.tcx.type_of(alias.def_id).instantiate(self.tcx, alias.args).fold_with(self)
1064 });
1065 self.depth -= 1;
1066 ty
1067 }
1068
1069 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1070 if !ct.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1071 return ct;
1072 }
1073 ct.super_fold_with(self)
1074 }
1075}
1076
1077impl<'tcx> Ty<'tcx> {
1078 pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1080 match *self.kind() {
1081 ty::Bool => Size::from_bytes(1),
1082 ty::Char => Size::from_bytes(4),
1083 ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1084 ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1085 ty::Float(fty) => Float::from_float_ty(fty).size(),
1086 _ => bug!("non primitive type"),
1087 }
1088 }
1089
1090 pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1091 match *self.kind() {
1092 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1093 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1094 _ => bug!("non integer discriminant"),
1095 }
1096 }
1097
1098 pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1101 use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1102 Some(match self.kind() {
1103 ty::Int(_) | ty::Uint(_) => {
1104 let (size, signed) = self.int_size_and_signed(tcx);
1105 let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1106 let max =
1107 if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1108 (min, max)
1109 }
1110 ty::Char => (0, std::char::MAX as u128),
1111 ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1112 ty::Float(ty::FloatTy::F32) => {
1113 ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1114 }
1115 ty::Float(ty::FloatTy::F64) => {
1116 ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1117 }
1118 ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1119 _ => return None,
1120 })
1121 }
1122
1123 pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1126 let typing_env = TypingEnv::fully_monomorphized();
1127 self.numeric_min_and_max_as_bits(tcx)
1128 .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1129 }
1130
1131 pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1134 let typing_env = TypingEnv::fully_monomorphized();
1135 self.numeric_min_and_max_as_bits(tcx)
1136 .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1137 }
1138
1139 pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1146 self.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1147 || tcx.is_sized_raw(typing_env.as_query_input(self))
1148 }
1149
1150 pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1158 self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1159 }
1160
1161 pub fn is_trivially_freeze(self) -> bool {
1166 match self.kind() {
1167 ty::Int(_)
1168 | ty::Uint(_)
1169 | ty::Float(_)
1170 | ty::Bool
1171 | ty::Char
1172 | ty::Str
1173 | ty::Never
1174 | ty::Ref(..)
1175 | ty::RawPtr(_, _)
1176 | ty::FnDef(..)
1177 | ty::Error(_)
1178 | ty::FnPtr(..) => true,
1179 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1180 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1181 ty::Adt(..)
1182 | ty::Bound(..)
1183 | ty::Closure(..)
1184 | ty::CoroutineClosure(..)
1185 | ty::Dynamic(..)
1186 | ty::Foreign(_)
1187 | ty::Coroutine(..)
1188 | ty::CoroutineWitness(..)
1189 | ty::UnsafeBinder(_)
1190 | ty::Infer(_)
1191 | ty::Alias(..)
1192 | ty::Param(_)
1193 | ty::Placeholder(_) => false,
1194 }
1195 }
1196
1197 pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1199 self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1200 }
1201
1202 fn is_trivially_unpin(self) -> bool {
1207 match self.kind() {
1208 ty::Int(_)
1209 | ty::Uint(_)
1210 | ty::Float(_)
1211 | ty::Bool
1212 | ty::Char
1213 | ty::Str
1214 | ty::Never
1215 | ty::Ref(..)
1216 | ty::RawPtr(_, _)
1217 | ty::FnDef(..)
1218 | ty::Error(_)
1219 | ty::FnPtr(..) => true,
1220 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1221 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1222 ty::Adt(..)
1223 | ty::Bound(..)
1224 | ty::Closure(..)
1225 | ty::CoroutineClosure(..)
1226 | ty::Dynamic(..)
1227 | ty::Foreign(_)
1228 | ty::Coroutine(..)
1229 | ty::CoroutineWitness(..)
1230 | ty::UnsafeBinder(_)
1231 | ty::Infer(_)
1232 | ty::Alias(..)
1233 | ty::Param(_)
1234 | ty::Placeholder(_) => false,
1235 }
1236 }
1237
1238 pub fn has_unsafe_fields(self) -> bool {
1240 if let ty::Adt(adt_def, ..) = self.kind() {
1241 adt_def.all_fields().any(|x| x.safety.is_unsafe())
1242 } else {
1243 false
1244 }
1245 }
1246
1247 pub fn is_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1249 !self.is_trivially_not_async_drop()
1250 && tcx.is_async_drop_raw(typing_env.as_query_input(self))
1251 }
1252
1253 fn is_trivially_not_async_drop(self) -> bool {
1258 match self.kind() {
1259 ty::Int(_)
1260 | ty::Uint(_)
1261 | ty::Float(_)
1262 | ty::Bool
1263 | ty::Char
1264 | ty::Str
1265 | ty::Never
1266 | ty::Ref(..)
1267 | ty::RawPtr(..)
1268 | ty::FnDef(..)
1269 | ty::Error(_)
1270 | ty::FnPtr(..) => true,
1271 ty::UnsafeBinder(_) => todo!(),
1273 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_not_async_drop),
1274 ty::Pat(elem_ty, _) | ty::Slice(elem_ty) | ty::Array(elem_ty, _) => {
1275 elem_ty.is_trivially_not_async_drop()
1276 }
1277 ty::Adt(..)
1278 | ty::Bound(..)
1279 | ty::Closure(..)
1280 | ty::CoroutineClosure(..)
1281 | ty::Dynamic(..)
1282 | ty::Foreign(_)
1283 | ty::Coroutine(..)
1284 | ty::CoroutineWitness(..)
1285 | ty::Infer(_)
1286 | ty::Alias(..)
1287 | ty::Param(_)
1288 | ty::Placeholder(_) => false,
1289 }
1290 }
1291
1292 #[inline]
1301 pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1302 match needs_drop_components(tcx, self) {
1304 Err(AlwaysRequiresDrop) => true,
1305 Ok(components) => {
1306 let query_ty = match *components {
1307 [] => return false,
1308 [component_ty] => component_ty,
1311 _ => self,
1312 };
1313
1314 debug_assert!(!typing_env.param_env.has_infer());
1317 let query_ty = tcx
1318 .try_normalize_erasing_regions(typing_env, query_ty)
1319 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
1320
1321 tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1322 }
1323 }
1324 }
1325
1326 #[inline]
1337 pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1338 match needs_drop_components(tcx, self) {
1340 Err(AlwaysRequiresDrop) => true,
1341 Ok(components) => {
1342 let query_ty = match *components {
1343 [] => return false,
1344 [component_ty] => component_ty,
1347 _ => self,
1348 };
1349
1350 debug_assert!(!typing_env.has_infer());
1354 let query_ty = tcx
1355 .try_normalize_erasing_regions(typing_env, query_ty)
1356 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
1357
1358 tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1359 }
1360 }
1361 }
1362
1363 #[inline]
1372 pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1373 match needs_drop_components(tcx, self) {
1375 Err(AlwaysRequiresDrop) => true,
1376 Ok(components) => {
1377 let query_ty = match *components {
1378 [] => return false,
1379 [component_ty] => component_ty,
1382 _ => self,
1383 };
1384
1385 if query_ty.has_infer() {
1392 return true;
1393 }
1394
1395 let erased = tcx.normalize_erasing_regions(typing_env, query_ty);
1398 tcx.has_significant_drop_raw(typing_env.as_query_input(erased))
1399 }
1400 }
1401 }
1402
1403 #[inline]
1418 pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1419 match self.kind() {
1420 ty::Adt(..) => tcx.has_structural_eq_impl(self),
1422
1423 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
1425
1426 ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
1431
1432 ty::RawPtr(_, _) | ty::FnPtr(..) => true,
1434
1435 ty::Float(_) => false,
1437
1438 ty::FnDef(..)
1442 | ty::Closure(..)
1443 | ty::CoroutineClosure(..)
1444 | ty::Dynamic(..)
1445 | ty::Coroutine(..) => false,
1446
1447 ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1452 false
1453 }
1454
1455 ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1456 }
1457 }
1458
1459 pub fn peel_refs(self) -> Ty<'tcx> {
1470 let mut ty = self;
1471 while let ty::Ref(_, inner_ty, _) = ty.kind() {
1472 ty = *inner_ty;
1473 }
1474 ty
1475 }
1476
1477 #[inline]
1479 pub fn outer_exclusive_binder(self) -> ty::DebruijnIndex {
1480 self.0.outer_exclusive_binder
1481 }
1482}
1483
1484#[inline]
1491pub fn needs_drop_components<'tcx>(
1492 tcx: TyCtxt<'tcx>,
1493 ty: Ty<'tcx>,
1494) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1495 needs_drop_components_with_async(tcx, ty, Asyncness::No)
1496}
1497
1498pub fn needs_drop_components_with_async<'tcx>(
1502 tcx: TyCtxt<'tcx>,
1503 ty: Ty<'tcx>,
1504 asyncness: Asyncness,
1505) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1506 match *ty.kind() {
1507 ty::Infer(ty::FreshIntTy(_))
1508 | ty::Infer(ty::FreshFloatTy(_))
1509 | ty::Bool
1510 | ty::Int(_)
1511 | ty::Uint(_)
1512 | ty::Float(_)
1513 | ty::Never
1514 | ty::FnDef(..)
1515 | ty::FnPtr(..)
1516 | ty::Char
1517 | ty::RawPtr(_, _)
1518 | ty::Ref(..)
1519 | ty::Str => Ok(SmallVec::new()),
1520
1521 ty::Foreign(..) => Ok(SmallVec::new()),
1523
1524 ty::Dynamic(..) | ty::Error(_) => {
1526 if asyncness.is_async() {
1527 Ok(SmallVec::new())
1528 } else {
1529 Err(AlwaysRequiresDrop)
1530 }
1531 }
1532
1533 ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1534 ty::Array(elem_ty, size) => {
1535 match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1536 Ok(v) if v.is_empty() => Ok(v),
1537 res => match size.try_to_target_usize(tcx) {
1538 Some(0) => Ok(SmallVec::new()),
1541 Some(_) => res,
1542 None => Ok(smallvec![ty]),
1546 },
1547 }
1548 }
1549 ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1551 acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1552 Ok(acc)
1553 }),
1554
1555 ty::Adt(..)
1557 | ty::Alias(..)
1558 | ty::Param(_)
1559 | ty::Bound(..)
1560 | ty::Placeholder(..)
1561 | ty::Infer(_)
1562 | ty::Closure(..)
1563 | ty::CoroutineClosure(..)
1564 | ty::Coroutine(..)
1565 | ty::CoroutineWitness(..)
1566 | ty::UnsafeBinder(_) => Ok(smallvec![ty]),
1567 }
1568}
1569
1570pub fn fold_list<'tcx, F, L, T>(
1576 list: L,
1577 folder: &mut F,
1578 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1579) -> L
1580where
1581 F: TypeFolder<TyCtxt<'tcx>>,
1582 L: AsRef<[T]>,
1583 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1584{
1585 let slice = list.as_ref();
1586 let mut iter = slice.iter().copied();
1587 match iter.by_ref().enumerate().find_map(|(i, t)| {
1589 let new_t = t.fold_with(folder);
1590 if new_t != t { Some((i, new_t)) } else { None }
1591 }) {
1592 Some((i, new_t)) => {
1593 let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1595 new_list.extend_from_slice(&slice[..i]);
1596 new_list.push(new_t);
1597 for t in iter {
1598 new_list.push(t.fold_with(folder))
1599 }
1600 intern(folder.cx(), &new_list)
1601 }
1602 None => list,
1603 }
1604}
1605
1606pub fn try_fold_list<'tcx, F, L, T>(
1612 list: L,
1613 folder: &mut F,
1614 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1615) -> Result<L, F::Error>
1616where
1617 F: FallibleTypeFolder<TyCtxt<'tcx>>,
1618 L: AsRef<[T]>,
1619 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1620{
1621 let slice = list.as_ref();
1622 let mut iter = slice.iter().copied();
1623 match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1625 Ok(new_t) if new_t == t => None,
1626 new_t => Some((i, new_t)),
1627 }) {
1628 Some((i, Ok(new_t))) => {
1629 let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1631 new_list.extend_from_slice(&slice[..i]);
1632 new_list.push(new_t);
1633 for t in iter {
1634 new_list.push(t.try_fold_with(folder)?)
1635 }
1636 Ok(intern(folder.cx(), &new_list))
1637 }
1638 Some((_, Err(err))) => {
1639 return Err(err);
1640 }
1641 None => Ok(list),
1642 }
1643}
1644
1645#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
1646pub struct AlwaysRequiresDrop;
1647
1648pub fn reveal_opaque_types_in_bounds<'tcx>(
1651 tcx: TyCtxt<'tcx>,
1652 val: ty::Clauses<'tcx>,
1653) -> ty::Clauses<'tcx> {
1654 assert!(!tcx.next_trait_solver_globally());
1655 let mut visitor = OpaqueTypeExpander {
1656 seen_opaque_tys: FxHashSet::default(),
1657 expanded_cache: FxHashMap::default(),
1658 primary_def_id: None,
1659 found_recursion: false,
1660 found_any_recursion: false,
1661 check_recursion: false,
1662 tcx,
1663 };
1664 val.fold_with(&mut visitor)
1665}
1666
1667fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1669 let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
1670 attrs.iter().any(|attr| attr.is_doc_hidden())
1671}
1672
1673pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1675 let attrs = tcx.get_all_attrs(def_id);
1676 attrs.iter().any(|attr| matches!(attr, hir::Attribute::Parsed(AttributeKind::Doc(doc)) if doc.notable_trait.is_some()))
1677}
1678
1679pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1685 if tcx.features().intrinsics() && tcx.has_attr(def_id, sym::rustc_intrinsic) {
1686 let must_be_overridden = match tcx.hir_node_by_def_id(def_id) {
1687 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1688 !has_body
1689 }
1690 _ => true,
1691 };
1692 Some(ty::IntrinsicDef {
1693 name: tcx.item_name(def_id),
1694 must_be_overridden,
1695 const_stable: tcx.has_attr(def_id, sym::rustc_intrinsic_const_stable_indirect),
1696 })
1697 } else {
1698 None
1699 }
1700}
1701
1702pub fn provide(providers: &mut Providers) {
1703 *providers = Providers {
1704 reveal_opaque_types_in_bounds,
1705 is_doc_hidden,
1706 is_doc_notable_trait,
1707 intrinsic_raw,
1708 ..*providers
1709 }
1710}