1//! Check whether a type has (potentially) non-trivial drop glue.
23use rustc_data_structures::fx::FxHashSet;
4use rustc_hir::def_id::DefId;
5use rustc_hir::find_attr;
6use rustc_hir::limit::Limit;
7use rustc_middle::bug;
8use rustc_middle::query::Providers;
9use rustc_middle::ty::util::{AlwaysRequiresDrop, needs_drop_components};
10use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt, Unnormalized};
11use tracing::{debug, instrument};
1213use crate::diagnostics::NeedsDropOverflow;
1415type NeedsDropResult<T> = Result<T, AlwaysRequiresDrop>;
1617fn needs_drop_raw<'tcx>(
18 tcx: TyCtxt<'tcx>,
19 query: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
20) -> bool {
21// If we don't know a type doesn't need drop, for example if it's a type
22 // parameter without a `Copy` bound, then we conservatively return that it
23 // needs drop.
24let adt_has_dtor =
25 |adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant);
26let res = drop_tys_helper(
27tcx,
28query.value,
29query.typing_env,
30adt_has_dtor,
31DropTysOptions::default(),
32 )
33 .filter(filter_array_elements(tcx, query.typing_env))
34 .next()
35 .is_some();
3637{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/needs_drop.rs:37",
"rustc_ty_utils::needs_drop", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/needs_drop.rs"),
::tracing_core::__macro_support::Option::Some(37u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::needs_drop"),
::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!("needs_drop_raw({0:?}) = {1:?}",
query, res) as &dyn Value))])
});
} else { ; }
};debug!("needs_drop_raw({:?}) = {:?}", query, res);
38res39}
4041fn needs_async_drop_raw<'tcx>(
42 tcx: TyCtxt<'tcx>,
43 query: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
44) -> bool {
45// If we don't know a type doesn't need async drop, for example if it's a
46 // type parameter without a `Copy` bound, then we conservatively return that
47 // it needs async drop.
48let adt_has_async_dtor =
49 |adt_def: ty::AdtDef<'tcx>| adt_def.async_destructor(tcx).map(|_| DtorType::Significant);
50let res = drop_tys_helper(
51tcx,
52query.value,
53query.typing_env,
54adt_has_async_dtor,
55DropTysOptions::default().recurse_into_box_for_async_drop(),
56 )
57 .filter(filter_array_elements_async(tcx, query.typing_env))
58 .next()
59 .is_some();
6061{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/needs_drop.rs:61",
"rustc_ty_utils::needs_drop", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/needs_drop.rs"),
::tracing_core::__macro_support::Option::Some(61u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::needs_drop"),
::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!("needs_async_drop_raw({0:?}) = {1:?}",
query, res) as &dyn Value))])
});
} else { ; }
};debug!("needs_async_drop_raw({:?}) = {:?}", query, res);
62res63}
6465/// HACK: in order to not mistakenly assume that `[PhantomData<T>; N]` requires drop glue
66/// we check the element type for drop glue. The correct fix would be looking at the
67/// entirety of the code around `needs_drop_components` and this file and come up with
68/// logic that is easier to follow while not repeating any checks that may thus diverge.
69fn filter_array_elements<'tcx>(
70 tcx: TyCtxt<'tcx>,
71 typing_env: ty::TypingEnv<'tcx>,
72) -> impl Fn(&Result<Ty<'tcx>, AlwaysRequiresDrop>) -> bool {
73move |ty| match ty {
74Ok(ty) => match *ty.kind() {
75 ty::Array(elem, _) => tcx.needs_drop_raw(typing_env.as_query_input(elem)),
76_ => true,
77 },
78Err(AlwaysRequiresDrop) => true,
79 }
80}
81fn filter_array_elements_async<'tcx>(
82 tcx: TyCtxt<'tcx>,
83 typing_env: ty::TypingEnv<'tcx>,
84) -> impl Fn(&Result<Ty<'tcx>, AlwaysRequiresDrop>) -> bool {
85move |ty| match ty {
86Ok(ty) => match *ty.kind() {
87 ty::Array(elem, _) => tcx.needs_async_drop_raw(typing_env.as_query_input(elem)),
88_ => true,
89 },
90Err(AlwaysRequiresDrop) => true,
91 }
92}
9394fn has_significant_drop_raw<'tcx>(
95 tcx: TyCtxt<'tcx>,
96 query: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
97) -> bool {
98let res = drop_tys_helper(
99tcx,
100query.value,
101query.typing_env,
102adt_consider_insignificant_dtor(tcx),
103DropTysOptions::default().only_significant(),
104 )
105 .filter(filter_array_elements(tcx, query.typing_env))
106 .next()
107 .is_some();
108{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/needs_drop.rs:108",
"rustc_ty_utils::needs_drop", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/needs_drop.rs"),
::tracing_core::__macro_support::Option::Some(108u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::needs_drop"),
::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!("has_significant_drop_raw({0:?}) = {1:?}",
query, res) as &dyn Value))])
});
} else { ; }
};debug!("has_significant_drop_raw({:?}) = {:?}", query, res);
109res110}
111112struct NeedsDropTypes<'tcx, F> {
113 tcx: TyCtxt<'tcx>,
114 typing_env: ty::TypingEnv<'tcx>,
115 query_ty: Ty<'tcx>,
116 seen_tys: FxHashSet<Ty<'tcx>>,
117/// A stack of types left to process, and the recursion depth when we
118 /// pushed that type. Each round, we pop something from the stack and check
119 /// if it needs drop. If the result depends on whether some other types
120 /// need drop we push them onto the stack.
121unchecked_tys: Vec<(Ty<'tcx>, usize)>,
122 recursion_limit: Limit,
123 adt_components: F,
124/// Set this to true if an exhaustive list of types involved in
125 /// drop obligation is requested.
126// FIXME: Calling this bool `exhaustive` is confusing and possibly a footgun,
127 // since it does two things: It makes the iterator yield *all* of the types
128 // that need drop, and it also affects the computation of the drop components
129 // on `Coroutine`s. The latter is somewhat confusing, and probably should be
130 // a function of `typing_env`. See the HACK comment below for why this is
131 // necessary. If this isn't possible, then we probably should turn this into
132 // a `NeedsDropMode` so that we can have a variant like `CollectAllSignificantDrops`,
133 // which will more accurately indicate that we want *all* of the *significant*
134 // drops, which are the two important behavioral changes toggled by this bool.
135exhaustive: bool,
136}
137138impl<'tcx, F> NeedsDropTypes<'tcx, F> {
139fn new(
140 tcx: TyCtxt<'tcx>,
141 typing_env: ty::TypingEnv<'tcx>,
142 ty: Ty<'tcx>,
143 exhaustive: bool,
144 adt_components: F,
145 ) -> Self {
146let mut seen_tys = FxHashSet::default();
147seen_tys.insert(ty);
148Self {
149tcx,
150typing_env,
151seen_tys,
152 query_ty: ty,
153 unchecked_tys: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ty, 0)]))vec![(ty, 0)],
154 recursion_limit: tcx.recursion_limit(),
155adt_components,
156exhaustive,
157 }
158 }
159160/// Called when `ty` is found to always require drop.
161 /// If the exhaustive flag is true, then `Ok(ty)` is returned like any other type.
162 /// Otherwise, `Err(AlwaysRequireDrop)` is returned, which will cause iteration to abort.
163fn always_drop_component(&self, ty: Ty<'tcx>) -> NeedsDropResult<Ty<'tcx>> {
164if self.exhaustive { Ok(ty) } else { Err(AlwaysRequiresDrop) }
165 }
166}
167168impl<'tcx, F, I> Iteratorfor NeedsDropTypes<'tcx, F>
169where
170F: Fn(ty::AdtDef<'tcx>, GenericArgsRef<'tcx>) -> NeedsDropResult<I>,
171 I: Iterator<Item = Ty<'tcx>>,
172{
173type Item = NeedsDropResult<Ty<'tcx>>;
174175x;#[instrument(level = "debug", skip(self), ret)]176fn next(&mut self) -> Option<NeedsDropResult<Ty<'tcx>>> {
177let tcx = self.tcx;
178179while let Some((ty, level)) = self.unchecked_tys.pop() {
180debug!(?ty, "needs_drop_components: inspect");
181if !self.recursion_limit.value_within_limit(level) {
182// Not having a `Span` isn't great. But there's hopefully some other
183 // recursion limit error as well.
184debug!("needs_drop_components: recursion limit exceeded");
185 tcx.dcx().emit_err(NeedsDropOverflow { query_ty: self.query_ty });
186return Some(self.always_drop_component(ty));
187 }
188189let components = match needs_drop_components(tcx, ty) {
190Err(AlwaysRequiresDrop) => return Some(self.always_drop_component(ty)),
191Ok(components) => components,
192 };
193debug!("needs_drop_components({:?}) = {:?}", ty, components);
194195let queue_type = move |this: &mut Self, component: Ty<'tcx>| {
196if this.seen_tys.insert(component) {
197 this.unchecked_tys.push((component, level + 1));
198 }
199 };
200201for component in components {
202match *component.kind() {
203// The information required to determine whether a coroutine has drop is
204 // computed on MIR, while this very method is used to build MIR.
205 // To avoid cycles, we consider that coroutines always require drop.
206 //
207 // HACK: Because we erase regions contained in the coroutine witness, we
208 // have to conservatively assume that every region captured by the
209 // coroutine has to be live when dropped. This results in a lot of
210 // undesirable borrowck errors. During borrowck, we call `needs_drop`
211 // for the coroutine witness and check whether any of the contained types
212 // need to be dropped, and only require the captured types to be live
213 // if they do.
214ty::Coroutine(def_id, args) => {
215// FIXME: See FIXME on `exhaustive` field above.
216if self.exhaustive {
217for upvar in args.as_coroutine().upvar_tys() {
218 queue_type(self, upvar);
219 }
220 queue_type(self, args.as_coroutine().resume_ty());
221if let Some(witness) = tcx.mir_coroutine_witnesses(def_id) {
222for field_ty in &witness.field_tys {
223 queue_type(
224self,
225 EarlyBinder::bind(field_ty.ty)
226 .instantiate(tcx, args)
227 .skip_norm_wip(),
228 );
229 }
230 }
231 } else {
232return Some(self.always_drop_component(ty));
233 }
234 }
235 ty::CoroutineWitness(..) => {
236unreachable!("witness should be handled in parent");
237 }
238239 ty::UnsafeBinder(bound_ty) => {
240let ty = self.tcx.instantiate_bound_regions_with_erased(bound_ty.into());
241 queue_type(self, ty);
242 }
243244_ if tcx.type_is_copy_modulo_regions(self.typing_env, component) => {}
245246 ty::Closure(_, args) => {
247for upvar in args.as_closure().upvar_tys() {
248 queue_type(self, upvar);
249 }
250 }
251252 ty::CoroutineClosure(_, args) => {
253for upvar in args.as_coroutine_closure().upvar_tys() {
254 queue_type(self, upvar);
255 }
256 }
257258// Check for a `Drop` impl and whether this is a union or
259 // `ManuallyDrop`. If it's a struct or enum without a `Drop`
260 // impl then check whether the field types need `Drop`.
261ty::Adt(adt_def, args) => {
262let tys = match (self.adt_components)(adt_def, args) {
263Err(AlwaysRequiresDrop) => {
264return Some(self.always_drop_component(ty));
265 }
266Ok(tys) => tys,
267 };
268for required_ty in tys {
269let required = tcx
270 .try_normalize_erasing_regions(
271self.typing_env,
272 Unnormalized::new_wip(required_ty),
273 )
274 .unwrap_or(required_ty);
275276 queue_type(self, required);
277 }
278 }
279 ty::Alias(..) | ty::Array(..) | ty::Placeholder(_) | ty::Param(_) => {
280if ty == component {
281// Return the type to the caller: they may be able
282 // to normalize further than we can.
283return Some(Ok(component));
284 } else {
285// Store the type for later. We can't return here
286 // because we would then lose any other components
287 // of the type.
288queue_type(self, component);
289 }
290 }
291292 ty::Foreign(_) | ty::Dynamic(..) => {
293debug!("needs_drop_components: foreign or dynamic");
294return Some(self.always_drop_component(ty));
295 }
296297 ty::Bool
298 | ty::Char
299 | ty::Int(_)
300 | ty::Uint(_)
301 | ty::Float(_)
302 | ty::Str
303 | ty::Slice(_)
304 | ty::Ref(..)
305 | ty::RawPtr(..)
306 | ty::FnDef(..)
307 | ty::Pat(..)
308 | ty::FnPtr(..)
309 | ty::Tuple(_)
310 | ty::Bound(..)
311 | ty::Never
312 | ty::Infer(_)
313 | ty::Error(_) => {
314bug!("unexpected type returned by `needs_drop_components`: {component}")
315 }
316 }
317 }
318 }
319320None
321}
322}
323324enum DtorType {
325/// Type has a `Drop` but it is considered insignificant.
326 /// Check the query `adt_significant_drop_tys` for understanding
327 /// "significant" / "insignificant".
328Insignificant,
329330/// Type has a `Drop` implantation.
331Significant,
332}
333334#[derive(#[automatically_derived]
impl ::core::marker::Copy for DropTysOptions { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DropTysOptions {
#[inline]
fn clone(&self) -> DropTysOptions {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]
impl ::core::default::Default for DropTysOptions {
#[inline]
fn default() -> DropTysOptions {
DropTysOptions {
only_significant: ::core::default::Default::default(),
exhaustive: ::core::default::Default::default(),
async_drop_recurses_into_box: ::core::default::Default::default(),
}
}
}Default)]
335struct DropTysOptions {
336 only_significant: bool,
337 exhaustive: bool,
338 async_drop_recurses_into_box: bool,
339}
340341impl DropTysOptions {
342fn only_significant(mut self) -> Self {
343self.only_significant = true;
344self345 }
346347fn exhaustive(mut self) -> Self {
348self.exhaustive = true;
349self350 }
351352fn recurse_into_box_for_async_drop(mut self) -> Self {
353self.async_drop_recurses_into_box = true;
354self355 }
356}
357358// This is a helper function for `adt_drop_tys` and `adt_significant_drop_tys`.
359// Depending on the implantation of `adt_has_dtor`, it is used to check if the
360// ADT has a destructor or if the ADT only has a significant destructor. For
361// understanding significant destructor look at `adt_significant_drop_tys`.
362fn drop_tys_helper<'tcx>(
363 tcx: TyCtxt<'tcx>,
364 ty: Ty<'tcx>,
365 typing_env: ty::TypingEnv<'tcx>,
366 adt_has_dtor: impl Fn(ty::AdtDef<'tcx>) -> Option<DtorType>,
367 options: DropTysOptions,
368) -> impl Iterator<Item = NeedsDropResult<Ty<'tcx>>> {
369fn with_query_cache<'tcx>(
370 tcx: TyCtxt<'tcx>,
371 iter: impl IntoIterator<Item = Ty<'tcx>>,
372 ) -> NeedsDropResult<Vec<Ty<'tcx>>> {
373iter.into_iter().try_fold(Vec::new(), |mut vec, subty| {
374match subty.kind() {
375 ty::Adt(adt_id, args) => {
376for subty in tcx.adt_drop_tys(adt_id.did())? {
377 vec.push(EarlyBinder::bind(subty).instantiate(tcx, args).skip_norm_wip());
378 }
379 }
380_ => vec.push(subty),
381 };
382Ok(vec)
383 })
384 }
385386let adt_components = move |adt_def: ty::AdtDef<'tcx>, args: GenericArgsRef<'tcx>| {
387if adt_def.is_manually_drop() {
388{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/needs_drop.rs:388",
"rustc_ty_utils::needs_drop", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/needs_drop.rs"),
::tracing_core::__macro_support::Option::Some(388u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::needs_drop"),
::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!("drop_tys_helper: `{0:?}` is manually drop",
adt_def) as &dyn Value))])
});
} else { ; }
};debug!("drop_tys_helper: `{:?}` is manually drop", adt_def);
389Ok(Vec::new())
390 } else if options.async_drop_recurses_into_box && adt_def.is_box() {
391let box_components = match args.as_slice() {
392 [boxed_ty, allocator_ty] => {
393let boxed_ty = boxed_ty.expect_ty();
394let allocator_ty = allocator_ty.expect_ty();
395match boxed_ty.kind() {
396// FIXME(async_drop): boxed dyn pointees are deliberately skipped here
397 // because async drop glue does not yet dispatch through dyn metadata.
398 // Once that is supported, this should include the boxed pointee too.
399 ty::Dynamic(..) | ty::Error(_) => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[allocator_ty]))vec![allocator_ty],
400_ => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[boxed_ty, allocator_ty]))vec![boxed_ty, allocator_ty],
401 }
402 }
403_ => {
404::rustc_middle::util::bug::bug_fmt(format_args!("drop_tys_helper: `Box` has unexpected generic args: {0:?}",
args));bug!("drop_tys_helper: `Box` has unexpected generic args: {args:?}");
405 }
406 };
407Ok(box_components)
408 } else if let Some(dtor_info) = adt_has_dtor(adt_def) {
409match dtor_info {
410 DtorType::Significant => {
411{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/needs_drop.rs:411",
"rustc_ty_utils::needs_drop", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/needs_drop.rs"),
::tracing_core::__macro_support::Option::Some(411u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::needs_drop"),
::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!("drop_tys_helper: `{0:?}` implements `Drop`",
adt_def) as &dyn Value))])
});
} else { ; }
};debug!("drop_tys_helper: `{:?}` implements `Drop`", adt_def);
412Err(AlwaysRequiresDrop)
413 }
414 DtorType::Insignificant => {
415{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/needs_drop.rs:415",
"rustc_ty_utils::needs_drop", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/needs_drop.rs"),
::tracing_core::__macro_support::Option::Some(415u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::needs_drop"),
::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!("drop_tys_helper: `{0:?}` drop is insignificant",
adt_def) as &dyn Value))])
});
} else { ; }
};debug!("drop_tys_helper: `{:?}` drop is insignificant", adt_def);
416417// Since the destructor is insignificant, we just want to make sure all of
418 // the passed in type parameters are also insignificant.
419 // Eg: Vec<T> dtor is insignificant when T=i32 but significant when T=Mutex.
420Ok(args.types().collect())
421 }
422 }
423 } else if adt_def.is_union() {
424{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/needs_drop.rs:424",
"rustc_ty_utils::needs_drop", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/needs_drop.rs"),
::tracing_core::__macro_support::Option::Some(424u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::needs_drop"),
::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!("drop_tys_helper: `{0:?}` is a union",
adt_def) as &dyn Value))])
});
} else { ; }
};debug!("drop_tys_helper: `{:?}` is a union", adt_def);
425Ok(Vec::new())
426 } else {
427let field_tys = adt_def.all_fields().map(|field| {
428let r = tcx.type_of(field.did).instantiate(tcx, args).skip_norm_wip();
429{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_ty_utils/src/needs_drop.rs:429",
"rustc_ty_utils::needs_drop", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/needs_drop.rs"),
::tracing_core::__macro_support::Option::Some(429u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::needs_drop"),
::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!("drop_tys_helper: Instantiate into {0:?} with {1:?} getting {2:?}",
field, args, r) as &dyn Value))])
});
} else { ; }
};debug!(
430"drop_tys_helper: Instantiate into {:?} with {:?} getting {:?}",
431 field, args, r
432 );
433r434 });
435if options.only_significant {
436// We can't recurse through the query system here because we might induce a cycle
437Ok(field_tys.collect())
438 } else {
439// We can use the query system if we consider all drops significant. In that case,
440 // ADTs are `needs_drop` exactly if they `impl Drop` or if any of their "transitive"
441 // fields do. There can be no cycles here, because ADTs cannot contain themselves as
442 // fields.
443with_query_cache(tcx, field_tys)
444 }
445 }
446 .map(|v| v.into_iter())
447 };
448449NeedsDropTypes::new(tcx, typing_env, ty, options.exhaustive, adt_components)
450}
451452fn adt_consider_insignificant_dtor<'tcx>(
453 tcx: TyCtxt<'tcx>,
454) -> impl Fn(ty::AdtDef<'tcx>) -> Option<DtorType> {
455move |adt_def: ty::AdtDef<'tcx>| {
456if {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(adt_def.did(), &tcx)
{
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcInsignificantDtor) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, adt_def.did(), RustcInsignificantDtor) {
457// In some cases like `std::collections::HashMap` where the struct is a wrapper around
458 // a type that is a Drop type, and the wrapped type (eg: `hashbrown::HashMap`) lies
459 // outside stdlib, we might choose to still annotate the wrapper (std HashMap) with
460 // `rustc_insignificant_dtor`, even if the type itself doesn't have a `Drop` impl.
461Some(DtorType::Insignificant)
462 } else if adt_def.destructor(tcx).is_some() {
463// There is a Drop impl and the type isn't marked insignificant, therefore Drop must be
464 // significant.
465Some(DtorType::Significant)
466 } else {
467// No destructor found nor the type is annotated with `rustc_insignificant_dtor`, we
468 // treat this as the simple case of Drop impl for type.
469None470 }
471 }
472}
473474fn adt_drop_tys<'tcx>(
475 tcx: TyCtxt<'tcx>,
476 def_id: DefId,
477) -> Result<&'tcx ty::List<Ty<'tcx>>, AlwaysRequiresDrop> {
478// This is for the "adt_drop_tys" query, that considers all `Drop` impls, therefore all dtors are
479 // significant.
480let adt_has_dtor =
481 |adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant);
482// `tcx.type_of(def_id)` identical to `tcx.make_adt(def, identity_args)`
483drop_tys_helper(
484tcx,
485tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
486 ty::TypingEnv::non_body_analysis(tcx, def_id),
487adt_has_dtor,
488DropTysOptions::default(),
489 )
490 .collect::<Result<Vec<_>, _>>()
491 .map(|components| tcx.mk_type_list(&components))
492}
493494fn adt_async_drop_tys<'tcx>(
495 tcx: TyCtxt<'tcx>,
496 def_id: DefId,
497) -> Result<&'tcx ty::List<Ty<'tcx>>, AlwaysRequiresDrop> {
498// This is for the "adt_async_drop_tys" query, that considers all `AsyncDrop` impls.
499let adt_has_dtor =
500 |adt_def: ty::AdtDef<'tcx>| adt_def.async_destructor(tcx).map(|_| DtorType::Significant);
501// `tcx.type_of(def_id)` identical to `tcx.make_adt(def, identity_args)`
502drop_tys_helper(
503tcx,
504tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
505 ty::TypingEnv::non_body_analysis(tcx, def_id),
506adt_has_dtor,
507DropTysOptions::default().recurse_into_box_for_async_drop(),
508 )
509 .collect::<Result<Vec<_>, _>>()
510 .map(|components| tcx.mk_type_list(&components))
511}
512513// If `def_id` refers to a generic ADT, the queries above and below act as if they had been handed
514// a `tcx.make_ty(def, identity_args)` and as such it is legal to instantiate the generic parameters
515// of the ADT into the outputted `ty`s.
516fn adt_significant_drop_tys(
517 tcx: TyCtxt<'_>,
518 def_id: DefId,
519) -> Result<&ty::List<Ty<'_>>, AlwaysRequiresDrop> {
520drop_tys_helper(
521tcx,
522tcx.type_of(def_id).instantiate_identity().skip_norm_wip(), // identical to `tcx.make_adt(def, identity_args)`
523ty::TypingEnv::non_body_analysis(tcx, def_id),
524adt_consider_insignificant_dtor(tcx),
525DropTysOptions::default().only_significant(),
526 )
527 .collect::<Result<Vec<_>, _>>()
528 .map(|components| tcx.mk_type_list(&components))
529}
530531x;#[instrument(level = "debug", skip(tcx), ret)]532fn list_significant_drop_tys<'tcx>(
533 tcx: TyCtxt<'tcx>,
534 key: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
535) -> &'tcx ty::List<Ty<'tcx>> {
536 tcx.mk_type_list(
537&drop_tys_helper(
538 tcx,
539 key.value,
540 key.typing_env,
541 adt_consider_insignificant_dtor(tcx),
542 DropTysOptions::default().only_significant().exhaustive(),
543 )
544 .filter_map(|res| res.ok())
545 .collect::<Vec<_>>(),
546 )
547}
548549pub(crate) fn provide(providers: &mut Providers) {
550*providers = Providers {
551needs_drop_raw,
552needs_async_drop_raw,
553has_significant_drop_raw,
554adt_drop_tys,
555adt_async_drop_tys,
556adt_significant_drop_tys,
557list_significant_drop_tys,
558 ..*providers559 };
560}