]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/select/confirmation.rs
Auto merge of #104610 - ouz-a:revert-overflow, r=compiler-errors
[rust.git] / compiler / rustc_trait_selection / src / traits / select / confirmation.rs
1 //! Confirmation.
2 //!
3 //! Confirmation unifies the output type parameters of the trait
4 //! with the values found in the obligation, possibly yielding a
5 //! type error.  See the [rustc dev guide] for more details.
6 //!
7 //! [rustc dev guide]:
8 //! https://rustc-dev-guide.rust-lang.org/traits/resolution.html#confirmation
9 use rustc_data_structures::stack::ensure_sufficient_stack;
10 use rustc_hir::lang_items::LangItem;
11 use rustc_index::bit_set::GrowableBitSet;
12 use rustc_infer::infer::InferOk;
13 use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType;
14 use rustc_middle::ty::{
15     self, GenericArg, GenericArgKind, GenericParamDefKind, InternalSubsts, SubstsRef,
16     ToPolyTraitRef, ToPredicate, Ty, TyCtxt,
17 };
18 use rustc_span::def_id::DefId;
19
20 use crate::traits::project::{normalize_with_depth, normalize_with_depth_to};
21 use crate::traits::util::{self, closure_trait_ref_and_return_type, predicate_for_trait_def};
22 use crate::traits::{
23     BuiltinDerivedObligation, ImplDerivedObligation, ImplDerivedObligationCause, ImplSource,
24     ImplSourceAutoImplData, ImplSourceBuiltinData, ImplSourceClosureData,
25     ImplSourceConstDestructData, ImplSourceDiscriminantKindData, ImplSourceFnPointerData,
26     ImplSourceGeneratorData, ImplSourceObjectData, ImplSourcePointeeData, ImplSourceTraitAliasData,
27     ImplSourceTraitUpcastingData, ImplSourceUserDefinedData, Normalized, ObjectCastObligation,
28     Obligation, ObligationCause, OutputTypeParameterMismatch, PredicateObligation, Selection,
29     SelectionError, TraitNotObjectSafe, TraitObligation, Unimplemented, VtblSegment,
30 };
31
32 use super::BuiltinImplConditions;
33 use super::SelectionCandidate::{self, *};
34 use super::SelectionContext;
35
36 use std::iter;
37 use std::ops::ControlFlow;
38
39 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
40     #[instrument(level = "debug", skip(self))]
41     pub(super) fn confirm_candidate(
42         &mut self,
43         obligation: &TraitObligation<'tcx>,
44         candidate: SelectionCandidate<'tcx>,
45     ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
46         let mut impl_src = match candidate {
47             BuiltinCandidate { has_nested } => {
48                 let data = self.confirm_builtin_candidate(obligation, has_nested);
49                 ImplSource::Builtin(data)
50             }
51
52             TransmutabilityCandidate => {
53                 let data = self.confirm_transmutability_candidate(obligation)?;
54                 ImplSource::Builtin(data)
55             }
56
57             ParamCandidate(param) => {
58                 let obligations =
59                     self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref));
60                 ImplSource::Param(obligations, param.skip_binder().constness)
61             }
62
63             ImplCandidate(impl_def_id) => {
64                 ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id))
65             }
66
67             AutoImplCandidate => {
68                 let data = self.confirm_auto_impl_candidate(obligation);
69                 ImplSource::AutoImpl(data)
70             }
71
72             ProjectionCandidate(idx, constness) => {
73                 let obligations = self.confirm_projection_candidate(obligation, idx)?;
74                 ImplSource::Param(obligations, constness)
75             }
76
77             ObjectCandidate(idx) => {
78                 let data = self.confirm_object_candidate(obligation, idx)?;
79                 ImplSource::Object(data)
80             }
81
82             ClosureCandidate => {
83                 let vtable_closure = self.confirm_closure_candidate(obligation)?;
84                 ImplSource::Closure(vtable_closure)
85             }
86
87             GeneratorCandidate => {
88                 let vtable_generator = self.confirm_generator_candidate(obligation)?;
89                 ImplSource::Generator(vtable_generator)
90             }
91
92             FnPointerCandidate { .. } => {
93                 let data = self.confirm_fn_pointer_candidate(obligation)?;
94                 ImplSource::FnPointer(data)
95             }
96
97             DiscriminantKindCandidate => {
98                 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
99             }
100
101             PointeeCandidate => ImplSource::Pointee(ImplSourcePointeeData),
102
103             TraitAliasCandidate => {
104                 let data = self.confirm_trait_alias_candidate(obligation);
105                 ImplSource::TraitAlias(data)
106             }
107
108             BuiltinObjectCandidate => {
109                 // This indicates something like `Trait + Send: Send`. In this case, we know that
110                 // this holds because that's what the object type is telling us, and there's really
111                 // no additional obligations to prove and no types in particular to unify, etc.
112                 ImplSource::Param(Vec::new(), ty::BoundConstness::NotConst)
113             }
114
115             BuiltinUnsizeCandidate => {
116                 let data = self.confirm_builtin_unsize_candidate(obligation)?;
117                 ImplSource::Builtin(data)
118             }
119
120             TraitUpcastingUnsizeCandidate(idx) => {
121                 let data = self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?;
122                 ImplSource::TraitUpcasting(data)
123             }
124
125             ConstDestructCandidate(def_id) => {
126                 let data = self.confirm_const_destruct_candidate(obligation, def_id)?;
127                 ImplSource::ConstDestruct(data)
128             }
129         };
130
131         if !obligation.predicate.is_const_if_const() {
132             // normalize nested predicates according to parent predicate's constness.
133             impl_src = impl_src.map(|mut o| {
134                 o.predicate = o.predicate.without_const(self.tcx());
135                 o
136             });
137         }
138
139         Ok(impl_src)
140     }
141
142     fn confirm_projection_candidate(
143         &mut self,
144         obligation: &TraitObligation<'tcx>,
145         idx: usize,
146     ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
147         let tcx = self.tcx();
148
149         let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
150         let placeholder_trait_predicate =
151             self.infcx().replace_bound_vars_with_placeholders(trait_predicate).trait_ref;
152         let placeholder_self_ty = placeholder_trait_predicate.self_ty();
153         let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate);
154         let (def_id, substs) = match *placeholder_self_ty.kind() {
155             ty::Projection(proj) => (proj.item_def_id, proj.substs),
156             ty::Opaque(def_id, substs) => (def_id, substs),
157             _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
158         };
159
160         let candidate_predicate =
161             tcx.bound_item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs);
162         let candidate = candidate_predicate
163             .to_opt_poly_trait_pred()
164             .expect("projection candidate is not a trait predicate")
165             .map_bound(|t| t.trait_ref);
166         let mut obligations = Vec::new();
167         let candidate = normalize_with_depth_to(
168             self,
169             obligation.param_env,
170             obligation.cause.clone(),
171             obligation.recursion_depth + 1,
172             candidate,
173             &mut obligations,
174         );
175
176         obligations.extend(self.infcx.commit_if_ok(|_| {
177             self.infcx
178                 .at(&obligation.cause, obligation.param_env)
179                 .sup(placeholder_trait_predicate, candidate)
180                 .map(|InferOk { obligations, .. }| obligations)
181                 .map_err(|_| Unimplemented)
182         })?);
183
184         if let ty::Projection(..) = placeholder_self_ty.kind() {
185             let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates;
186             debug!(?predicates, "projection predicates");
187             for predicate in predicates {
188                 let normalized = normalize_with_depth_to(
189                     self,
190                     obligation.param_env,
191                     obligation.cause.clone(),
192                     obligation.recursion_depth + 1,
193                     predicate,
194                     &mut obligations,
195                 );
196                 obligations.push(Obligation::with_depth(
197                     self.tcx(),
198                     obligation.cause.clone(),
199                     obligation.recursion_depth + 1,
200                     obligation.param_env,
201                     normalized,
202                 ));
203             }
204         }
205
206         Ok(obligations)
207     }
208
209     fn confirm_param_candidate(
210         &mut self,
211         obligation: &TraitObligation<'tcx>,
212         param: ty::PolyTraitRef<'tcx>,
213     ) -> Vec<PredicateObligation<'tcx>> {
214         debug!(?obligation, ?param, "confirm_param_candidate");
215
216         // During evaluation, we already checked that this
217         // where-clause trait-ref could be unified with the obligation
218         // trait-ref. Repeat that unification now without any
219         // transactional boundary; it should not fail.
220         match self.match_where_clause_trait_ref(obligation, param) {
221             Ok(obligations) => obligations,
222             Err(()) => {
223                 bug!(
224                     "Where clause `{:?}` was applicable to `{:?}` but now is not",
225                     param,
226                     obligation
227                 );
228             }
229         }
230     }
231
232     fn confirm_builtin_candidate(
233         &mut self,
234         obligation: &TraitObligation<'tcx>,
235         has_nested: bool,
236     ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
237         debug!(?obligation, ?has_nested, "confirm_builtin_candidate");
238
239         let lang_items = self.tcx().lang_items();
240         let obligations = if has_nested {
241             let trait_def = obligation.predicate.def_id();
242             let conditions = if Some(trait_def) == lang_items.sized_trait() {
243                 self.sized_conditions(obligation)
244             } else if Some(trait_def) == lang_items.copy_trait() {
245                 self.copy_clone_conditions(obligation)
246             } else if Some(trait_def) == lang_items.clone_trait() {
247                 self.copy_clone_conditions(obligation)
248             } else {
249                 bug!("unexpected builtin trait {:?}", trait_def)
250             };
251             let BuiltinImplConditions::Where(nested) = conditions else {
252                 bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
253             };
254
255             let cause = obligation.derived_cause(BuiltinDerivedObligation);
256             ensure_sufficient_stack(|| {
257                 self.collect_predicates_for_types(
258                     obligation.param_env,
259                     cause,
260                     obligation.recursion_depth + 1,
261                     trait_def,
262                     nested,
263                 )
264             })
265         } else {
266             vec![]
267         };
268
269         debug!(?obligations);
270
271         ImplSourceBuiltinData { nested: obligations }
272     }
273
274     fn confirm_transmutability_candidate(
275         &mut self,
276         obligation: &TraitObligation<'tcx>,
277     ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
278         debug!(?obligation, "confirm_transmutability_candidate");
279
280         let predicate = obligation.predicate;
281
282         let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i));
283         let const_at = |i| predicate.skip_binder().trait_ref.substs.const_at(i);
284
285         let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types {
286             dst: p.trait_ref.substs.type_at(0),
287             src: p.trait_ref.substs.type_at(1),
288         });
289
290         let scope = type_at(2).skip_binder();
291
292         let Some(assume) =
293             rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, const_at(3)) else {
294                 return Err(Unimplemented);
295             };
296
297         let cause = obligation.cause.clone();
298
299         let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
300
301         let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume);
302
303         use rustc_transmute::Answer;
304
305         match maybe_transmutable {
306             Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }),
307             _ => Err(Unimplemented),
308         }
309     }
310
311     /// This handles the case where an `auto trait Foo` impl is being used.
312     /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
313     ///
314     /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
315     /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
316     fn confirm_auto_impl_candidate(
317         &mut self,
318         obligation: &TraitObligation<'tcx>,
319     ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
320         debug!(?obligation, "confirm_auto_impl_candidate");
321
322         let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
323         let types = self.constituent_types_for_ty(self_ty);
324         self.vtable_auto_impl(obligation, obligation.predicate.def_id(), types)
325     }
326
327     /// See `confirm_auto_impl_candidate`.
328     fn vtable_auto_impl(
329         &mut self,
330         obligation: &TraitObligation<'tcx>,
331         trait_def_id: DefId,
332         nested: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
333     ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
334         debug!(?nested, "vtable_auto_impl");
335         ensure_sufficient_stack(|| {
336             let cause = obligation.derived_cause(BuiltinDerivedObligation);
337
338             let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
339             let trait_ref = self.infcx.replace_bound_vars_with_placeholders(poly_trait_ref);
340             let trait_obligations: Vec<PredicateObligation<'_>> = self.impl_or_trait_obligations(
341                 &cause,
342                 obligation.recursion_depth + 1,
343                 obligation.param_env,
344                 trait_def_id,
345                 &trait_ref.substs,
346                 obligation.predicate,
347             );
348
349             let mut obligations = self.collect_predicates_for_types(
350                 obligation.param_env,
351                 cause,
352                 obligation.recursion_depth + 1,
353                 trait_def_id,
354                 nested,
355             );
356
357             // Adds the predicates from the trait.  Note that this contains a `Self: Trait`
358             // predicate as usual.  It won't have any effect since auto traits are coinductive.
359             obligations.extend(trait_obligations);
360
361             debug!(?obligations, "vtable_auto_impl");
362
363             ImplSourceAutoImplData { trait_def_id, nested: obligations }
364         })
365     }
366
367     fn confirm_impl_candidate(
368         &mut self,
369         obligation: &TraitObligation<'tcx>,
370         impl_def_id: DefId,
371     ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
372         debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");
373
374         // First, create the substitutions by matching the impl again,
375         // this time not in a probe.
376         let substs = self.rematch_impl(impl_def_id, obligation);
377         debug!(?substs, "impl substs");
378         ensure_sufficient_stack(|| {
379             self.vtable_impl(
380                 impl_def_id,
381                 substs,
382                 &obligation.cause,
383                 obligation.recursion_depth + 1,
384                 obligation.param_env,
385                 obligation.predicate,
386             )
387         })
388     }
389
390     fn vtable_impl(
391         &mut self,
392         impl_def_id: DefId,
393         substs: Normalized<'tcx, SubstsRef<'tcx>>,
394         cause: &ObligationCause<'tcx>,
395         recursion_depth: usize,
396         param_env: ty::ParamEnv<'tcx>,
397         parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
398     ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
399         debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl");
400
401         let mut impl_obligations = self.impl_or_trait_obligations(
402             cause,
403             recursion_depth,
404             param_env,
405             impl_def_id,
406             &substs.value,
407             parent_trait_pred,
408         );
409
410         debug!(?impl_obligations, "vtable_impl");
411
412         // Because of RFC447, the impl-trait-ref and obligations
413         // are sufficient to determine the impl substs, without
414         // relying on projections in the impl-trait-ref.
415         //
416         // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
417         impl_obligations.extend(substs.obligations);
418
419         ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations }
420     }
421
422     fn confirm_object_candidate(
423         &mut self,
424         obligation: &TraitObligation<'tcx>,
425         index: usize,
426     ) -> Result<ImplSourceObjectData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
427         let tcx = self.tcx();
428         debug!(?obligation, ?index, "confirm_object_candidate");
429
430         let trait_predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
431         let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
432         let obligation_trait_ref = ty::Binder::dummy(trait_predicate.trait_ref);
433         let ty::Dynamic(data, ..) = *self_ty.kind() else {
434             span_bug!(obligation.cause.span, "object candidate with non-object");
435         };
436
437         let object_trait_ref = data.principal().unwrap_or_else(|| {
438             span_bug!(obligation.cause.span, "object candidate with no principal")
439         });
440         let object_trait_ref = self.infcx.replace_bound_vars_with_fresh_vars(
441             obligation.cause.span,
442             HigherRankedType,
443             object_trait_ref,
444         );
445         let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);
446
447         let mut nested = vec![];
448
449         let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
450         let unnormalized_upcast_trait_ref =
451             supertraits.nth(index).expect("supertraits iterator no longer has as many elements");
452
453         let upcast_trait_ref = normalize_with_depth_to(
454             self,
455             obligation.param_env,
456             obligation.cause.clone(),
457             obligation.recursion_depth + 1,
458             unnormalized_upcast_trait_ref,
459             &mut nested,
460         );
461
462         nested.extend(self.infcx.commit_if_ok(|_| {
463             self.infcx
464                 .at(&obligation.cause, obligation.param_env)
465                 .sup(obligation_trait_ref, upcast_trait_ref)
466                 .map(|InferOk { obligations, .. }| obligations)
467                 .map_err(|_| Unimplemented)
468         })?);
469
470         // Check supertraits hold. This is so that their associated type bounds
471         // will be checked in the code below.
472         for super_trait in tcx
473             .super_predicates_of(trait_predicate.def_id())
474             .instantiate(tcx, trait_predicate.trait_ref.substs)
475             .predicates
476             .into_iter()
477         {
478             let normalized_super_trait = normalize_with_depth_to(
479                 self,
480                 obligation.param_env,
481                 obligation.cause.clone(),
482                 obligation.recursion_depth + 1,
483                 super_trait,
484                 &mut nested,
485             );
486             nested.push(obligation.with(tcx, normalized_super_trait));
487         }
488
489         let assoc_types: Vec<_> = tcx
490             .associated_items(trait_predicate.def_id())
491             .in_definition_order()
492             .filter_map(
493                 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
494             )
495             .collect();
496
497         for assoc_type in assoc_types {
498             let defs: &ty::Generics = tcx.generics_of(assoc_type);
499
500             if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
501                 tcx.sess.delay_span_bug(
502                     obligation.cause.span,
503                     "GATs in trait object shouldn't have been considered",
504                 );
505                 return Err(SelectionError::Unimplemented);
506             }
507
508             // This maybe belongs in wf, but that can't (doesn't) handle
509             // higher-ranked things.
510             // Prevent, e.g., `dyn Iterator<Item = str>`.
511             for bound in self.tcx().bound_item_bounds(assoc_type).transpose_iter() {
512                 let subst_bound =
513                     if defs.count() == 0 {
514                         bound.subst(tcx, trait_predicate.trait_ref.substs)
515                     } else {
516                         let mut substs = smallvec::SmallVec::with_capacity(defs.count());
517                         substs.extend(trait_predicate.trait_ref.substs.iter());
518                         let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
519                             smallvec::SmallVec::with_capacity(
520                                 bound.0.kind().bound_vars().len() + defs.count(),
521                             );
522                         bound_vars.extend(bound.0.kind().bound_vars().into_iter());
523                         InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
524                             .kind
525                         {
526                             GenericParamDefKind::Type { .. } => {
527                                 let kind = ty::BoundTyKind::Param(param.name);
528                                 let bound_var = ty::BoundVariableKind::Ty(kind);
529                                 bound_vars.push(bound_var);
530                                 tcx.mk_ty(ty::Bound(
531                                     ty::INNERMOST,
532                                     ty::BoundTy {
533                                         var: ty::BoundVar::from_usize(bound_vars.len() - 1),
534                                         kind,
535                                     },
536                                 ))
537                                 .into()
538                             }
539                             GenericParamDefKind::Lifetime => {
540                                 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
541                                 let bound_var = ty::BoundVariableKind::Region(kind);
542                                 bound_vars.push(bound_var);
543                                 tcx.mk_region(ty::ReLateBound(
544                                     ty::INNERMOST,
545                                     ty::BoundRegion {
546                                         var: ty::BoundVar::from_usize(bound_vars.len() - 1),
547                                         kind,
548                                     },
549                                 ))
550                                 .into()
551                             }
552                             GenericParamDefKind::Const { .. } => {
553                                 let bound_var = ty::BoundVariableKind::Const;
554                                 bound_vars.push(bound_var);
555                                 tcx.mk_const(
556                                     ty::ConstKind::Bound(
557                                         ty::INNERMOST,
558                                         ty::BoundVar::from_usize(bound_vars.len() - 1),
559                                     ),
560                                     tcx.type_of(param.def_id),
561                                 )
562                                 .into()
563                             }
564                         });
565                         let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
566                         let assoc_ty_substs = tcx.intern_substs(&substs);
567
568                         let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
569                         let bound =
570                             bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs);
571                         tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
572                     };
573                 let normalized_bound = normalize_with_depth_to(
574                     self,
575                     obligation.param_env,
576                     obligation.cause.clone(),
577                     obligation.recursion_depth + 1,
578                     subst_bound,
579                     &mut nested,
580                 );
581                 nested.push(obligation.with(tcx, normalized_bound));
582             }
583         }
584
585         debug!(?nested, "object nested obligations");
586
587         let vtable_base = super::super::vtable_trait_first_method_offset(
588             tcx,
589             (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
590         );
591
592         Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
593     }
594
595     fn confirm_fn_pointer_candidate(
596         &mut self,
597         obligation: &TraitObligation<'tcx>,
598     ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
599     {
600         debug!(?obligation, "confirm_fn_pointer_candidate");
601
602         // Okay to skip binder; it is reintroduced below.
603         let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
604         let sig = self_ty.fn_sig(self.tcx());
605         let trait_ref = closure_trait_ref_and_return_type(
606             self.tcx(),
607             obligation.predicate.def_id(),
608             self_ty,
609             sig,
610             util::TupleArgumentsFlag::Yes,
611         )
612         .map_bound(|(trait_ref, _)| trait_ref);
613
614         let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
615
616         // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
617         let cause = obligation.derived_cause(BuiltinDerivedObligation);
618         // The binder on the Fn obligation is "less" important than the one on
619         // the signature, as evidenced by how we treat it during projection.
620         // The safe thing to do here is to liberate it, though, which should
621         // have no worse effect than skipping the binder here.
622         let liberated_fn_ty =
623             self.infcx.replace_bound_vars_with_placeholders(obligation.predicate.rebind(self_ty));
624         let output_ty = self
625             .infcx
626             .replace_bound_vars_with_placeholders(liberated_fn_ty.fn_sig(self.tcx()).output());
627         let output_ty = normalize_with_depth_to(
628             self,
629             obligation.param_env,
630             cause.clone(),
631             obligation.recursion_depth,
632             output_ty,
633             &mut nested,
634         );
635         let tr =
636             ty::Binder::dummy(self.tcx().at(cause.span).mk_trait_ref(LangItem::Sized, [output_ty]));
637         nested.push(Obligation::new(
638             self.infcx.tcx,
639             cause,
640             obligation.param_env,
641             tr.to_poly_trait_predicate(),
642         ));
643
644         Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
645     }
646
647     fn confirm_trait_alias_candidate(
648         &mut self,
649         obligation: &TraitObligation<'tcx>,
650     ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
651         debug!(?obligation, "confirm_trait_alias_candidate");
652
653         let alias_def_id = obligation.predicate.def_id();
654         let predicate = self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
655         let trait_ref = predicate.trait_ref;
656         let trait_def_id = trait_ref.def_id;
657         let substs = trait_ref.substs;
658
659         let trait_obligations = self.impl_or_trait_obligations(
660             &obligation.cause,
661             obligation.recursion_depth,
662             obligation.param_env,
663             trait_def_id,
664             &substs,
665             obligation.predicate,
666         );
667
668         debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
669
670         ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
671     }
672
673     fn confirm_generator_candidate(
674         &mut self,
675         obligation: &TraitObligation<'tcx>,
676     ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
677     {
678         // Okay to skip binder because the substs on generator types never
679         // touch bound regions, they just capture the in-scope
680         // type/region parameters.
681         let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
682         let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
683             bug!("closure candidate for non-closure {:?}", obligation);
684         };
685
686         debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
687
688         let trait_ref = self.generator_trait_ref_unnormalized(obligation, substs);
689
690         let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
691         debug!(?trait_ref, ?nested, "generator candidate obligations");
692
693         Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
694     }
695
696     #[instrument(skip(self), level = "debug")]
697     fn confirm_closure_candidate(
698         &mut self,
699         obligation: &TraitObligation<'tcx>,
700     ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
701         let kind = self
702             .tcx()
703             .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
704             .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
705
706         // Okay to skip binder because the substs on closure types never
707         // touch bound regions, they just capture the in-scope
708         // type/region parameters.
709         let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
710         let ty::Closure(closure_def_id, substs) = *self_ty.kind() else {
711             bug!("closure candidate for non-closure {:?}", obligation);
712         };
713
714         let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
715         let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
716
717         debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
718
719         // FIXME: Chalk
720
721         if !self.tcx().sess.opts.unstable_opts.chalk {
722             nested.push(obligation.with(
723                 self.tcx(),
724                 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind)),
725             ));
726         }
727
728         Ok(ImplSourceClosureData { closure_def_id, substs, nested })
729     }
730
731     /// In the case of closure types and fn pointers,
732     /// we currently treat the input type parameters on the trait as
733     /// outputs. This means that when we have a match we have only
734     /// considered the self type, so we have to go back and make sure
735     /// to relate the argument types too. This is kind of wrong, but
736     /// since we control the full set of impls, also not that wrong,
737     /// and it DOES yield better error messages (since we don't report
738     /// errors as if there is no applicable impl, but rather report
739     /// errors are about mismatched argument types.
740     ///
741     /// Here is an example. Imagine we have a closure expression
742     /// and we desugared it so that the type of the expression is
743     /// `Closure`, and `Closure` expects `i32` as argument. Then it
744     /// is "as if" the compiler generated this impl:
745     /// ```ignore (illustrative)
746     /// impl Fn(i32) for Closure { ... }
747     /// ```
748     /// Now imagine our obligation is `Closure: Fn(usize)`. So far
749     /// we have matched the self type `Closure`. At this point we'll
750     /// compare the `i32` to `usize` and generate an error.
751     ///
752     /// Note that this checking occurs *after* the impl has selected,
753     /// because these output type parameters should not affect the
754     /// selection of the impl. Therefore, if there is a mismatch, we
755     /// report an error to the user.
756     #[instrument(skip(self), level = "trace")]
757     fn confirm_poly_trait_refs(
758         &mut self,
759         obligation: &TraitObligation<'tcx>,
760         expected_trait_ref: ty::PolyTraitRef<'tcx>,
761     ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
762         let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
763         // Normalize the obligation and expected trait refs together, because why not
764         let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
765             ensure_sufficient_stack(|| {
766                 normalize_with_depth(
767                     self,
768                     obligation.param_env,
769                     obligation.cause.clone(),
770                     obligation.recursion_depth + 1,
771                     (obligation_trait_ref, expected_trait_ref),
772                 )
773             });
774
775         self.infcx
776             .at(&obligation.cause, obligation.param_env)
777             .sup(obligation_trait_ref, expected_trait_ref)
778             .map(|InferOk { mut obligations, .. }| {
779                 obligations.extend(nested);
780                 obligations
781             })
782             .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
783     }
784
785     fn confirm_trait_upcasting_unsize_candidate(
786         &mut self,
787         obligation: &TraitObligation<'tcx>,
788         idx: usize,
789     ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
790     {
791         let tcx = self.tcx();
792
793         // `assemble_candidates_for_unsizing` should ensure there are no late-bound
794         // regions here. See the comment there for more details.
795         let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
796         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
797         let target = self.infcx.shallow_resolve(target);
798
799         debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
800
801         let mut nested = vec![];
802         let source_trait_ref;
803         let upcast_trait_ref;
804         match (source.kind(), target.kind()) {
805             // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
806             (&ty::Dynamic(ref data_a, r_a, repr_a), &ty::Dynamic(ref data_b, r_b, repr_b))
807                 if repr_a == repr_b =>
808             {
809                 // See `assemble_candidates_for_unsizing` for more info.
810                 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
811                 let principal_a = data_a.principal().unwrap();
812                 source_trait_ref = principal_a.with_self_ty(tcx, source);
813                 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
814                 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
815                 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
816                     ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
817                         tcx, trait_ref,
818                     ))
819                 });
820                 let iter = Some(existential_predicate)
821                     .into_iter()
822                     .chain(
823                         data_a
824                             .projection_bounds()
825                             .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
826                     )
827                     .chain(
828                         data_b
829                             .auto_traits()
830                             .map(ty::ExistentialPredicate::AutoTrait)
831                             .map(ty::Binder::dummy),
832                     );
833                 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
834                 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, repr_b);
835
836                 // Require that the traits involved in this upcast are **equal**;
837                 // only the **lifetime bound** is changed.
838                 let InferOk { obligations, .. } = self
839                     .infcx
840                     .at(&obligation.cause, obligation.param_env)
841                     .sup(target, source_trait)
842                     .map_err(|_| Unimplemented)?;
843                 nested.extend(obligations);
844
845                 // Register one obligation for 'a: 'b.
846                 let cause = ObligationCause::new(
847                     obligation.cause.span,
848                     obligation.cause.body_id,
849                     ObjectCastObligation(source, target),
850                 );
851                 let outlives = ty::OutlivesPredicate(r_a, r_b);
852                 nested.push(Obligation::with_depth(
853                     tcx,
854                     cause,
855                     obligation.recursion_depth + 1,
856                     obligation.param_env,
857                     obligation.predicate.rebind(outlives),
858                 ));
859             }
860             _ => bug!(),
861         };
862
863         let vtable_segment_callback = {
864             let mut vptr_offset = 0;
865             move |segment| {
866                 match segment {
867                     VtblSegment::MetadataDSA => {
868                         vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
869                     }
870                     VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
871                         vptr_offset += util::count_own_vtable_entries(tcx, trait_ref);
872                         if trait_ref == upcast_trait_ref {
873                             if emit_vptr {
874                                 return ControlFlow::Break(Some(vptr_offset));
875                             } else {
876                                 return ControlFlow::Break(None);
877                             }
878                         }
879
880                         if emit_vptr {
881                             vptr_offset += 1;
882                         }
883                     }
884                 }
885                 ControlFlow::Continue(())
886             }
887         };
888
889         let vtable_vptr_slot =
890             super::super::prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback)
891                 .unwrap();
892
893         Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
894     }
895
896     fn confirm_builtin_unsize_candidate(
897         &mut self,
898         obligation: &TraitObligation<'tcx>,
899     ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
900         let tcx = self.tcx();
901
902         // `assemble_candidates_for_unsizing` should ensure there are no late-bound
903         // regions here. See the comment there for more details.
904         let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
905         let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
906         let target = self.infcx.shallow_resolve(target);
907
908         debug!(?source, ?target, "confirm_builtin_unsize_candidate");
909
910         let mut nested = vec![];
911         match (source.kind(), target.kind()) {
912             // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
913             (&ty::Dynamic(ref data_a, r_a, dyn_a), &ty::Dynamic(ref data_b, r_b, dyn_b))
914                 if dyn_a == dyn_b =>
915             {
916                 // See `assemble_candidates_for_unsizing` for more info.
917                 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
918                 let iter = data_a
919                     .principal()
920                     .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
921                     .into_iter()
922                     .chain(
923                         data_a
924                             .projection_bounds()
925                             .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
926                     )
927                     .chain(
928                         data_b
929                             .auto_traits()
930                             .map(ty::ExistentialPredicate::AutoTrait)
931                             .map(ty::Binder::dummy),
932                     );
933                 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
934                 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, dyn_a);
935
936                 // Require that the traits involved in this upcast are **equal**;
937                 // only the **lifetime bound** is changed.
938                 let InferOk { obligations, .. } = self
939                     .infcx
940                     .at(&obligation.cause, obligation.param_env)
941                     .sup(target, source_trait)
942                     .map_err(|_| Unimplemented)?;
943                 nested.extend(obligations);
944
945                 // Register one obligation for 'a: 'b.
946                 let cause = ObligationCause::new(
947                     obligation.cause.span,
948                     obligation.cause.body_id,
949                     ObjectCastObligation(source, target),
950                 );
951                 let outlives = ty::OutlivesPredicate(r_a, r_b);
952                 nested.push(Obligation::with_depth(
953                     tcx,
954                     cause,
955                     obligation.recursion_depth + 1,
956                     obligation.param_env,
957                     obligation.predicate.rebind(outlives),
958                 ));
959             }
960
961             // `T` -> `Trait`
962             (_, &ty::Dynamic(ref data, r, ty::Dyn)) => {
963                 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
964                 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
965                     return Err(TraitNotObjectSafe(did));
966                 }
967
968                 let cause = ObligationCause::new(
969                     obligation.cause.span,
970                     obligation.cause.body_id,
971                     ObjectCastObligation(source, target),
972                 );
973
974                 let predicate_to_obligation = |predicate| {
975                     Obligation::with_depth(
976                         tcx,
977                         cause.clone(),
978                         obligation.recursion_depth + 1,
979                         obligation.param_env,
980                         predicate,
981                     )
982                 };
983
984                 // Create obligations:
985                 //  - Casting `T` to `Trait`
986                 //  - For all the various builtin bounds attached to the object cast. (In other
987                 //  words, if the object type is `Foo + Send`, this would create an obligation for
988                 //  the `Send` check.)
989                 //  - Projection predicates
990                 nested.extend(
991                     data.iter().map(|predicate| {
992                         predicate_to_obligation(predicate.with_self_ty(tcx, source))
993                     }),
994                 );
995
996                 // We can only make objects from sized types.
997                 let tr =
998                     ty::Binder::dummy(tcx.at(cause.span).mk_trait_ref(LangItem::Sized, [source]));
999                 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
1000
1001                 // If the type is `Foo + 'a`, ensure that the type
1002                 // being cast to `Foo + 'a` outlives `'a`:
1003                 let outlives = ty::OutlivesPredicate(source, r);
1004                 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
1005             }
1006
1007             // `[T; n]` -> `[T]`
1008             (&ty::Array(a, _), &ty::Slice(b)) => {
1009                 let InferOk { obligations, .. } = self
1010                     .infcx
1011                     .at(&obligation.cause, obligation.param_env)
1012                     .eq(b, a)
1013                     .map_err(|_| Unimplemented)?;
1014                 nested.extend(obligations);
1015             }
1016
1017             // `Struct<T>` -> `Struct<U>`
1018             (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
1019                 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
1020                     GenericArgKind::Type(ty) => match ty.kind() {
1021                         ty::Param(p) => Some(p.index),
1022                         _ => None,
1023                     },
1024
1025                     // Lifetimes aren't allowed to change during unsizing.
1026                     GenericArgKind::Lifetime(_) => None,
1027
1028                     GenericArgKind::Const(ct) => match ct.kind() {
1029                         ty::ConstKind::Param(p) => Some(p.index),
1030                         _ => None,
1031                     },
1032                 };
1033
1034                 // FIXME(eddyb) cache this (including computing `unsizing_params`)
1035                 // by putting it in a query; it would only need the `DefId` as it
1036                 // looks at declared field types, not anything substituted.
1037
1038                 // The last field of the structure has to exist and contain type/const parameters.
1039                 let (tail_field, prefix_fields) =
1040                     def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
1041                 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1042
1043                 let mut unsizing_params = GrowableBitSet::new_empty();
1044                 for arg in tail_field_ty.0.walk() {
1045                     if let Some(i) = maybe_unsizing_param_idx(arg) {
1046                         unsizing_params.insert(i);
1047                     }
1048                 }
1049
1050                 // Ensure none of the other fields mention the parameters used
1051                 // in unsizing.
1052                 for field in prefix_fields {
1053                     for arg in tcx.type_of(field.did).walk() {
1054                         if let Some(i) = maybe_unsizing_param_idx(arg) {
1055                             unsizing_params.remove(i);
1056                         }
1057                     }
1058                 }
1059
1060                 if unsizing_params.is_empty() {
1061                     return Err(Unimplemented);
1062                 }
1063
1064                 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
1065                 // normalizing in the process, since `type_of` returns something directly from
1066                 // astconv (which means it's un-normalized).
1067                 let source_tail = normalize_with_depth_to(
1068                     self,
1069                     obligation.param_env,
1070                     obligation.cause.clone(),
1071                     obligation.recursion_depth + 1,
1072                     tail_field_ty.subst(tcx, substs_a),
1073                     &mut nested,
1074                 );
1075                 let target_tail = normalize_with_depth_to(
1076                     self,
1077                     obligation.param_env,
1078                     obligation.cause.clone(),
1079                     obligation.recursion_depth + 1,
1080                     tail_field_ty.subst(tcx, substs_b),
1081                     &mut nested,
1082                 );
1083
1084                 // Check that the source struct with the target's
1085                 // unsizing parameters is equal to the target.
1086                 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1087                     if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1088                 }));
1089                 let new_struct = tcx.mk_adt(def, substs);
1090                 let InferOk { obligations, .. } = self
1091                     .infcx
1092                     .at(&obligation.cause, obligation.param_env)
1093                     .eq(target, new_struct)
1094                     .map_err(|_| Unimplemented)?;
1095                 nested.extend(obligations);
1096
1097                 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1098                 nested.push(predicate_for_trait_def(
1099                     tcx,
1100                     obligation.param_env,
1101                     obligation.cause.clone(),
1102                     obligation.predicate.def_id(),
1103                     obligation.recursion_depth + 1,
1104                     [source_tail, target_tail],
1105                 ));
1106             }
1107
1108             // `(.., T)` -> `(.., U)`
1109             (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1110                 assert_eq!(tys_a.len(), tys_b.len());
1111
1112                 // The last field of the tuple has to exist.
1113                 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1114                 let &b_last = tys_b.last().unwrap();
1115
1116                 // Check that the source tuple with the target's
1117                 // last element is equal to the target.
1118                 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1119                 let InferOk { obligations, .. } = self
1120                     .infcx
1121                     .at(&obligation.cause, obligation.param_env)
1122                     .eq(target, new_tuple)
1123                     .map_err(|_| Unimplemented)?;
1124                 nested.extend(obligations);
1125
1126                 // Construct the nested `T: Unsize<U>` predicate.
1127                 nested.push(ensure_sufficient_stack(|| {
1128                     predicate_for_trait_def(
1129                         tcx,
1130                         obligation.param_env,
1131                         obligation.cause.clone(),
1132                         obligation.predicate.def_id(),
1133                         obligation.recursion_depth + 1,
1134                         [a_last, b_last],
1135                     )
1136                 }));
1137             }
1138
1139             _ => bug!("source: {source}, target: {target}"),
1140         };
1141
1142         Ok(ImplSourceBuiltinData { nested })
1143     }
1144
1145     fn confirm_const_destruct_candidate(
1146         &mut self,
1147         obligation: &TraitObligation<'tcx>,
1148         impl_def_id: Option<DefId>,
1149     ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1150         // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1151         if !obligation.is_const() {
1152             return Ok(ImplSourceConstDestructData { nested: vec![] });
1153         }
1154
1155         let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1156
1157         let tcx = self.tcx();
1158         let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1159
1160         let mut nested = vec![];
1161         let cause = obligation.derived_cause(BuiltinDerivedObligation);
1162
1163         // If we have a custom `impl const Drop`, then
1164         // first check it like a regular impl candidate.
1165         // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1166         if let Some(impl_def_id) = impl_def_id {
1167             let mut new_obligation = obligation.clone();
1168             new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1169                 trait_pred.trait_ref.def_id = drop_trait;
1170                 trait_pred
1171             });
1172             let substs = self.rematch_impl(impl_def_id, &new_obligation);
1173             debug!(?substs, "impl substs");
1174
1175             let cause = obligation.derived_cause(|derived| {
1176                 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1177                     derived,
1178                     impl_def_id,
1179                     span: obligation.cause.span,
1180                 }))
1181             });
1182             let obligations = ensure_sufficient_stack(|| {
1183                 self.vtable_impl(
1184                     impl_def_id,
1185                     substs,
1186                     &cause,
1187                     new_obligation.recursion_depth + 1,
1188                     new_obligation.param_env,
1189                     obligation.predicate,
1190                 )
1191             });
1192             nested.extend(obligations.nested);
1193         }
1194
1195         // We want to confirm the ADT's fields if we have an ADT
1196         let mut stack = match *self_ty.skip_binder().kind() {
1197             ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1198             _ => vec![self_ty.skip_binder()],
1199         };
1200
1201         while let Some(nested_ty) = stack.pop() {
1202             match *nested_ty.kind() {
1203                 // We know these types are trivially drop
1204                 ty::Bool
1205                 | ty::Char
1206                 | ty::Int(_)
1207                 | ty::Uint(_)
1208                 | ty::Float(_)
1209                 | ty::Infer(ty::IntVar(_))
1210                 | ty::Infer(ty::FloatVar(_))
1211                 | ty::Str
1212                 | ty::RawPtr(_)
1213                 | ty::Ref(..)
1214                 | ty::FnDef(..)
1215                 | ty::FnPtr(_)
1216                 | ty::Never
1217                 | ty::Foreign(_) => {}
1218
1219                 // `ManuallyDrop` is trivially drop
1220                 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().manually_drop() => {}
1221
1222                 // These types are built-in, so we can fast-track by registering
1223                 // nested predicates for their constituent type(s)
1224                 ty::Array(ty, _) | ty::Slice(ty) => {
1225                     stack.push(ty);
1226                 }
1227                 ty::Tuple(tys) => {
1228                     stack.extend(tys.iter());
1229                 }
1230                 ty::Closure(_, substs) => {
1231                     stack.push(substs.as_closure().tupled_upvars_ty());
1232                 }
1233                 ty::Generator(_, substs, _) => {
1234                     let generator = substs.as_generator();
1235                     stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1236                 }
1237                 ty::GeneratorWitness(tys) => {
1238                     stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1239                 }
1240
1241                 // If we have a projection type, make sure to normalize it so we replace it
1242                 // with a fresh infer variable
1243                 ty::Projection(..) => {
1244                     let predicate = normalize_with_depth_to(
1245                         self,
1246                         obligation.param_env,
1247                         cause.clone(),
1248                         obligation.recursion_depth + 1,
1249                         self_ty.rebind(ty::TraitPredicate {
1250                             trait_ref: self
1251                                 .tcx()
1252                                 .at(cause.span)
1253                                 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1254                             constness: ty::BoundConstness::ConstIfConst,
1255                             polarity: ty::ImplPolarity::Positive,
1256                         }),
1257                         &mut nested,
1258                     );
1259
1260                     nested.push(Obligation::with_depth(
1261                         tcx,
1262                         cause.clone(),
1263                         obligation.recursion_depth + 1,
1264                         obligation.param_env,
1265                         predicate,
1266                     ));
1267                 }
1268
1269                 // If we have any other type (e.g. an ADT), just register a nested obligation
1270                 // since it's either not `const Drop` (and we raise an error during selection),
1271                 // or it's an ADT (and we need to check for a custom impl during selection)
1272                 _ => {
1273                     let predicate = self_ty.rebind(ty::TraitPredicate {
1274                         trait_ref: self
1275                             .tcx()
1276                             .at(cause.span)
1277                             .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1278                         constness: ty::BoundConstness::ConstIfConst,
1279                         polarity: ty::ImplPolarity::Positive,
1280                     });
1281
1282                     nested.push(Obligation::with_depth(
1283                         tcx,
1284                         cause.clone(),
1285                         obligation.recursion_depth + 1,
1286                         obligation.param_env,
1287                         predicate,
1288                     ));
1289                 }
1290             }
1291         }
1292
1293         Ok(ImplSourceConstDestructData { nested })
1294     }
1295 }