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