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