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