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