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