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