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