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