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