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::attrs::AttributeKind;
14use rustc_hir::def::{CtorOf, DefKind, Res};
15use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
16use rustc_hir::limit::Limit;
17use rustc_hir::{self as hir, find_attr};
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(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for Discr<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for Discr<'tcx> {
#[inline]
fn clone(&self) -> Discr<'tcx> {
let _: ::core::clone::AssertParamIsClone<u128>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Discr<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "Discr", "val",
&self.val, "ty", &&self.ty)
}
}Debug)]
37pub struct Discr<'tcx> {
38 pub val: u128,
40 pub ty: Ty<'tcx>,
41}
42
43#[derive(#[automatically_derived]
impl ::core::marker::Copy for CheckRegions { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CheckRegions {
#[inline]
fn clone(&self) -> CheckRegions { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CheckRegions {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CheckRegions::No => "No",
CheckRegions::OnlyParam => "OnlyParam",
CheckRegions::FromFunction => "FromFunction",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CheckRegions {
#[inline]
fn eq(&self, other: &CheckRegions) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CheckRegions {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq)]
45pub enum CheckRegions {
46 No,
47 OnlyParam,
51 FromFunction,
55}
56
57#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for NotUniqueParam<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for NotUniqueParam<'tcx> {
#[inline]
fn clone(&self) -> NotUniqueParam<'tcx> {
let _: ::core::clone::AssertParamIsClone<ty::GenericArg<'tcx>>;
let _: ::core::clone::AssertParamIsClone<ty::GenericArg<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for NotUniqueParam<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
NotUniqueParam::DuplicateParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DuplicateParam", &__self_0),
NotUniqueParam::NotParam(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"NotParam", &__self_0),
}
}
}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 fmt.write_fmt(format_args!("{0}", x))write!(fmt, "{x}")
72 }
73 _ => fmt.write_fmt(format_args!("{0}", self.val))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 if !(n < (i128::MAX as u128)) {
::core::panicking::panic("assertion failed: n < (i128::MAX as u128)")
};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
108impl IntTypeExt for IntegerType {
fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
match self {
IntegerType::Pointer(true) => tcx.types.isize,
IntegerType::Pointer(false) => tcx.types.usize,
IntegerType::Fixed(i, s) => i.to_ty(tcx, *s),
}
}
fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> {
Discr { val: 0, ty: self.to_ty(tcx) }
}
fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option<Discr<'tcx>>)
-> Option<Discr<'tcx>> {
if let Some(val) = val {
match (&self.to_ty(tcx), &val.ty) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let (new, oflo) = val.checked_add(tcx, 1);
if oflo { None } else { Some(new) }
} else { Some(self.initial_discriminant(tcx)) }
}
}#[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 _ => crate::util::bug::bug_fmt(format_args!("unexpected unsized tail: {0:?}",
tail))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 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/util.rs:492",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(492u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("destructor_constraints({0:?}) - no dtor",
def.did()) as &dyn Value))])
});
} else { ; }
};debug!("destructor_constraints({:?}) - no dtor", def.did());
493 return ::alloc::vec::Vec::new()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 _ => crate::util::bug::span_bug_fmt(self.def_span(impl_def_id),
format_args!("expected ADT for self type of `Drop` impl"))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 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/ty/util.rs:555",
"rustc_middle::ty::util", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/ty/util.rs"),
::tracing_core::__macro_support::Option::Some(555u32),
::tracing_core::__macro_support::Option::Some("rustc_middle::ty::util"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("destructor_constraint({0:?}) = {1:?}",
def.did(), result) as &dyn Value))])
});
} else { ; }
};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 {
615 #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Closure => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Closure)
616 }
617
618 pub fn is_typeck_child(self, def_id: DefId) -> bool {
621 self.def_kind(def_id).is_typeck_child()
622 }
623
624 pub fn is_trait(self, def_id: DefId) -> bool {
626 self.def_kind(def_id) == DefKind::Trait
627 }
628
629 pub fn is_trait_alias(self, def_id: DefId) -> bool {
632 self.def_kind(def_id) == DefKind::TraitAlias
633 }
634
635 pub fn is_constructor(self, def_id: DefId) -> bool {
638 #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Ctor(..) => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Ctor(..))
639 }
640
641 pub fn typeck_root_def_id(self, def_id: DefId) -> DefId {
648 let mut def_id = def_id;
649 while self.is_typeck_child(def_id) {
650 def_id = self.parent(def_id);
651 }
652 def_id
653 }
654
655 pub fn closure_env_ty(
666 self,
667 closure_ty: Ty<'tcx>,
668 closure_kind: ty::ClosureKind,
669 env_region: ty::Region<'tcx>,
670 ) -> Ty<'tcx> {
671 match closure_kind {
672 ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty),
673 ty::ClosureKind::FnMut => Ty::new_mut_ref(self, env_region, closure_ty),
674 ty::ClosureKind::FnOnce => closure_ty,
675 }
676 }
677
678 #[inline]
680 pub fn is_static(self, def_id: DefId) -> bool {
681 #[allow(non_exhaustive_omitted_patterns)] match self.def_kind(def_id) {
DefKind::Static { .. } => true,
_ => false,
}matches!(self.def_kind(def_id), DefKind::Static { .. })
682 }
683
684 #[inline]
685 pub fn static_mutability(self, def_id: DefId) -> Option<hir::Mutability> {
686 if let DefKind::Static { mutability, .. } = self.def_kind(def_id) {
687 Some(mutability)
688 } else {
689 None
690 }
691 }
692
693 pub fn is_thread_local_static(self, def_id: DefId) -> bool {
695 self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
696 }
697
698 #[inline]
700 pub fn is_mutable_static(self, def_id: DefId) -> bool {
701 self.static_mutability(def_id) == Some(hir::Mutability::Mut)
702 }
703
704 #[inline]
707 pub fn needs_thread_local_shim(self, def_id: DefId) -> bool {
708 !self.sess.target.dll_tls_export
709 && self.is_thread_local_static(def_id)
710 && !self.is_foreign_item(def_id)
711 }
712
713 pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> {
715 let static_ty = self.type_of(def_id).instantiate_identity();
716 if self.is_mutable_static(def_id) {
717 Ty::new_mut_ptr(self, static_ty)
718 } else if self.is_foreign_item(def_id) {
719 Ty::new_imm_ptr(self, static_ty)
720 } else {
721 Ty::new_imm_ref(self, self.lifetimes.re_static, static_ty)
723 }
724 }
725
726 pub fn static_ptr_ty(self, def_id: DefId, typing_env: ty::TypingEnv<'tcx>) -> Ty<'tcx> {
728 let static_ty =
730 self.normalize_erasing_regions(typing_env, self.type_of(def_id).instantiate_identity());
731
732 if self.is_mutable_static(def_id) {
735 Ty::new_mut_ptr(self, static_ty)
736 } else if self.is_foreign_item(def_id) {
737 Ty::new_imm_ptr(self, static_ty)
738 } else {
739 Ty::new_imm_ref(self, self.lifetimes.re_erased, static_ty)
740 }
741 }
742
743 x;#[instrument(skip(self), level = "debug", ret)]
745 pub fn try_expand_impl_trait_type(
746 self,
747 def_id: DefId,
748 args: GenericArgsRef<'tcx>,
749 ) -> Result<Ty<'tcx>, Ty<'tcx>> {
750 let mut visitor = OpaqueTypeExpander {
751 seen_opaque_tys: FxHashSet::default(),
752 expanded_cache: FxHashMap::default(),
753 primary_def_id: Some(def_id),
754 found_recursion: false,
755 found_any_recursion: false,
756 check_recursion: true,
757 tcx: self,
758 };
759
760 let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap();
761 if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) }
762 }
763
764 pub fn def_descr(self, def_id: DefId) -> &'static str {
766 self.def_kind_descr(self.def_kind(def_id), def_id)
767 }
768
769 pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str {
771 match def_kind {
772 DefKind::AssocFn if self.associated_item(def_id).is_method() => "method",
773 DefKind::AssocTy if self.opt_rpitit_info(def_id).is_some() => "opaque type",
774 DefKind::Closure if let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
775 match coroutine_kind {
776 hir::CoroutineKind::Desugared(
777 hir::CoroutineDesugaring::Async,
778 hir::CoroutineSource::Fn,
779 ) => "async fn",
780 hir::CoroutineKind::Desugared(
781 hir::CoroutineDesugaring::Async,
782 hir::CoroutineSource::Block,
783 ) => "async block",
784 hir::CoroutineKind::Desugared(
785 hir::CoroutineDesugaring::Async,
786 hir::CoroutineSource::Closure,
787 ) => "async closure",
788 hir::CoroutineKind::Desugared(
789 hir::CoroutineDesugaring::AsyncGen,
790 hir::CoroutineSource::Fn,
791 ) => "async gen fn",
792 hir::CoroutineKind::Desugared(
793 hir::CoroutineDesugaring::AsyncGen,
794 hir::CoroutineSource::Block,
795 ) => "async gen block",
796 hir::CoroutineKind::Desugared(
797 hir::CoroutineDesugaring::AsyncGen,
798 hir::CoroutineSource::Closure,
799 ) => "async gen closure",
800 hir::CoroutineKind::Desugared(
801 hir::CoroutineDesugaring::Gen,
802 hir::CoroutineSource::Fn,
803 ) => "gen fn",
804 hir::CoroutineKind::Desugared(
805 hir::CoroutineDesugaring::Gen,
806 hir::CoroutineSource::Block,
807 ) => "gen block",
808 hir::CoroutineKind::Desugared(
809 hir::CoroutineDesugaring::Gen,
810 hir::CoroutineSource::Closure,
811 ) => "gen closure",
812 hir::CoroutineKind::Coroutine(_) => "coroutine",
813 }
814 }
815 _ => def_kind.descr(def_id),
816 }
817 }
818
819 pub fn def_descr_article(self, def_id: DefId) -> &'static str {
821 self.def_kind_descr_article(self.def_kind(def_id), def_id)
822 }
823
824 pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str {
826 match def_kind {
827 DefKind::AssocFn if self.associated_item(def_id).is_method() => "a",
828 DefKind::Closure if let Some(coroutine_kind) = self.coroutine_kind(def_id) => {
829 match coroutine_kind {
830 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, ..) => "an",
831 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, ..) => "an",
832 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, ..) => "a",
833 hir::CoroutineKind::Coroutine(_) => "a",
834 }
835 }
836 _ => def_kind.article(),
837 }
838 }
839
840 pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
847 if self.features().enabled(sym::rustc_private) {
849 return true;
850 }
851
852 !self.is_private_dep(key)
859 || self.extern_crate(key).is_some_and(|e| e.is_direct())
863 }
864
865 pub fn expand_free_alias_tys<T: TypeFoldable<TyCtxt<'tcx>>>(self, value: T) -> T {
886 value.fold_with(&mut FreeAliasTypeExpander { tcx: self, depth: 0 })
887 }
888
889 pub fn peel_off_free_alias_tys(self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
904 let ty::Alias(ty::Free, _) = ty.kind() else { return ty };
905
906 let limit = self.recursion_limit();
907 let mut depth = 0;
908
909 while let ty::Alias(ty::Free, alias) = ty.kind() {
910 if !limit.value_within_limit(depth) {
911 let guar = self.dcx().delayed_bug("overflow expanding free alias type");
912 return Ty::new_error(self, guar);
913 }
914
915 ty = self.type_of(alias.def_id).instantiate(self, alias.args);
916 depth += 1;
917 }
918
919 ty
920 }
921
922 pub fn opt_alias_variances(
925 self,
926 kind: impl Into<ty::AliasTermKind>,
927 def_id: DefId,
928 ) -> Option<&'tcx [ty::Variance]> {
929 match kind.into() {
930 ty::AliasTermKind::ProjectionTy => {
931 if self.is_impl_trait_in_trait(def_id) {
932 Some(self.variances_of(def_id))
933 } else {
934 None
935 }
936 }
937 ty::AliasTermKind::OpaqueTy => Some(self.variances_of(def_id)),
938 ty::AliasTermKind::InherentTy
939 | ty::AliasTermKind::InherentConst
940 | ty::AliasTermKind::FreeTy
941 | ty::AliasTermKind::FreeConst
942 | ty::AliasTermKind::UnevaluatedConst
943 | ty::AliasTermKind::ProjectionConst => None,
944 }
945 }
946}
947
948struct OpaqueTypeExpander<'tcx> {
949 seen_opaque_tys: FxHashSet<DefId>,
954 expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>,
957 primary_def_id: Option<DefId>,
958 found_recursion: bool,
959 found_any_recursion: bool,
960 check_recursion: bool,
964 tcx: TyCtxt<'tcx>,
965}
966
967impl<'tcx> OpaqueTypeExpander<'tcx> {
968 fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> {
969 if self.found_any_recursion {
970 return None;
971 }
972 let args = args.fold_with(self);
973 if !self.check_recursion || self.seen_opaque_tys.insert(def_id) {
974 let expanded_ty = match self.expanded_cache.get(&(def_id, args)) {
975 Some(expanded_ty) => *expanded_ty,
976 None => {
977 let generic_ty = self.tcx.type_of(def_id);
978 let concrete_ty = generic_ty.instantiate(self.tcx, args);
979 let expanded_ty = self.fold_ty(concrete_ty);
980 self.expanded_cache.insert((def_id, args), expanded_ty);
981 expanded_ty
982 }
983 };
984 if self.check_recursion {
985 self.seen_opaque_tys.remove(&def_id);
986 }
987 Some(expanded_ty)
988 } else {
989 self.found_any_recursion = true;
992 self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap();
993 None
994 }
995 }
996}
997
998impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> {
999 fn cx(&self) -> TyCtxt<'tcx> {
1000 self.tcx
1001 }
1002
1003 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
1004 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) = *t.kind() {
1005 self.expand_opaque_ty(def_id, args).unwrap_or(t)
1006 } else if t.has_opaque_types() {
1007 t.super_fold_with(self)
1008 } else {
1009 t
1010 }
1011 }
1012
1013 fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
1014 if let ty::PredicateKind::Clause(clause) = p.kind().skip_binder()
1015 && let ty::ClauseKind::Projection(projection_pred) = clause
1016 {
1017 p.kind()
1018 .rebind(ty::ProjectionPredicate {
1019 projection_term: projection_pred.projection_term.fold_with(self),
1020 term: projection_pred.term,
1026 })
1027 .upcast(self.tcx)
1028 } else {
1029 p.super_fold_with(self)
1030 }
1031 }
1032}
1033
1034struct FreeAliasTypeExpander<'tcx> {
1035 tcx: TyCtxt<'tcx>,
1036 depth: usize,
1037}
1038
1039impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FreeAliasTypeExpander<'tcx> {
1040 fn cx(&self) -> TyCtxt<'tcx> {
1041 self.tcx
1042 }
1043
1044 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1045 if !ty.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1046 return ty;
1047 }
1048 let ty::Alias(ty::Free, alias) = ty.kind() else {
1049 return ty.super_fold_with(self);
1050 };
1051 if !self.tcx.recursion_limit().value_within_limit(self.depth) {
1052 let guar = self.tcx.dcx().delayed_bug("overflow expanding free alias type");
1053 return Ty::new_error(self.tcx, guar);
1054 }
1055
1056 self.depth += 1;
1057 let ty = ensure_sufficient_stack(|| {
1058 self.tcx.type_of(alias.def_id).instantiate(self.tcx, alias.args).fold_with(self)
1059 });
1060 self.depth -= 1;
1061 ty
1062 }
1063
1064 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1065 if !ct.has_type_flags(ty::TypeFlags::HAS_TY_FREE_ALIAS) {
1066 return ct;
1067 }
1068 ct.super_fold_with(self)
1069 }
1070}
1071
1072impl<'tcx> Ty<'tcx> {
1073 pub fn primitive_size(self, tcx: TyCtxt<'tcx>) -> Size {
1075 match *self.kind() {
1076 ty::Bool => Size::from_bytes(1),
1077 ty::Char => Size::from_bytes(4),
1078 ty::Int(ity) => Integer::from_int_ty(&tcx, ity).size(),
1079 ty::Uint(uty) => Integer::from_uint_ty(&tcx, uty).size(),
1080 ty::Float(fty) => Float::from_float_ty(fty).size(),
1081 _ => crate::util::bug::bug_fmt(format_args!("non primitive type"))bug!("non primitive type"),
1082 }
1083 }
1084
1085 pub fn int_size_and_signed(self, tcx: TyCtxt<'tcx>) -> (Size, bool) {
1086 match *self.kind() {
1087 ty::Int(ity) => (Integer::from_int_ty(&tcx, ity).size(), true),
1088 ty::Uint(uty) => (Integer::from_uint_ty(&tcx, uty).size(), false),
1089 _ => crate::util::bug::bug_fmt(format_args!("non integer discriminant"))bug!("non integer discriminant"),
1090 }
1091 }
1092
1093 pub fn numeric_min_and_max_as_bits(self, tcx: TyCtxt<'tcx>) -> Option<(u128, u128)> {
1096 use rustc_apfloat::ieee::{Double, Half, Quad, Single};
1097 Some(match self.kind() {
1098 ty::Int(_) | ty::Uint(_) => {
1099 let (size, signed) = self.int_size_and_signed(tcx);
1100 let min = if signed { size.truncate(size.signed_int_min() as u128) } else { 0 };
1101 let max =
1102 if signed { size.signed_int_max() as u128 } else { size.unsigned_int_max() };
1103 (min, max)
1104 }
1105 ty::Char => (0, std::char::MAX as u128),
1106 ty::Float(ty::FloatTy::F16) => ((-Half::INFINITY).to_bits(), Half::INFINITY.to_bits()),
1107 ty::Float(ty::FloatTy::F32) => {
1108 ((-Single::INFINITY).to_bits(), Single::INFINITY.to_bits())
1109 }
1110 ty::Float(ty::FloatTy::F64) => {
1111 ((-Double::INFINITY).to_bits(), Double::INFINITY.to_bits())
1112 }
1113 ty::Float(ty::FloatTy::F128) => ((-Quad::INFINITY).to_bits(), Quad::INFINITY.to_bits()),
1114 _ => return None,
1115 })
1116 }
1117
1118 pub fn numeric_max_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1121 let typing_env = TypingEnv::fully_monomorphized();
1122 self.numeric_min_and_max_as_bits(tcx)
1123 .map(|(_, max)| mir::Const::from_bits(tcx, max, typing_env, self))
1124 }
1125
1126 pub fn numeric_min_val(self, tcx: TyCtxt<'tcx>) -> Option<mir::Const<'tcx>> {
1129 let typing_env = TypingEnv::fully_monomorphized();
1130 self.numeric_min_and_max_as_bits(tcx)
1131 .map(|(min, _)| mir::Const::from_bits(tcx, min, typing_env, self))
1132 }
1133
1134 pub fn is_sized(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1141 self.has_trivial_sizedness(tcx, SizedTraitKind::Sized)
1142 || tcx.is_sized_raw(typing_env.as_query_input(self))
1143 }
1144
1145 pub fn is_freeze(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1153 self.is_trivially_freeze() || tcx.is_freeze_raw(typing_env.as_query_input(self))
1154 }
1155
1156 pub fn is_trivially_freeze(self) -> bool {
1161 match self.kind() {
1162 ty::Int(_)
1163 | ty::Uint(_)
1164 | ty::Float(_)
1165 | ty::Bool
1166 | ty::Char
1167 | ty::Str
1168 | ty::Never
1169 | ty::Ref(..)
1170 | ty::RawPtr(_, _)
1171 | ty::FnDef(..)
1172 | ty::Error(_)
1173 | ty::FnPtr(..) => true,
1174 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_freeze),
1175 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_freeze(),
1176 ty::Adt(..)
1177 | ty::Bound(..)
1178 | ty::Closure(..)
1179 | ty::CoroutineClosure(..)
1180 | ty::Dynamic(..)
1181 | ty::Foreign(_)
1182 | ty::Coroutine(..)
1183 | ty::CoroutineWitness(..)
1184 | ty::UnsafeBinder(_)
1185 | ty::Infer(_)
1186 | ty::Alias(..)
1187 | ty::Param(_)
1188 | ty::Placeholder(_) => false,
1189 }
1190 }
1191
1192 pub fn is_unpin(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1194 self.is_trivially_unpin() || tcx.is_unpin_raw(typing_env.as_query_input(self))
1195 }
1196
1197 fn is_trivially_unpin(self) -> bool {
1202 match self.kind() {
1203 ty::Int(_)
1204 | ty::Uint(_)
1205 | ty::Float(_)
1206 | ty::Bool
1207 | ty::Char
1208 | ty::Str
1209 | ty::Never
1210 | ty::Ref(..)
1211 | ty::RawPtr(_, _)
1212 | ty::FnDef(..)
1213 | ty::Error(_)
1214 | ty::FnPtr(..) => true,
1215 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_unpin),
1216 ty::Pat(ty, _) | ty::Slice(ty) | ty::Array(ty, _) => ty.is_trivially_unpin(),
1217 ty::Adt(..)
1218 | ty::Bound(..)
1219 | ty::Closure(..)
1220 | ty::CoroutineClosure(..)
1221 | ty::Dynamic(..)
1222 | ty::Foreign(_)
1223 | ty::Coroutine(..)
1224 | ty::CoroutineWitness(..)
1225 | ty::UnsafeBinder(_)
1226 | ty::Infer(_)
1227 | ty::Alias(..)
1228 | ty::Param(_)
1229 | ty::Placeholder(_) => false,
1230 }
1231 }
1232
1233 pub fn has_unsafe_fields(self) -> bool {
1235 if let ty::Adt(adt_def, ..) = self.kind() {
1236 adt_def.all_fields().any(|x| x.safety.is_unsafe())
1237 } else {
1238 false
1239 }
1240 }
1241
1242 pub fn is_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1244 !self.is_trivially_not_async_drop()
1245 && tcx.is_async_drop_raw(typing_env.as_query_input(self))
1246 }
1247
1248 fn is_trivially_not_async_drop(self) -> bool {
1253 match self.kind() {
1254 ty::Int(_)
1255 | ty::Uint(_)
1256 | ty::Float(_)
1257 | ty::Bool
1258 | ty::Char
1259 | ty::Str
1260 | ty::Never
1261 | ty::Ref(..)
1262 | ty::RawPtr(..)
1263 | ty::FnDef(..)
1264 | ty::Error(_)
1265 | ty::FnPtr(..) => true,
1266 ty::UnsafeBinder(_) => ::core::panicking::panic("not yet implemented")todo!(),
1268 ty::Tuple(fields) => fields.iter().all(Self::is_trivially_not_async_drop),
1269 ty::Pat(elem_ty, _) | ty::Slice(elem_ty) | ty::Array(elem_ty, _) => {
1270 elem_ty.is_trivially_not_async_drop()
1271 }
1272 ty::Adt(..)
1273 | ty::Bound(..)
1274 | ty::Closure(..)
1275 | ty::CoroutineClosure(..)
1276 | ty::Dynamic(..)
1277 | ty::Foreign(_)
1278 | ty::Coroutine(..)
1279 | ty::CoroutineWitness(..)
1280 | ty::Infer(_)
1281 | ty::Alias(..)
1282 | ty::Param(_)
1283 | ty::Placeholder(_) => false,
1284 }
1285 }
1286
1287 #[inline]
1296 pub fn needs_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1297 match needs_drop_components(tcx, self) {
1299 Err(AlwaysRequiresDrop) => true,
1300 Ok(components) => {
1301 let query_ty = match *components {
1302 [] => return false,
1303 [component_ty] => component_ty,
1306 _ => self,
1307 };
1308
1309 if true {
if !!typing_env.param_env.has_infer() {
::core::panicking::panic("assertion failed: !typing_env.param_env.has_infer()")
};
};debug_assert!(!typing_env.param_env.has_infer());
1312 let query_ty = tcx
1313 .try_normalize_erasing_regions(typing_env, query_ty)
1314 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
1315
1316 tcx.needs_drop_raw(typing_env.as_query_input(query_ty))
1317 }
1318 }
1319 }
1320
1321 #[inline]
1332 pub fn needs_async_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1333 match needs_drop_components(tcx, self) {
1335 Err(AlwaysRequiresDrop) => true,
1336 Ok(components) => {
1337 let query_ty = match *components {
1338 [] => return false,
1339 [component_ty] => component_ty,
1342 _ => self,
1343 };
1344
1345 if true {
if !!typing_env.has_infer() {
::core::panicking::panic("assertion failed: !typing_env.has_infer()")
};
};debug_assert!(!typing_env.has_infer());
1349 let query_ty = tcx
1350 .try_normalize_erasing_regions(typing_env, query_ty)
1351 .unwrap_or_else(|_| tcx.erase_and_anonymize_regions(query_ty));
1352
1353 tcx.needs_async_drop_raw(typing_env.as_query_input(query_ty))
1354 }
1355 }
1356 }
1357
1358 #[inline]
1367 pub fn has_significant_drop(self, tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1368 match needs_drop_components(tcx, self) {
1370 Err(AlwaysRequiresDrop) => true,
1371 Ok(components) => {
1372 let query_ty = match *components {
1373 [] => return false,
1374 [component_ty] => component_ty,
1377 _ => self,
1378 };
1379
1380 if query_ty.has_infer() {
1387 return true;
1388 }
1389
1390 tcx.try_normalize_erasing_regions(typing_env, query_ty)
1394 .map(|erased| tcx.has_significant_drop_raw(typing_env.as_query_input(erased)))
1395 .unwrap_or(true)
1396 }
1397 }
1398 }
1399
1400 #[inline]
1415 pub fn is_structural_eq_shallow(self, tcx: TyCtxt<'tcx>) -> bool {
1416 match self.kind() {
1417 ty::Adt(..) => tcx.has_structural_eq_impl(self),
1419
1420 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => true,
1422
1423 ty::Pat(..) | ty::Ref(..) | ty::Array(..) | ty::Slice(_) | ty::Tuple(..) => true,
1428
1429 ty::RawPtr(_, _) | ty::FnPtr(..) => true,
1431
1432 ty::Float(_) => false,
1434
1435 ty::FnDef(..)
1439 | ty::Closure(..)
1440 | ty::CoroutineClosure(..)
1441 | ty::Dynamic(..)
1442 | ty::Coroutine(..) => false,
1443
1444 ty::Alias(..) | ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) => {
1449 false
1450 }
1451
1452 ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false,
1453 }
1454 }
1455
1456 pub fn peel_refs(self) -> Ty<'tcx> {
1467 let mut ty = self;
1468 while let ty::Ref(_, inner_ty, _) = ty.kind() {
1469 ty = *inner_ty;
1470 }
1471 ty
1472 }
1473
1474 #[inline]
1476 pub fn outer_exclusive_binder(self) -> ty::DebruijnIndex {
1477 self.0.outer_exclusive_binder
1478 }
1479}
1480
1481#[inline]
1488pub fn needs_drop_components<'tcx>(
1489 tcx: TyCtxt<'tcx>,
1490 ty: Ty<'tcx>,
1491) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1492 needs_drop_components_with_async(tcx, ty, Asyncness::No)
1493}
1494
1495pub fn needs_drop_components_with_async<'tcx>(
1499 tcx: TyCtxt<'tcx>,
1500 ty: Ty<'tcx>,
1501 asyncness: Asyncness,
1502) -> Result<SmallVec<[Ty<'tcx>; 2]>, AlwaysRequiresDrop> {
1503 match *ty.kind() {
1504 ty::Infer(ty::FreshIntTy(_))
1505 | ty::Infer(ty::FreshFloatTy(_))
1506 | ty::Bool
1507 | ty::Int(_)
1508 | ty::Uint(_)
1509 | ty::Float(_)
1510 | ty::Never
1511 | ty::FnDef(..)
1512 | ty::FnPtr(..)
1513 | ty::Char
1514 | ty::RawPtr(_, _)
1515 | ty::Ref(..)
1516 | ty::Str => Ok(SmallVec::new()),
1517
1518 ty::Foreign(..) => Ok(SmallVec::new()),
1520
1521 ty::Dynamic(..) | ty::Error(_) => {
1523 if asyncness.is_async() {
1524 Ok(SmallVec::new())
1525 } else {
1526 Err(AlwaysRequiresDrop)
1527 }
1528 }
1529
1530 ty::Pat(ty, _) | ty::Slice(ty) => needs_drop_components_with_async(tcx, ty, asyncness),
1531 ty::Array(elem_ty, size) => {
1532 match needs_drop_components_with_async(tcx, elem_ty, asyncness) {
1533 Ok(v) if v.is_empty() => Ok(v),
1534 res => match size.try_to_target_usize(tcx) {
1535 Some(0) => Ok(SmallVec::new()),
1538 Some(_) => res,
1539 None => Ok({
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(ty);
vec
} else {
::smallvec::SmallVec::from_vec(<[_]>::into_vec(::alloc::boxed::box_new([ty])))
}
}smallvec![ty]),
1543 },
1544 }
1545 }
1546 ty::Tuple(fields) => fields.iter().try_fold(SmallVec::new(), move |mut acc, elem| {
1548 acc.extend(needs_drop_components_with_async(tcx, elem, asyncness)?);
1549 Ok(acc)
1550 }),
1551
1552 ty::Adt(..)
1554 | ty::Alias(..)
1555 | ty::Param(_)
1556 | ty::Bound(..)
1557 | ty::Placeholder(..)
1558 | ty::Infer(_)
1559 | ty::Closure(..)
1560 | ty::CoroutineClosure(..)
1561 | ty::Coroutine(..)
1562 | ty::CoroutineWitness(..)
1563 | ty::UnsafeBinder(_) => Ok({
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(ty);
vec
} else {
::smallvec::SmallVec::from_vec(<[_]>::into_vec(::alloc::boxed::box_new([ty])))
}
}smallvec![ty]),
1564 }
1565}
1566
1567pub fn fold_list<'tcx, F, L, T>(
1573 list: L,
1574 folder: &mut F,
1575 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1576) -> L
1577where
1578 F: TypeFolder<TyCtxt<'tcx>>,
1579 L: AsRef<[T]>,
1580 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1581{
1582 let slice = list.as_ref();
1583 let mut iter = slice.iter().copied();
1584 match iter.by_ref().enumerate().find_map(|(i, t)| {
1586 let new_t = t.fold_with(folder);
1587 if new_t != t { Some((i, new_t)) } else { None }
1588 }) {
1589 Some((i, new_t)) => {
1590 let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1592 new_list.extend_from_slice(&slice[..i]);
1593 new_list.push(new_t);
1594 for t in iter {
1595 new_list.push(t.fold_with(folder))
1596 }
1597 intern(folder.cx(), &new_list)
1598 }
1599 None => list,
1600 }
1601}
1602
1603pub fn try_fold_list<'tcx, F, L, T>(
1609 list: L,
1610 folder: &mut F,
1611 intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> L,
1612) -> Result<L, F::Error>
1613where
1614 F: FallibleTypeFolder<TyCtxt<'tcx>>,
1615 L: AsRef<[T]>,
1616 T: TypeFoldable<TyCtxt<'tcx>> + PartialEq + Copy,
1617{
1618 let slice = list.as_ref();
1619 let mut iter = slice.iter().copied();
1620 match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) {
1622 Ok(new_t) if new_t == t => None,
1623 new_t => Some((i, new_t)),
1624 }) {
1625 Some((i, Ok(new_t))) => {
1626 let mut new_list = SmallVec::<[_; 8]>::with_capacity(slice.len());
1628 new_list.extend_from_slice(&slice[..i]);
1629 new_list.push(new_t);
1630 for t in iter {
1631 new_list.push(t.try_fold_with(folder)?)
1632 }
1633 Ok(intern(folder.cx(), &new_list))
1634 }
1635 Some((_, Err(err))) => {
1636 return Err(err);
1637 }
1638 None => Ok(list),
1639 }
1640}
1641
1642#[derive(#[automatically_derived]
impl ::core::marker::Copy for AlwaysRequiresDrop { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AlwaysRequiresDrop {
#[inline]
fn clone(&self) -> AlwaysRequiresDrop { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AlwaysRequiresDrop {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "AlwaysRequiresDrop")
}
}Debug, const _: () =
{
impl<'__ctx>
::rustc_data_structures::stable_hasher::HashStable<::rustc_query_system::ich::StableHashingContext<'__ctx>>
for AlwaysRequiresDrop {
#[inline]
fn hash_stable(&self,
__hcx:
&mut ::rustc_query_system::ich::StableHashingContext<'__ctx>,
__hasher:
&mut ::rustc_data_structures::stable_hasher::StableHasher) {
match *self { AlwaysRequiresDrop => {} }
}
}
};HashStable, const _: () =
{
impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
::rustc_serialize::Encodable<__E> for AlwaysRequiresDrop {
fn encode(&self, __encoder: &mut __E) {
match *self { AlwaysRequiresDrop => {} }
}
}
};TyEncodable, const _: () =
{
impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
::rustc_serialize::Decodable<__D> for AlwaysRequiresDrop {
fn decode(__decoder: &mut __D) -> Self { AlwaysRequiresDrop }
}
};TyDecodable)]
1643pub struct AlwaysRequiresDrop;
1644
1645pub fn reveal_opaque_types_in_bounds<'tcx>(
1648 tcx: TyCtxt<'tcx>,
1649 val: ty::Clauses<'tcx>,
1650) -> ty::Clauses<'tcx> {
1651 if !!tcx.next_trait_solver_globally() {
::core::panicking::panic("assertion failed: !tcx.next_trait_solver_globally()")
};assert!(!tcx.next_trait_solver_globally());
1652 let mut visitor = OpaqueTypeExpander {
1653 seen_opaque_tys: FxHashSet::default(),
1654 expanded_cache: FxHashMap::default(),
1655 primary_def_id: None,
1656 found_recursion: false,
1657 found_any_recursion: false,
1658 check_recursion: false,
1659 tcx,
1660 };
1661 val.fold_with(&mut visitor)
1662}
1663
1664fn is_doc_hidden(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1666 let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
1667 attrs.iter().any(|attr| attr.is_doc_hidden())
1668}
1669
1670pub fn is_doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1672 let attrs = tcx.get_all_attrs(def_id);
1673 attrs.iter().any(|attr| #[allow(non_exhaustive_omitted_patterns)] match attr {
hir::Attribute::Parsed(AttributeKind::Doc(doc)) if
doc.notable_trait.is_some() => true,
_ => false,
}matches!(attr, hir::Attribute::Parsed(AttributeKind::Doc(doc)) if doc.notable_trait.is_some()))
1674}
1675
1676pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::IntrinsicDef> {
1682 if tcx.features().intrinsics()
1683 && {
{
'done:
{
for i in tcx.get_all_attrs(def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::RustcIntrinsic)
=> {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(tcx.get_all_attrs(def_id), AttributeKind::RustcIntrinsic)
1684 {
1685 let must_be_overridden = match tcx.hir_node_by_def_id(def_id) {
1686 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => {
1687 !has_body
1688 }
1689 _ => true,
1690 };
1691 Some(ty::IntrinsicDef {
1692 name: tcx.item_name(def_id),
1693 must_be_overridden,
1694 const_stable: {
{
'done:
{
for i in tcx.get_all_attrs(def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::RustcIntrinsicConstStableIndirect)
=> {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(
1695 tcx.get_all_attrs(def_id),
1696 AttributeKind::RustcIntrinsicConstStableIndirect
1697 ),
1698 })
1699 } else {
1700 None
1701 }
1702}
1703
1704pub fn provide(providers: &mut Providers) {
1705 *providers = Providers {
1706 reveal_opaque_types_in_bounds,
1707 is_doc_hidden,
1708 is_doc_notable_trait,
1709 intrinsic_raw,
1710 ..*providers
1711 }
1712}