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