Skip to main content

rustc_trait_selection/traits/query/
dropck_outlives.rs

1use rustc_data_structures::fx::FxHashSet;
2use rustc_infer::traits::TraitErrors;
3use rustc_infer::traits::query::type_op::DropckOutlives;
4use rustc_middle::traits::query::{DropckConstraint, DropckOutlivesResult};
5use rustc_middle::ty::consts::ConstExt;
6use rustc_middle::ty::{self, EarlyBinder, ParamEnvAnd, Ty, TyCtxt, Unnormalized};
7use rustc_span::Span;
8use thin_vec::ThinVec;
9use tracing::{debug, instrument};
10
11use crate::solve::NextSolverError;
12use crate::traits::query::NoSolution;
13use crate::traits::query::normalize::QueryNormalizeExt;
14use crate::traits::{FromSolverError, Normalized, ObligationCause, ObligationCtxt, OldSolverError};
15
16/// This returns true if the type `ty` is "trivial" for
17/// dropck-outlives -- that is, if it doesn't require any types to
18/// outlive. This is similar but not *quite* the same as the
19/// `needs_drop` test in the compiler already -- that is, for every
20/// type T for which this function return true, needs-drop would
21/// return `false`. But the reverse does not hold: in particular,
22/// `needs_drop` returns false for `PhantomData`, but it is not
23/// trivial for dropck-outlives.
24///
25/// Note also that `needs_drop` requires a "global" type (i.e., one
26/// with erased regions), but this function does not.
27///
28// FIXME(@lcnr): remove this module and move this function somewhere else.
29pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
30    match ty.kind() {
31        // None of these types have a destructor and hence they do not
32        // require anything in particular to outlive the dtor's
33        // execution.
34        ty::Infer(ty::FreshIntTy(_))
35        | ty::Infer(ty::FreshFloatTy(_))
36        | ty::Bool
37        | ty::Int(_)
38        | ty::Uint(_)
39        | ty::Float(_)
40        | ty::Never
41        | ty::FnDef(..)
42        | ty::FnPtr(..)
43        | ty::Char
44        | ty::CoroutineWitness(..)
45        | ty::RawPtr(_, _)
46        | ty::Ref(..)
47        | ty::Str
48        | ty::Foreign(..)
49        | ty::Error(_) => true,
50
51        // `T is PAT` and `[T]` have same properties as T.
52        ty::Pat(ty, _) | ty::Slice(ty) => trivial_dropck_outlives(tcx, *ty),
53        ty::Array(ty, size) => {
54            // Empty array never has a dtor. See issue #110288.
55            match size.try_to_target_usize(tcx) {
56                Some(0) => true,
57                _ => trivial_dropck_outlives(tcx, *ty),
58            }
59        }
60
61        // (T1..Tn) and closures have same properties as T1..Tn --
62        // check if *all* of them are trivial.
63        ty::Tuple(tys) => tys.iter().all(|t| trivial_dropck_outlives(tcx, t)),
64
65        ty::Closure(_, args) => trivial_dropck_outlives(tcx, args.as_closure().tupled_upvars_ty()),
66        ty::CoroutineClosure(_, args) => {
67            trivial_dropck_outlives(tcx, args.as_coroutine_closure().tupled_upvars_ty())
68        }
69
70        ty::Adt(def, _) => {
71            if def.is_manually_drop() {
72                // `ManuallyDrop` never has a dtor.
73                true
74            } else {
75                // Other types might. Moreover, PhantomData doesn't
76                // have a dtor, but it is considered to own its
77                // content, so it is non-trivial. Unions can have `impl Drop`,
78                // and hence are non-trivial as well.
79                false
80            }
81        }
82
83        // The following *might* require a destructor: needs deeper inspection.
84        ty::Dynamic(..)
85        | ty::Alias(..)
86        | ty::Param(_)
87        | ty::Placeholder(..)
88        | ty::Infer(_)
89        | ty::Bound(..)
90        | ty::Coroutine(..)
91        | ty::UnsafeBinder(_) => false,
92    }
93}
94
95pub fn compute_dropck_outlives_inner<'tcx>(
96    ocx: &ObligationCtxt<'_, 'tcx>,
97    goal: ParamEnvAnd<'tcx, DropckOutlives<'tcx>>,
98    span: Span,
99) -> Result<DropckOutlivesResult<'tcx>, NoSolution> {
100    match compute_dropck_outlives_with_errors(ocx, goal, span) {
101        Ok(r) => Ok(r),
102        Err(_) => Err(NoSolution),
103    }
104}
105
106pub fn compute_dropck_outlives_with_errors<'tcx, E>(
107    ocx: &ObligationCtxt<'_, 'tcx, E>,
108    goal: ParamEnvAnd<'tcx, DropckOutlives<'tcx>>,
109    span: Span,
110) -> Result<DropckOutlivesResult<'tcx>, ThinVec<E>>
111where
112    E: FromSolverError<'tcx, NextSolverError<'tcx>> + FromSolverError<'tcx, OldSolverError<'tcx>>,
113{
114    let tcx = ocx.infcx.tcx;
115    let ParamEnvAnd { param_env, value: DropckOutlives { dropped_ty } } = goal;
116
117    let mut result = DropckOutlivesResult { kinds: ::alloc::vec::Vec::new()vec![], overflows: ::alloc::vec::Vec::new()vec![] };
118
119    // A stack of types left to process. Each round, we pop
120    // something from the stack and invoke
121    // `dtorck_constraint_for_ty_inner`. This may produce new types that
122    // have to be pushed on the stack. This continues until we have explored
123    // all the reachable types from the type `dropped_ty`.
124    //
125    // Example: Imagine that we have the following code:
126    //
127    // ```rust
128    // struct A {
129    //     value: B,
130    //     children: Vec<A>,
131    // }
132    //
133    // struct B {
134    //     value: u32
135    // }
136    //
137    // fn f() {
138    //   let a: A = ...;
139    //   ..
140    // } // here, `a` is dropped
141    // ```
142    //
143    // at the point where `a` is dropped, we need to figure out
144    // which types inside of `a` contain region data that may be
145    // accessed by any destructors in `a`. We begin by pushing `A`
146    // onto the stack, as that is the type of `a`. We will then
147    // invoke `dtorck_constraint_for_ty_inner` which will expand `A`
148    // into the types of its fields `(B, Vec<A>)`. These will get
149    // pushed onto the stack. Eventually, expanding `Vec<A>` will
150    // lead to us trying to push `A` a second time -- to prevent
151    // infinite recursion, we notice that `A` was already pushed
152    // once and stop.
153    let mut ty_stack = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(dropped_ty, 0)]))vec![(dropped_ty, 0)];
154
155    // Set used to detect infinite recursion.
156    let mut ty_set = FxHashSet::default();
157
158    let cause = ObligationCause::dummy_with_span(span);
159    let mut constraints = DropckConstraint::empty();
160    while let Some((ty, depth)) = ty_stack.pop() {
161        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs:161",
                        "rustc_trait_selection::traits::query::dropck_outlives",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs"),
                        ::tracing_core::__macro_support::Option::Some(161u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::dropck_outlives"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("{0} kinds, {1} overflows, {2} ty_stack",
                                                    result.kinds.len(), result.overflows.len(), ty_stack.len())
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
162            "{} kinds, {} overflows, {} ty_stack",
163            result.kinds.len(),
164            result.overflows.len(),
165            ty_stack.len()
166        );
167        dtorck_constraint_for_ty_inner(
168            tcx,
169            ocx.infcx.typing_env(param_env),
170            span,
171            depth,
172            ty,
173            &mut constraints,
174        );
175
176        // "outlives" represent types/regions that may be touched
177        // by a destructor.
178        result.kinds.append(&mut constraints.outlives);
179        result.overflows.append(&mut constraints.overflows);
180
181        // If we have even one overflow, we should stop trying to evaluate further --
182        // chances are, the subsequent overflows for this evaluation won't provide useful
183        // information and will just decrease the speed at which we can emit these errors
184        // (since we'll be printing for just that much longer for the often enormous types
185        // that result here).
186        if !result.overflows.is_empty() {
187            break;
188        }
189
190        // dtorck types are "types that will get dropped but which
191        // do not themselves define a destructor", more or less. We have
192        // to push them onto the stack to be expanded.
193        for ty in constraints.dtorck_types.drain(..) {
194            let ty = if let Ok(Normalized { value: ty, obligations }) =
195                ocx.infcx.at(&cause, param_env).query_normalize(ty)
196            {
197                ocx.register_obligations(obligations);
198
199                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs:199",
                        "rustc_trait_selection::traits::query::dropck_outlives",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs"),
                        ::tracing_core::__macro_support::Option::Some(199u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::dropck_outlives"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("dropck_outlives: ty from dtorck_types = {0:?}",
                                                    ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("dropck_outlives: ty from dtorck_types = {:?}", ty);
200                ty
201            } else {
202                // Flush errors b/c `deeply_normalize` doesn't expect pending
203                // obligations, and we may have pending obligations from the
204                // branch above (from other types).
205                let errors = ocx.evaluate_obligations_error_on_ambiguity();
206                if let TraitErrors::HasErrors(errors) = errors {
207                    return Err(errors);
208                }
209
210                // When query normalization fails, we don't get back an interesting
211                // reason that we could use to report an error in borrowck. In order to turn
212                // this into a reportable error, we deeply normalize again. We don't expect
213                // this to succeed, so delay a bug if it does.
214                match ocx.deeply_normalize(&cause, param_env, Unnormalized::new_wip(ty)) {
215                    Ok(_) => {
216                        tcx.dcx().span_delayed_bug(
217                            span,
218                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("query normalize succeeded of {0}, but deep normalize failed",
                ty))
    })format!(
219                                "query normalize succeeded of {ty}, \
220                                but deep normalize failed",
221                            ),
222                        );
223                        ty
224                    }
225                    Err(errors) => return Err(errors),
226                }
227            };
228
229            match ty.kind() {
230                // All parameters live for the duration of the
231                // function.
232                ty::Param(..) => {}
233
234                // A projection that we couldn't resolve - it
235                // might have a destructor.
236                ty::Alias(..) => {
237                    result.kinds.push(ty.into());
238                }
239
240                _ => {
241                    if ty_set.insert(ty) {
242                        ty_stack.push((ty, depth + 1));
243                    }
244                }
245            }
246        }
247    }
248
249    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs:249",
                        "rustc_trait_selection::traits::query::dropck_outlives",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs"),
                        ::tracing_core::__macro_support::Option::Some(249u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::dropck_outlives"),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("dropck_outlives: result = {0:#?}",
                                                    result) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("dropck_outlives: result = {:#?}", result);
250    Ok(result)
251}
252
253/// Returns a set of constraints that needs to be satisfied in
254/// order for `ty` to be valid for destruction.
255{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("dtorck_constraint_for_ty_inner",
                                    "rustc_trait_selection::traits::query::dropck_outlives",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs"),
                                    ::tracing_core::__macro_support::Option::Some(255u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::query::dropck_outlives"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("depth")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("depth");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&depth
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !tcx.recursion_limit().value_within_limit(depth) {
                constraints.overflows.push(ty);
                return;
            }
            if trivial_dropck_outlives(tcx, ty) { return; }
            match *ty.kind() {
                ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_)
                    | ty::Str | ty::Never | ty::Foreign(..) | ty::RawPtr(..) |
                    ty::Ref(..) | ty::FnDef(..) | ty::FnPtr(..) |
                    ty::CoroutineWitness(..) => {}
                ty::Pat(ety, _) | ty::Array(ety, _) | ty::Slice(ety) => {
                    dtorck_constraint_for_ty_inner(tcx, typing_env, span,
                        depth + 1, ety, constraints);
                }
                ty::Tuple(tys) => {
                    for ty in tys.iter() {
                        dtorck_constraint_for_ty_inner(tcx, typing_env, span,
                            depth + 1, ty, constraints);
                    }
                }
                ty::Closure(_, args) => {
                    for ty in args.as_closure().upvar_tys() {
                        dtorck_constraint_for_ty_inner(tcx, typing_env, span,
                            depth + 1, ty, constraints);
                    }
                }
                ty::CoroutineClosure(_, args) => {
                    for ty in args.as_coroutine_closure().upvar_tys() {
                        dtorck_constraint_for_ty_inner(tcx, typing_env, span,
                            depth + 1, ty, constraints);
                    }
                }
                ty::Coroutine(def_id, args) => {
                    let args = args.as_coroutine();
                    let typing_env =
                        tcx.erase_and_anonymize_regions(typing_env);
                    let needs_drop =
                        tcx.mir_coroutine_witnesses(def_id).is_some_and(|witness|
                                {
                                    witness.field_tys.iter().any(|field|
                                            field.ty.needs_drop(tcx, typing_env))
                                });
                    if needs_drop {
                        constraints.outlives.extend(args.upvar_tys().iter().map(ty::GenericArg::from));
                        constraints.outlives.push(args.resume_ty().into());
                    } else {
                        for ty in args.upvar_tys() {
                            dtorck_constraint_for_ty_inner(tcx, typing_env, span,
                                depth + 1, ty, constraints);
                        }
                    }
                }
                ty::Adt(def, args) => {
                    let DropckConstraint { dtorck_types, outlives, overflows } =
                        tcx.at(span).adt_dtorck_constraint(def.did());
                    constraints.dtorck_types.extend(dtorck_types.iter().map(|t|
                                EarlyBinder::bind(tcx,
                                            *t).instantiate(tcx, args).skip_norm_wip()));
                    constraints.outlives.extend(outlives.iter().map(|t|
                                EarlyBinder::bind(tcx,
                                            *t).instantiate(tcx, args).skip_norm_wip()));
                    constraints.overflows.extend(overflows.iter().map(|t|
                                EarlyBinder::bind(tcx,
                                            *t).instantiate(tcx, args).skip_norm_wip()));
                }
                ty::Dynamic(..) => { constraints.outlives.push(ty.into()); }
                ty::Alias(..) | ty::Param(..) => {
                    constraints.dtorck_types.push(ty);
                }
                ty::UnsafeBinder(_) => { constraints.dtorck_types.push(ty); }
                ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) |
                    ty::Error(_) => {
                    tcx.dcx().span_delayed_bug(span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("Unresolved type in dropck: {0:?}.",
                                        ty))
                            }));
                }
            }
        }
    }
}#[instrument(level = "debug", skip(tcx, typing_env, span, constraints))]
256pub fn dtorck_constraint_for_ty_inner<'tcx>(
257    tcx: TyCtxt<'tcx>,
258    typing_env: ty::TypingEnv<'tcx>,
259    span: Span,
260    depth: usize,
261    ty: Ty<'tcx>,
262    constraints: &mut DropckConstraint<'tcx>,
263) {
264    if !tcx.recursion_limit().value_within_limit(depth) {
265        constraints.overflows.push(ty);
266        return;
267    }
268
269    if trivial_dropck_outlives(tcx, ty) {
270        return;
271    }
272
273    match *ty.kind() {
274        ty::Bool
275        | ty::Char
276        | ty::Int(_)
277        | ty::Uint(_)
278        | ty::Float(_)
279        | ty::Str
280        | ty::Never
281        | ty::Foreign(..)
282        | ty::RawPtr(..)
283        | ty::Ref(..)
284        | ty::FnDef(..)
285        | ty::FnPtr(..)
286        | ty::CoroutineWitness(..) => {
287            // these types never have a destructor
288        }
289
290        ty::Pat(ety, _) | ty::Array(ety, _) | ty::Slice(ety) => {
291            // single-element containers, behave like their element
292            dtorck_constraint_for_ty_inner(tcx, typing_env, span, depth + 1, ety, constraints);
293        }
294
295        ty::Tuple(tys) => {
296            for ty in tys.iter() {
297                dtorck_constraint_for_ty_inner(tcx, typing_env, span, depth + 1, ty, constraints);
298            }
299        }
300
301        ty::Closure(_, args) => {
302            for ty in args.as_closure().upvar_tys() {
303                dtorck_constraint_for_ty_inner(tcx, typing_env, span, depth + 1, ty, constraints);
304            }
305        }
306
307        ty::CoroutineClosure(_, args) => {
308            for ty in args.as_coroutine_closure().upvar_tys() {
309                dtorck_constraint_for_ty_inner(tcx, typing_env, span, depth + 1, ty, constraints);
310            }
311        }
312
313        ty::Coroutine(def_id, args) => {
314            // rust-lang/rust#49918: Locals can be stored across await points in the coroutine,
315            // called interior/witness types. Since we do not compute these witnesses until after
316            // building MIR, we consider all coroutines to unconditionally require a drop during
317            // MIR building. However, considering the coroutine to unconditionally require a drop
318            // here may unnecessarily require its upvars' regions to be live when they don't need
319            // to be, leading to borrowck errors: <https://github.com/rust-lang/rust/issues/116242>.
320            //
321            // Here, we implement a more precise approximation for the coroutine's dtorck constraint
322            // by considering whether any of the interior types needs drop. Note that this is still
323            // an approximation because the coroutine interior has its regions erased, so we must add
324            // *all* of the upvars to live types set if we find that *any* interior type needs drop.
325            // This is because any of the regions captured in the upvars may be stored in the interior,
326            // which then has its regions replaced by a binder (conceptually erasing the regions),
327            // so there's no way to enforce that the precise region in the interior type is live
328            // since we've lost that information by this point.
329            //
330            // Note also that this check requires that the coroutine's upvars are use-live, since
331            // a region from a type that does not have a destructor that was captured in an upvar
332            // may flow into an interior type with a destructor. This is stronger than requiring
333            // the upvars are drop-live.
334            //
335            // For example, if we capture two upvar references `&'1 (), &'2 ()` and have some type
336            // in the interior, `for<'r> { NeedsDrop<'r> }`, we have no way to tell whether the
337            // region `'r` came from the `'1` or `'2` region, so we require both are live. This
338            // could even be unnecessary if `'r` was actually a `'static` region or some region
339            // local to the coroutine! That's why it's an approximation.
340            let args = args.as_coroutine();
341
342            // Note that we don't care about whether the resume type has any drops since this is
343            // redundant; there is no storage for the resume type, so if it is actually stored
344            // in the interior, we'll already detect the need for a drop by checking the interior.
345            //
346            // FIXME(@lcnr): Why do we erase regions in the env here? Seems odd
347            let typing_env = tcx.erase_and_anonymize_regions(typing_env);
348            let needs_drop = tcx.mir_coroutine_witnesses(def_id).is_some_and(|witness| {
349                witness.field_tys.iter().any(|field| field.ty.needs_drop(tcx, typing_env))
350            });
351            if needs_drop {
352                // Pushing types directly to `constraints.outlives` is equivalent
353                // to requiring them to be use-live, since if we were instead to
354                // recurse on them like we do below, we only end up collecting the
355                // types that are relevant for drop-liveness.
356                constraints.outlives.extend(args.upvar_tys().iter().map(ty::GenericArg::from));
357                constraints.outlives.push(args.resume_ty().into());
358            } else {
359                // Even if a witness type doesn't need a drop, we still require that
360                // the upvars are drop-live. This is only needed if we aren't already
361                // counting *all* of the upvars as use-live above, since use-liveness
362                // is a *stronger requirement* than drop-liveness. Recursing here
363                // unconditionally would just be collecting duplicated types for no
364                // reason.
365                for ty in args.upvar_tys() {
366                    dtorck_constraint_for_ty_inner(
367                        tcx,
368                        typing_env,
369                        span,
370                        depth + 1,
371                        ty,
372                        constraints,
373                    );
374                }
375            }
376        }
377
378        ty::Adt(def, args) => {
379            let DropckConstraint { dtorck_types, outlives, overflows } =
380                tcx.at(span).adt_dtorck_constraint(def.did());
381            // FIXME: we can try to recursively `dtorck_constraint_on_ty`
382            // there, but that needs some way to handle cycles.
383            constraints.dtorck_types.extend(
384                dtorck_types
385                    .iter()
386                    .map(|t| EarlyBinder::bind(tcx, *t).instantiate(tcx, args).skip_norm_wip()),
387            );
388            constraints.outlives.extend(
389                outlives
390                    .iter()
391                    .map(|t| EarlyBinder::bind(tcx, *t).instantiate(tcx, args).skip_norm_wip()),
392            );
393            constraints.overflows.extend(
394                overflows
395                    .iter()
396                    .map(|t| EarlyBinder::bind(tcx, *t).instantiate(tcx, args).skip_norm_wip()),
397            );
398        }
399
400        // Objects must be alive in order for their destructor
401        // to be called.
402        ty::Dynamic(..) => {
403            constraints.outlives.push(ty.into());
404        }
405
406        // Types that can't be resolved. Pass them forward.
407        ty::Alias(..) | ty::Param(..) => {
408            constraints.dtorck_types.push(ty);
409        }
410
411        // Can't instantiate binder here.
412        ty::UnsafeBinder(_) => {
413            constraints.dtorck_types.push(ty);
414        }
415
416        ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => {
417            // By the time this code runs, all type variables ought to
418            // be fully resolved.
419            tcx.dcx().span_delayed_bug(span, format!("Unresolved type in dropck: {:?}.", ty));
420        }
421    }
422}