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