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::{self, EarlyBinder, ParamEnvAnd, Ty, TyCtxt, Unnormalized};
6use rustc_span::Span;
7use thin_vec::ThinVec;
8use tracing::{debug, instrument};
9
10use crate::solve::NextSolverError;
11use crate::traits::query::NoSolution;
12use crate::traits::query::normalize::QueryNormalizeExt;
13use crate::traits::{FromSolverError, Normalized, ObligationCause, ObligationCtxt, OldSolverError};
14
15/// This returns true if the type `ty` is "trivial" for
16/// dropck-outlives -- that is, if it doesn't require any types to
17/// outlive. This is similar but not *quite* the same as the
18/// `needs_drop` test in the compiler already -- that is, for every
19/// type T for which this function return true, needs-drop would
20/// return `false`. But the reverse does not hold: in particular,
21/// `needs_drop` returns false for `PhantomData`, but it is not
22/// trivial for dropck-outlives.
23///
24/// Note also that `needs_drop` requires a "global" type (i.e., one
25/// with erased regions), but this function does not.
26///
27// FIXME(@lcnr): remove this module and move this function somewhere else.
28pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
29    match ty.kind() {
30        // None of these types have a destructor and hence they do not
31        // require anything in particular to outlive the dtor's
32        // execution.
33        ty::Infer(ty::FreshIntTy(_))
34        | ty::Infer(ty::FreshFloatTy(_))
35        | ty::Bool
36        | ty::Int(_)
37        | ty::Uint(_)
38        | ty::Float(_)
39        | ty::Never
40        | ty::FnDef(..)
41        | ty::FnPtr(..)
42        | ty::Char
43        | ty::CoroutineWitness(..)
44        | ty::RawPtr(_, _)
45        | ty::Ref(..)
46        | ty::Str
47        | ty::Foreign(..)
48        | ty::Error(_) => true,
49
50        // `T is PAT` and `[T]` have same properties as T.
51        ty::Pat(ty, _) | ty::Slice(ty) => trivial_dropck_outlives(tcx, *ty),
52        ty::Array(ty, size) => {
53            // Empty array never has a dtor. See issue #110288.
54            match size.try_to_target_usize(tcx) {
55                Some(0) => true,
56                _ => trivial_dropck_outlives(tcx, *ty),
57            }
58        }
59
60        // (T1..Tn) and closures have same properties as T1..Tn --
61        // check if *all* of them are trivial.
62        ty::Tuple(tys) => tys.iter().all(|t| trivial_dropck_outlives(tcx, t)),
63
64        ty::Closure(_, args) => trivial_dropck_outlives(tcx, args.as_closure().tupled_upvars_ty()),
65        ty::CoroutineClosure(_, args) => {
66            trivial_dropck_outlives(tcx, args.as_coroutine_closure().tupled_upvars_ty())
67        }
68
69        ty::Adt(def, _) => {
70            if def.is_manually_drop() {
71                // `ManuallyDrop` never has a dtor.
72                true
73            } else {
74                // Other types might. Moreover, PhantomData doesn't
75                // have a dtor, but it is considered to own its
76                // content, so it is non-trivial. Unions can have `impl Drop`,
77                // and hence are non-trivial as well.
78                false
79            }
80        }
81
82        // The following *might* require a destructor: needs deeper inspection.
83        ty::Dynamic(..)
84        | ty::Alias(..)
85        | ty::Param(_)
86        | ty::Placeholder(..)
87        | ty::Infer(_)
88        | ty::Bound(..)
89        | ty::Coroutine(..)
90        | ty::UnsafeBinder(_) => false,
91
92        // FIXME(scrabsha)
93        ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
94    }
95}
96
97pub fn compute_dropck_outlives_inner<'tcx>(
98    ocx: &ObligationCtxt<'_, 'tcx>,
99    goal: ParamEnvAnd<'tcx, DropckOutlives<'tcx>>,
100    span: Span,
101) -> Result<DropckOutlivesResult<'tcx>, NoSolution> {
102    match compute_dropck_outlives_with_errors(ocx, goal, span) {
103        Ok(r) => Ok(r),
104        Err(_) => Err(NoSolution),
105    }
106}
107
108pub fn compute_dropck_outlives_with_errors<'tcx, E>(
109    ocx: &ObligationCtxt<'_, 'tcx, E>,
110    goal: ParamEnvAnd<'tcx, DropckOutlives<'tcx>>,
111    span: Span,
112) -> Result<DropckOutlivesResult<'tcx>, ThinVec<E>>
113where
114    E: FromSolverError<'tcx, NextSolverError<'tcx>> + FromSolverError<'tcx, OldSolverError<'tcx>>,
115{
116    let tcx = ocx.infcx.tcx;
117    let ParamEnvAnd { param_env, value: DropckOutlives { dropped_ty } } = goal;
118
119    let mut result = DropckOutlivesResult { kinds: ::alloc::vec::Vec::new()vec![], overflows: ::alloc::vec::Vec::new()vec![] };
120
121    // A stack of types left to process. Each round, we pop
122    // something from the stack and invoke
123    // `dtorck_constraint_for_ty_inner`. This may produce new types that
124    // have to be pushed on the stack. This continues until we have explored
125    // all the reachable types from the type `dropped_ty`.
126    //
127    // Example: Imagine that we have the following code:
128    //
129    // ```rust
130    // struct A {
131    //     value: B,
132    //     children: Vec<A>,
133    // }
134    //
135    // struct B {
136    //     value: u32
137    // }
138    //
139    // fn f() {
140    //   let a: A = ...;
141    //   ..
142    // } // here, `a` is dropped
143    // ```
144    //
145    // at the point where `a` is dropped, we need to figure out
146    // which types inside of `a` contain region data that may be
147    // accessed by any destructors in `a`. We begin by pushing `A`
148    // onto the stack, as that is the type of `a`. We will then
149    // invoke `dtorck_constraint_for_ty_inner` which will expand `A`
150    // into the types of its fields `(B, Vec<A>)`. These will get
151    // pushed onto the stack. Eventually, expanding `Vec<A>` will
152    // lead to us trying to push `A` a second time -- to prevent
153    // infinite recursion, we notice that `A` was already pushed
154    // once and stop.
155    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)];
156
157    // Set used to detect infinite recursion.
158    let mut ty_set = FxHashSet::default();
159
160    let cause = ObligationCause::dummy_with_span(span);
161    let mut constraints = DropckConstraint::empty();
162    while let Some((ty, depth)) = ty_stack.pop() {
163        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs:163",
                        "rustc_trait_selection::traits::query::dropck_outlives",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs"),
                        ::tracing_core::__macro_support::Option::Some(163u32),
                        ::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!(
164            "{} kinds, {} overflows, {} ty_stack",
165            result.kinds.len(),
166            result.overflows.len(),
167            ty_stack.len()
168        );
169        dtorck_constraint_for_ty_inner(
170            tcx,
171            ocx.infcx.typing_env(param_env),
172            span,
173            depth,
174            ty,
175            &mut constraints,
176        );
177
178        // "outlives" represent types/regions that may be touched
179        // by a destructor.
180        result.kinds.append(&mut constraints.outlives);
181        result.overflows.append(&mut constraints.overflows);
182
183        // If we have even one overflow, we should stop trying to evaluate further --
184        // chances are, the subsequent overflows for this evaluation won't provide useful
185        // information and will just decrease the speed at which we can emit these errors
186        // (since we'll be printing for just that much longer for the often enormous types
187        // that result here).
188        if !result.overflows.is_empty() {
189            break;
190        }
191
192        // dtorck types are "types that will get dropped but which
193        // do not themselves define a destructor", more or less. We have
194        // to push them onto the stack to be expanded.
195        for ty in constraints.dtorck_types.drain(..) {
196            let ty = if let Ok(Normalized { value: ty, obligations }) =
197                ocx.infcx.at(&cause, param_env).query_normalize(ty)
198            {
199                ocx.register_obligations(obligations);
200
201                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs:201",
                        "rustc_trait_selection::traits::query::dropck_outlives",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs"),
                        ::tracing_core::__macro_support::Option::Some(201u32),
                        ::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);
202                ty
203            } else {
204                // Flush errors b/c `deeply_normalize` doesn't expect pending
205                // obligations, and we may have pending obligations from the
206                // branch above (from other types).
207                let errors = ocx.evaluate_obligations_error_on_ambiguity();
208                if let TraitErrors::HasErrors(errors) = errors {
209                    return Err(errors);
210                }
211
212                // When query normalization fails, we don't get back an interesting
213                // reason that we could use to report an error in borrowck. In order to turn
214                // this into a reportable error, we deeply normalize again. We don't expect
215                // this to succeed, so delay a bug if it does.
216                match ocx.deeply_normalize(&cause, param_env, Unnormalized::new_wip(ty)) {
217                    Ok(_) => {
218                        tcx.dcx().span_delayed_bug(
219                            span,
220                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("query normalize succeeded of {0}, but deep normalize failed",
                ty))
    })format!(
221                                "query normalize succeeded of {ty}, \
222                                but deep normalize failed",
223                            ),
224                        );
225                        ty
226                    }
227                    Err(errors) => return Err(errors),
228                }
229            };
230
231            match ty.kind() {
232                // All parameters live for the duration of the
233                // function.
234                ty::Param(..) => {}
235
236                // A projection that we couldn't resolve - it
237                // might have a destructor.
238                ty::Alias(..) => {
239                    result.kinds.push(ty.into());
240                }
241
242                _ => {
243                    if ty_set.insert(ty) {
244                        ty_stack.push((ty, depth + 1));
245                    }
246                }
247            }
248        }
249    }
250
251    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs:251",
                        "rustc_trait_selection::traits::query::dropck_outlives",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs"),
                        ::tracing_core::__macro_support::Option::Some(251u32),
                        ::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);
