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