rustc_trait_selection/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
10use std::ops::ControlFlow;
11
12use rustc_data_structures::stack::ensure_sufficient_stack;
13use rustc_hir::lang_items::LangItem;
14use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk};
15use rustc_infer::traits::ObligationCauseCode;
16use rustc_middle::traits::{BuiltinImplSource, SignatureMismatchData};
17use rustc_middle::ty::{self, GenericArgsRef, Region, SizedTraitKind, Ty, TyCtxt, Upcast};
18use rustc_middle::{bug, span_bug};
19use rustc_span::def_id::DefId;
20use thin_vec::thin_vec;
21use tracing::{debug, instrument};
22
23use super::SelectionCandidate::{self, *};
24use super::{PredicateObligations, SelectionContext};
25use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to};
26use crate::traits::util::{self, closure_trait_ref_and_return_type};
27use crate::traits::{
28    ImplSource, ImplSourceUserDefinedData, Normalized, Obligation, ObligationCause,
29    PolyTraitObligation, PredicateObligation, Selection, SelectionError, TraitObligation,
30};
31
32impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
33    #[instrument(level = "debug", skip(self))]
34    pub(super) fn confirm_candidate(
35        &mut self,
36        obligation: &PolyTraitObligation<'tcx>,
37        candidate: SelectionCandidate<'tcx>,
38    ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
39        Ok(match candidate {
40            SizedCandidate => {
41                let data = self.confirm_builtin_candidate(obligation);
42                ImplSource::Builtin(BuiltinImplSource::Misc, data)
43            }
44
45            BuiltinCandidate => {
46                let data = self.confirm_builtin_candidate(obligation);
47                ImplSource::Builtin(BuiltinImplSource::Misc, data)
48            }
49
50            TransmutabilityCandidate => {
51                let data = self.confirm_transmutability_candidate(obligation)?;
52                ImplSource::Builtin(BuiltinImplSource::Misc, data)
53            }
54
55            ParamCandidate(param) => {
56                let obligations =
57                    self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref));
58                ImplSource::Param(obligations)
59            }
60
61            ImplCandidate(impl_def_id) => {
62                ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id))
63            }
64
65            AutoImplCandidate => {
66                let data = self.confirm_auto_impl_candidate(obligation)?;
67                ImplSource::Builtin(BuiltinImplSource::Misc, data)
68            }
69
70            ProjectionCandidate { idx, .. } => {
71                let obligations = self.confirm_projection_candidate(obligation, idx)?;
72                ImplSource::Param(obligations)
73            }
74
75            ObjectCandidate(idx) => self.confirm_object_candidate(obligation, idx)?,
76
77            ClosureCandidate { .. } => {
78                let vtable_closure = self.confirm_closure_candidate(obligation)?;
79                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_closure)
80            }
81
82            AsyncClosureCandidate => {
83                let vtable_closure = self.confirm_async_closure_candidate(obligation)?;
84                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_closure)
85            }
86
87            // No nested obligations or confirmation process. The checks that we do in
88            // candidate assembly are sufficient.
89            AsyncFnKindHelperCandidate => {
90                ImplSource::Builtin(BuiltinImplSource::Misc, PredicateObligations::new())
91            }
92
93            CoroutineCandidate => {
94                let vtable_coroutine = self.confirm_coroutine_candidate(obligation)?;
95                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_coroutine)
96            }
97
98            FutureCandidate => {
99                let vtable_future = self.confirm_future_candidate(obligation)?;
100                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_future)
101            }
102
103            IteratorCandidate => {
104                let vtable_iterator = self.confirm_iterator_candidate(obligation)?;
105                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_iterator)
106            }
107
108            AsyncIteratorCandidate => {
109                let vtable_iterator = self.confirm_async_iterator_candidate(obligation)?;
110                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_iterator)
111            }
112
113            FnPointerCandidate => {
114                let data = self.confirm_fn_pointer_candidate(obligation)?;
115                ImplSource::Builtin(BuiltinImplSource::Misc, data)
116            }
117
118            PointerLikeCandidate => {
119                let data = self.confirm_pointer_like_candidate(obligation);
120                ImplSource::Builtin(BuiltinImplSource::Misc, data)
121            }
122
123            TraitAliasCandidate => {
124                let data = self.confirm_trait_alias_candidate(obligation);
125                ImplSource::Builtin(BuiltinImplSource::Misc, data)
126            }
127
128            BuiltinObjectCandidate => {
129                // This indicates something like `Trait + Send: Send`. In this case, we know that
130                // this holds because that's what the object type is telling us, and there's really
131                // no additional obligations to prove and no types in particular to unify, etc.
132                ImplSource::Builtin(BuiltinImplSource::Misc, PredicateObligations::new())
133            }
134
135            BuiltinUnsizeCandidate => self.confirm_builtin_unsize_candidate(obligation)?,
136
137            TraitUpcastingUnsizeCandidate(idx) => {
138                self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?
139            }
140
141            BikeshedGuaranteedNoDropCandidate => {
142                self.confirm_bikeshed_guaranteed_no_drop_candidate(obligation)
143            }
144        })
145    }
146
147    fn confirm_projection_candidate(
148        &mut self,
149        obligation: &PolyTraitObligation<'tcx>,
150        idx: usize,
151    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
152        let placeholder_trait_predicate =
153            self.infcx.enter_forall_and_leak_universe(obligation.predicate).trait_ref;
154        let placeholder_self_ty = self.infcx.shallow_resolve(placeholder_trait_predicate.self_ty());
155        let candidate_predicate = self
156            .for_each_item_bound(
157                placeholder_self_ty,
158                |_, clause, clause_idx, _| {
159                    if clause_idx == idx {
160                        ControlFlow::Break(clause)
161                    } else {
162                        ControlFlow::Continue(())
163                    }
164                },
165                || unreachable!(),
166            )
167            .break_value()
168            .expect("expected to index into clause that exists");
169        let candidate_predicate = candidate_predicate
170            .as_trait_clause()
171            .expect("projection candidate is not a trait predicate");
172        let candidate_predicate =
173            util::lazily_elaborate_sizedness_candidate(self.infcx, obligation, candidate_predicate);
174
175        let candidate = candidate_predicate.map_bound(|t| t.trait_ref);
176
177        let candidate = self.infcx.instantiate_binder_with_fresh_vars(
178            obligation.cause.span,
179            BoundRegionConversionTime::HigherRankedType,
180            candidate,
181        );
182        let mut obligations = PredicateObligations::new();
183        let candidate = normalize_with_depth_to(
184            self,
185            obligation.param_env,
186            obligation.cause.clone(),
187            obligation.recursion_depth + 1,
188            candidate,
189            &mut obligations,
190        );
191
192        obligations.extend(
193            self.infcx
194                .at(&obligation.cause, obligation.param_env)
195                .eq(DefineOpaqueTypes::No, placeholder_trait_predicate, candidate)
196                .map(|InferOk { obligations, .. }| obligations)
197                .map_err(|_| SelectionError::Unimplemented)?,
198        );
199
200        Ok(obligations)
201    }
202
203    fn confirm_param_candidate(
204        &mut self,
205        obligation: &PolyTraitObligation<'tcx>,
206        param: ty::PolyTraitRef<'tcx>,
207    ) -> PredicateObligations<'tcx> {
208        debug!(?obligation, ?param, "confirm_param_candidate");
209
210        let param = util::lazily_elaborate_sizedness_candidate(
211            self.infcx,
212            obligation,
213            param.upcast(self.infcx.tcx),
214        )
215        .map_bound(|p| p.trait_ref);
216
217        // During evaluation, we already checked that this
218        // where-clause trait-ref could be unified with the obligation
219        // trait-ref. Repeat that unification now without any
220        // transactional boundary; it should not fail.
221        match self.match_where_clause_trait_ref(obligation, param) {
222            Ok(obligations) => obligations,
223            Err(()) => {
224                bug!(
225                    "Where clause `{:?}` was applicable to `{:?}` but now is not",
226                    param,
227                    obligation
228                );
229            }
230        }
231    }
232
233    #[instrument(level = "debug", skip(self), ret)]
234    fn confirm_builtin_candidate(
235        &mut self,
236        obligation: &PolyTraitObligation<'tcx>,
237    ) -> PredicateObligations<'tcx> {
238        debug!(?obligation, "confirm_builtin_candidate");
239        let tcx = self.tcx();
240        let trait_def = obligation.predicate.def_id();
241        let self_ty = self.infcx.shallow_resolve(
242            self.infcx.enter_forall_and_leak_universe(obligation.predicate.self_ty()),
243        );
244        let types = match tcx.as_lang_item(trait_def) {
245            Some(LangItem::Sized) => self.sizedness_conditions(self_ty, SizedTraitKind::Sized),
246            Some(LangItem::MetaSized) => {
247                self.sizedness_conditions(self_ty, SizedTraitKind::MetaSized)
248            }
249            Some(LangItem::PointeeSized) => {
250                bug!("`PointeeSized` is removing during lowering");
251            }
252            Some(LangItem::Copy | LangItem::Clone) => self.copy_clone_conditions(self_ty),
253            Some(LangItem::FusedIterator) => {
254                if self.coroutine_is_gen(self_ty) {
255                    ty::Binder::dummy(vec![])
256                } else {
257                    unreachable!("tried to assemble `FusedIterator` for non-gen coroutine");
258                }
259            }
260            Some(
261                LangItem::Destruct
262                | LangItem::DiscriminantKind
263                | LangItem::FnPtrTrait
264                | LangItem::PointeeTrait
265                | LangItem::Tuple
266                | LangItem::Unpin,
267            ) => ty::Binder::dummy(vec![]),
268            other => bug!("unexpected builtin trait {trait_def:?} ({other:?})"),
269        };
270        let types = self.infcx.enter_forall_and_leak_universe(types);
271
272        let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerived);
273        self.collect_predicates_for_types(
274            obligation.param_env,
275            cause,
276            obligation.recursion_depth + 1,
277            trait_def,
278            types,
279        )
280    }
281
282    #[instrument(level = "debug", skip(self))]
283    fn confirm_transmutability_candidate(
284        &mut self,
285        obligation: &PolyTraitObligation<'tcx>,
286    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
287        use rustc_transmute::{Answer, Assume, Condition};
288
289        /// Flatten the `Condition` tree into a conjunction of obligations.
290        #[instrument(level = "debug", skip(tcx, obligation))]
291        fn flatten_answer_tree<'tcx>(
292            tcx: TyCtxt<'tcx>,
293            obligation: &PolyTraitObligation<'tcx>,
294            cond: Condition<Region<'tcx>, Ty<'tcx>>,
295            assume: Assume,
296        ) -> PredicateObligations<'tcx> {
297            match cond {
298                // FIXME(bryangarza): Add separate `IfAny` case, instead of treating as `IfAll`
299                // Not possible until the trait solver supports disjunctions of obligations
300                Condition::IfAll(conds) | Condition::IfAny(conds) => conds
301                    .into_iter()
302                    .flat_map(|cond| flatten_answer_tree(tcx, obligation, cond, assume))
303                    .collect(),
304                Condition::Immutable { ty } => {
305                    let trait_ref = ty::TraitRef::new(
306                        tcx,
307                        tcx.require_lang_item(LangItem::Freeze, obligation.cause.span),
308                        [ty::GenericArg::from(ty)],
309                    );
310                    thin_vec![Obligation::with_depth(
311                        tcx,
312                        obligation.cause.clone(),
313                        obligation.recursion_depth + 1,
314                        obligation.param_env,
315                        trait_ref,
316                    )]
317                }
318                Condition::Outlives { long, short } => {
319                    let outlives = ty::OutlivesPredicate(long, short);
320                    thin_vec![Obligation::with_depth(
321                        tcx,
322                        obligation.cause.clone(),
323                        obligation.recursion_depth + 1,
324                        obligation.param_env,
325                        outlives,
326                    )]
327                }
328                Condition::Transmutable { src, dst } => {
329                    let transmute_trait = obligation.predicate.def_id();
330                    let assume = obligation.predicate.skip_binder().trait_ref.args.const_at(2);
331                    let trait_ref = ty::TraitRef::new(
332                        tcx,
333                        transmute_trait,
334                        [
335                            ty::GenericArg::from(dst),
336                            ty::GenericArg::from(src),
337                            ty::GenericArg::from(assume),
338                        ],
339                    );
340                    thin_vec![Obligation::with_depth(
341                        tcx,
342                        obligation.cause.clone(),
343                        obligation.recursion_depth + 1,
344                        obligation.param_env,
345                        trait_ref,
346                    )]
347                }
348            }
349        }
350
351        let predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
352
353        let mut assume = predicate.trait_ref.args.const_at(2);
354        if self.tcx().features().generic_const_exprs() {
355            assume = crate::traits::evaluate_const(self.infcx, assume, obligation.param_env)
356        }
357        let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
358            return Err(SelectionError::Unimplemented);
359        };
360
361        let dst = predicate.trait_ref.args.type_at(0);
362        let src = predicate.trait_ref.args.type_at(1);
363
364        debug!(?src, ?dst);
365        let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx);
366        let maybe_transmutable =
367            transmute_env.is_transmutable(rustc_transmute::Types { dst, src }, assume);
368
369        let fully_flattened = match maybe_transmutable {
370            Answer::No(_) => Err(SelectionError::Unimplemented)?,
371            Answer::If(cond) => flatten_answer_tree(self.tcx(), obligation, cond, assume),
372            Answer::Yes => PredicateObligations::new(),
373        };
374
375        debug!(?fully_flattened);
376        Ok(fully_flattened)
377    }
378
379    /// This handles the case where an `auto trait Foo` impl is being used.
380    /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
381    ///
382    /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
383    /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
384    fn confirm_auto_impl_candidate(
385        &mut self,
386        obligation: &PolyTraitObligation<'tcx>,
387    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
388        ensure_sufficient_stack(|| {
389            assert_eq!(obligation.predicate.polarity(), ty::PredicatePolarity::Positive);
390
391            let self_ty =
392                obligation.predicate.self_ty().map_bound(|ty| self.infcx.shallow_resolve(ty));
393            let self_ty = self.infcx.enter_forall_and_leak_universe(self_ty);
394
395            let constituents = self.constituent_types_for_auto_trait(self_ty)?;
396            let constituents = self.infcx.enter_forall_and_leak_universe(constituents);
397
398            let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerived);
399            let mut obligations = self.collect_predicates_for_types(
400                obligation.param_env,
401                cause.clone(),
402                obligation.recursion_depth + 1,
403                obligation.predicate.def_id(),
404                constituents.types,
405            );
406
407            // Only normalize these goals if `-Zhigher-ranked-assumptions` is enabled, since
408            // we don't want to cause ourselves to do extra work if we're not even able to
409            // take advantage of these assumption clauses.
410            if self.tcx().sess.opts.unstable_opts.higher_ranked_assumptions {
411                // FIXME(coroutine_clone): We could uplift this into `collect_predicates_for_types`
412                // and do this for `Copy`/`Clone` too, but that's feature-gated so it doesn't really
413                // matter yet.
414                for assumption in constituents.assumptions {
415                    let assumption = normalize_with_depth_to(
416                        self,
417                        obligation.param_env,
418                        cause.clone(),
419                        obligation.recursion_depth + 1,
420                        assumption,
421                        &mut obligations,
422                    );
423                    self.infcx.register_region_assumption(assumption);
424                }
425            }
426
427            Ok(obligations)
428        })
429    }
430
431    fn confirm_impl_candidate(
432        &mut self,
433        obligation: &PolyTraitObligation<'tcx>,
434        impl_def_id: DefId,
435    ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
436        debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");
437
438        // First, create the generic parameters by matching the impl again,
439        // this time not in a probe.
440        let args = self.rematch_impl(impl_def_id, obligation);
441        debug!(?args, "impl args");
442        ensure_sufficient_stack(|| {
443            self.vtable_impl(
444                impl_def_id,
445                args,
446                &obligation.cause,
447                obligation.recursion_depth + 1,
448                obligation.param_env,
449                obligation.predicate,
450            )
451        })
452    }
453
454    fn vtable_impl(
455        &mut self,
456        impl_def_id: DefId,
457        args: Normalized<'tcx, GenericArgsRef<'tcx>>,
458        cause: &ObligationCause<'tcx>,
459        recursion_depth: usize,
460        param_env: ty::ParamEnv<'tcx>,
461        parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
462    ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
463        debug!(?impl_def_id, ?args, ?recursion_depth, "vtable_impl");
464
465        let mut impl_obligations = self.impl_or_trait_obligations(
466            cause,
467            recursion_depth,
468            param_env,
469            impl_def_id,
470            args.value,
471            parent_trait_pred,
472        );
473
474        debug!(?impl_obligations, "vtable_impl");
475
476        // Because of RFC447, the impl-trait-ref and obligations
477        // are sufficient to determine the impl args, without
478        // relying on projections in the impl-trait-ref.
479        //
480        // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
481        impl_obligations.extend(args.obligations);
482
483        ImplSourceUserDefinedData { impl_def_id, args: args.value, nested: impl_obligations }
484    }
485
486    fn confirm_object_candidate(
487        &mut self,
488        obligation: &PolyTraitObligation<'tcx>,
489        index: usize,
490    ) -> Result<ImplSource<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
491        let tcx = self.tcx();
492        debug!(?obligation, ?index, "confirm_object_candidate");
493
494        let trait_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
495        let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
496        let ty::Dynamic(data, ..) = *self_ty.kind() else {
497            span_bug!(obligation.cause.span, "object candidate with non-object");
498        };
499
500        let object_trait_ref = data.principal().unwrap_or_else(|| {
501            span_bug!(obligation.cause.span, "object candidate with no principal")
502        });
503        let object_trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
504            obligation.cause.span,
505            BoundRegionConversionTime::HigherRankedType,
506            object_trait_ref,
507        );
508        let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);
509
510        let mut nested = PredicateObligations::new();
511
512        let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
513        let unnormalized_upcast_trait_ref =
514            supertraits.nth(index).expect("supertraits iterator no longer has as many elements");
515
516        let upcast_trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
517            obligation.cause.span,
518            BoundRegionConversionTime::HigherRankedType,
519            unnormalized_upcast_trait_ref,
520        );
521        let upcast_trait_ref = normalize_with_depth_to(
522            self,
523            obligation.param_env,
524            obligation.cause.clone(),
525            obligation.recursion_depth + 1,
526            upcast_trait_ref,
527            &mut nested,
528        );
529
530        nested.extend(
531            self.infcx
532                .at(&obligation.cause, obligation.param_env)
533                .eq(DefineOpaqueTypes::No, trait_predicate.trait_ref, upcast_trait_ref)
534                .map(|InferOk { obligations, .. }| obligations)
535                .map_err(|_| SelectionError::Unimplemented)?,
536        );
537
538        // Check supertraits hold. This is so that their associated type bounds
539        // will be checked in the code below.
540        for (supertrait, _) in tcx
541            .explicit_super_predicates_of(trait_predicate.def_id())
542            .iter_instantiated_copied(tcx, trait_predicate.trait_ref.args)
543        {
544            let normalized_supertrait = normalize_with_depth_to(
545                self,
546                obligation.param_env,
547                obligation.cause.clone(),
548                obligation.recursion_depth + 1,
549                supertrait,
550                &mut nested,
551            );
552            nested.push(obligation.with(tcx, normalized_supertrait));
553        }
554
555        let assoc_types: Vec<_> = tcx
556            .associated_items(trait_predicate.def_id())
557            .in_definition_order()
558            // Associated types that require `Self: Sized` do not show up in the built-in
559            // implementation of `Trait for dyn Trait`, and can be dropped here.
560            .filter(|item| !tcx.generics_require_sized_self(item.def_id))
561            .filter_map(|item| if item.is_type() { Some(item.def_id) } else { None })
562            .collect();
563
564        for assoc_type in assoc_types {
565            let defs: &ty::Generics = tcx.generics_of(assoc_type);
566
567            if !defs.own_params.is_empty() {
568                tcx.dcx().span_delayed_bug(
569                    obligation.cause.span,
570                    "GATs in trait object shouldn't have been considered",
571                );
572                return Err(SelectionError::TraitDynIncompatible(trait_predicate.trait_ref.def_id));
573            }
574
575            // This maybe belongs in wf, but that can't (doesn't) handle
576            // higher-ranked things.
577            // Prevent, e.g., `dyn Iterator<Item = str>`.
578            for bound in self.tcx().item_bounds(assoc_type).transpose_iter() {
579                let normalized_bound = normalize_with_depth_to(
580                    self,
581                    obligation.param_env,
582                    obligation.cause.clone(),
583                    obligation.recursion_depth + 1,
584                    bound.instantiate(tcx, trait_predicate.trait_ref.args),
585                    &mut nested,
586                );
587                nested.push(obligation.with(tcx, normalized_bound));
588            }
589        }
590
591        debug!(?nested, "object nested obligations");
592
593        Ok(ImplSource::Builtin(BuiltinImplSource::Object(index), nested))
594    }
595
596    fn confirm_fn_pointer_candidate(
597        &mut self,
598        obligation: &PolyTraitObligation<'tcx>,
599    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
600        debug!(?obligation, "confirm_fn_pointer_candidate");
601        let placeholder_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
602        let self_ty = self.infcx.shallow_resolve(placeholder_predicate.self_ty());
603
604        let tcx = self.tcx();
605        let sig = self_ty.fn_sig(tcx);
606        let trait_ref = closure_trait_ref_and_return_type(
607            tcx,
608            obligation.predicate.def_id(),
609            self_ty,
610            sig,
611            util::TupleArgumentsFlag::Yes,
612        )
613        .map_bound(|(trait_ref, _)| trait_ref);
614
615        let mut nested =
616            self.equate_trait_refs(obligation.with(tcx, placeholder_predicate), trait_ref)?;
617        let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerived);
618
619        // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
620        let output_ty = self.infcx.enter_forall_and_leak_universe(sig.output());
621        let output_ty = normalize_with_depth_to(
622            self,
623            obligation.param_env,
624            cause.clone(),
625            obligation.recursion_depth,
626            output_ty,
627            &mut nested,
628        );
629        let tr = ty::TraitRef::new(
630            self.tcx(),
631            self.tcx().require_lang_item(LangItem::Sized, cause.span),
632            [output_ty],
633        );
634        nested.push(Obligation::new(self.infcx.tcx, cause, obligation.param_env, tr));
635
636        Ok(nested)
637    }
638
639    fn confirm_pointer_like_candidate(
640        &mut self,
641        obligation: &PolyTraitObligation<'tcx>,
642    ) -> PredicateObligations<'tcx> {
643        debug!(?obligation, "confirm_pointer_like_candidate");
644        let placeholder_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
645        let self_ty = self.infcx.shallow_resolve(placeholder_predicate.self_ty());
646        let ty::Pat(base, _) = *self_ty.kind() else { bug!() };
647        let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerived);
648
649        self.collect_predicates_for_types(
650            obligation.param_env,
651            cause,
652            obligation.recursion_depth + 1,
653            placeholder_predicate.def_id(),
654            vec![base],
655        )
656    }
657
658    fn confirm_trait_alias_candidate(
659        &mut self,
660        obligation: &PolyTraitObligation<'tcx>,
661    ) -> PredicateObligations<'tcx> {
662        debug!(?obligation, "confirm_trait_alias_candidate");
663
664        let predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
665        let trait_ref = predicate.trait_ref;
666        let trait_def_id = trait_ref.def_id;
667        let args = trait_ref.args;
668
669        let trait_obligations = self.impl_or_trait_obligations(
670            &obligation.cause,
671            obligation.recursion_depth,
672            obligation.param_env,
673            trait_def_id,
674            args,
675            obligation.predicate,
676        );
677
678        debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
679
680        trait_obligations
681    }
682
683    fn confirm_coroutine_candidate(
684        &mut self,
685        obligation: &PolyTraitObligation<'tcx>,
686    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
687        let placeholder_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
688        let self_ty = self.infcx.shallow_resolve(placeholder_predicate.self_ty());
689        let ty::Coroutine(coroutine_def_id, args) = *self_ty.kind() else {
690            bug!("closure candidate for non-closure {:?}", obligation);
691        };
692
693        debug!(?obligation, ?coroutine_def_id, ?args, "confirm_coroutine_candidate");
694
695        let coroutine_sig = args.as_coroutine().sig();
696
697        let (trait_ref, _, _) = super::util::coroutine_trait_ref_and_outputs(
698            self.tcx(),
699            obligation.predicate.def_id(),
700            self_ty,
701            coroutine_sig,
702        );
703
704        let nested = self.equate_trait_refs(
705            obligation.with(self.tcx(), placeholder_predicate),
706            ty::Binder::dummy(trait_ref),
707        )?;
708        debug!(?trait_ref, ?nested, "coroutine candidate obligations");
709
710        Ok(nested)
711    }
712
713    fn confirm_future_candidate(
714        &mut self,
715        obligation: &PolyTraitObligation<'tcx>,
716    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
717        let placeholder_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
718        let self_ty = self.infcx.shallow_resolve(placeholder_predicate.self_ty());
719        let ty::Coroutine(coroutine_def_id, args) = *self_ty.kind() else {
720            bug!("closure candidate for non-closure {:?}", obligation);
721        };
722
723        debug!(?obligation, ?coroutine_def_id, ?args, "confirm_future_candidate");
724
725        let coroutine_sig = args.as_coroutine().sig();
726
727        let (trait_ref, _) = super::util::future_trait_ref_and_outputs(
728            self.tcx(),
729            obligation.predicate.def_id(),
730            self_ty,
731            coroutine_sig,
732        );
733
734        let nested = self.equate_trait_refs(
735            obligation.with(self.tcx(), placeholder_predicate),
736            ty::Binder::dummy(trait_ref),
737        )?;
738        debug!(?trait_ref, ?nested, "future candidate obligations");
739
740        Ok(nested)
741    }
742
743    fn confirm_iterator_candidate(
744        &mut self,
745        obligation: &PolyTraitObligation<'tcx>,
746    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
747        let placeholder_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
748        let self_ty = self.infcx.shallow_resolve(placeholder_predicate.self_ty());
749        let ty::Coroutine(coroutine_def_id, args) = *self_ty.kind() else {
750            bug!("closure candidate for non-closure {:?}", obligation);
751        };
752
753        debug!(?obligation, ?coroutine_def_id, ?args, "confirm_iterator_candidate");
754
755        let gen_sig = args.as_coroutine().sig();
756
757        let (trait_ref, _) = super::util::iterator_trait_ref_and_outputs(
758            self.tcx(),
759            obligation.predicate.def_id(),
760            self_ty,
761            gen_sig,
762        );
763
764        let nested = self.equate_trait_refs(
765            obligation.with(self.tcx(), placeholder_predicate),
766            ty::Binder::dummy(trait_ref),
767        )?;
768        debug!(?trait_ref, ?nested, "iterator candidate obligations");
769
770        Ok(nested)
771    }
772
773    fn confirm_async_iterator_candidate(
774        &mut self,
775        obligation: &PolyTraitObligation<'tcx>,
776    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
777        let placeholder_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
778        let self_ty = self.infcx.shallow_resolve(placeholder_predicate.self_ty());
779        let ty::Coroutine(coroutine_def_id, args) = *self_ty.kind() else {
780            bug!("closure candidate for non-closure {:?}", obligation);
781        };
782
783        debug!(?obligation, ?coroutine_def_id, ?args, "confirm_async_iterator_candidate");
784
785        let gen_sig = args.as_coroutine().sig();
786
787        let (trait_ref, _) = super::util::async_iterator_trait_ref_and_outputs(
788            self.tcx(),
789            obligation.predicate.def_id(),
790            self_ty,
791            gen_sig,
792        );
793
794        let nested = self.equate_trait_refs(
795            obligation.with(self.tcx(), placeholder_predicate),
796            ty::Binder::dummy(trait_ref),
797        )?;
798        debug!(?trait_ref, ?nested, "iterator candidate obligations");
799
800        Ok(nested)
801    }
802
803    #[instrument(skip(self), level = "debug")]
804    fn confirm_closure_candidate(
805        &mut self,
806        obligation: &PolyTraitObligation<'tcx>,
807    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
808        let placeholder_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
809        let self_ty: Ty<'_> = self.infcx.shallow_resolve(placeholder_predicate.self_ty());
810
811        let trait_ref = match *self_ty.kind() {
812            ty::Closure(..) => {
813                self.closure_trait_ref_unnormalized(self_ty, obligation.predicate.def_id())
814            }
815            ty::CoroutineClosure(_, args) => {
816                args.as_coroutine_closure().coroutine_closure_sig().map_bound(|sig| {
817                    ty::TraitRef::new(
818                        self.tcx(),
819                        obligation.predicate.def_id(),
820                        [self_ty, sig.tupled_inputs_ty],
821                    )
822                })
823            }
824            _ => {
825                bug!("closure candidate for non-closure {:?}", obligation);
826            }
827        };
828
829        self.equate_trait_refs(obligation.with(self.tcx(), placeholder_predicate), trait_ref)
830    }
831
832    #[instrument(skip(self), level = "debug")]
833    fn confirm_async_closure_candidate(
834        &mut self,
835        obligation: &PolyTraitObligation<'tcx>,
836    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
837        let placeholder_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
838        let self_ty = self.infcx.shallow_resolve(placeholder_predicate.self_ty());
839
840        let tcx = self.tcx();
841
842        let mut nested = PredicateObligations::new();
843        let (trait_ref, kind_ty) = match *self_ty.kind() {
844            ty::CoroutineClosure(_, args) => {
845                let args = args.as_coroutine_closure();
846                let trait_ref = args.coroutine_closure_sig().map_bound(|sig| {
847                    ty::TraitRef::new(
848                        self.tcx(),
849                        obligation.predicate.def_id(),
850                        [self_ty, sig.tupled_inputs_ty],
851                    )
852                });
853
854                // Note that unlike below, we don't need to check `Future + Sized` for
855                // the output coroutine because they are `Future + Sized` by construction.
856
857                (trait_ref, args.kind_ty())
858            }
859            ty::FnDef(..) | ty::FnPtr(..) => {
860                let sig = self_ty.fn_sig(tcx);
861                let trait_ref = sig.map_bound(|sig| {
862                    ty::TraitRef::new(
863                        self.tcx(),
864                        obligation.predicate.def_id(),
865                        [self_ty, Ty::new_tup(tcx, sig.inputs())],
866                    )
867                });
868
869                // We must additionally check that the return type impls `Future + Sized`.
870                let future_trait_def_id =
871                    tcx.require_lang_item(LangItem::Future, obligation.cause.span);
872                nested.push(obligation.with(
873                    tcx,
874                    sig.output().map_bound(|output_ty| {
875                        ty::TraitRef::new(tcx, future_trait_def_id, [output_ty])
876                    }),
877                ));
878                let sized_trait_def_id =
879                    tcx.require_lang_item(LangItem::Sized, obligation.cause.span);
880                nested.push(obligation.with(
881                    tcx,
882                    sig.output().map_bound(|output_ty| {
883                        ty::TraitRef::new(tcx, sized_trait_def_id, [output_ty])
884                    }),
885                ));
886
887                (trait_ref, Ty::from_closure_kind(tcx, ty::ClosureKind::Fn))
888            }
889            ty::Closure(_, args) => {
890                let args = args.as_closure();
891                let sig = args.sig();
892                let trait_ref = sig.map_bound(|sig| {
893                    ty::TraitRef::new(
894                        self.tcx(),
895                        obligation.predicate.def_id(),
896                        [self_ty, sig.inputs()[0]],
897                    )
898                });
899
900                // We must additionally check that the return type impls `Future + Sized`.
901                let future_trait_def_id =
902                    tcx.require_lang_item(LangItem::Future, obligation.cause.span);
903                let placeholder_output_ty = self.infcx.enter_forall_and_leak_universe(sig.output());
904                nested.push(obligation.with(
905                    tcx,
906                    ty::TraitRef::new(tcx, future_trait_def_id, [placeholder_output_ty]),
907                ));
908                let sized_trait_def_id =
909                    tcx.require_lang_item(LangItem::Sized, obligation.cause.span);
910                nested.push(obligation.with(
911                    tcx,
912                    sig.output().map_bound(|output_ty| {
913                        ty::TraitRef::new(tcx, sized_trait_def_id, [output_ty])
914                    }),
915                ));
916
917                (trait_ref, args.kind_ty())
918            }
919            _ => bug!("expected callable type for AsyncFn candidate"),
920        };
921
922        nested.extend(
923            self.equate_trait_refs(obligation.with(tcx, placeholder_predicate), trait_ref)?,
924        );
925
926        let goal_kind =
927            self.tcx().async_fn_trait_kind_from_def_id(obligation.predicate.def_id()).unwrap();
928
929        // If we have not yet determined the `ClosureKind` of the closure or coroutine-closure,
930        // then additionally register an `AsyncFnKindHelper` goal which will fail if the kind
931        // is constrained to an insufficient type later on.
932        if let Some(closure_kind) = self.infcx.shallow_resolve(kind_ty).to_opt_closure_kind() {
933            if !closure_kind.extends(goal_kind) {
934                return Err(SelectionError::Unimplemented);
935            }
936        } else {
937            nested.push(Obligation::new(
938                self.tcx(),
939                obligation.derived_cause(ObligationCauseCode::BuiltinDerived),
940                obligation.param_env,
941                ty::TraitRef::new(
942                    self.tcx(),
943                    self.tcx()
944                        .require_lang_item(LangItem::AsyncFnKindHelper, obligation.cause.span),
945                    [kind_ty, Ty::from_closure_kind(self.tcx(), goal_kind)],
946                ),
947            ));
948        }
949
950        Ok(nested)
951    }
952
953    /// In the case of closure types and fn pointers,
954    /// we currently treat the input type parameters on the trait as
955    /// outputs. This means that when we have a match we have only
956    /// considered the self type, so we have to go back and make sure
957    /// to relate the argument types too. This is kind of wrong, but
958    /// since we control the full set of impls, also not that wrong,
959    /// and it DOES yield better error messages (since we don't report
960    /// errors as if there is no applicable impl, but rather report
961    /// errors are about mismatched argument types.
962    ///
963    /// Here is an example. Imagine we have a closure expression
964    /// and we desugared it so that the type of the expression is
965    /// `Closure`, and `Closure` expects `i32` as argument. Then it
966    /// is "as if" the compiler generated this impl:
967    /// ```ignore (illustrative)
968    /// impl Fn(i32) for Closure { ... }
969    /// ```
970    /// Now imagine our obligation is `Closure: Fn(usize)`. So far
971    /// we have matched the self type `Closure`. At this point we'll
972    /// compare the `i32` to `usize` and generate an error.
973    ///
974    /// Note that this checking occurs *after* the impl has selected,
975    /// because these output type parameters should not affect the
976    /// selection of the impl. Therefore, if there is a mismatch, we
977    /// report an error to the user.
978    #[instrument(skip(self), level = "trace")]
979    fn equate_trait_refs(
980        &mut self,
981        obligation: TraitObligation<'tcx>,
982        found_trait_ref: ty::PolyTraitRef<'tcx>,
983    ) -> Result<PredicateObligations<'tcx>, SelectionError<'tcx>> {
984        let found_trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
985            obligation.cause.span,
986            BoundRegionConversionTime::HigherRankedType,
987            found_trait_ref,
988        );
989        // Normalize the obligation and expected trait refs together, because why not
990        let Normalized { obligations: nested, value: (obligation_trait_ref, found_trait_ref) } =
991            ensure_sufficient_stack(|| {
992                normalize_with_depth(
993                    self,
994                    obligation.param_env,
995                    obligation.cause.clone(),
996                    obligation.recursion_depth + 1,
997                    (obligation.predicate.trait_ref, found_trait_ref),
998                )
999            });
1000
1001        // needed to define opaque types for tests/ui/type-alias-impl-trait/assoc-projection-ice.rs
1002        self.infcx
1003            .at(&obligation.cause, obligation.param_env)
1004            .eq(DefineOpaqueTypes::Yes, obligation_trait_ref, found_trait_ref)
1005            .map(|InferOk { mut obligations, .. }| {
1006                obligations.extend(nested);
1007                obligations
1008            })
1009            .map_err(|terr| {
1010                SelectionError::SignatureMismatch(Box::new(SignatureMismatchData {
1011                    expected_trait_ref: obligation_trait_ref,
1012                    found_trait_ref,
1013                    terr,
1014                }))
1015            })
1016    }
1017
1018    fn confirm_trait_upcasting_unsize_candidate(
1019        &mut self,
1020        obligation: &PolyTraitObligation<'tcx>,
1021        idx: usize,
1022    ) -> Result<ImplSource<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1023        let tcx = self.tcx();
1024
1025        // `assemble_candidates_for_unsizing` should ensure there are no late-bound
1026        // regions here. See the comment there for more details.
1027        let predicate = obligation.predicate.no_bound_vars().unwrap();
1028        let a_ty = self.infcx.shallow_resolve(predicate.self_ty());
1029        let b_ty = self.infcx.shallow_resolve(predicate.trait_ref.args.type_at(1));
1030
1031        let ty::Dynamic(a_data, a_region) = *a_ty.kind() else {
1032            bug!("expected `dyn` type in `confirm_trait_upcasting_unsize_candidate`")
1033        };
1034        let ty::Dynamic(b_data, b_region) = *b_ty.kind() else {
1035            bug!("expected `dyn` type in `confirm_trait_upcasting_unsize_candidate`")
1036        };
1037
1038        let source_principal = a_data.principal().unwrap().with_self_ty(tcx, a_ty);
1039        let unnormalized_upcast_principal =
1040            util::supertraits(tcx, source_principal).nth(idx).unwrap();
1041
1042        let nested = self
1043            .match_upcast_principal(
1044                obligation,
1045                unnormalized_upcast_principal,
1046                a_data,
1047                b_data,
1048                a_region,
1049                b_region,
1050            )?
1051            .expect("did not expect ambiguity during confirmation");
1052
1053        Ok(ImplSource::Builtin(BuiltinImplSource::TraitUpcasting(idx), nested))
1054    }
1055
1056    fn confirm_builtin_unsize_candidate(
1057        &mut self,
1058        obligation: &PolyTraitObligation<'tcx>,
1059    ) -> Result<ImplSource<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1060        let tcx = self.tcx();
1061
1062        // `assemble_candidates_for_unsizing` should ensure there are no late-bound
1063        // regions here. See the comment there for more details.
1064        let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
1065        let target = obligation.predicate.skip_binder().trait_ref.args.type_at(1);
1066        let target = self.infcx.shallow_resolve(target);
1067        debug!(?source, ?target, "confirm_builtin_unsize_candidate");
1068
1069        Ok(match (source.kind(), target.kind()) {
1070            // `dyn Trait + Kx + 'a` -> `dyn Trait + Ky + 'b` (auto traits and lifetime subtyping).
1071            (&ty::Dynamic(data_a, r_a), &ty::Dynamic(data_b, r_b)) => {
1072                // See `assemble_candidates_for_unsizing` for more info.
1073                // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
1074                let existential_predicates = if data_b.principal().is_some() {
1075                    tcx.mk_poly_existential_predicates_from_iter(
1076                        data_a
1077                            .principal()
1078                            .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
1079                            .into_iter()
1080                            .chain(
1081                                data_a
1082                                    .projection_bounds()
1083                                    .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
1084                            )
1085                            .chain(
1086                                data_b
1087                                    .auto_traits()
1088                                    .map(ty::ExistentialPredicate::AutoTrait)
1089                                    .map(ty::Binder::dummy),
1090                            ),
1091                    )
1092                } else {
1093                    // If we're unsizing to a dyn type that has no principal, then drop
1094                    // the principal and projections from the type. We use the auto traits
1095                    // from the RHS type since as we noted that we've checked for auto
1096                    // trait compatibility during unsizing.
1097                    tcx.mk_poly_existential_predicates_from_iter(
1098                        data_b
1099                            .auto_traits()
1100                            .map(ty::ExistentialPredicate::AutoTrait)
1101                            .map(ty::Binder::dummy),
1102                    )
1103                };
1104                let source_trait = Ty::new_dynamic(tcx, existential_predicates, r_b);
1105
1106                // Require that the traits involved in this upcast are **equal**;
1107                // only the **lifetime bound** is changed.
1108                let InferOk { mut obligations, .. } = self
1109                    .infcx
1110                    .at(&obligation.cause, obligation.param_env)
1111                    .sup(DefineOpaqueTypes::Yes, target, source_trait)
1112                    .map_err(|_| SelectionError::Unimplemented)?;
1113
1114                // Register one obligation for 'a: 'b.
1115                let outlives = ty::OutlivesPredicate(r_a, r_b);
1116                obligations.push(Obligation::with_depth(
1117                    tcx,
1118                    obligation.cause.clone(),
1119                    obligation.recursion_depth + 1,
1120                    obligation.param_env,
1121                    obligation.predicate.rebind(outlives),
1122                ));
1123
1124                ImplSource::Builtin(BuiltinImplSource::Misc, obligations)
1125            }
1126
1127            // `T` -> `dyn Trait`
1128            (_, &ty::Dynamic(data, r)) => {
1129                let mut object_dids = data.auto_traits().chain(data.principal_def_id());
1130                if let Some(did) = object_dids.find(|did| !tcx.is_dyn_compatible(*did)) {
1131                    return Err(SelectionError::TraitDynIncompatible(did));
1132                }
1133
1134                let predicate_to_obligation = |predicate| {
1135                    Obligation::with_depth(
1136                        tcx,
1137                        obligation.cause.clone(),
1138                        obligation.recursion_depth + 1,
1139                        obligation.param_env,
1140                        predicate,
1141                    )
1142                };
1143
1144                // Create obligations:
1145                //  - Casting `T` to `Trait`
1146                //  - For all the various builtin bounds attached to the object cast. (In other
1147                //  words, if the object type is `Foo + Send`, this would create an obligation for
1148                //  the `Send` check.)
1149                //  - Projection predicates
1150                let mut nested: PredicateObligations<'_> = data
1151                    .iter()
1152                    .map(|predicate| predicate_to_obligation(predicate.with_self_ty(tcx, source)))
1153                    .collect();
1154
1155                // We can only make objects from sized types.
1156                let tr = ty::TraitRef::new(
1157                    tcx,
1158                    tcx.require_lang_item(LangItem::Sized, obligation.cause.span),
1159                    [source],
1160                );
1161                nested.push(predicate_to_obligation(tr.upcast(tcx)));
1162
1163                // If the type is `Foo + 'a`, ensure that the type
1164                // being cast to `Foo + 'a` outlives `'a`:
1165                let outlives = ty::OutlivesPredicate(source, r);
1166                nested.push(predicate_to_obligation(
1167                    ty::ClauseKind::TypeOutlives(outlives).upcast(tcx),
1168                ));
1169
1170                ImplSource::Builtin(BuiltinImplSource::Misc, nested)
1171            }
1172
1173            // `[T; n]` -> `[T]`
1174            (&ty::Array(a, _), &ty::Slice(b)) => {
1175                let InferOk { obligations, .. } = self
1176                    .infcx
1177                    .at(&obligation.cause, obligation.param_env)
1178                    .eq(DefineOpaqueTypes::Yes, b, a)
1179                    .map_err(|_| SelectionError::Unimplemented)?;
1180
1181                ImplSource::Builtin(BuiltinImplSource::Misc, obligations)
1182            }
1183
1184            // `Struct<T>` -> `Struct<U>`
1185            (&ty::Adt(def, args_a), &ty::Adt(_, args_b)) => {
1186                let unsizing_params = tcx.unsizing_params_for_adt(def.did());
1187                if unsizing_params.is_empty() {
1188                    return Err(SelectionError::Unimplemented);
1189                }
1190
1191                let tail_field = def.non_enum_variant().tail();
1192                let tail_field_ty = tcx.type_of(tail_field.did);
1193
1194                let mut nested = PredicateObligations::new();
1195
1196                // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
1197                // normalizing in the process, since `type_of` returns something directly from
1198                // HIR ty lowering (which means it's un-normalized).
1199                let source_tail = normalize_with_depth_to(
1200                    self,
1201                    obligation.param_env,
1202                    obligation.cause.clone(),
1203                    obligation.recursion_depth + 1,
1204                    tail_field_ty.instantiate(tcx, args_a),
1205                    &mut nested,
1206                );
1207                let target_tail = normalize_with_depth_to(
1208                    self,
1209                    obligation.param_env,
1210                    obligation.cause.clone(),
1211                    obligation.recursion_depth + 1,
1212                    tail_field_ty.instantiate(tcx, args_b),
1213                    &mut nested,
1214                );
1215
1216                // Check that the source struct with the target's
1217                // unsizing parameters is equal to the target.
1218                let args =
1219                    tcx.mk_args_from_iter(args_a.iter().enumerate().map(|(i, k)| {
1220                        if unsizing_params.contains(i as u32) { args_b[i] } else { k }
1221                    }));
1222                let new_struct = Ty::new_adt(tcx, def, args);
1223                let InferOk { obligations, .. } = self
1224                    .infcx
1225                    .at(&obligation.cause, obligation.param_env)
1226                    .eq(DefineOpaqueTypes::Yes, target, new_struct)
1227                    .map_err(|_| SelectionError::Unimplemented)?;
1228                nested.extend(obligations);
1229
1230                // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1231                let tail_unsize_obligation = obligation.with(
1232                    tcx,
1233                    ty::TraitRef::new(
1234                        tcx,
1235                        obligation.predicate.def_id(),
1236                        [source_tail, target_tail],
1237                    ),
1238                );
1239                nested.push(tail_unsize_obligation);
1240
1241                ImplSource::Builtin(BuiltinImplSource::Misc, nested)
1242            }
1243
1244            _ => bug!("source: {source}, target: {target}"),
1245        })
1246    }
1247
1248    fn confirm_bikeshed_guaranteed_no_drop_candidate(
1249        &mut self,
1250        obligation: &PolyTraitObligation<'tcx>,
1251    ) -> ImplSource<'tcx, PredicateObligation<'tcx>> {
1252        let mut obligations = thin_vec![];
1253
1254        let tcx = self.tcx();
1255        let self_ty = obligation.predicate.self_ty();
1256        match *self_ty.skip_binder().kind() {
1257            // `&mut T` and `&T` always implement `BikeshedGuaranteedNoDrop`.
1258            ty::Ref(..) => {}
1259            // `ManuallyDrop<T>` always implements `BikeshedGuaranteedNoDrop`.
1260            ty::Adt(def, _) if def.is_manually_drop() => {}
1261            // Arrays and tuples implement `BikeshedGuaranteedNoDrop` only if
1262            // their constituent types implement `BikeshedGuaranteedNoDrop`.
1263            ty::Tuple(tys) => {
1264                obligations.extend(tys.iter().map(|elem_ty| {
1265                    obligation.with(
1266                        tcx,
1267                        self_ty.rebind(ty::TraitRef::new(
1268                            tcx,
1269                            obligation.predicate.def_id(),
1270                            [elem_ty],
1271                        )),
1272                    )
1273                }));
1274            }
1275            ty::Array(elem_ty, _) => {
1276                obligations.push(obligation.with(
1277                    tcx,
1278                    self_ty.rebind(ty::TraitRef::new(
1279                        tcx,
1280                        obligation.predicate.def_id(),
1281                        [elem_ty],
1282                    )),
1283                ));
1284            }
1285
1286            // All other types implement `BikeshedGuaranteedNoDrop` only if
1287            // they implement `Copy`. We could be smart here and short-circuit
1288            // some trivially `Copy`/`!Copy` types, but there's no benefit.
1289            ty::FnDef(..)
1290            | ty::FnPtr(..)
1291            | ty::Error(_)
1292            | ty::Uint(_)
1293            | ty::Int(_)
1294            | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
1295            | ty::Bool
1296            | ty::Float(_)
1297            | ty::Char
1298            | ty::RawPtr(..)
1299            | ty::Never
1300            | ty::Pat(..)
1301            | ty::Dynamic(..)
1302            | ty::Str
1303            | ty::Slice(_)
1304            | ty::Foreign(..)
1305            | ty::Adt(..)
1306            | ty::Alias(..)
1307            | ty::Param(_)
1308            | ty::Placeholder(..)
1309            | ty::Closure(..)
1310            | ty::CoroutineClosure(..)
1311            | ty::Coroutine(..)
1312            | ty::UnsafeBinder(_)
1313            | ty::CoroutineWitness(..)
1314            | ty::Bound(..) => {
1315                obligations.push(obligation.with(
1316                    tcx,
1317                    self_ty.map_bound(|ty| {
1318                        ty::TraitRef::new(
1319                            tcx,
1320                            tcx.require_lang_item(LangItem::Copy, obligation.cause.span),
1321                            [ty],
1322                        )
1323                    }),
1324                ));
1325            }
1326
1327            ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
1328                panic!("unexpected type `{self_ty:?}`")
1329            }
1330        }
1331
1332        ImplSource::Builtin(BuiltinImplSource::Misc, obligations)
1333    }
1334}