1use std::{fmt, iter};
4
5use rustc_abi::{ExternAbi, Float, Integer, IntegerType, Size};
6use rustc_apfloat::Float as _;
7use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher};
9use rustc_data_structures::stack::ensure_sufficient_stack;
10use rustc_errors::ErrorGuaranteed;
11use rustc_hir as hir;
12use rustc_hir::def::{CtorOf, DefKind, Res};
13use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
14use rustc_index::bit_set::GrowableBitSet;
15use rustc_macros::{HashStable, TyDecodable, TyEncodable, extension};
16use rustc_session::Limit;
17use rustc_span::sym;
18use smallvec::{SmallVec, smallvec};
19use tracing::{debug, instrument};
20
21use super::TypingEnv;
22use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
23use crate::mir;
24use crate::query::Providers;
25use crate::ty::fold::fold_regions;
26use crate::ty::layout::{FloatExt, IntegerExt};
27use crate::ty::{
28 self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable,
29 TypeFolder, TypeSuperFoldable, TypeVisitableExt, Upcast,
30};
31
32#[derive(Copy, Clone, Debug)]
33pub struct Discr<'tcx> {
34 pub val: u128,
36 pub ty: Ty<'tcx>,
37}
38
39#[derive(Copy, Clone, Debug, PartialEq, Eq)]
41pub enum CheckRegions {
42 No,
43 OnlyParam,
47 FromFunction,
51}
52
53#[derive(Copy, Clone, Debug)]
54pub enum NotUniqueParam<'tcx> {
55 DuplicateParam(ty::GenericArg<'tcx>),
56 NotParam(ty::GenericArg<'tcx>),
57}
58
59impl<'tcx> fmt::Display for Discr<'tcx> {
60 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
61 match *self.ty.kind() {
62 ty::Int(ity) => {
63 let size = ty::tls::with(|tcx| Integer::from_int_ty(&tcx, ity).size());
64 let x = self.val;
65 let x = size.sign_extend(x) as i128;
67 write!(fmt, "{x}")
68 }
69 _ => write!(fmt, "{}", self.val),
70 }
71 }
72}
73
74impl<'tcx> Discr<'tcx> {
75 pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self {
77 self.checked_add(tcx, 1).0
78 }
79 pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) {
80 let (size, signed) = self.ty.int_size_and_signed(tcx);
81 let (val, oflo) = if signed {
82 let min = size.signed_int_min();
83 let max = size.signed_int_max();
84 let val = size.sign_extend(self.val);
85 assert!(n < (i128::MAX as u128));
86 let n = n as i128;
87 let oflo = val > max - n;
88 let val = if oflo { min + (n - (max - val) - 1) } else { val + n };
89 let val = val as u128;
91 let val = size.truncate(val);
92 (val, oflo)
93 } else {
94 let max = size.unsigned_int_max();
95 let val = self.val;
96 let oflo = val > max - n;
97 let val = if oflo { n - (max - val) - 1 } else { val + n };
98 (val, oflo)
99 };
100 (Self { val, ty: self.ty }, oflo)
101 }
102}
103
104#[extension(pub trait IntTypeExt)]
105impl IntegerType {
106 fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
107 match self {
108 IntegerType::Pointer(true) => tcx.types.isize,
109 IntegerType::Pointer(false) => tcx.types.usize,
110 IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
111 }
112 }
113
114 fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
115 Discr { val: 0, ty: self.to_ty(tcx) }
116 }
117
118 fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>) -> Option<Discr<'tcx>> {
119 if let Some(val) = val {
120 assert_eq!(self.to_ty(tcx), val.ty);
121 let (new, oflo) = val.checked_add(tcx, 1);
122 if oflo { None } else { Some(new) }
123 } else {
124 Some(self.initial_discriminant(tcx))
125 }
126 }
127}
128
129impl<'tcx> TyCtxt<'tcx> {
130 pub fn type_id_hash(self, ty: Ty<'tcx>) -> Hash128 {
133 let ty = self.erase_regions(ty);
137
138 self.with_stable_hashing_context(|mut hcx| {
139 let mut hasher = StableHasher::new();
140 hcx.while_hashing_spans(false, |hcx| ty.hash_stable(hcx, &mut hasher));
141 hasher.finish()
142 })
143 }
144
145 pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
146 match res {
147 Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
148 Some(self.parent(self.parent(def_id)))
149 }
150 Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
151 Some(self.parent(def_id))
152 }
153 Res::Def(
156 DefKind::Struct
157 | DefKind::Union
158 | DefKind::Enum
159 | DefKind::Trait
160 | DefKind::OpaqueTy
161 | DefKind::TyAlias
162 | DefKind::ForeignTy
163 | DefKind::TraitAlias
164 | DefKind::AssocTy
165 | DefKind::Fn
166 | DefKind::AssocFn
167 | DefKind::AssocConst
168 | DefKind::Impl { .. },
169 def_id,
170 ) => Some(def_id),
171 Res::Err => None,
172 _ => None,
173 }
174 }
175
176 pub fn type_is_copy_modulo_regions(
187 self,
188 typing_env: ty::TypingEnv<'tcx>,
189 ty: Ty<'tcx>,
190 ) -> bool {
191 ty.is_trivially_pure_clone_copy() || self.is_copy_raw(typing_env.as_query_input(ty))
192 }
193
194 pub fn struct_tail_for_codegen(
202 self,
203 ty: Ty<'tcx>,
204 typing_env: ty::TypingEnv<'tcx>,
205 ) -> Ty<'tcx> {
206 let tcx = self;
207 tcx.struct_tail_raw(ty, |ty| tcx.normalize_erasing_regions(typing_env, ty), || {})
208 }
209
210 pub fn struct_tail_raw(
223 self,
224 mut ty: Ty<'tcx>,
225 mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
226 mut f: impl FnMut() -> (),
230 ) -> Ty<'tcx> {
231 let recursion_limit = self.recursion_limit();
232 for iteration in 0.. {
233 if !recursion_limit.value_within_limit(iteration) {
234 let suggested_limit = match recursion_limit {
235 Limit(0) => Limit(2),
236 limit => limit * 2,
237 };
238 let reported = self
239 .dcx()
240 .emit_err(crate::error::RecursionLimitReached { ty, suggested_limit });
241 return Ty::new_error(self, reported);
242 }
243 match *ty.kind() {
244 ty::Adt(def, args) => {
245 if !def.is_struct() {
246 break;
247 }
248 match def.non_enum_variant().tail_opt() {
249 Some(field) => {
250 f();
251 ty = field.ty(self, args);
252 }
253 None => break,
254 }
255 }
256
257 ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
258 f();
259 ty = last_ty;
260 }
261
262 ty::Tuple(_) => break,
263
264 ty::Pat(inner, _) => {
265 f();
266 ty = inner;
267 }
268
269 ty::Alias(..) => {
270 let normalized = normalize(ty);
271 if ty == normalized {
272 return ty;
273 } else {
274 ty = normalized;
275 }
276 }
277
278 _ => {
279 break;
280 }
281 }
282 }
283 ty
284 }
285
286 pub fn struct_lockstep_tails_for_codegen(
296 self,
297 source: Ty<'tcx>,
298 target: Ty<'tcx>,
299 typing_env: ty::TypingEnv<'tcx>,
300 ) -> (Ty<'tcx>, Ty<'tcx>) {
301 let tcx = self;
302 tcx.struct_lockstep_tails_raw(source, target, |ty| {
303 tcx.normalize_erasing_regions(typing_env, ty)
304 })
305 }
306
307 pub fn struct_lockstep_tails_raw(
316 self,
317 source: Ty<'tcx>,
318 target: Ty<'tcx>,
319 normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>,
320 ) -> (Ty<'tcx>, Ty<'tcx>) {
321 let (mut a, mut b) = (source, target);
322 loop {
323 match (a.kind(), b.kind()) {
324 (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args))
325 if a_def == b_def && a_def.is_struct() =>
326 {
327 if let Some(f) = a_def.non_enum_variant().tail_opt() {
328 a = f.ty(self, a_args);
329 b = f.ty(self, b_args);
330 } else {
331 break;
332 }
333 }
334 (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) if a_tys.len() == b_tys.len() => {
335 if let Some(&a_last) = a_tys.last() {
336 a = a_last;
337 b = *b_tys.last().unwrap();
338 } else {
339 break;
340 }
341 }
342 (ty::Alias(..), _) | (_, ty::Alias(..)) => {
343 let a_norm = normalize(a);
348 let b_norm = normalize(b);
349 if a == a_norm && b == b_norm {
350 break;
351 } else {
352 a = a_norm;
353 b = b_norm;
354 }
355 }
356
357 _ => break,
358 }
359 }
360 (a, b)
361 }
362
363 pub fn calculate_dtor(
365 self,
366 adt_did: DefId,
367 validate: impl Fn(Self, DefId) -> Result<(), ErrorGuaranteed>,
368 ) -> Option<ty::Destructor> {
369 let drop_trait = self.lang_items().drop_trait()?;
370 self.ensure_ok().coherent_trait(drop_trait).ok()?;
371
372 let ty = self.type_of(adt_did).instantiate_identity();
373 let mut dtor_candidate = None;
374 self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
375 if validate(self, impl_did).is_err() {
376 return;
378 }
379
380 let Some(item_id) = self.associated_item_def_ids(impl_did).first() else {
381 self.dcx()
382 .span_delayed_bug(self.def_span(impl_did), "Drop impl without drop function");
383 return;
384 };
385
386 if let Some((old_item_id, _)) = dtor_candidate {
387 self.dcx()
388 .struct_span_err(self.def_span(item_id), "multiple drop impls found")
389 .with_span_note(self.def_span(old_item_id), "other impl here")
390 .delay_as_bug();
391 }
392
393 dtor_candidate = Some((*item_id, self.impl_trait_header(impl_did).unwrap().constness));
394 });
395
396 let (did, constness) = dtor_candidate?;
397 Some(ty::Destructor { did, constness })
398 }
399
400 pub fn calculate_async_dtor(
402 self,
403 adt_did: DefId,
404 validate: impl Fn(Self, DefId) -> Result<(), ErrorGuaranteed>,
405 ) -> Option<ty::AsyncDestructor> {
406 let async_drop_trait = self.lang_items().async_drop_trait()?;
407 self.ensure_ok().coherent_trait(async_drop_trait).ok()?;
408
409 let ty = self.type_of(adt_did).instantiate_identity();
410 let mut dtor_candidate = None;
411 self.for_each_relevant_impl(async_drop_trait, ty, |impl_did| {
412 if validate(self, impl_did).is_err() {
413 return;
415 }
416
417 let [future, ctor] = self.associated_item_def_ids(impl_did) else {
418 self.dcx().span_delayed_bug(
419 self.def_span(impl_did),
420 "AsyncDrop impl without async_drop function or Dropper type",
421 );
422 return;
423 };
424
425 if let Some((_, _, old_impl_did)) = dtor_candidate {
426 self.dcx()
427 .struct_span_err(self.def_span(impl_did), "multiple async drop impls found")
428 .with_span_note(self.def_span(old_impl_did), "other impl here")
429 .delay_as_bug();
430 }
431
432 dtor_candidate = Some((*future, *ctor, impl_did));
433 });
434
435 let (future, ctor, _) = dtor_candidate?;
436 Some(ty::AsyncDestructor { future, ctor })
437 }
438
439 pub fn async_drop_glue_morphology(self, did: DefId) -> AsyncDropGlueMorphology {
444 let ty: Ty<'tcx> = self.type_of(did).instantiate_identity();
445
446 let typing_env = ty::TypingEnv::fully_monomorphized();
449 if ty.needs_async_drop(self, typing_env) {
450 AsyncDropGlueMorphology::Custom
451 } else if ty.needs_drop(self, typing_env) {
452 AsyncDropGlueMorphology::DeferredDropInPlace
453 } else {
454 AsyncDropGlueMorphology::Noop
455 }
456 }
457
458 pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> {
466 let dtor = match def.destructor(self) {
467 None => {
468 debug!("destructor_constraints({:?}) - no dtor", def.did());
469 return vec![];
470 }
471 Some(dtor) => dtor.did,
472 };
473
474 let impl_def_id = self.parent(dtor);
475 let impl_generics = self.generics_of(impl_def_id);
476
477 let impl_args = match *self.type_of(impl_def_id).instantiate_identity().kind() {
499 ty::Adt(def_, args) if def_ == def => args,
500 _ => span_bug!(self.def_span(impl_def_id), "expected ADT for self type of `Drop` impl"),
501 };
502
503 let item_args = ty::GenericArgs::identity_for_item(self, def.did());
504
505 let result = iter::zip(item_args, impl_args)
506 .filter(|&(_, k)| {
507 match k.unpack() {
508 GenericArgKind::Lifetime(region) => match region.kind() {
509 ty::ReEarlyParam(ebr) => {
510 !impl_generics.region_param(ebr, self).pure_wrt_drop
511 }
512 _ => false,
514 },
515 GenericArgKind::Type(ty) => match *ty.kind() {
516 ty::Param(pt) => !impl_generics.type_param(pt, self).pure_wrt_drop,
517 _ => false,
519 },
520 GenericArgKind::Const(ct) => match ct.kind() {
521 ty::ConstKind::Param(pc) => {
522 !impl_generics.const_param(pc, self).pure_wrt_drop
523 }
524 _ => false,
526 },
527 }
528 })
529 .map(|(item_param, _)| item_param)
530 .collect();
531 debug!("destructor_constraint({:?}) = {:?}", def.did(), result);
532 result
533 }
534
535 pub fn uses_unique_generic_params(
537 self,
538 args: &[ty::GenericArg<'tcx>],
539 ignore_regions: CheckRegions,
540 ) -> Result<(), NotUniqueParam<'tcx>> {
541 let mut seen = GrowableBitSet::default();
542 let mut seen_late = FxHashSet::default();
543 for arg in args {
544 match arg.unpack() {
545 GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) {
546 (CheckRegions::FromFunction, ty::ReBound(di, reg)) => {
547 if !seen_late.insert((di, reg)) {
548 return Err(NotUniqueParam::DuplicateParam(lt.into()));
549 }
550 }
551 (CheckRegions::OnlyParam | CheckRegions::FromFunction, ty::ReEarlyParam(p)) => {
552 if !seen.insert(p.index) {
553 return Err(NotUniqueParam::DuplicateParam(lt.into()));
554 }
555 }
556 (CheckRegions::OnlyParam | CheckRegions::FromFunction, _) => {
557 return Err(NotUniqueParam::NotParam(lt.into()));
558 }
559 (CheckRegions::No, _) => {}
560 },
561 GenericArgKind::Type(t) => match t.kind() {
562 ty::Param(p) => {
563 if !seen.insert(p.index) {
564 return Err(NotUniqueParam::DuplicateParam(t.into()));
565 }
566 }
567 _ => return Err(NotUniqueParam::NotParam(t.into())),
568 },
569 GenericArgKind::Const(c) => match c.kind() {
570 ty::ConstKind::Param(p) => {
571 if !seen.insert(p.index) {
572 return Err(NotUniqueParam::DuplicateParam(c.into()));
573 }
574 }
575 _ => return Err(NotUniqueParam::NotParam(c.into())),
576 },
577 }
578 }
579
580 Ok(())
581 }
582
583 pub fn is_closure_like(self, def_id: DefId) -> bool {
592 matches!(self.def_kind(def_id), DefKind::Closure)
593 }
594
595 pub fn is_typeck_child(self, def_id: DefId) -> bool {
598 matches!(
599 self.def_kind(def_id),
600 DefKind::Closure | DefKind::InlineConst | DefKind::SyntheticCoroutineBody
601 )
602 }
603
604 pub fn is_trait(self, def_id: DefId) -> bool {
606 self.def_kind(def_id) == DefKind::Trait
607 }
608
609 pub fn is_trait_alias(self, def_id: DefId) -> bool {
612 self.def_kind(def_id) == DefKind::TraitAlias
613 }
614
615 pub fn is_constructor(self, def_id: DefId) -> bool {
618 matches!(self.def_kind(def_id), DefKind::Ctor(..))
619 }
620
621 pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
632 let mut def_id = def_id;
633 while self.is_typeck_child(def_id) {
634 def_id = self.parent(def_id);
635 }
636 def_id
637 }
638
639 pub fn closure_env_ty(
650 self,
651 closure_ty: Ty<'tcx>,
652 closure_kind: ty::ClosureKind,
653 env_region: ty::Region<'tcx>,
654 ) -> Ty<'tcx> {
655 match closure_kind {
656 ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
657 ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
658 ty::ClosureKind::FnOnce => closure_ty,
659 }
660 }
661
662 #[inline]
664 pub fn is_static(self, def_id: DefId) -> bool {
665 matches!(self.def_kind(def_id), DefKind::Static { .. })
666 }
667
668 #[inline]
669 pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
670 if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
671 Some(mutability)
672 } else {
673 None
674 }
675 }
676
677 pub fn is_thread_local_static(self, def_id: DefId) -> bool {
679 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
680 }
681
682 #[inline]
684 pub fn is_mutable_static(self, def_id: DefId) -> bool {
685 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
686 }
687
688 #[inline]
691 pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
692 !self.sess.target.dll_tls_export
693 && self.is_thread_local_static(def_id)
694 && !self.is_foreign_item(def_id)
695 }
696
697 pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
699 let static_ty = self.type_of(def_id).instantiate_identity();
700 if self.is_mutable_static(def_id) {
701 Ty::new_mut_ptr(self, static_ty)
702 } else if self.is_foreign_item(def_id) {
703 Ty::new_imm_ptr(self, static_ty)
704 } else {
705 Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
707 }
708 }
709
710 pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
712 let static_ty =
714 self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
715
716 if self.is_mutable_static(def_id) {
719 Ty::new_mut_ptr(self, static_ty)
720 } else if self.is_foreign_item(def_id) {
721 Ty::new_imm_ptr(self, static_ty)
722 } else {
723 Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
724 }
725 }
726
727 pub fn coroutine_hidden_types(
733 self,
734 def_id: DefId,
735 ) -> impl Iterator<Item = ty::EarlyBinder<'tcx, Ty<'tcx>>> {
736 let coroutine_layout = self.mir_coroutine_witnesses(def_id);
737 coroutine_layout
738 .as_ref()
739 .map_or_else(|| [].iter(), |l| l.field_tys.iter())
740 .filter(|decl| !decl.ignore_for_traits)
741 .map(|decl| ty::EarlyBinder::bind(decl.ty))
742 }
743
744 pub fn bound_coroutine_hidden_types(
748 self,
749 def_id: DefId,
750 ) -> impl Iterator<Item = ty::EarlyBinder<'tcx, ty::Binder<'tcx, Ty<'tcx>>>> {
751 let coroutine_layout = self.mir_coroutine_witnesses(def_id);
752 coroutine_layout
753 .as_ref()
754 .map_or_else(|| [].iter(), |l| l.field_tys.iter())
755 .filter(|decl| !decl.ignore_for_traits)
756 .map(move |decl| {
757 let mut vars = vec![];
758 let ty = fold_regions(self, decl.ty, |re, debruijn| {
759 assert_eq!(re, self.lifetimes.re_erased);
760 let var = ty::BoundVar::from_usize(vars.len());
761 vars.push(ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon));
762 ty::Region::new_bound(
763 self,
764 debruijn,
765 ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon },
766 )
767 });
768 ty::EarlyBinder::bind(ty::Binder::bind_with_vars(
769 ty,
770 self.mk_bound_variable_kinds(&vars),
771 ))
772 })
773 }
774
775 #[instrument(skip(self), level = "debug", ret)]
777 pub fn try_expand_impl_trait_type(
778 self,
779 def_id: DefId,
780 args: GenericArgsRef<'tcx>,
781 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
782 let mut visitor = OpaqueTypeExpander {
783 seen_opaque_tys: FxHashSet::default(),
784 expanded_cache: FxHashMap::default(),
785 primary_def_id: Some(def_id),
786 found_recursion: false,
787 found_any_recursion: false,
788 check_recursion: true,
789 tcx: self,
790 };
791
792 let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
793 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
794 }
795
796 pub fn def_descr(self, def_id: DefId) -> &'static str {
798 self.def_kind_descr(self.def_kind(def_id), def_id)
799 }
800
801 pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
803 match def_kind {
804 DefKind::AssocFn if self.associated_item(def_id).fn_has_self_parameter => "method",
805 DefKind::Closure if let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
806 match coroutine_kind {
807 hir::CoroutineKind::Desugared(
808 hir::CoroutineDesugaring::Async,
809 hir::CoroutineSource::Fn,
810 ) => "async fn",
811 hir::CoroutineKind::Desugared(
812 hir::CoroutineDesugaring::Async,
813 hir::CoroutineSource::Block,
814 ) => "async block",
815 hir::CoroutineKind::Desugared(
816 hir::CoroutineDesugaring::Async,
817 hir::CoroutineSource::Closure,
818 ) => "async closure",
819 hir::CoroutineKind::Desugared(
820 hir::CoroutineDesugaring::AsyncGen,
821 hir::CoroutineSource::Fn,
822 ) => "async gen fn",
823 hir::CoroutineKind::Desugared(
824 hir::CoroutineDesugaring::AsyncGen,
825 hir::CoroutineSource::Block,
826 ) => "async gen block",
827 hir::CoroutineKind::Desugared(
828 hir::CoroutineDesugaring::AsyncGen,
829 hir::CoroutineSource::Closure,
830 ) => "async gen closure",
831 hir::CoroutineKind::Desugared(
832 hir::CoroutineDesugaring::Gen,
833 hir::CoroutineSource::Fn,
834 ) => "gen fn",
835 hir::CoroutineKind::Desugared(
836 hir::CoroutineDesugaring::Gen,
837 hir::CoroutineSource::Block,
838 ) => "gen block",
839 hir::CoroutineKind::Desugared(
840 hir::CoroutineDesugaring::Gen,
841 hir::CoroutineSource::Closure,
842 ) => "gen closure",
843 hir::CoroutineKind::Coroutine(_) => "coroutine",
844 }
845 }
846 _ => def_kind.descr(def_id),
847 }
848 }
849
850 pub fn def_descr_article(self, def_id: DefId) -> &'static str {
852 self.def_kind_descr_article(self.def_kind(def_id), def_id)
853 }
854
855 pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
857 match def_kind {
858 DefKind::AssocFn if self.associated_item(def_id).fn_has_self_parameter => "a",
859 DefKind::Closure if let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
860 match coroutine_kind {
861 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
862 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
863 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
864 hir::CoroutineKind::Coroutine(_) => "a",
865 }
866 }
867 _ => def_kind.article(),
868 }
869 }
870
871 pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
878 if self.features().enabled(sym::rustc_private) {
880 return true;
881 }
882
883 !self.is_private_dep(key)
890 || self.extern_crate(key).is_some_and(|e| e.is_direct())
894 }
895
896 pub fn expand_weak_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
917 value.fold_with(&mut WeakAliasTypeExpander { tcx: self, depth: 0 })
918 }
919
920 pub fn peel_off_weak_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
935 let ty::Alias(ty::Weak, _) = ty.kind() else { return ty };
936
937 let limit = self.recursion_limit();
938 let mut depth = 0;
939
940 while let ty::Alias(ty::Weak, alias) = ty.kind() {
941 if !limit.value_within_limit(depth) {
942 let guar = self.dcx().delayed_bug("overflow expanding weak alias type");
943 return Ty::new_error(self, guar);
944 }
945
946 ty = self.type_of(alias.def_id).instantiate(self, alias.args);
947 depth += 1;
948 }
949
950 ty
951 }
952
953 pub fn opt_alias_variances(
956 self,
957 kind: impl Into<ty::AliasTermKind>,
958 def_id: DefId,
959 ) -> Option<&'tcx [ty::Variance]> {
960 match kind.into() {
961 ty::AliasTermKind::ProjectionTy => {
962 if self.is_impl_trait_in_trait(def_id) {
963 Some(self.variances_of(def_id))
964 } else {
965 None
966 }
967 }
968 ty::AliasTermKind::OpaqueTy => Some(self.variances_of(def_id)),
969 ty::AliasTermKind::InherentTy
970 | ty::AliasTermKind::WeakTy
971 | ty::AliasTermKind::UnevaluatedConst
972 | ty::AliasTermKind::ProjectionConst => None,
973 }
974 }
975}
976
977struct OpaqueTypeExpander<'tcx> {
978 seen_opaque_tys: FxHashSet<DefId>,
983 expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
986 primary_def_id: Option<DefId>,
987 found_recursion: bool,
988 found_any_recursion: bool,
989 check_recursion: bool,
993 tcx: TyCtxt<'tcx>,
994}
995
996impl<'tcx> OpaqueTypeExpander<'tcx> {
997 fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
998 if self.found_any_recursion {
999 return None;
1000 }
1001 let args = args.fold_with(self);
1002 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
1003 let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
1004 Some(expanded_ty) => *expanded_ty,
1005 None => {
1006 let generic_ty = self.tcx.type_of(def_id);
1007 let concrete_ty = generic_ty.instantiate(self.tcx, args);
1008 let expanded_ty = self.fold_ty(concrete_ty);
1009 self.expanded_cache.insert((def_id, args), expanded_ty);
1010 expanded_ty
1011 }
1012 };
1013 if self.check_recursion {
1014 self.seen_opaque_tys.remove(&def_id);
1015 }
1016 Some(expanded_ty)
1017 } else {
1018 self.found_any_recursion = true;
1021 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
1022 None
1023 }
1024 }
1025}
1026
1027impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
1028 fn cx(&self) -> TyCtxt<'tcx> {
1029 self.tcx
1030 }
1031
1032 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1033 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) = *t.kind() {
1034 self.expand_opaque_ty(def_id, args).unwrap_or(t)
1035 } else if t.has_opaque_types() {
1036 t.super_fold_with(self)
1037 } else {
1038 t
1039 }
1040 }
1041
1042 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1043 if let ty::PredicateKind::Clause(clause) = p.kind().skip_binder()
1044 && let ty::ClauseKind::Projection(projection_pred) = clause
1045 {
1046 p.kind()
1047 .rebind(ty::ProjectionPredicate {
1048 projection_term: projection_pred.projection_term.fold_with(self),
1049 term: projection_pred.term,
1055 })
1056 .upcast(self.tcx)
1057 } else {
1058 p.super_fold_with(self)
1059 }
1060 }
1061}
1062
1063struct WeakAliasTypeExpander<'tcx> {
1064 tcx: TyCtxt<'tcx>,
1065 depth: usize,
1066}
1067
1068impl<'tcx> TypeFolder<TyCtxt<'tcx>> for WeakAliasTypeExpander<'tcx> {
1069 fn cx(&self) -> TyCtxt<'tcx> {
1070 self.tcx
1071 }
1072
1073 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1074 if !ty.has_type_flags(ty::TypeFlags::HAS_TY_WEAK) {
1075 return ty;
1076 }
1077 let ty::Alias(ty::Weak, alias) = ty.kind() else {
1078 return ty.super_fold_with(self);
1079 };
1080 if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1081 let guar = self.tcx.dcx().delayed_bug("overflow expanding weak alias type");
1082 return Ty::new_error(self.tcx, guar);
1083 }
1084
1085 self.depth += 1;
1086 ensure_sufficient_stack(|| {
1087 self.tcx.type_of(alias.def_id).instantiate(self.tcx, alias.args).fold_with(self)
1088 })
1089 }
1090
1091 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1092 if !ct.has_type_flags(ty::TypeFlags::HAS_TY_WEAK) {
1093 return ct;
1094 }
1095 ct.super_fold_with(self)
1096 }
1097}
1098
1099#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1102pub enum AsyncDropGlueMorphology {
1103 Noop,
1105 DeferredDropInPlace,
1107 Custom,
1109}
1110
1111impl<'tcx> Ty<'tcx> {
1112 pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1114 match *self.kind() {
1115 ty::Bool => Size::from_bytes(1),
1116 ty::Char => Size::from_bytes(4),
1117 ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1118 ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1119 ty::Float(fty) => Float::from_float_ty(fty).size(),
1120 _ => bug!("non primitive type"),
1121 }
1122 }
1123
1124 pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1125 match *self.kind() {
1126 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1127 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1128 _ => bug!("non integer discriminant"),
1129 }
1130 }
1131
1132 pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1135 use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1136 Some(match self.kind() {
1137 ty::Int(_) | ty::Uint(_) => {
1138 let (size, signed) = self.int_size_and_signed(tcx);
1139 let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1140 let max =
1141 if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1142 (min, max)
1143 }
1144 ty::Char => (0, std::char::MAX as u128),
1145 ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1146 ty::Float(ty::FloatTy::F32) => {
1147 ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1148 }
1149 ty::Float(ty::FloatTy::F64) => {
1150 ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1151 }
1152 ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1153 _ => return None,
1154 })
1155 }
1156
1157 pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1160 let typing_env = TypingEnv::fully_monomorphized();
1161 self.numeric_min_and_max_as_bits(tcx)
1162 .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1163 }
1164
1165 pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1168 let typing_env = TypingEnv::fully_monomorphized();
1169 self.numeric_min_and_max_as_bits(tcx)
1170 .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1171 }
1172
1173 pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1180 self.is_trivially_sized(tcx) || tcx.is_sized_raw(typing_env.as_query_input(self))
1181 }
1182
1183 pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1191 self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1192 }
1193
1194 pub fn is_trivially_freeze(self) -> bool {
1199 match self.kind() {
1200 ty::Int(_)
1201 | ty::Uint(_)
1202 | ty::Float(_)
1203 | ty::Bool
1204 | ty::Char
1205 | ty::Str
1206 | ty::Never
1207 | ty::Ref(..)
1208 | ty::RawPtr(_, _)
1209 | ty::FnDef(..)
1210 | ty::Error(_)
1211 | ty::FnPtr(..) => true,
1212 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1213 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1214 ty::Adt(..)
1215 | ty::Bound(..)
1216 | ty::Closure(..)
1217 | ty::CoroutineClosure(..)
1218 | ty::Dynamic(..)
1219 | ty::Foreign(_)
1220 | ty::Coroutine(..)
1221 | ty::CoroutineWitness(..)
1222 | ty::UnsafeBinder(_)
1223 | ty::Infer(_)
1224 | ty::Alias(..)
1225 | ty::Param(_)
1226 | ty::Placeholder(_) => false,
1227 }
1228 }
1229
1230 pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1232 self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1233 }
1234
1235 fn is_trivially_unpin(self) -> bool {
1240 match self.kind() {
1241 ty::Int(_)
1242 | ty::Uint(_)
1243 | ty::Float(_)
1244 | ty::Bool
1245 | ty::Char
1246 | ty::Str
1247 | ty::Never
1248 | ty::Ref(..)
1249 | ty::RawPtr(_, _)
1250 | ty::FnDef(..)
1251 | ty::Error(_)
1252 | ty::FnPtr(..) => true,
1253 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1254 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1255 ty::Adt(..)
1256 | ty::Bound(..)
1257 | ty::Closure(..)
1258 | ty::CoroutineClosure(..)
1259 | ty::Dynamic(..)
1260 | ty::Foreign(_)
1261 | ty::Coroutine(..)
1262 | ty::CoroutineWitness(..)
1263 | ty::UnsafeBinder(_)
1264 | ty::Infer(_)
1265 | ty::Alias(..)
1266 | ty::Param(_)
1267 | ty::Placeholder(_) => false,
1268 }
1269 }
1270
1271 pub fn has_unsafe_fields(self) -> bool {
1273 if let ty::Adt(adt_def, ..) = self.kind() {
1274 adt_def.all_fields().any(|x| x.safety.is_unsafe())
1275 } else {
1276 false
1277 }
1278 }
1279
1280 pub fn async_drop_glue_morphology(self, tcx: TyCtxt<'tcx>) -> AsyncDropGlueMorphology {
1290 match self.kind() {
1291 ty::Int(_)
1292 | ty::Uint(_)
1293 | ty::Float(_)
1294 | ty::Bool
1295 | ty::Char
1296 | ty::Str
1297 | ty::Never
1298 | ty::Ref(..)
1299 | ty::RawPtr(..)
1300 | ty::FnDef(..)
1301 | ty::FnPtr(..)
1302 | ty::Infer(ty::FreshIntTy(_))
1303 | ty::Infer(ty::FreshFloatTy(_)) => AsyncDropGlueMorphology::Noop,
1304
1305 ty::UnsafeBinder(_) => todo!(),
1307
1308 ty::Tuple(tys) if tys.is_empty() => AsyncDropGlueMorphology::Noop,
1309 ty::Adt(adt_def, _) if adt_def.is_manually_drop() => AsyncDropGlueMorphology::Noop,
1310
1311 ty::Foreign(_) => AsyncDropGlueMorphology::Noop,
1313
1314 ty::Error(_) | ty::Dynamic(..) => AsyncDropGlueMorphology::DeferredDropInPlace,
1316
1317 ty::Tuple(_) | ty::Array(_, _) | ty::Slice(_) => {
1318 AsyncDropGlueMorphology::Custom
1327 }
1328 ty::Pat(ty, _) => ty.async_drop_glue_morphology(tcx),
1329
1330 ty::Adt(adt_def, _) => tcx.async_drop_glue_morphology(adt_def.did()),
1331
1332 ty::Closure(did, _)
1333 | ty::CoroutineClosure(did, _)
1334 | ty::Coroutine(did, _)
1335 | ty::CoroutineWitness(did, _) => tcx.async_drop_glue_morphology(*did),
1336
1337 ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(..) | ty::Infer(_) => {
1338 AsyncDropGlueMorphology::Custom
1340 }
1341 }
1342 }
1343
1344 #[inline]
1353 pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1354 match needs_drop_components(tcx, self) {
1356 Err(AlwaysRequiresDrop) => true,
1357 Ok(components) => {
1358 let query_ty = match *components {
1359 [] => return false,
1360 [component_ty] => component_ty,
1363 _ => self,
1364 };
1365
1366 debug_assert!(!typing_env.param_env.has_infer());
1369 let query_ty = tcx
1370 .try_normalize_erasing_regions(typing_env, query_ty)
1371 .unwrap_or_else(|_| tcx.erase_regions(query_ty));
1372
1373 tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1374 }
1375 }
1376 }
1377
1378 #[inline]
1392 pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1393 match needs_drop_components(tcx, self) {
1395 Err(AlwaysRequiresDrop) => true,
1396 Ok(components) => {
1397 let query_ty = match *components {
1398 [] => return false,
1399 [component_ty] => component_ty,
1402 _ => self,
1403 };
1404
1405 debug_assert!(!typing_env.has_infer());
1409 let query_ty = tcx
1410 .try_normalize_erasing_regions(typing_env, query_ty)
1411 .unwrap_or_else(|_| tcx.erase_regions(query_ty));
1412
1413 tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1414 }
1415 }
1416 }
1417
1418 #[inline]
1427 pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1428 match needs_drop_components(tcx, self) {
1430 Err(AlwaysRequiresDrop) => true,
1431 Ok(components) => {
1432 let query_ty = match *components {
1433 [] => return false,
1434 [component_ty] => component_ty,
1437 _ => self,
1438 };
1439
1440 if query_ty.has_infer() {
1445 return true;
1446 }
1447
1448 let erased = tcx.normalize_erasing_regions(typing_env, query_ty);
1451 tcx.has_significant_drop_raw(typing_env.as_query_input(erased))
1452 }
1453 }
1454 }
1455
1456 #[inline]
1471 pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1472 match self.kind() {
1473 ty::Adt(..) => tcx.has_structural_eq_impl(self),
1475
1476 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
1478
1479 ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
1484
1485 ty::RawPtr(_, _) | ty::FnPtr(..) => true,
1487
1488 ty::Float(_) => false,
1490
1491 ty::FnDef(..)
1495 | ty::Closure(..)
1496 | ty::CoroutineClosure(..)
1497 | ty::Dynamic(..)
1498 | ty::Coroutine(..) => false,
1499
1500 ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1505 false
1506 }
1507
1508 ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1509 }
1510 }
1511
1512 pub fn peel_refs(self) -> Ty<'tcx> {
1523 let mut ty = self;
1524 while let ty::Ref(_, inner_ty, _) = ty.kind() {
1525 ty = *inner_ty;
1526 }
1527 ty
1528 }
1529
1530 #[inline]
1532 pub fn outer_exclusive_binder(self) -> ty::DebruijnIndex {
1533 self.0.outer_exclusive_binder
1534 }
1535}
1536
1537pub enum ExplicitSelf<'tcx> {
1538 ByValue,
1539 ByReference(ty::Region<'tcx>, hir::Mutability),
1540 ByRawPointer(hir::Mutability),
1541 ByBox,
1542 Other,
1543}
1544
1545impl<'tcx> ExplicitSelf<'tcx> {
1546 pub fn determine<P>(self_arg_ty: Ty<'tcx>, is_self_ty: P) -> ExplicitSelf<'tcx>
1571 where
1572 P: Fn(Ty<'tcx>) -> bool,
1573 {
1574 use self::ExplicitSelf::*;
1575
1576 match *self_arg_ty.kind() {
1577 _ if is_self_ty(self_arg_ty) => ByValue,
1578 ty::Ref(region, ty, mutbl) if is_self_ty(ty) => ByReference(region, mutbl),
1579 ty::RawPtr(ty, mutbl) if is_self_ty(ty) => ByRawPointer(mutbl),
1580 _ if self_arg_ty.boxed_ty().is_some_and(is_self_ty) => ByBox,
1581 _ => Other,
1582 }
1583 }
1584}
1585
1586#[inline]
1593pub fn needs_drop_components<'tcx>(
1594 tcx: TyCtxt<'tcx>,
1595 ty: Ty<'tcx>,
1596) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1597 needs_drop_components_with_async(tcx, ty, Asyncness::No)
1598}
1599
1600pub fn needs_drop_components_with_async<'tcx>(
1604 tcx: TyCtxt<'tcx>,
1605 ty: Ty<'tcx>,
1606 asyncness: Asyncness,
1607) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1608 match *ty.kind() {
1609 ty::Infer(ty::FreshIntTy(_))
1610 | ty::Infer(ty::FreshFloatTy(_))
1611 | ty::Bool
1612 | ty::Int(_)
1613 | ty::Uint(_)
1614 | ty::Float(_)
1615 | ty::Never
1616 | ty::FnDef(..)
1617 | ty::FnPtr(..)
1618 | ty::Char
1619 | ty::RawPtr(_, _)
1620 | ty::Ref(..)
1621 | ty::Str => Ok(SmallVec::new()),
1622
1623 ty::Foreign(..) => Ok(SmallVec::new()),
1625
1626 ty::Dynamic(..) | ty::Error(_) => {
1628 if asyncness.is_async() {
1629 Ok(SmallVec::new())
1630 } else {
1631 Err(AlwaysRequiresDrop)
1632 }
1633 }
1634
1635 ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1636 ty::Array(elem_ty, size) => {
1637 match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1638 Ok(v) if v.is_empty() => Ok(v),
1639 res => match size.try_to_target_usize(tcx) {
1640 Some(0) => Ok(SmallVec::new()),
1643 Some(_) => res,
1644 None => Ok(smallvec![ty]),
1648 },
1649 }
1650 }
1651 ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1653 acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1654 Ok(acc)
1655 }),
1656
1657 ty::Adt(..)
1659 | ty::Alias(..)
1660 | ty::Param(_)
1661 | ty::Bound(..)
1662 | ty::Placeholder(..)
1663 | ty::Infer(_)
1664 | ty::Closure(..)
1665 | ty::CoroutineClosure(..)
1666 | ty::Coroutine(..)
1667 | ty::CoroutineWitness(..)
1668 | ty::UnsafeBinder(_) => Ok(smallvec![ty]),
1669 }
1670}
1671
1672pub fn fold_list<'tcx, F, L, T>(
1678 list: L,
1679 folder: &mut F,
1680 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1681) -> Result<L, F::Error>
1682where
1683 F: FallibleTypeFolder<TyCtxt<'tcx>>,
1684 L: AsRef<[T]>,
1685 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1686{
1687 let slice = list.as_ref();
1688 let mut iter = slice.iter().copied();
1689 match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1691 Ok(new_t) if new_t == t => None,
1692 new_t => Some((i, new_t)),
1693 }) {
1694 Some((i, Ok(new_t))) => {
1695 let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1697 new_list.extend_from_slice(&slice[..i]);
1698 new_list.push(new_t);
1699 for t in iter {
1700 new_list.push(t.try_fold_with(folder)?)
1701 }
1702 Ok(intern(folder.cx(), &new_list))
1703 }
1704 Some((_, Err(err))) => {
1705 return Err(err);
1706 }
1707 None => Ok(list),
1708 }
1709}
1710
1711#[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)]
1712pub struct AlwaysRequiresDrop;
1713
1714pub fn reveal_opaque_types_in_bounds<'tcx>(
1717 tcx: TyCtxt<'tcx>,
1718 val: ty::Clauses<'tcx>,
1719) -> ty::Clauses<'tcx> {
1720 assert!(!tcx.next_trait_solver_globally());
1721 let mut visitor = OpaqueTypeExpander {
1722 seen_opaque_tys: FxHashSet::default(),
1723 expanded_cache: FxHashMap::default(),
1724 primary_def_id: None,
1725 found_recursion: false,
1726 found_any_recursion: false,
1727 check_recursion: false,
1728 tcx,
1729 };
1730 val.fold_with(&mut visitor)
1731}
1732
1733fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1735 tcx.get_attrs(def_id, sym::doc)
1736 .filter_map(|attr| attr.meta_item_list())
1737 .any(|items| items.iter().any(|item| item.has_name(sym::hidden)))
1738}
1739
1740pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1742 tcx.get_attrs(def_id, sym::doc)
1743 .filter_map(|attr| attr.meta_item_list())
1744 .any(|items| items.iter().any(|item| item.has_name(sym::notable_trait)))
1745}
1746
1747pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1753 if tcx.features().intrinsics()
1754 && (matches!(tcx.fn_sig(def_id).skip_binder().abi(), ExternAbi::RustIntrinsic)
1755 || tcx.has_attr(def_id, sym::rustc_intrinsic))
1756 {
1757 let must_be_overridden = tcx.has_attr(def_id, sym::rustc_intrinsic_must_be_overridden)
1758 || match tcx.hir_node_by_def_id(def_id) {
1759 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1760 !has_body
1761 }
1762 _ => true,
1763 };
1764 Some(ty::IntrinsicDef {
1765 name: tcx.item_name(def_id.into()),
1766 must_be_overridden,
1767 const_stable: tcx.has_attr(def_id, sym::rustc_intrinsic_const_stable_indirect),
1768 })
1769 } else {
1770 None
1771 }
1772}
1773
1774pub fn provide(providers: &mut Providers) {
1775 *providers = Providers {
1776 reveal_opaque_types_in_bounds,
1777 is_doc_hidden,
1778 is_doc_notable_trait,
1779 intrinsic_raw,
1780 ..*providers
1781 }
1782}