Skip to main content

rustc_ty_utils/
needs_drop.rs

1//! Check whether a type has (potentially) non-trivial drop glue.
2
3use 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};
12
13use crate::diagnostics::NeedsDropOverflow;
14
15type NeedsDropResult<T> = Result<T, AlwaysRequiresDrop>;
16
17fn 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.
24    let adt_has_dtor =
25        |adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant);
26    let res = drop_tys_helper(
27        tcx,
28        query.value,
29        query.typing_env,
30        adt_has_dtor,
31        DropTysOptions::default(),
32    )
33    .filter(filter_array_elements(tcx, query.typing_env))
34    .next()
35    .is_some();
36
37    {
    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);
38    res
39}
40
41fn 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.
48    let adt_has_async_dtor =
49        |adt_def: ty::AdtDef<'tcx>| adt_def.async_destructor(tcx).map(|_| DtorType::Significant);
50    let res = drop_tys_helper(
51        tcx,
52        query.value,
53        query.typing_env,
54        adt_has_async_dtor,
55        DropTysOptions::default().recurse_into_box_for_async_drop(),
56    )
57    .filter(filter_array_elements_async(tcx, query.typing_env))
58    .next()
59    .is_some();
60
61    {
    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);
62    res
63}
64
65/// 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 {
73    move |ty| match ty {
74        Ok(ty) => match *ty.kind() {
75            ty::Array(elem, _) => tcx.needs_drop_raw(typing_env.as_query_input(elem)),
76            _ => true,
77        },
78        Err(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 {
85    move |ty| match ty {
86        Ok(ty) => match *ty.kind() {
87            ty::Array(elem, _) => tcx.needs_async_drop_raw(typing_env.as_query_input(elem)),
88            _ => true,
89        },
90        Err(AlwaysRequiresDrop) => true,
91    }
92}
93
94fn has_significant_drop_raw<'tcx>(
95    tcx: TyCtxt<'tcx>,
96    query: ty::PseudoCanonicalInput<'tcx, Ty<'tcx>>,
97) -> bool {
98    let res = drop_tys_helper(
99        tcx,
100        query.value,
101        query.typing_env,
102        adt_consider_insignificant_dtor(tcx),
103        DropTysOptions::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);
109    res
110}
111
112struct 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.
121    unchecked_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.
135    exhaustive: bool,
136}
137
138impl<'tcx, F> NeedsDropTypes<'tcx, F> {
139    fn new(
140        tcx: TyCtxt<'tcx>,
141        typing_env: ty::TypingEnv<'tcx>,
142        ty: Ty<'tcx>,
143        exhaustive: bool,
144        adt_components: F,
145    ) -> Self {
146        let mut seen_tys = FxHashSet::default();
147        seen_tys.insert(ty);
148        Self {
149            tcx,
150            typing_env,
151            seen_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(),
155            adt_components,
156            exhaustive,
157        }
158    }
159
160    /// 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.
163    fn always_drop_component(&self, ty: Ty<'tcx>) -> NeedsDropResult<Ty<'tcx>> {
164        if self.exhaustive { Ok(ty) } else { Err(AlwaysRequiresDrop) }
165    }
166}
167
168impl<'tcx, F, I> Iterator for NeedsDropTypes<'tcx, F>
169where
170    F: Fn(ty::AdtDef<'tcx>, GenericArgsRef<'tcx>) -> NeedsDropResult<I>,
171    I: Iterator<Item = Ty<'tcx>>,
172{
173    type Item = NeedsDropResult<Ty<'tcx>>;
174
175    x;#[instrument(level = "debug", skip(self), ret)]
176    fn next(&mut self) -> Option<NeedsDropResult<Ty<'tcx>>> {
177        let tcx = self.tcx;
178
179        while let Some((ty, level)) = self.unchecked_tys.pop() {
180            debug!(?ty, "needs_drop_components: inspect");
181            if !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.
184                debug!("needs_drop_components: recursion limit exceeded");
185                tcx.dcx().emit_err(NeedsDropOverflow { query_ty: self.query_ty });
186                return Some(self.always_drop_component(ty));
187            }
188
189            let components = match needs_drop_components(tcx, ty) {
190                Err(AlwaysRequiresDrop) => return Some(self.always_drop_component(ty)),
191                Ok(components) => components,
192            };
193            debug!("needs_drop_components({:?}) = {:?}", ty, components);
194
195            let queue_type = move |this: &mut Self, component: Ty<'tcx>| {
196                if this.seen_tys.insert(component) {
197                    this.unchecked_tys.push((component, level + 1));
198                }
199            };
200
201            for component in components {
202                match *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.
214                    ty::Coroutine(def_id, args) => {
215                        // FIXME: See FIXME on `exhaustive` field above.
216                        if self.exhaustive {
217                            for upvar in args.as_coroutine().upvar_tys() {
218                                queue_type(self, upvar);
219                            }
220                            queue_type(self, args.as_coroutine().resume_ty());
221                            if let Some(witness) = tcx.mir_coroutine_witnesses(def_id) {
222                                for field_ty in &witness.field_tys {
223                                    queue_type(
224                                        self,
225                                        EarlyBinder::bind(field_ty.ty)
226                                            .instantiate(tcx, args)
227                                            .skip_norm_wip(),
228                                    );
229                                }
230                            }
231                        } else {
232                            return Some(self.always_drop_component(ty));
233                        }
234                    }
235                    ty::CoroutineWitness(..) => {
236                        unreachable!("witness should be handled in parent");
237                    }
238
239                    ty::UnsafeBinder(bound_ty) => {
240                        let ty = self.tcx.instantiate_bound_regions_with_erased(bound_ty.into());
241                        queue_type(self, ty);
242                    }
243
244                    _ if tcx.type_is_copy_modulo_regions(self.typing_env, component) => {}
245
246                    ty::Closure(_, args) => {
247                        for upvar in args.as_closure().upvar_tys() {
248                            queue_type(self, upvar);
249                        }
250                    }
251
252                    ty::CoroutineClosure(_, args) => {
253                        for upvar in args.as_coroutine_closure().upvar_tys() {
254                            queue_type(self, upvar);
255                        }
256                    }
257
258                    // 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`.
261                    ty::Adt(adt_def, args) => {
262                        let tys = match (self.adt_components)(adt_def, args) {
263                            Err(AlwaysRequiresDrop) => {
264                                return Some(self.always_drop_component(ty));
265                            }
266                            Ok(tys) => tys,
267                        };
268                        for required_ty in tys {
269                            let required = tcx
270                                .try_normalize_erasing_regions(
271                                    self.typing_env,
272                                    Unnormalized::new_wip(required_ty),
273                                )
274                                .unwrap_or(required_ty);
275
276                            queue_type(self, required);
277                        }
278                    }
279                    ty::Alias(..) | ty::Array(..) | ty::Placeholder(_) | ty::Param(_) => {
280                        if ty == component {
281                            // Return the type to the caller: they may be able
282                            // to normalize further than we can.
283                            return 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.
288                            queue_type(self, component);
289                        }
290                    }
291
292                    ty::Foreign(_) | ty::Dynamic(..) => {
293                        debug!("needs_drop_components: foreign or dynamic");
294                        return Some(self.always_drop_component(ty));
295                    }
296
297                    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(_) => {
314                        bug!("unexpected type returned by `needs_drop_components`: {component}")
315                    }
316                }
317            }
318        }
319
320        None
321    }
322}
323
324enum DtorType {
325    /// Type has a `Drop` but it is considered insignificant.
326    /// Check the query `adt_significant_drop_tys` for understanding
327    /// "significant" / "insignificant".
328    Insignificant,
329
330    /// Type has a `Drop` implantation.
331    Significant,
332}
333
334#[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}
340
341impl DropTysOptions {
342    fn only_significant(mut self) -> Self {
343        self.only_significant = true;
344        self
345    }
346
347    fn exhaustive(mut self) -> Self {
348        self.exhaustive = true;
349        self
350    }
351
352    fn recurse_into_box_for_async_drop(mut self) -> Self {
353        self.async_drop_recurses_into_box = true;
354        self
355    }
356}
357
358// 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>>> {
369    fn with_query_cache<'tcx>(
370        tcx: TyCtxt<'tcx>,
371        iter: impl IntoIterator<Item = Ty<'tcx>>,
372    ) -> NeedsDropResult<Vec<Ty<'tcx>>> {
373        iter.into_iter().try_fold(Vec::new(), |mut vec, subty| {
374            match subty.kind() {
375                ty::Adt(adt_id, args) => {
376                    for 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            };
382            Ok(vec)
383        })
384    }
385
386    let adt_components = move |adt_def: ty::AdtDef<'tcx>, args: GenericArgsRef<'tcx>| {
387        if 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);
389            Ok(Vec::new())
390        } else if options.async_drop_recurses_into_box && adt_def.is_box() {
391            let box_components = match args.as_slice() {
392                [boxed_ty, allocator_ty] => {
393                    let boxed_ty = boxed_ty.expect_ty();
394                    let allocator_ty = allocator_ty.expect_ty();
395                    match 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            };
407            Ok(box_components)
408        } else if let Some(dtor_info) = adt_has_dtor(adt_def) {
409            match 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);
412                    Err(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);
416
417                    // 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.
420                    Ok(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);
425            Ok(Vec::new())
426        } else {
427            let field_tys = adt_def.all_fields().map(|field| {
428                let 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                );
433                r
434            });
435            if options.only_significant {
436                // We can't recurse through the query system here because we might induce a cycle
437                Ok(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.
443                with_query_cache(tcx, field_tys)
444            }
445        }
446        .map(|v| v.into_iter())
447    };
448
449    NeedsDropTypes::new(tcx, typing_env, ty, options.exhaustive, adt_components)
450}
451
452fn adt_consider_insignificant_dtor<'tcx>(
453    tcx: TyCtxt<'tcx>,
454) -> impl Fn(ty::AdtDef<'tcx>) -> Option<DtorType> {
455    move |adt_def: ty::AdtDef<'tcx>| {
456        if {
        {
            '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.
461            Some(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.
465            Some(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.
469            None
470        }
471    }
472}
473
474fn 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.
480    let 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)`
483    drop_tys_helper(
484        tcx,
485        tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
486        ty::TypingEnv::non_body_analysis(tcx, def_id),
487        adt_has_dtor,
488        DropTysOptions::default(),
489    )
490    .collect::<Result<Vec<_>, _>>()
491    .map(|components| tcx.mk_type_list(&components))
492}
493
494fn 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.
499    let 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)`
502    drop_tys_helper(
503        tcx,
504        tcx.type_of(def_id).instantiate_identity().skip_norm_wip(),
505        ty::TypingEnv::non_body_analysis(tcx, def_id),
506        adt_has_dtor,
507        DropTysOptions::default().recurse_into_box_for_async_drop(),
508    )
509    .collect::<Result<Vec<_>, _>>()
510    .map(|components| tcx.mk_type_list(&components))
511}
512
513// 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> {
520    drop_tys_helper(
521        tcx,
522        tcx.type_of(def_id).instantiate_identity().skip_norm_wip(), // identical to `tcx.make_adt(def, identity_args)`
523        ty::TypingEnv::non_body_analysis(tcx, def_id),
524        adt_consider_insignificant_dtor(tcx),
525        DropTysOptions::default().only_significant(),
526    )
527    .collect::<Result<Vec<_>, _>>()
528    .map(|components| tcx.mk_type_list(&components))
529}
530
531x;#[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}
548
549pub(crate) fn provide(providers: &mut Providers) {
550    *providers = Providers {
551        needs_drop_raw,
552        needs_async_drop_raw,
553        has_significant_drop_raw,
554        adt_drop_tys,
555        adt_async_drop_tys,
556        adt_significant_drop_tys,
557        list_significant_drop_tys,
558        ..*providers
559    };
560}