252    Ok(result)
253}
254
255/// Returns a set of constraints that needs to be satisfied in
256/// order for `ty` to be valid for destruction.
257{}
#[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/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs"),
                                    ::tracing_core::__macro_support::Option::Some(257u32),
                                    ::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))
                            }));
                }
                ty::View(..) =>
                    ::core::panicking::unimplemented_default_msg(),
            }
        }
    }
}#[instrument(level = "debug", skip(tcx, typing_env, span, constraints))]
258pub fn dtorck_constraint_for_ty_inner<'tcx>(
259    tcx: TyCtxt<'tcx>,
260    typing_env: ty::TypingEnv<'tcx>,
261    span: Span,
262    depth: usize,
263    ty: Ty<'tcx>,
264    constraints: &mut DropckConstraint<'tcx>,
265) {
266    if !tcx.recursion_limit().value_within_limit(depth) {
267        constraints.overflows.push(ty);
268        return;
269    }
270
271    if trivial_dropck_outlives(tcx, ty) {
272        return;
273    }
274
275    match *ty.kind() {
276        ty::Bool
277        | ty::Char
278        | ty::Int(_)
279        | ty::Uint(_)
280        | ty::Float(_)
281        | ty::Str
282        | ty::Never
283        | ty::Foreign(..)
284        | ty::RawPtr(..)
285        | ty::Ref(..)
286        | ty::FnDef(..)
287        | ty::FnPtr(..)
288        | ty::CoroutineWitness(..) => {
289            // these types never have a destructor
290        }
291
292        ty::Pat(ety, _) | ty::Array(ety, _) | ty::Slice(ety) => {
293            // single-element containers, behave like their element
294            dtorck_constraint_for_ty_inner(tcx, typing_env, span, depth + 1, ety, constraints);
295        }
296
297        ty::Tuple(tys) => {
298            for ty in tys.iter() {
299                dtorck_constraint_for_ty_inner(tcx, typing_env, span, depth + 1, ty, constraints);
300            }
301        }
302
303        ty::Closure(_, args) => {
304            for ty in args.as_closure().upvar_tys() {
305                dtorck_constraint_for_ty_inner(tcx, typing_env, span, depth + 1, ty, constraints);
306            }
307        }
308
309        ty::CoroutineClosure(_, args) => {
310            for ty in args.as_coroutine_closure().upvar_tys() {
311                dtorck_constraint_for_ty_inner(tcx, typing_env, span, depth + 1, ty, constraints);
312            }
313        }
314
315        ty::Coroutine(def_id, args) => {
316            // rust-lang/rust#49918: Locals can be stored across await points in the coroutine,
317            // called interior/witness types. Since we do not compute these witnesses until after
318            // building MIR, we consider all coroutines to unconditionally require a drop during
319            // MIR building. However, considering the coroutine to unconditionally require a drop
320            // here may unnecessarily require its upvars' regions to be live when they don't need
321            // to be, leading to borrowck errors: <https://github.com/rust-lang/rust/issues/116242>.
322            //
323            // Here, we implement a more precise approximation for the coroutine's dtorck constraint
324            // by considering whether any of the interior types needs drop. Note that this is still
325            // an approximation because the coroutine interior has its regions erased, so we must add
326            // *all* of the upvars to live types set if we find that *any* interior type needs drop.
327            // This is because any of the regions captured in the upvars may be stored in the interior,
328            // which then has its regions replaced by a binder (conceptually erasing the regions),
329            // so there's no way to enforce that the precise region in the interior type is live
330            // since we've lost that information by this point.
331            //
332            // Note also that this check requires that the coroutine's upvars are use-live, since
333            // a region from a type that does not have a destructor that was captured in an upvar
334            // may flow into an interior type with a destructor. This is stronger than requiring
335            // the upvars are drop-live.
336            //
337            // For example, if we capture two upvar references `&'1 (), &'2 ()` and have some type
338            // in the interior, `for<'r> { NeedsDrop<'r> }`, we have no way to tell whether the
339            // region `'r` came from the `'1` or `'2` region, so we require both are live. This
340            // could even be unnecessary if `'r` was actually a `'static` region or some region
341            // local to the coroutine! That's why it's an approximation.
342            let args = args.as_coroutine();
343
344            // Note that we don't care about whether the resume type has any drops since this is
345            // redundant; there is no storage for the resume type, so if it is actually stored
346            // in the interior, we'll already detect the need for a drop by checking the interior.
347            //
348            // FIXME(@lcnr): Why do we erase regions in the env here? Seems odd
349            let typing_env = tcx.erase_and_anonymize_regions(typing_env);
350            let needs_drop = tcx.mir_coroutine_witnesses(def_id).is_some_and(|witness| {
351                witness.field_tys.iter().any(|field| field.ty.needs_drop(tcx, typing_env))
352            });
353            if needs_drop {
354                // Pushing types directly to `constraints.outlives` is equivalent
355                // to requiring them to be use-live, since if we were instead to
356                // recurse on them like we do below, we only end up collecting the
357                // types that are relevant for drop-liveness.
358                constraints.outlives.extend(args.upvar_tys().iter().map(ty::GenericArg::from));
359                constraints.outlives.push(args.resume_ty().into());
360            } else {
361                // Even if a witness type doesn't need a drop, we still require that
362                // the upvars are drop-live. This is only needed if we aren't already
363                // counting *all* of the upvars as use-live above, since use-liveness
364                // is a *stronger requirement* than drop-liveness. Recursing here
365                // unconditionally would just be collecting duplicated types for no
366                // reason.
367                for ty in args.upvar_tys() {
368                    dtorck_constraint_for_ty_inner(
369                        tcx,
370                        typing_env,
371                        span,
372                        depth + 1,
373                        ty,
374                        constraints,
375                    );
376                }
377            }
378        }
379
380        ty::Adt(def, args) => {
381            let DropckConstraint { dtorck_types, outlives, overflows } =
382                tcx.at(span).adt_dtorck_constraint(def.did());
383            // FIXME: we can try to recursively `dtorck_constraint_on_ty`
384            // there, but that needs some way to handle cycles.
385            constraints.dtorck_types.extend(
386                dtorck_types
387                    .iter()
388                    .map(|t| EarlyBinder::bind(tcx, *t).instantiate(tcx, args).skip_norm_wip()),
389            );
390            constraints.outlives.extend(
391                outlives
392                    .iter()
393                    .map(|t| EarlyBinder::bind(tcx, *t).instantiate(tcx, args).skip_norm_wip()),
394            );
395            constraints.overflows.extend(
396                overflows
397                    .iter()
398                    .map(|t| EarlyBinder::bind(tcx, *t).instantiate(tcx, args).skip_norm_wip()),
399            );
400        }
401
402        // Objects must be alive in order for their destructor
403        // to be called.
404        ty::Dynamic(..) => {
405            constraints.outlives.push(ty.into());
406        }
407
408        // Types that can't be resolved. Pass them forward.
409        ty::Alias(..) | ty::Param(..) => {
410            constraints.dtorck_types.push(ty);
411        }
412
413        // Can't instantiate binder here.
414        ty::UnsafeBinder(_) => {
415            constraints.dtorck_types.push(ty);
416        }
417
418        ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => {
419            // By the time this code runs, all type variables ought to
420            // be fully resolved.
421            tcx.dcx().span_delayed_bug(span, format!("Unresolved type in dropck: {:?}.", ty));
422        }
423
424        // FIXME(scrabsha)
425        ty::View(..) => unimplemented!(),
426    }
427}