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::errors::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(tcx, query.value, query.typing_env, adt_has_dtor, false, false)
27 .filter(filter_array_elements(tcx, query.typing_env))
28 .next()
29 .is_some();
3031{
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:31",
"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(31u32),
::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);
32res33}
3435fn needs_async_drop_raw<'tcx>(
36 tcx: TyCtxt<'tcx>,
37 query: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
38) -> bool {
39// If we don't know a type doesn't need async drop, for example if it's a
40 // type parameter without a `Copy` bound, then we conservatively return that
41 // it needs async drop.
42let adt_has_async_dtor =
43 |adt_def: ty::AdtDef<'tcx>| adt_def.async_destructor(tcx).map(|_| DtorType::Significant);
44let res = drop_tys_helper(tcx, query.value, query.typing_env, adt_has_async_dtor, false, false)
45 .filter(filter_array_elements_async(tcx, query.typing_env))
46 .next()
47 .is_some();
4849{
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:49",
"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(49u32),
::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);
50res51}
5253/// HACK: in order to not mistakenly assume that `[PhantomData<T>; N]` requires drop glue
54/// we check the element type for drop glue. The correct fix would be looking at the
55/// entirety of the code around `needs_drop_components` and this file and come up with
56/// logic that is easier to follow while not repeating any checks that may thus diverge.
57fn filter_array_elements<'tcx>(
58 tcx: TyCtxt<'tcx>,
59 typing_env: ty::TypingEnv<'tcx>,
60) -> impl Fn(&Result<Ty<'tcx>, AlwaysRequiresDrop>) -> bool {
61move |ty| match ty {
62Ok(ty) => match *ty.kind() {
63 ty::Array(elem, _) => tcx.needs_drop_raw(typing_env.as_query_input(elem)),
64_ => true,
65 },
66Err(AlwaysRequiresDrop) => true,
67 }
68}
69fn filter_array_elements_async<'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_async_drop_raw(typing_env.as_query_input(elem)),
76_ => true,
77 },
78Err(AlwaysRequiresDrop) => true,
79 }
80}
8182fn has_significant_drop_raw<'tcx>(
83 tcx: TyCtxt<'tcx>,
84 query: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
85) -> bool {
86let res = drop_tys_helper(
87tcx,
88query.value,
89query.typing_env,
90adt_consider_insignificant_dtor(tcx),
91true,
92false,
93 )
94 .filter(filter_array_elements(tcx, query.typing_env))
95 .next()
96 .is_some();
97{
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:97",
"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(97u32),
::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);
98res99}
100101struct NeedsDropTypes<'tcx, F> {
102 tcx: TyCtxt<'tcx>,
103 typing_env: ty::TypingEnv<'tcx>,
104 query_ty: Ty<'tcx>,
105 seen_tys: FxHashSet<Ty<'tcx>>,
106/// A stack of types left to process, and the recursion depth when we
107 /// pushed that type. Each round, we pop something from the stack and check
108 /// if it needs drop. If the result depends on whether some other types
109 /// need drop we push them onto the stack.
110unchecked_tys: Vec<(Ty<'tcx>, usize)>,
111 recursion_limit: Limit,
112 adt_components: F,
113/// Set this to true if an exhaustive list of types involved in
114 /// drop obligation is requested.
115// FIXME: Calling this bool `exhaustive` is confusing and possibly a footgun,
116 // since it does two things: It makes the iterator yield *all* of the types
117 // that need drop, and it also affects the computation of the drop components
118 // on `Coroutine`s. The latter is somewhat confusing, and probably should be
119 // a function of `typing_env`. See the HACK comment below for why this is
120 // necessary. If this isn't possible, then we probably should turn this into
121 // a `NeedsDropMode` so that we can have a variant like `CollectAllSignificantDrops`,
122 // which will more accurately indicate that we want *all* of the *significant*
123 // drops, which are the two important behavioral changes toggled by this bool.
124exhaustive: bool,
125}
126127impl<'tcx, F> NeedsDropTypes<'tcx, F> {
128fn new(
129 tcx: TyCtxt<'tcx>,
130 typing_env: ty::TypingEnv<'tcx>,
131 ty: Ty<'tcx>,
132 exhaustive: bool,
133 adt_components: F,
134 ) -> Self {
135let mut seen_tys = FxHashSet::default();
136seen_tys.insert(ty);
137Self {
138tcx,
139typing_env,
140seen_tys,
141 query_ty: ty,
142 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)],
143 recursion_limit: tcx.recursion_limit(),
144adt_components,
145exhaustive,
146 }
147 }
148149/// Called when `ty` is found to always require drop.
150 /// If the exhaustive flag is true, then `Ok(ty)` is returned like any other type.
151 /// Otherwise, `Err(AlwaysRequireDrop)` is returned, which will cause iteration to abort.
152fn always_drop_component(&self, ty: Ty<'tcx>) -> NeedsDropResult<Ty<'tcx>> {
153if self.exhaustive { Ok(ty) } else { Err(AlwaysRequiresDrop) }
154 }
155}
156157impl<'tcx, F, I> Iteratorfor NeedsDropTypes<'tcx, F>
158where
159F: Fn(ty::AdtDef<'tcx>, GenericArgsRef<'tcx>) -> NeedsDropResult<I>,
160 I: Iterator<Item = Ty<'tcx>>,
161{
162type Item = NeedsDropResult<Ty<'tcx>>;
163164x;#[instrument(level = "debug", skip(self), ret)]165fn next(&mut self) -> Option<NeedsDropResult<Ty<'tcx>>> {
166let tcx = self.tcx;
167168while let Some((ty, level)) = self.unchecked_tys.pop() {
169debug!(?ty, "needs_drop_components: inspect");
170if !self.recursion_limit.value_within_limit(level) {
171// Not having a `Span` isn't great. But there's hopefully some other
172 // recursion limit error as well.
173debug!("needs_drop_components: recursion limit exceeded");
174 tcx.dcx().emit_err(NeedsDropOverflow { query_ty: self.query_ty });
175return Some(self.always_drop_component(ty));
176 }
177178let components = match needs_drop_components(tcx, ty) {
179Err(AlwaysRequiresDrop) => return Some(self.always_drop_component(ty)),
180Ok(components) => components,
181 };
182debug!("needs_drop_components({:?}) = {:?}", ty, components);
183184let queue_type = move |this: &mut Self, component: Ty<'tcx>| {
185if this.seen_tys.insert(component) {
186 this.unchecked_tys.push((component, level + 1));
187 }
188 };
189190for component in components {
191match *component.kind() {
192// The information required to determine whether a coroutine has drop is
193 // computed on MIR, while this very method is used to build MIR.
194 // To avoid cycles, we consider that coroutines always require drop.
195 //
196 // HACK: Because we erase regions contained in the coroutine witness, we
197 // have to conservatively assume that every region captured by the
198 // coroutine has to be live when dropped. This results in a lot of
199 // undesirable borrowck errors. During borrowck, we call `needs_drop`
200 // for the coroutine witness and check whether any of the contained types
201 // need to be dropped, and only require the captured types to be live
202 // if they do.
203ty::Coroutine(def_id, args) => {
204// FIXME: See FIXME on `exhaustive` field above.
205if self.exhaustive {
206for upvar in args.as_coroutine().upvar_tys() {
207 queue_type(self, upvar);
208 }
209 queue_type(self, args.as_coroutine().resume_ty());
210if let Some(witness) = tcx.mir_coroutine_witnesses(def_id) {
211for field_ty in &witness.field_tys {
212 queue_type(
213self,
214 EarlyBinder::bind(field_ty.ty)
215 .instantiate(tcx, args)
216 .skip_norm_wip(),
217 );
218 }
219 }
220 } else {
221return Some(self.always_drop_component(ty));
222 }
223 }
224 ty::CoroutineWitness(..) => {
225unreachable!("witness should be handled in parent");
226 }
227228 ty::UnsafeBinder(bound_ty) => {
229let ty = self.tcx.instantiate_bound_regions_with_erased(bound_ty.into());
230 queue_type(self, ty);
231 }
232233_ if tcx.type_is_copy_modulo_regions(self.typing_env, component) => {}
234235 ty::Closure(_, args) => {
236for upvar in args.as_closure().upvar_tys() {
237 queue_type(self, upvar);
238 }
239 }
240241 ty::CoroutineClosure(_, args) => {
242for upvar in args.as_coroutine_closure().upvar_tys() {
243 queue_type(self, upvar);
244 }
245 }
246247// Check for a `Drop` impl and whether this is a union or
248 // `ManuallyDrop`. If it's a struct or enum without a `Drop`
249 // impl then check whether the field types need `Drop`.
250ty::Adt(adt_def, args) => {
251let tys = match (self.adt_components)(adt_def, args) {
252Err(AlwaysRequiresDrop) => {
253return Some(self.always_drop_component(ty));
254 }
255Ok(tys) => tys,
256 };
257for required_ty in tys {
258let required = tcx
259 .try_normalize_erasing_regions(
260self.typing_env,
261 Unnormalized::new_wip(required_ty),
262 )
263 .unwrap_or(required_ty);
264265 queue_type(self, required);
266 }
267 }
268 ty::Alias(..) | ty::Array(..) | ty::Placeholder(_) | ty::Param(_) => {
269if ty == component {
270// Return the type to the caller: they may be able
271 // to normalize further than we can.
272return Some(Ok(component));
273 } else {
274// Store the type for later. We can't return here
275 // because we would then lose any other components
276 // of the type.
277queue_type(self, component);
278 }
279 }
280281 ty::Foreign(_) | ty::Dynamic(..) => {
282debug!("needs_drop_components: foreign or dynamic");
283return Some(self.always_drop_component(ty));
284 }
285286 ty::Bool
287 | ty::Char
288 | ty::Int(_)
289 | ty::Uint(_)
290 | ty::Float(_)
291 | ty::Str
292 | ty::Slice(_)
293 | ty::Ref(..)
294 | ty::RawPtr(..)
295 | ty::FnDef(..)
296 | ty::Pat(..)
297 | ty::FnPtr(..)
298 | ty::Tuple(_)
299 | ty::Bound(..)
300 | ty::Never
301 | ty::Infer(_)
302 | ty::Error(_) => {
303bug!("unexpected type returned by `needs_drop_components`: {component}")
304 }
305 }
306 }
307 }
308309None
310}
311}
312313enum DtorType {
314/// Type has a `Drop` but it is considered insignificant.
315 /// Check the query `adt_significant_drop_tys` for understanding
316 /// "significant" / "insignificant".
317Insignificant,
318319/// Type has a `Drop` implantation.
320Significant,
321}
322323// This is a helper function for `adt_drop_tys` and `adt_significant_drop_tys`.
324// Depending on the implantation of `adt_has_dtor`, it is used to check if the
325// ADT has a destructor or if the ADT only has a significant destructor. For
326// understanding significant destructor look at `adt_significant_drop_tys`.
327fn drop_tys_helper<'tcx>(
328 tcx: TyCtxt<'tcx>,
329 ty: Ty<'tcx>,
330 typing_env: ty::TypingEnv<'tcx>,
331 adt_has_dtor: impl Fn(ty::AdtDef<'tcx>) -> Option<DtorType>,
332 only_significant: bool,
333 exhaustive: bool,
334) -> impl Iterator<Item = NeedsDropResult<Ty<'tcx>>> {
335fn with_query_cache<'tcx>(
336 tcx: TyCtxt<'tcx>,
337 iter: impl IntoIterator<Item = Ty<'tcx>>,
338 ) -> NeedsDropResult<Vec<Ty<'tcx>>> {
339iter.into_iter().try_fold(Vec::new(), |mut vec, subty| {
340match subty.kind() {
341 ty::Adt(adt_id, args) => {
342for subty in tcx.adt_drop_tys(adt_id.did())? {
343 vec.push(EarlyBinder::bind(subty).instantiate(tcx, args).skip_norm_wip());
344 }
345 }
346_ => vec.push(subty),
347 };
348Ok(vec)
349 })
350 }
351352let adt_components = move |adt_def: ty::AdtDef<'tcx>, args: GenericArgsRef<'tcx>| {
353if adt_def.is_manually_drop() {
354{
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:354",
"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(354u32),
::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);
355Ok(Vec::new())
356 } else if let Some(dtor_info) = adt_has_dtor(adt_def) {
357match dtor_info {
358 DtorType::Significant => {
359{
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:359",
"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(359u32),
::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);
360Err(AlwaysRequiresDrop)
361 }
362 DtorType::Insignificant => {
363{
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:363",
"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(363u32),
::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);
364365// Since the destructor is insignificant, we just want to make sure all of
366 // the passed in type parameters are also insignificant.
367 // Eg: Vec<T> dtor is insignificant when T=i32 but significant when T=Mutex.
368Ok(args.types().collect())
369 }
370 }
371 } else if adt_def.is_union() {
372{
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:372",
"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(372u32),
::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);
373Ok(Vec::new())
374 } else {
375let field_tys = adt_def.all_fields().map(|field| {
376let r = tcx.type_of(field.did).instantiate(tcx, args).skip_norm_wip();
377{
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:377",
"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(377u32),
::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!(
378"drop_tys_helper: Instantiate into {:?} with {:?} getting {:?}",
379 field, args, r
380 );
381r382 });
383if only_significant {
384// We can't recurse through the query system here because we might induce a cycle
385Ok(field_tys.collect())
386 } else {
387// We can use the query system if we consider all drops significant. In that case,
388 // ADTs are `needs_drop` exactly if they `impl Drop` or if any of their "transitive"
389 // fields do. There can be no cycles here, because ADTs cannot contain themselves as
390 // fields.
391with_query_cache(tcx, field_tys)
392 }
393 }
394 .map(|v| v.into_iter())
395 };
396397NeedsDropTypes::new(tcx, typing_env, ty, exhaustive, adt_components)
398}
399400fn adt_consider_insignificant_dtor<'tcx>(
401 tcx: TyCtxt<'tcx>,
402) -> impl Fn(ty::AdtDef<'tcx>) -> Option<DtorType> {
403move |adt_def: ty::AdtDef<'tcx>| {
404if {
{
'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) {
405// In some cases like `std::collections::HashMap` where the struct is a wrapper around
406 // a type that is a Drop type, and the wrapped type (eg: `hashbrown::HashMap`) lies
407 // outside stdlib, we might choose to still annotate the wrapper (std HashMap) with
408 // `rustc_insignificant_dtor`, even if the type itself doesn't have a `Drop` impl.
409Some(DtorType::Insignificant)
410 } else if adt_def.destructor(tcx).is_some() {
411// There is a Drop impl and the type isn't marked insignificant, therefore Drop must be
412 // significant.
413Some(DtorType::Significant)
414 } else {
415// No destructor found nor the type is annotated with `rustc_insignificant_dtor`, we
416 // treat this as the simple case of Drop impl for type.
417None418 }
419 }
420}
421422fn adt_drop_tys<'tcx>(
423 tcx: TyCtxt<'tcx>,
424 def_id: DefId,
425) -> Result<&'tcx ty::List<Ty<'tcx>>, AlwaysRequiresDrop> {
426// This is for the "adt_drop_tys" query, that considers all `Drop` impls, therefore all dtors are
427 // significant.
428let adt_has_dtor =
429 |adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant);
430// `tcx.type_of(def_id)` identical to `tcx.make_adt(def, identity_args)`
431drop_tys_helper(
432tcx,
433tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
434 ty::TypingEnv::non_body_analysis(tcx, def_id),
435adt_has_dtor,
436false,
437false,
438 )
439 .collect::<Result<Vec<_>, _>>()
440 .map(|components| tcx.mk_type_list(&components))
441}
442443fn adt_async_drop_tys<'tcx>(
444 tcx: TyCtxt<'tcx>,
445 def_id: DefId,
446) -> Result<&'tcx ty::List<Ty<'tcx>>, AlwaysRequiresDrop> {
447// This is for the "adt_async_drop_tys" query, that considers all `AsyncDrop` impls.
448let adt_has_dtor =
449 |adt_def: ty::AdtDef<'tcx>| adt_def.async_destructor(tcx).map(|_| DtorType::Significant);
450// `tcx.type_of(def_id)` identical to `tcx.make_adt(def, identity_args)`
451drop_tys_helper(
452tcx,
453tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
454 ty::TypingEnv::non_body_analysis(tcx, def_id),
455adt_has_dtor,
456false,
457false,
458 )
459 .collect::<Result<Vec<_>, _>>()
460 .map(|components| tcx.mk_type_list(&components))
461}
462463// If `def_id` refers to a generic ADT, the queries above and below act as if they had been handed
464// a `tcx.make_ty(def, identity_args)` and as such it is legal to instantiate the generic parameters
465// of the ADT into the outputted `ty`s.
466fn adt_significant_drop_tys(
467 tcx: TyCtxt<'_>,
468 def_id: DefId,
469) -> Result<&ty::List<Ty<'_>>, AlwaysRequiresDrop> {
470drop_tys_helper(
471tcx,
472tcx.type_of(def_id).instantiate_identity().skip_norm_wip(), // identical to `tcx.make_adt(def, identity_args)`
473ty::TypingEnv::non_body_analysis(tcx, def_id),
474adt_consider_insignificant_dtor(tcx),
475true,
476false,
477 )
478 .collect::<Result<Vec<_>, _>>()
479 .map(|components| tcx.mk_type_list(&components))
480}
481482x;#[instrument(level = "debug", skip(tcx), ret)]483fn list_significant_drop_tys<'tcx>(
484 tcx: TyCtxt<'tcx>,
485 key: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
486) -> &'tcx ty::List<Ty<'tcx>> {
487 tcx.mk_type_list(
488&drop_tys_helper(
489 tcx,
490 key.value,
491 key.typing_env,
492 adt_consider_insignificant_dtor(tcx),
493true,
494true,
495 )
496 .filter_map(|res| res.ok())
497 .collect::<Vec<_>>(),
498 )
499}
500501pub(crate) fn provide(providers: &mut Providers) {
502*providers = Providers {
503needs_drop_raw,
504needs_async_drop_raw,
505has_significant_drop_raw,
506adt_drop_tys,
507adt_async_drop_tys,
508adt_significant_drop_tys,
509list_significant_drop_tys,
510 ..*providers511 };
512}