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.
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_infer::infer::InferOk;
12 use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType;
13 use rustc_middle::ty::{
14 self, Binder, GenericParamDefKind, InternalSubsts, SubstsRef, ToPolyTraitRef, ToPredicate,
15 TraitRef, Ty, TyCtxt, TypeVisitable,
17 use rustc_session::config::TraitSolver;
18 use rustc_span::def_id::DefId;
20 use crate::traits::project::{normalize_with_depth, normalize_with_depth_to};
21 use crate::traits::util::{self, closure_trait_ref_and_return_type, predicate_for_trait_def};
22 use crate::traits::vtable::{
23 count_own_vtable_entries, prepare_vtable_segments, vtable_trait_first_method_offset,
27 BuiltinDerivedObligation, ImplDerivedObligation, ImplDerivedObligationCause, ImplSource,
28 ImplSourceAutoImplData, ImplSourceBuiltinData, ImplSourceClosureData,
29 ImplSourceConstDestructData, ImplSourceFnPointerData, ImplSourceFutureData,
30 ImplSourceGeneratorData, ImplSourceObjectData, ImplSourceTraitAliasData,
31 ImplSourceTraitUpcastingData, ImplSourceUserDefinedData, Normalized, ObjectCastObligation,
32 Obligation, ObligationCause, OutputTypeParameterMismatch, PredicateObligation, Selection,
33 SelectionError, TraitNotObjectSafe, TraitObligation, Unimplemented,
36 use super::BuiltinImplConditions;
37 use super::SelectionCandidate::{self, *};
38 use super::SelectionContext;
41 use std::ops::ControlFlow;
43 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
44 #[instrument(level = "debug", skip(self))]
45 pub(super) fn confirm_candidate(
47 obligation: &TraitObligation<'tcx>,
48 candidate: SelectionCandidate<'tcx>,
49 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
50 let mut impl_src = match candidate {
51 BuiltinCandidate { has_nested } => {
52 let data = self.confirm_builtin_candidate(obligation, has_nested);
53 ImplSource::Builtin(data)
56 TransmutabilityCandidate => {
57 let data = self.confirm_transmutability_candidate(obligation)?;
58 ImplSource::Builtin(data)
61 ParamCandidate(param) => {
63 self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref));
64 ImplSource::Param(obligations, param.skip_binder().constness)
67 ImplCandidate(impl_def_id) => {
68 ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id))
71 AutoImplCandidate => {
72 let data = self.confirm_auto_impl_candidate(obligation);
73 ImplSource::AutoImpl(data)
76 ProjectionCandidate(idx, constness) => {
77 let obligations = self.confirm_projection_candidate(obligation, idx)?;
78 ImplSource::Param(obligations, constness)
81 ObjectCandidate(idx) => {
82 let data = self.confirm_object_candidate(obligation, idx)?;
83 ImplSource::Object(data)
86 ClosureCandidate { .. } => {
87 let vtable_closure = self.confirm_closure_candidate(obligation)?;
88 ImplSource::Closure(vtable_closure)
91 GeneratorCandidate => {
92 let vtable_generator = self.confirm_generator_candidate(obligation)?;
93 ImplSource::Generator(vtable_generator)
97 let vtable_future = self.confirm_future_candidate(obligation)?;
98 ImplSource::Future(vtable_future)
101 FnPointerCandidate { is_const } => {
102 let data = self.confirm_fn_pointer_candidate(obligation, is_const)?;
103 ImplSource::FnPointer(data)
106 TraitAliasCandidate => {
107 let data = self.confirm_trait_alias_candidate(obligation);
108 ImplSource::TraitAlias(data)
111 BuiltinObjectCandidate => {
112 // This indicates something like `Trait + Send: Send`. In this case, we know that
113 // this holds because that's what the object type is telling us, and there's really
114 // no additional obligations to prove and no types in particular to unify, etc.
115 ImplSource::Param(Vec::new(), ty::BoundConstness::NotConst)
118 BuiltinUnsizeCandidate => {
119 let data = self.confirm_builtin_unsize_candidate(obligation)?;
120 ImplSource::Builtin(data)
123 TraitUpcastingUnsizeCandidate(idx) => {
124 let data = self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?;
125 ImplSource::TraitUpcasting(data)
128 ConstDestructCandidate(def_id) => {
129 let data = self.confirm_const_destruct_candidate(obligation, def_id)?;
130 ImplSource::ConstDestruct(data)
134 if !obligation.predicate.is_const_if_const() {
135 // normalize nested predicates according to parent predicate's constness.
136 impl_src = impl_src.map(|mut o| {
137 o.predicate = o.predicate.without_const(self.tcx());
145 fn confirm_projection_candidate(
147 obligation: &TraitObligation<'tcx>,
149 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
150 let tcx = self.tcx();
152 let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
153 let placeholder_trait_predicate =
154 self.infcx.replace_bound_vars_with_placeholders(trait_predicate).trait_ref;
155 let placeholder_self_ty = placeholder_trait_predicate.self_ty();
156 let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate);
157 let (def_id, substs) = match *placeholder_self_ty.kind() {
158 ty::Alias(_, ty::AliasTy { def_id, substs, .. }) => (def_id, substs),
159 _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
162 let candidate_predicate = tcx.item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs);
163 let candidate = candidate_predicate
164 .to_opt_poly_trait_pred()
165 .expect("projection candidate is not a trait predicate")
166 .map_bound(|t| t.trait_ref);
167 let mut obligations = Vec::new();
168 let candidate = normalize_with_depth_to(
170 obligation.param_env,
171 obligation.cause.clone(),
172 obligation.recursion_depth + 1,
177 obligations.extend(self.infcx.commit_if_ok(|_| {
179 .at(&obligation.cause, obligation.param_env)
180 .sup(placeholder_trait_predicate, candidate)
181 .map(|InferOk { obligations, .. }| obligations)
182 .map_err(|_| Unimplemented)
185 if let ty::Alias(ty::Projection, ..) = placeholder_self_ty.kind() {
186 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
187 for (predicate, _) in predicates {
188 let normalized = normalize_with_depth_to(
190 obligation.param_env,
191 obligation.cause.clone(),
192 obligation.recursion_depth + 1,
196 obligations.push(Obligation::with_depth(
198 obligation.cause.clone(),
199 obligation.recursion_depth + 1,
200 obligation.param_env,
209 fn confirm_param_candidate(
211 obligation: &TraitObligation<'tcx>,
212 param: ty::PolyTraitRef<'tcx>,
213 ) -> Vec<PredicateObligation<'tcx>> {
214 debug!(?obligation, ?param, "confirm_param_candidate");
216 // During evaluation, we already checked that this
217 // where-clause trait-ref could be unified with the obligation
218 // trait-ref. Repeat that unification now without any
219 // transactional boundary; it should not fail.
220 match self.match_where_clause_trait_ref(obligation, param) {
221 Ok(obligations) => obligations,
224 "Where clause `{:?}` was applicable to `{:?}` but now is not",
232 fn confirm_builtin_candidate(
234 obligation: &TraitObligation<'tcx>,
236 ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
237 debug!(?obligation, ?has_nested, "confirm_builtin_candidate");
239 let lang_items = self.tcx().lang_items();
240 let obligations = if has_nested {
241 let trait_def = obligation.predicate.def_id();
242 let conditions = if Some(trait_def) == lang_items.sized_trait() {
243 self.sized_conditions(obligation)
244 } else if Some(trait_def) == lang_items.copy_trait() {
245 self.copy_clone_conditions(obligation)
246 } else if Some(trait_def) == lang_items.clone_trait() {
247 self.copy_clone_conditions(obligation)
249 bug!("unexpected builtin trait {:?}", trait_def)
251 let BuiltinImplConditions::Where(nested) = conditions else {
252 bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
255 let cause = obligation.derived_cause(BuiltinDerivedObligation);
256 ensure_sufficient_stack(|| {
257 self.collect_predicates_for_types(
258 obligation.param_env,
260 obligation.recursion_depth + 1,
269 debug!(?obligations);
271 ImplSourceBuiltinData { nested: obligations }
274 fn confirm_transmutability_candidate(
276 obligation: &TraitObligation<'tcx>,
277 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
278 debug!(?obligation, "confirm_transmutability_candidate");
280 let predicate = obligation.predicate;
282 let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i));
283 let const_at = |i| predicate.skip_binder().trait_ref.substs.const_at(i);
285 let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types {
286 dst: p.trait_ref.substs.type_at(0),
287 src: p.trait_ref.substs.type_at(1),
290 let scope = type_at(2).skip_binder();
293 rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, const_at(3)) else {
294 return Err(Unimplemented);
297 let cause = obligation.cause.clone();
299 let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
301 let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume);
303 use rustc_transmute::Answer;
305 match maybe_transmutable {
306 Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }),
307 _ => Err(Unimplemented),
311 /// This handles the case where an `auto trait Foo` impl is being used.
312 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
314 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
315 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
316 fn confirm_auto_impl_candidate(
318 obligation: &TraitObligation<'tcx>,
319 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
320 debug!(?obligation, "confirm_auto_impl_candidate");
322 let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
323 let types = self.constituent_types_for_ty(self_ty);
324 self.vtable_auto_impl(obligation, obligation.predicate.def_id(), types)
327 /// See `confirm_auto_impl_candidate`.
330 obligation: &TraitObligation<'tcx>,
332 nested: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
333 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
334 debug!(?nested, "vtable_auto_impl");
335 ensure_sufficient_stack(|| {
336 let cause = obligation.derived_cause(BuiltinDerivedObligation);
338 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
339 let trait_ref = self.infcx.replace_bound_vars_with_placeholders(poly_trait_ref);
340 let trait_obligations: Vec<PredicateObligation<'_>> = self.impl_or_trait_obligations(
342 obligation.recursion_depth + 1,
343 obligation.param_env,
346 obligation.predicate,
349 let mut obligations = self.collect_predicates_for_types(
350 obligation.param_env,
352 obligation.recursion_depth + 1,
357 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
358 // predicate as usual. It won't have any effect since auto traits are coinductive.
359 obligations.extend(trait_obligations);
361 debug!(?obligations, "vtable_auto_impl");
363 ImplSourceAutoImplData { trait_def_id, nested: obligations }
367 fn confirm_impl_candidate(
369 obligation: &TraitObligation<'tcx>,
371 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
372 debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");
374 // First, create the substitutions by matching the impl again,
375 // this time not in a probe.
376 let substs = self.rematch_impl(impl_def_id, obligation);
377 debug!(?substs, "impl substs");
378 ensure_sufficient_stack(|| {
383 obligation.recursion_depth + 1,
384 obligation.param_env,
385 obligation.predicate,
393 substs: Normalized<'tcx, SubstsRef<'tcx>>,
394 cause: &ObligationCause<'tcx>,
395 recursion_depth: usize,
396 param_env: ty::ParamEnv<'tcx>,
397 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
398 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
399 debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl");
401 let mut impl_obligations = self.impl_or_trait_obligations(
410 debug!(?impl_obligations, "vtable_impl");
412 // Because of RFC447, the impl-trait-ref and obligations
413 // are sufficient to determine the impl substs, without
414 // relying on projections in the impl-trait-ref.
416 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
417 impl_obligations.extend(substs.obligations);
419 ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations }
422 fn confirm_object_candidate(
424 obligation: &TraitObligation<'tcx>,
426 ) -> Result<ImplSourceObjectData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
427 let tcx = self.tcx();
428 debug!(?obligation, ?index, "confirm_object_candidate");
430 let trait_predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
431 let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
432 let obligation_trait_ref = ty::Binder::dummy(trait_predicate.trait_ref);
433 let ty::Dynamic(data, ..) = *self_ty.kind() else {
434 span_bug!(obligation.cause.span, "object candidate with non-object");
437 let object_trait_ref = data.principal().unwrap_or_else(|| {
438 span_bug!(obligation.cause.span, "object candidate with no principal")
440 let object_trait_ref = self.infcx.replace_bound_vars_with_fresh_vars(
441 obligation.cause.span,
445 let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);
447 let mut nested = vec![];
449 let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
450 let unnormalized_upcast_trait_ref =
451 supertraits.nth(index).expect("supertraits iterator no longer has as many elements");
453 let upcast_trait_ref = normalize_with_depth_to(
455 obligation.param_env,
456 obligation.cause.clone(),
457 obligation.recursion_depth + 1,
458 unnormalized_upcast_trait_ref,
462 nested.extend(self.infcx.commit_if_ok(|_| {
464 .at(&obligation.cause, obligation.param_env)
465 .sup(obligation_trait_ref, upcast_trait_ref)
466 .map(|InferOk { obligations, .. }| obligations)
467 .map_err(|_| Unimplemented)
470 // Check supertraits hold. This is so that their associated type bounds
471 // will be checked in the code below.
472 for super_trait in tcx
473 .super_predicates_of(trait_predicate.def_id())
474 .instantiate(tcx, trait_predicate.trait_ref.substs)
478 let normalized_super_trait = normalize_with_depth_to(
480 obligation.param_env,
481 obligation.cause.clone(),
482 obligation.recursion_depth + 1,
486 nested.push(obligation.with(tcx, normalized_super_trait));
489 let assoc_types: Vec<_> = tcx
490 .associated_items(trait_predicate.def_id())
491 .in_definition_order()
493 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
497 for assoc_type in assoc_types {
498 let defs: &ty::Generics = tcx.generics_of(assoc_type);
500 if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
501 tcx.sess.delay_span_bug(
502 obligation.cause.span,
503 "GATs in trait object shouldn't have been considered",
505 return Err(SelectionError::Unimplemented);
508 // This maybe belongs in wf, but that can't (doesn't) handle
509 // higher-ranked things.
510 // Prevent, e.g., `dyn Iterator<Item = str>`.
511 for bound in self.tcx().item_bounds(assoc_type).transpose_iter() {
513 if defs.count() == 0 {
514 bound.subst(tcx, trait_predicate.trait_ref.substs)
516 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
517 substs.extend(trait_predicate.trait_ref.substs.iter());
518 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
519 smallvec::SmallVec::with_capacity(
520 bound.0.kind().bound_vars().len() + defs.count(),
522 bound_vars.extend(bound.0.kind().bound_vars().into_iter());
523 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
526 GenericParamDefKind::Type { .. } => {
527 let kind = ty::BoundTyKind::Param(param.def_id, param.name);
528 let bound_var = ty::BoundVariableKind::Ty(kind);
529 bound_vars.push(bound_var);
533 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
539 GenericParamDefKind::Lifetime => {
540 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
541 let bound_var = ty::BoundVariableKind::Region(kind);
542 bound_vars.push(bound_var);
543 tcx.mk_region(ty::ReLateBound(
546 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
552 GenericParamDefKind::Const { .. } => {
553 let bound_var = ty::BoundVariableKind::Const;
554 bound_vars.push(bound_var);
556 ty::ConstKind::Bound(
558 ty::BoundVar::from_usize(bound_vars.len() - 1),
560 tcx.type_of(param.def_id),
565 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
566 let assoc_ty_substs = tcx.intern_substs(&substs);
568 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
570 bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs);
571 tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
573 let normalized_bound = normalize_with_depth_to(
575 obligation.param_env,
576 obligation.cause.clone(),
577 obligation.recursion_depth + 1,
581 nested.push(obligation.with(tcx, normalized_bound));
585 debug!(?nested, "object nested obligations");
587 let vtable_base = vtable_trait_first_method_offset(
589 (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
592 Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
595 fn confirm_fn_pointer_candidate(
597 obligation: &TraitObligation<'tcx>,
599 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
601 debug!(?obligation, "confirm_fn_pointer_candidate");
603 let tcx = self.tcx();
606 .shallow_resolve(obligation.self_ty().no_bound_vars())
607 .expect("fn pointer should not capture bound vars from predicate");
608 let sig = self_ty.fn_sig(tcx);
609 let trait_ref = closure_trait_ref_and_return_type(
611 obligation.predicate.def_id(),
614 util::TupleArgumentsFlag::Yes,
616 .map_bound(|(trait_ref, _)| trait_ref);
618 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
619 let cause = obligation.derived_cause(BuiltinDerivedObligation);
621 if obligation.is_const() && !is_const {
622 // function is a trait method
623 if let ty::FnDef(def_id, substs) = self_ty.kind() && let Some(trait_id) = tcx.trait_of_item(*def_id) {
624 let trait_ref = TraitRef::from_method(tcx, trait_id, *substs);
625 let poly_trait_pred = Binder::dummy(trait_ref).with_constness(ty::BoundConstness::ConstIfConst);
626 let obligation = Obligation::new(tcx, cause.clone(), obligation.param_env, poly_trait_pred);
627 nested.push(obligation);
631 // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
632 let output_ty = self.infcx.replace_bound_vars_with_placeholders(sig.output());
633 let output_ty = normalize_with_depth_to(
635 obligation.param_env,
637 obligation.recursion_depth,
642 ty::Binder::dummy(self.tcx().at(cause.span).mk_trait_ref(LangItem::Sized, [output_ty]));
643 nested.push(Obligation::new(self.infcx.tcx, cause, obligation.param_env, tr));
645 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
648 fn confirm_trait_alias_candidate(
650 obligation: &TraitObligation<'tcx>,
651 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
652 debug!(?obligation, "confirm_trait_alias_candidate");
654 let alias_def_id = obligation.predicate.def_id();
655 let predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
656 let trait_ref = predicate.trait_ref;
657 let trait_def_id = trait_ref.def_id;
658 let substs = trait_ref.substs;
660 let trait_obligations = self.impl_or_trait_obligations(
662 obligation.recursion_depth,
663 obligation.param_env,
666 obligation.predicate,
669 debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
671 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
674 fn confirm_generator_candidate(
676 obligation: &TraitObligation<'tcx>,
677 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
679 // Okay to skip binder because the substs on generator types never
680 // touch bound regions, they just capture the in-scope
681 // type/region parameters.
682 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
683 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
684 bug!("closure candidate for non-closure {:?}", obligation);
687 debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
689 let gen_sig = substs.as_generator().poly_sig();
691 // NOTE: The self-type is a generator type and hence is
692 // in fact unparameterized (or at least does not reference any
693 // regions bound in the obligation).
694 let self_ty = obligation
698 .expect("unboxed closure type should not capture bound vars from the predicate");
700 let trait_ref = super::util::generator_trait_ref_and_outputs(
702 obligation.predicate.def_id(),
706 .map_bound(|(trait_ref, ..)| trait_ref);
708 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
709 debug!(?trait_ref, ?nested, "generator candidate obligations");
711 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
714 fn confirm_future_candidate(
716 obligation: &TraitObligation<'tcx>,
717 ) -> Result<ImplSourceFutureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
718 // Okay to skip binder because the substs on generator types never
719 // touch bound regions, they just capture the in-scope
720 // type/region parameters.
721 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
722 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
723 bug!("closure candidate for non-closure {:?}", obligation);
726 debug!(?obligation, ?generator_def_id, ?substs, "confirm_future_candidate");
728 let gen_sig = substs.as_generator().poly_sig();
730 let trait_ref = super::util::future_trait_ref_and_outputs(
732 obligation.predicate.def_id(),
733 obligation.predicate.no_bound_vars().expect("future has no bound vars").self_ty(),
736 .map_bound(|(trait_ref, ..)| trait_ref);
738 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
739 debug!(?trait_ref, ?nested, "future candidate obligations");
741 Ok(ImplSourceFutureData { generator_def_id, substs, nested })
744 #[instrument(skip(self), level = "debug")]
745 fn confirm_closure_candidate(
747 obligation: &TraitObligation<'tcx>,
748 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
751 .fn_trait_kind_from_def_id(obligation.predicate.def_id())
752 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
754 // Okay to skip binder because the substs on closure types never
755 // touch bound regions, they just capture the in-scope
756 // type/region parameters.
757 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
758 let ty::Closure(closure_def_id, substs) = *self_ty.kind() else {
759 bug!("closure candidate for non-closure {:?}", obligation);
762 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
763 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
765 debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
768 if self.tcx().sess.opts.unstable_opts.trait_solver != TraitSolver::Chalk {
769 nested.push(obligation.with(
771 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind)),
775 Ok(ImplSourceClosureData { closure_def_id, substs, nested })
778 /// In the case of closure types and fn pointers,
779 /// we currently treat the input type parameters on the trait as
780 /// outputs. This means that when we have a match we have only
781 /// considered the self type, so we have to go back and make sure
782 /// to relate the argument types too. This is kind of wrong, but
783 /// since we control the full set of impls, also not that wrong,
784 /// and it DOES yield better error messages (since we don't report
785 /// errors as if there is no applicable impl, but rather report
786 /// errors are about mismatched argument types.
788 /// Here is an example. Imagine we have a closure expression
789 /// and we desugared it so that the type of the expression is
790 /// `Closure`, and `Closure` expects `i32` as argument. Then it
791 /// is "as if" the compiler generated this impl:
792 /// ```ignore (illustrative)
793 /// impl Fn(i32) for Closure { ... }
795 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
796 /// we have matched the self type `Closure`. At this point we'll
797 /// compare the `i32` to `usize` and generate an error.
799 /// Note that this checking occurs *after* the impl has selected,
800 /// because these output type parameters should not affect the
801 /// selection of the impl. Therefore, if there is a mismatch, we
802 /// report an error to the user.
803 #[instrument(skip(self), level = "trace")]
804 fn confirm_poly_trait_refs(
806 obligation: &TraitObligation<'tcx>,
807 expected_trait_ref: ty::PolyTraitRef<'tcx>,
808 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
809 let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
810 // Normalize the obligation and expected trait refs together, because why not
811 let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
812 ensure_sufficient_stack(|| {
813 normalize_with_depth(
815 obligation.param_env,
816 obligation.cause.clone(),
817 obligation.recursion_depth + 1,
818 (obligation_trait_ref, expected_trait_ref),
823 .at(&obligation.cause, obligation.param_env)
824 .sup(obligation_trait_ref, expected_trait_ref)
825 .map(|InferOk { mut obligations, .. }| {
826 obligations.extend(nested);
829 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
832 fn confirm_trait_upcasting_unsize_candidate(
834 obligation: &TraitObligation<'tcx>,
836 ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
838 let tcx = self.tcx();
840 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
841 // regions here. See the comment there for more details.
842 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
843 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
844 let target = self.infcx.shallow_resolve(target);
846 debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
848 let mut nested = vec![];
849 let source_trait_ref;
850 let upcast_trait_ref;
851 match (source.kind(), target.kind()) {
852 // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
854 &ty::Dynamic(ref data_a, r_a, repr_a @ ty::Dyn),
855 &ty::Dynamic(ref data_b, r_b, ty::Dyn),
857 // See `assemble_candidates_for_unsizing` for more info.
858 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
859 let principal_a = data_a.principal().unwrap();
860 source_trait_ref = principal_a.with_self_ty(tcx, source);
861 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
862 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
863 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
864 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
868 let iter = Some(existential_predicate)
873 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
878 .map(ty::ExistentialPredicate::AutoTrait)
879 .map(ty::Binder::dummy),
881 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
882 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, repr_a);
884 // Require that the traits involved in this upcast are **equal**;
885 // only the **lifetime bound** is changed.
886 let InferOk { obligations, .. } = self
888 .at(&obligation.cause, obligation.param_env)
889 .sup(target, source_trait)
890 .map_err(|_| Unimplemented)?;
891 nested.extend(obligations);
893 // Register one obligation for 'a: 'b.
894 let cause = ObligationCause::new(
895 obligation.cause.span,
896 obligation.cause.body_id,
897 ObjectCastObligation(source, target),
899 let outlives = ty::OutlivesPredicate(r_a, r_b);
900 nested.push(Obligation::with_depth(
903 obligation.recursion_depth + 1,
904 obligation.param_env,
905 obligation.predicate.rebind(outlives),
911 let vtable_segment_callback = {
912 let mut vptr_offset = 0;
915 VtblSegment::MetadataDSA => {
916 vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
918 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
919 vptr_offset += count_own_vtable_entries(tcx, trait_ref);
920 if trait_ref == upcast_trait_ref {
922 return ControlFlow::Break(Some(vptr_offset));
924 return ControlFlow::Break(None);
933 ControlFlow::Continue(())
937 let vtable_vptr_slot =
938 prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback).unwrap();
940 Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
943 fn confirm_builtin_unsize_candidate(
945 obligation: &TraitObligation<'tcx>,
946 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
947 let tcx = self.tcx();
949 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
950 // regions here. See the comment there for more details.
951 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
952 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
953 let target = self.infcx.shallow_resolve(target);
955 debug!(?source, ?target, "confirm_builtin_unsize_candidate");
957 let mut nested = vec![];
958 match (source.kind(), target.kind()) {
959 // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
960 (&ty::Dynamic(ref data_a, r_a, dyn_a), &ty::Dynamic(ref data_b, r_b, dyn_b))
963 // See `assemble_candidates_for_unsizing` for more info.
964 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
967 .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
972 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
977 .map(ty::ExistentialPredicate::AutoTrait)
978 .map(ty::Binder::dummy),
980 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
981 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, dyn_a);
983 // Require that the traits involved in this upcast are **equal**;
984 // only the **lifetime bound** is changed.
985 let InferOk { obligations, .. } = self
987 .at(&obligation.cause, obligation.param_env)
988 .sup(target, source_trait)
989 .map_err(|_| Unimplemented)?;
990 nested.extend(obligations);
992 // Register one obligation for 'a: 'b.
993 let cause = ObligationCause::new(
994 obligation.cause.span,
995 obligation.cause.body_id,
996 ObjectCastObligation(source, target),
998 let outlives = ty::OutlivesPredicate(r_a, r_b);
999 nested.push(Obligation::with_depth(
1002 obligation.recursion_depth + 1,
1003 obligation.param_env,
1004 obligation.predicate.rebind(outlives),
1009 (_, &ty::Dynamic(ref data, r, ty::Dyn)) => {
1010 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
1011 if let Some(did) = object_dids.find(|did| !tcx.check_is_object_safe(*did)) {
1012 return Err(TraitNotObjectSafe(did));
1015 let cause = ObligationCause::new(
1016 obligation.cause.span,
1017 obligation.cause.body_id,
1018 ObjectCastObligation(source, target),
1021 let predicate_to_obligation = |predicate| {
1022 Obligation::with_depth(
1025 obligation.recursion_depth + 1,
1026 obligation.param_env,
1031 // Create obligations:
1032 // - Casting `T` to `Trait`
1033 // - For all the various builtin bounds attached to the object cast. (In other
1034 // words, if the object type is `Foo + Send`, this would create an obligation for
1035 // the `Send` check.)
1036 // - Projection predicates
1038 data.iter().map(|predicate| {
1039 predicate_to_obligation(predicate.with_self_ty(tcx, source))
1043 // We can only make objects from sized types.
1045 ty::Binder::dummy(tcx.at(cause.span).mk_trait_ref(LangItem::Sized, [source]));
1046 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
1048 // If the type is `Foo + 'a`, ensure that the type
1049 // being cast to `Foo + 'a` outlives `'a`:
1050 let outlives = ty::OutlivesPredicate(source, r);
1051 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
1054 // `[T; n]` -> `[T]`
1055 (&ty::Array(a, _), &ty::Slice(b)) => {
1056 let InferOk { obligations, .. } = self
1058 .at(&obligation.cause, obligation.param_env)
1060 .map_err(|_| Unimplemented)?;
1061 nested.extend(obligations);
1064 // `Struct<T>` -> `Struct<U>`
1065 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
1066 let unsizing_params = tcx.unsizing_params_for_adt(def.did());
1067 if unsizing_params.is_empty() {
1068 return Err(Unimplemented);
1071 let tail_field = def
1075 .expect("expected unsized ADT to have a tail field");
1076 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1078 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
1079 // normalizing in the process, since `type_of` returns something directly from
1080 // astconv (which means it's un-normalized).
1081 let source_tail = normalize_with_depth_to(
1083 obligation.param_env,
1084 obligation.cause.clone(),
1085 obligation.recursion_depth + 1,
1086 tail_field_ty.subst(tcx, substs_a),
1089 let target_tail = normalize_with_depth_to(
1091 obligation.param_env,
1092 obligation.cause.clone(),
1093 obligation.recursion_depth + 1,
1094 tail_field_ty.subst(tcx, substs_b),
1098 // Check that the source struct with the target's
1099 // unsizing parameters is equal to the target.
1100 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1101 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1103 let new_struct = tcx.mk_adt(def, substs);
1104 let InferOk { obligations, .. } = self
1106 .at(&obligation.cause, obligation.param_env)
1107 .eq(target, new_struct)
1108 .map_err(|_| Unimplemented)?;
1109 nested.extend(obligations);
1111 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1112 nested.push(predicate_for_trait_def(
1114 obligation.param_env,
1115 obligation.cause.clone(),
1116 obligation.predicate.def_id(),
1117 obligation.recursion_depth + 1,
1118 [source_tail, target_tail],
1122 // `(.., T)` -> `(.., U)`
1123 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1124 assert_eq!(tys_a.len(), tys_b.len());
1126 // The last field of the tuple has to exist.
1127 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1128 let &b_last = tys_b.last().unwrap();
1130 // Check that the source tuple with the target's
1131 // last element is equal to the target.
1132 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1133 let InferOk { obligations, .. } = self
1135 .at(&obligation.cause, obligation.param_env)
1136 .eq(target, new_tuple)
1137 .map_err(|_| Unimplemented)?;
1138 nested.extend(obligations);
1140 // Construct the nested `T: Unsize<U>` predicate.
1141 nested.push(ensure_sufficient_stack(|| {
1142 predicate_for_trait_def(
1144 obligation.param_env,
1145 obligation.cause.clone(),
1146 obligation.predicate.def_id(),
1147 obligation.recursion_depth + 1,
1153 _ => bug!("source: {source}, target: {target}"),
1156 Ok(ImplSourceBuiltinData { nested })
1159 fn confirm_const_destruct_candidate(
1161 obligation: &TraitObligation<'tcx>,
1162 impl_def_id: Option<DefId>,
1163 ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1164 // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1165 if !obligation.is_const() {
1166 return Ok(ImplSourceConstDestructData { nested: vec![] });
1169 let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1171 let tcx = self.tcx();
1172 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1174 let mut nested = vec![];
1175 let cause = obligation.derived_cause(BuiltinDerivedObligation);
1177 // If we have a custom `impl const Drop`, then
1178 // first check it like a regular impl candidate.
1179 // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1180 if let Some(impl_def_id) = impl_def_id {
1181 let mut new_obligation = obligation.clone();
1182 new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1183 trait_pred.trait_ref.def_id = drop_trait;
1186 let substs = self.rematch_impl(impl_def_id, &new_obligation);
1187 debug!(?substs, "impl substs");
1189 let cause = obligation.derived_cause(|derived| {
1190 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1193 impl_def_predicate_index: None,
1194 span: obligation.cause.span,
1197 let obligations = ensure_sufficient_stack(|| {
1202 new_obligation.recursion_depth + 1,
1203 new_obligation.param_env,
1204 obligation.predicate,
1207 nested.extend(obligations.nested);
1210 // We want to confirm the ADT's fields if we have an ADT
1211 let mut stack = match *self_ty.skip_binder().kind() {
1212 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1213 _ => vec![self_ty.skip_binder()],
1216 while let Some(nested_ty) = stack.pop() {
1217 match *nested_ty.kind() {
1218 // We know these types are trivially drop
1224 | ty::Infer(ty::IntVar(_))
1225 | ty::Infer(ty::FloatVar(_))
1232 | ty::Foreign(_) => {}
1234 // `ManuallyDrop` is trivially drop
1235 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().manually_drop() => {}
1237 // These types are built-in, so we can fast-track by registering
1238 // nested predicates for their constituent type(s)
1239 ty::Array(ty, _) | ty::Slice(ty) => {
1243 stack.extend(tys.iter());
1245 ty::Closure(_, substs) => {
1246 stack.push(substs.as_closure().tupled_upvars_ty());
1248 ty::Generator(_, substs, _) => {
1249 let generator = substs.as_generator();
1250 stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1252 ty::GeneratorWitness(tys) => {
1253 stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1255 ty::GeneratorWitnessMIR(def_id, substs) => {
1256 let tcx = self.tcx();
1257 stack.extend(tcx.generator_hidden_types(def_id).map(|bty| {
1258 let ty = bty.subst(tcx, substs);
1259 debug_assert!(!ty.has_late_bound_regions());
1264 // If we have a projection type, make sure to normalize it so we replace it
1265 // with a fresh infer variable
1266 ty::Alias(ty::Projection, ..) => {
1267 let predicate = normalize_with_depth_to(
1269 obligation.param_env,
1271 obligation.recursion_depth + 1,
1272 self_ty.rebind(ty::TraitPredicate {
1276 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1277 constness: ty::BoundConstness::ConstIfConst,
1278 polarity: ty::ImplPolarity::Positive,
1283 nested.push(Obligation::with_depth(
1286 obligation.recursion_depth + 1,
1287 obligation.param_env,
1292 // If we have any other type (e.g. an ADT), just register a nested obligation
1293 // since it's either not `const Drop` (and we raise an error during selection),
1294 // or it's an ADT (and we need to check for a custom impl during selection)
1296 let predicate = self_ty.rebind(ty::TraitPredicate {
1300 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1301 constness: ty::BoundConstness::ConstIfConst,
1302 polarity: ty::ImplPolarity::Positive,
1305 nested.push(Obligation::with_depth(
1308 obligation.recursion_depth + 1,
1309 obligation.param_env,
1316 Ok(ImplSourceConstDestructData { nested })