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_index::bit_set::GrowableBitSet;
12 use rustc_infer::infer::InferOk;
13 use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType;
14 use rustc_middle::ty::{
15 self, GenericArg, GenericArgKind, GenericParamDefKind, InternalSubsts, SubstsRef,
16 ToPolyTraitRef, ToPredicate, Ty, TyCtxt,
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};
23 BuiltinDerivedObligation, ImplDerivedObligation, ImplDerivedObligationCause, ImplSource,
24 ImplSourceAutoImplData, ImplSourceBuiltinData, ImplSourceClosureData,
25 ImplSourceConstDestructData, ImplSourceFnPointerData, ImplSourceFutureData,
26 ImplSourceGeneratorData, ImplSourceObjectData, ImplSourceTraitAliasData,
27 ImplSourceTraitUpcastingData, ImplSourceUserDefinedData, Normalized, ObjectCastObligation,
28 Obligation, ObligationCause, OutputTypeParameterMismatch, PredicateObligation, Selection,
29 SelectionError, TraitNotObjectSafe, TraitObligation, Unimplemented, VtblSegment,
32 use super::BuiltinImplConditions;
33 use super::SelectionCandidate::{self, *};
34 use super::SelectionContext;
37 use std::ops::ControlFlow;
39 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
40 #[instrument(level = "debug", skip(self))]
41 pub(super) fn confirm_candidate(
43 obligation: &TraitObligation<'tcx>,
44 candidate: SelectionCandidate<'tcx>,
45 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
46 let mut impl_src = match candidate {
47 BuiltinCandidate { has_nested } => {
48 let data = self.confirm_builtin_candidate(obligation, has_nested);
49 ImplSource::Builtin(data)
52 TransmutabilityCandidate => {
53 let data = self.confirm_transmutability_candidate(obligation)?;
54 ImplSource::Builtin(data)
57 ParamCandidate(param) => {
59 self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref));
60 ImplSource::Param(obligations, param.skip_binder().constness)
63 ImplCandidate(impl_def_id) => {
64 ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id))
67 AutoImplCandidate => {
68 let data = self.confirm_auto_impl_candidate(obligation);
69 ImplSource::AutoImpl(data)
72 ProjectionCandidate(idx, constness) => {
73 let obligations = self.confirm_projection_candidate(obligation, idx)?;
74 ImplSource::Param(obligations, constness)
77 ObjectCandidate(idx) => {
78 let data = self.confirm_object_candidate(obligation, idx)?;
79 ImplSource::Object(data)
83 let vtable_closure = self.confirm_closure_candidate(obligation)?;
84 ImplSource::Closure(vtable_closure)
87 GeneratorCandidate => {
88 let vtable_generator = self.confirm_generator_candidate(obligation)?;
89 ImplSource::Generator(vtable_generator)
93 let vtable_future = self.confirm_future_candidate(obligation)?;
94 ImplSource::Future(vtable_future)
97 FnPointerCandidate { .. } => {
98 let data = self.confirm_fn_pointer_candidate(obligation)?;
99 ImplSource::FnPointer(data)
102 TraitAliasCandidate => {
103 let data = self.confirm_trait_alias_candidate(obligation);
104 ImplSource::TraitAlias(data)
107 BuiltinObjectCandidate => {
108 // This indicates something like `Trait + Send: Send`. In this case, we know that
109 // this holds because that's what the object type is telling us, and there's really
110 // no additional obligations to prove and no types in particular to unify, etc.
111 ImplSource::Param(Vec::new(), ty::BoundConstness::NotConst)
114 BuiltinUnsizeCandidate => {
115 let data = self.confirm_builtin_unsize_candidate(obligation)?;
116 ImplSource::Builtin(data)
119 TraitUpcastingUnsizeCandidate(idx) => {
120 let data = self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?;
121 ImplSource::TraitUpcasting(data)
124 ConstDestructCandidate(def_id) => {
125 let data = self.confirm_const_destruct_candidate(obligation, def_id)?;
126 ImplSource::ConstDestruct(data)
130 if !obligation.predicate.is_const_if_const() {
131 // normalize nested predicates according to parent predicate's constness.
132 impl_src = impl_src.map(|mut o| {
133 o.predicate = o.predicate.without_const(self.tcx());
141 fn confirm_projection_candidate(
143 obligation: &TraitObligation<'tcx>,
145 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
146 let tcx = self.tcx();
148 let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
149 let placeholder_trait_predicate =
150 self.infcx().replace_bound_vars_with_placeholders(trait_predicate).trait_ref;
151 let placeholder_self_ty = placeholder_trait_predicate.self_ty();
152 let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate);
153 let (def_id, substs) = match *placeholder_self_ty.kind() {
154 ty::Projection(proj) => (proj.item_def_id, proj.substs),
155 ty::Opaque(def_id, substs) => (def_id, substs),
156 _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
159 let candidate_predicate =
160 tcx.bound_item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs);
161 let candidate = candidate_predicate
162 .to_opt_poly_trait_pred()
163 .expect("projection candidate is not a trait predicate")
164 .map_bound(|t| t.trait_ref);
165 let mut obligations = Vec::new();
166 let candidate = normalize_with_depth_to(
168 obligation.param_env,
169 obligation.cause.clone(),
170 obligation.recursion_depth + 1,
175 obligations.extend(self.infcx.commit_if_ok(|_| {
177 .at(&obligation.cause, obligation.param_env)
178 .sup(placeholder_trait_predicate, candidate)
179 .map(|InferOk { obligations, .. }| obligations)
180 .map_err(|_| Unimplemented)
183 if let ty::Projection(..) = placeholder_self_ty.kind() {
184 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates;
185 debug!(?predicates, "projection predicates");
186 for predicate in predicates {
187 let normalized = normalize_with_depth_to(
189 obligation.param_env,
190 obligation.cause.clone(),
191 obligation.recursion_depth + 1,
195 obligations.push(Obligation::with_depth(
197 obligation.cause.clone(),
198 obligation.recursion_depth + 1,
199 obligation.param_env,
208 fn confirm_param_candidate(
210 obligation: &TraitObligation<'tcx>,
211 param: ty::PolyTraitRef<'tcx>,
212 ) -> Vec<PredicateObligation<'tcx>> {
213 debug!(?obligation, ?param, "confirm_param_candidate");
215 // During evaluation, we already checked that this
216 // where-clause trait-ref could be unified with the obligation
217 // trait-ref. Repeat that unification now without any
218 // transactional boundary; it should not fail.
219 match self.match_where_clause_trait_ref(obligation, param) {
220 Ok(obligations) => obligations,
223 "Where clause `{:?}` was applicable to `{:?}` but now is not",
231 fn confirm_builtin_candidate(
233 obligation: &TraitObligation<'tcx>,
235 ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
236 debug!(?obligation, ?has_nested, "confirm_builtin_candidate");
238 let lang_items = self.tcx().lang_items();
239 let obligations = if has_nested {
240 let trait_def = obligation.predicate.def_id();
241 let conditions = if Some(trait_def) == lang_items.sized_trait() {
242 self.sized_conditions(obligation)
243 } else if Some(trait_def) == lang_items.copy_trait() {
244 self.copy_clone_conditions(obligation)
245 } else if Some(trait_def) == lang_items.clone_trait() {
246 self.copy_clone_conditions(obligation)
248 bug!("unexpected builtin trait {:?}", trait_def)
250 let BuiltinImplConditions::Where(nested) = conditions else {
251 bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
254 let cause = obligation.derived_cause(BuiltinDerivedObligation);
255 ensure_sufficient_stack(|| {
256 self.collect_predicates_for_types(
257 obligation.param_env,
259 obligation.recursion_depth + 1,
268 debug!(?obligations);
270 ImplSourceBuiltinData { nested: obligations }
273 fn confirm_transmutability_candidate(
275 obligation: &TraitObligation<'tcx>,
276 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
277 debug!(?obligation, "confirm_transmutability_candidate");
279 let predicate = obligation.predicate;
281 let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i));
282 let const_at = |i| predicate.skip_binder().trait_ref.substs.const_at(i);
284 let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types {
285 dst: p.trait_ref.substs.type_at(0),
286 src: p.trait_ref.substs.type_at(1),
289 let scope = type_at(2).skip_binder();
292 rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, const_at(3)) else {
293 return Err(Unimplemented);
296 let cause = obligation.cause.clone();
298 let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
300 let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume);
302 use rustc_transmute::Answer;
304 match maybe_transmutable {
305 Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }),
306 _ => Err(Unimplemented),
310 /// This handles the case where an `auto trait Foo` impl is being used.
311 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
313 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
314 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
315 fn confirm_auto_impl_candidate(
317 obligation: &TraitObligation<'tcx>,
318 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
319 debug!(?obligation, "confirm_auto_impl_candidate");
321 let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
322 let types = self.constituent_types_for_ty(self_ty);
323 self.vtable_auto_impl(obligation, obligation.predicate.def_id(), types)
326 /// See `confirm_auto_impl_candidate`.
329 obligation: &TraitObligation<'tcx>,
331 nested: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
332 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
333 debug!(?nested, "vtable_auto_impl");
334 ensure_sufficient_stack(|| {
335 let cause = obligation.derived_cause(BuiltinDerivedObligation);
337 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
338 let trait_ref = self.infcx.replace_bound_vars_with_placeholders(poly_trait_ref);
339 let trait_obligations: Vec<PredicateObligation<'_>> = self.impl_or_trait_obligations(
341 obligation.recursion_depth + 1,
342 obligation.param_env,
345 obligation.predicate,
348 let mut obligations = self.collect_predicates_for_types(
349 obligation.param_env,
351 obligation.recursion_depth + 1,
356 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
357 // predicate as usual. It won't have any effect since auto traits are coinductive.
358 obligations.extend(trait_obligations);
360 debug!(?obligations, "vtable_auto_impl");
362 ImplSourceAutoImplData { trait_def_id, nested: obligations }
366 fn confirm_impl_candidate(
368 obligation: &TraitObligation<'tcx>,
370 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
371 debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");
373 // First, create the substitutions by matching the impl again,
374 // this time not in a probe.
375 let substs = self.rematch_impl(impl_def_id, obligation);
376 debug!(?substs, "impl substs");
377 ensure_sufficient_stack(|| {
382 obligation.recursion_depth + 1,
383 obligation.param_env,
384 obligation.predicate,
392 substs: Normalized<'tcx, SubstsRef<'tcx>>,
393 cause: &ObligationCause<'tcx>,
394 recursion_depth: usize,
395 param_env: ty::ParamEnv<'tcx>,
396 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
397 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
398 debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl");
400 let mut impl_obligations = self.impl_or_trait_obligations(
409 debug!(?impl_obligations, "vtable_impl");
411 // Because of RFC447, the impl-trait-ref and obligations
412 // are sufficient to determine the impl substs, without
413 // relying on projections in the impl-trait-ref.
415 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
416 impl_obligations.extend(substs.obligations);
418 ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations }
421 fn confirm_object_candidate(
423 obligation: &TraitObligation<'tcx>,
425 ) -> Result<ImplSourceObjectData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
426 let tcx = self.tcx();
427 debug!(?obligation, ?index, "confirm_object_candidate");
429 let trait_predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
430 let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
431 let obligation_trait_ref = ty::Binder::dummy(trait_predicate.trait_ref);
432 let ty::Dynamic(data, ..) = *self_ty.kind() else {
433 span_bug!(obligation.cause.span, "object candidate with non-object");
436 let object_trait_ref = data.principal().unwrap_or_else(|| {
437 span_bug!(obligation.cause.span, "object candidate with no principal")
439 let object_trait_ref = self.infcx.replace_bound_vars_with_fresh_vars(
440 obligation.cause.span,
444 let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);
446 let mut nested = vec![];
448 let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
449 let unnormalized_upcast_trait_ref =
450 supertraits.nth(index).expect("supertraits iterator no longer has as many elements");
452 let upcast_trait_ref = normalize_with_depth_to(
454 obligation.param_env,
455 obligation.cause.clone(),
456 obligation.recursion_depth + 1,
457 unnormalized_upcast_trait_ref,
461 nested.extend(self.infcx.commit_if_ok(|_| {
463 .at(&obligation.cause, obligation.param_env)
464 .sup(obligation_trait_ref, upcast_trait_ref)
465 .map(|InferOk { obligations, .. }| obligations)
466 .map_err(|_| Unimplemented)
469 // Check supertraits hold. This is so that their associated type bounds
470 // will be checked in the code below.
471 for super_trait in tcx
472 .super_predicates_of(trait_predicate.def_id())
473 .instantiate(tcx, trait_predicate.trait_ref.substs)
477 let normalized_super_trait = normalize_with_depth_to(
479 obligation.param_env,
480 obligation.cause.clone(),
481 obligation.recursion_depth + 1,
485 nested.push(obligation.with(tcx, normalized_super_trait));
488 let assoc_types: Vec<_> = tcx
489 .associated_items(trait_predicate.def_id())
490 .in_definition_order()
492 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
496 for assoc_type in assoc_types {
497 let defs: &ty::Generics = tcx.generics_of(assoc_type);
499 if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
500 tcx.sess.delay_span_bug(
501 obligation.cause.span,
502 "GATs in trait object shouldn't have been considered",
504 return Err(SelectionError::Unimplemented);
507 // This maybe belongs in wf, but that can't (doesn't) handle
508 // higher-ranked things.
509 // Prevent, e.g., `dyn Iterator<Item = str>`.
510 for bound in self.tcx().bound_item_bounds(assoc_type).transpose_iter() {
512 if defs.count() == 0 {
513 bound.subst(tcx, trait_predicate.trait_ref.substs)
515 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
516 substs.extend(trait_predicate.trait_ref.substs.iter());
517 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
518 smallvec::SmallVec::with_capacity(
519 bound.0.kind().bound_vars().len() + defs.count(),
521 bound_vars.extend(bound.0.kind().bound_vars().into_iter());
522 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
525 GenericParamDefKind::Type { .. } => {
526 let kind = ty::BoundTyKind::Param(param.name);
527 let bound_var = ty::BoundVariableKind::Ty(kind);
528 bound_vars.push(bound_var);
532 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
538 GenericParamDefKind::Lifetime => {
539 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
540 let bound_var = ty::BoundVariableKind::Region(kind);
541 bound_vars.push(bound_var);
542 tcx.mk_region(ty::ReLateBound(
545 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
551 GenericParamDefKind::Const { .. } => {
552 let bound_var = ty::BoundVariableKind::Const;
553 bound_vars.push(bound_var);
555 ty::ConstKind::Bound(
557 ty::BoundVar::from_usize(bound_vars.len() - 1),
559 tcx.type_of(param.def_id),
564 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
565 let assoc_ty_substs = tcx.intern_substs(&substs);
567 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
569 bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs);
570 tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
572 let normalized_bound = normalize_with_depth_to(
574 obligation.param_env,
575 obligation.cause.clone(),
576 obligation.recursion_depth + 1,
580 nested.push(obligation.with(tcx, normalized_bound));
584 debug!(?nested, "object nested obligations");
586 let vtable_base = super::super::vtable_trait_first_method_offset(
588 (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
591 Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
594 fn confirm_fn_pointer_candidate(
596 obligation: &TraitObligation<'tcx>,
597 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
599 debug!(?obligation, "confirm_fn_pointer_candidate");
603 .shallow_resolve(obligation.self_ty().no_bound_vars())
604 .expect("fn pointer should not capture bound vars from predicate");
605 let sig = self_ty.fn_sig(self.tcx());
606 let trait_ref = closure_trait_ref_and_return_type(
608 obligation.predicate.def_id(),
611 util::TupleArgumentsFlag::Yes,
613 .map_bound(|(trait_ref, _)| trait_ref);
615 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
617 // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
618 let cause = obligation.derived_cause(BuiltinDerivedObligation);
619 let output_ty = self.infcx.replace_bound_vars_with_placeholders(sig.output());
620 let output_ty = normalize_with_depth_to(
622 obligation.param_env,
624 obligation.recursion_depth,
629 ty::Binder::dummy(self.tcx().at(cause.span).mk_trait_ref(LangItem::Sized, [output_ty]));
630 nested.push(Obligation::new(
633 obligation.param_env,
634 tr.to_poly_trait_predicate(),
637 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
640 fn confirm_trait_alias_candidate(
642 obligation: &TraitObligation<'tcx>,
643 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
644 debug!(?obligation, "confirm_trait_alias_candidate");
646 let alias_def_id = obligation.predicate.def_id();
647 let predicate = self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
648 let trait_ref = predicate.trait_ref;
649 let trait_def_id = trait_ref.def_id;
650 let substs = trait_ref.substs;
652 let trait_obligations = self.impl_or_trait_obligations(
654 obligation.recursion_depth,
655 obligation.param_env,
658 obligation.predicate,
661 debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
663 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
666 fn confirm_generator_candidate(
668 obligation: &TraitObligation<'tcx>,
669 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
671 // Okay to skip binder because the substs on generator types never
672 // touch bound regions, they just capture the in-scope
673 // type/region parameters.
674 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
675 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
676 bug!("closure candidate for non-closure {:?}", obligation);
679 debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
681 let gen_sig = substs.as_generator().poly_sig();
683 // NOTE: The self-type is a generator type and hence is
684 // in fact unparameterized (or at least does not reference any
685 // regions bound in the obligation).
686 let self_ty = obligation
690 .expect("unboxed closure type should not capture bound vars from the predicate");
692 let trait_ref = super::util::generator_trait_ref_and_outputs(
694 obligation.predicate.def_id(),
698 .map_bound(|(trait_ref, ..)| trait_ref);
700 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
701 debug!(?trait_ref, ?nested, "generator candidate obligations");
703 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
706 fn confirm_future_candidate(
708 obligation: &TraitObligation<'tcx>,
709 ) -> Result<ImplSourceFutureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
710 // Okay to skip binder because the substs on generator types never
711 // touch bound regions, they just capture the in-scope
712 // type/region parameters.
713 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
714 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
715 bug!("closure candidate for non-closure {:?}", obligation);
718 debug!(?obligation, ?generator_def_id, ?substs, "confirm_future_candidate");
720 let gen_sig = substs.as_generator().poly_sig();
722 let trait_ref = super::util::future_trait_ref_and_outputs(
724 obligation.predicate.def_id(),
725 obligation.predicate.no_bound_vars().expect("future has no bound vars").self_ty(),
728 .map_bound(|(trait_ref, ..)| trait_ref);
730 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
731 debug!(?trait_ref, ?nested, "future candidate obligations");
733 Ok(ImplSourceFutureData { generator_def_id, substs, nested })
736 #[instrument(skip(self), level = "debug")]
737 fn confirm_closure_candidate(
739 obligation: &TraitObligation<'tcx>,
740 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
743 .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
744 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
746 // Okay to skip binder because the substs on closure types never
747 // touch bound regions, they just capture the in-scope
748 // type/region parameters.
749 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
750 let ty::Closure(closure_def_id, substs) = *self_ty.kind() else {
751 bug!("closure candidate for non-closure {:?}", obligation);
754 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
755 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
757 debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
761 if !self.tcx().sess.opts.unstable_opts.chalk {
762 nested.push(obligation.with(
764 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind)),
768 Ok(ImplSourceClosureData { closure_def_id, substs, nested })
771 /// In the case of closure types and fn pointers,
772 /// we currently treat the input type parameters on the trait as
773 /// outputs. This means that when we have a match we have only
774 /// considered the self type, so we have to go back and make sure
775 /// to relate the argument types too. This is kind of wrong, but
776 /// since we control the full set of impls, also not that wrong,
777 /// and it DOES yield better error messages (since we don't report
778 /// errors as if there is no applicable impl, but rather report
779 /// errors are about mismatched argument types.
781 /// Here is an example. Imagine we have a closure expression
782 /// and we desugared it so that the type of the expression is
783 /// `Closure`, and `Closure` expects `i32` as argument. Then it
784 /// is "as if" the compiler generated this impl:
785 /// ```ignore (illustrative)
786 /// impl Fn(i32) for Closure { ... }
788 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
789 /// we have matched the self type `Closure`. At this point we'll
790 /// compare the `i32` to `usize` and generate an error.
792 /// Note that this checking occurs *after* the impl has selected,
793 /// because these output type parameters should not affect the
794 /// selection of the impl. Therefore, if there is a mismatch, we
795 /// report an error to the user.
796 #[instrument(skip(self), level = "trace")]
797 fn confirm_poly_trait_refs(
799 obligation: &TraitObligation<'tcx>,
800 expected_trait_ref: ty::PolyTraitRef<'tcx>,
801 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
802 let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
803 // Normalize the obligation and expected trait refs together, because why not
804 let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
805 ensure_sufficient_stack(|| {
806 normalize_with_depth(
808 obligation.param_env,
809 obligation.cause.clone(),
810 obligation.recursion_depth + 1,
811 (obligation_trait_ref, expected_trait_ref),
816 .at(&obligation.cause, obligation.param_env)
817 .sup(obligation_trait_ref, expected_trait_ref)
818 .map(|InferOk { mut obligations, .. }| {
819 obligations.extend(nested);
822 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
825 fn confirm_trait_upcasting_unsize_candidate(
827 obligation: &TraitObligation<'tcx>,
829 ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
831 let tcx = self.tcx();
833 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
834 // regions here. See the comment there for more details.
835 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
836 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
837 let target = self.infcx.shallow_resolve(target);
839 debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
841 let mut nested = vec![];
842 let source_trait_ref;
843 let upcast_trait_ref;
844 match (source.kind(), target.kind()) {
845 // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
847 &ty::Dynamic(ref data_a, r_a, repr_a @ ty::Dyn),
848 &ty::Dynamic(ref data_b, r_b, ty::Dyn),
850 // See `assemble_candidates_for_unsizing` for more info.
851 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
852 let principal_a = data_a.principal().unwrap();
853 source_trait_ref = principal_a.with_self_ty(tcx, source);
854 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
855 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
856 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
857 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
861 let iter = Some(existential_predicate)
866 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
871 .map(ty::ExistentialPredicate::AutoTrait)
872 .map(ty::Binder::dummy),
874 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
875 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, repr_a);
877 // Require that the traits involved in this upcast are **equal**;
878 // only the **lifetime bound** is changed.
879 let InferOk { obligations, .. } = self
881 .at(&obligation.cause, obligation.param_env)
882 .sup(target, source_trait)
883 .map_err(|_| Unimplemented)?;
884 nested.extend(obligations);
886 // Register one obligation for 'a: 'b.
887 let cause = ObligationCause::new(
888 obligation.cause.span,
889 obligation.cause.body_id,
890 ObjectCastObligation(source, target),
892 let outlives = ty::OutlivesPredicate(r_a, r_b);
893 nested.push(Obligation::with_depth(
896 obligation.recursion_depth + 1,
897 obligation.param_env,
898 obligation.predicate.rebind(outlives),
904 let vtable_segment_callback = {
905 let mut vptr_offset = 0;
908 VtblSegment::MetadataDSA => {
909 vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
911 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
912 vptr_offset += util::count_own_vtable_entries(tcx, trait_ref);
913 if trait_ref == upcast_trait_ref {
915 return ControlFlow::Break(Some(vptr_offset));
917 return ControlFlow::Break(None);
926 ControlFlow::Continue(())
930 let vtable_vptr_slot =
931 super::super::prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback)
934 Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
937 fn confirm_builtin_unsize_candidate(
939 obligation: &TraitObligation<'tcx>,
940 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
941 let tcx = self.tcx();
943 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
944 // regions here. See the comment there for more details.
945 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
946 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
947 let target = self.infcx.shallow_resolve(target);
949 debug!(?source, ?target, "confirm_builtin_unsize_candidate");
951 let mut nested = vec![];
952 match (source.kind(), target.kind()) {
953 // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
954 (&ty::Dynamic(ref data_a, r_a, dyn_a), &ty::Dynamic(ref data_b, r_b, dyn_b))
957 // See `assemble_candidates_for_unsizing` for more info.
958 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
961 .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
966 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
971 .map(ty::ExistentialPredicate::AutoTrait)
972 .map(ty::Binder::dummy),
974 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
975 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, dyn_a);
977 // Require that the traits involved in this upcast are **equal**;
978 // only the **lifetime bound** is changed.
979 let InferOk { obligations, .. } = self
981 .at(&obligation.cause, obligation.param_env)
982 .sup(target, source_trait)
983 .map_err(|_| Unimplemented)?;
984 nested.extend(obligations);
986 // Register one obligation for 'a: 'b.
987 let cause = ObligationCause::new(
988 obligation.cause.span,
989 obligation.cause.body_id,
990 ObjectCastObligation(source, target),
992 let outlives = ty::OutlivesPredicate(r_a, r_b);
993 nested.push(Obligation::with_depth(
996 obligation.recursion_depth + 1,
997 obligation.param_env,
998 obligation.predicate.rebind(outlives),
1003 (_, &ty::Dynamic(ref data, r, ty::Dyn)) => {
1004 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
1005 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
1006 return Err(TraitNotObjectSafe(did));
1009 let cause = ObligationCause::new(
1010 obligation.cause.span,
1011 obligation.cause.body_id,
1012 ObjectCastObligation(source, target),
1015 let predicate_to_obligation = |predicate| {
1016 Obligation::with_depth(
1019 obligation.recursion_depth + 1,
1020 obligation.param_env,
1025 // Create obligations:
1026 // - Casting `T` to `Trait`
1027 // - For all the various builtin bounds attached to the object cast. (In other
1028 // words, if the object type is `Foo + Send`, this would create an obligation for
1029 // the `Send` check.)
1030 // - Projection predicates
1032 data.iter().map(|predicate| {
1033 predicate_to_obligation(predicate.with_self_ty(tcx, source))
1037 // We can only make objects from sized types.
1039 ty::Binder::dummy(tcx.at(cause.span).mk_trait_ref(LangItem::Sized, [source]));
1040 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
1042 // If the type is `Foo + 'a`, ensure that the type
1043 // being cast to `Foo + 'a` outlives `'a`:
1044 let outlives = ty::OutlivesPredicate(source, r);
1045 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
1048 // `[T; n]` -> `[T]`
1049 (&ty::Array(a, _), &ty::Slice(b)) => {
1050 let InferOk { obligations, .. } = self
1052 .at(&obligation.cause, obligation.param_env)
1054 .map_err(|_| Unimplemented)?;
1055 nested.extend(obligations);
1058 // `Struct<T>` -> `Struct<U>`
1059 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
1060 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
1061 GenericArgKind::Type(ty) => match ty.kind() {
1062 ty::Param(p) => Some(p.index),
1066 // Lifetimes aren't allowed to change during unsizing.
1067 GenericArgKind::Lifetime(_) => None,
1069 GenericArgKind::Const(ct) => match ct.kind() {
1070 ty::ConstKind::Param(p) => Some(p.index),
1075 // FIXME(eddyb) cache this (including computing `unsizing_params`)
1076 // by putting it in a query; it would only need the `DefId` as it
1077 // looks at declared field types, not anything substituted.
1079 // The last field of the structure has to exist and contain type/const parameters.
1080 let (tail_field, prefix_fields) =
1081 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
1082 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1084 let mut unsizing_params = GrowableBitSet::new_empty();
1085 for arg in tail_field_ty.0.walk() {
1086 if let Some(i) = maybe_unsizing_param_idx(arg) {
1087 unsizing_params.insert(i);
1091 // Ensure none of the other fields mention the parameters used
1093 for field in prefix_fields {
1094 for arg in tcx.type_of(field.did).walk() {
1095 if let Some(i) = maybe_unsizing_param_idx(arg) {
1096 unsizing_params.remove(i);
1101 if unsizing_params.is_empty() {
1102 return Err(Unimplemented);
1105 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
1106 // normalizing in the process, since `type_of` returns something directly from
1107 // astconv (which means it's un-normalized).
1108 let source_tail = normalize_with_depth_to(
1110 obligation.param_env,
1111 obligation.cause.clone(),
1112 obligation.recursion_depth + 1,
1113 tail_field_ty.subst(tcx, substs_a),
1116 let target_tail = normalize_with_depth_to(
1118 obligation.param_env,
1119 obligation.cause.clone(),
1120 obligation.recursion_depth + 1,
1121 tail_field_ty.subst(tcx, substs_b),
1125 // Check that the source struct with the target's
1126 // unsizing parameters is equal to the target.
1127 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1128 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1130 let new_struct = tcx.mk_adt(def, substs);
1131 let InferOk { obligations, .. } = self
1133 .at(&obligation.cause, obligation.param_env)
1134 .eq(target, new_struct)
1135 .map_err(|_| Unimplemented)?;
1136 nested.extend(obligations);
1138 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1139 nested.push(predicate_for_trait_def(
1141 obligation.param_env,
1142 obligation.cause.clone(),
1143 obligation.predicate.def_id(),
1144 obligation.recursion_depth + 1,
1145 [source_tail, target_tail],
1149 // `(.., T)` -> `(.., U)`
1150 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1151 assert_eq!(tys_a.len(), tys_b.len());
1153 // The last field of the tuple has to exist.
1154 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1155 let &b_last = tys_b.last().unwrap();
1157 // Check that the source tuple with the target's
1158 // last element is equal to the target.
1159 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1160 let InferOk { obligations, .. } = self
1162 .at(&obligation.cause, obligation.param_env)
1163 .eq(target, new_tuple)
1164 .map_err(|_| Unimplemented)?;
1165 nested.extend(obligations);
1167 // Construct the nested `T: Unsize<U>` predicate.
1168 nested.push(ensure_sufficient_stack(|| {
1169 predicate_for_trait_def(
1171 obligation.param_env,
1172 obligation.cause.clone(),
1173 obligation.predicate.def_id(),
1174 obligation.recursion_depth + 1,
1180 _ => bug!("source: {source}, target: {target}"),
1183 Ok(ImplSourceBuiltinData { nested })
1186 fn confirm_const_destruct_candidate(
1188 obligation: &TraitObligation<'tcx>,
1189 impl_def_id: Option<DefId>,
1190 ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1191 // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1192 if !obligation.is_const() {
1193 return Ok(ImplSourceConstDestructData { nested: vec![] });
1196 let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1198 let tcx = self.tcx();
1199 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1201 let mut nested = vec![];
1202 let cause = obligation.derived_cause(BuiltinDerivedObligation);
1204 // If we have a custom `impl const Drop`, then
1205 // first check it like a regular impl candidate.
1206 // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1207 if let Some(impl_def_id) = impl_def_id {
1208 let mut new_obligation = obligation.clone();
1209 new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1210 trait_pred.trait_ref.def_id = drop_trait;
1213 let substs = self.rematch_impl(impl_def_id, &new_obligation);
1214 debug!(?substs, "impl substs");
1216 let cause = obligation.derived_cause(|derived| {
1217 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1220 span: obligation.cause.span,
1223 let obligations = ensure_sufficient_stack(|| {
1228 new_obligation.recursion_depth + 1,
1229 new_obligation.param_env,
1230 obligation.predicate,
1233 nested.extend(obligations.nested);
1236 // We want to confirm the ADT's fields if we have an ADT
1237 let mut stack = match *self_ty.skip_binder().kind() {
1238 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1239 _ => vec![self_ty.skip_binder()],
1242 while let Some(nested_ty) = stack.pop() {
1243 match *nested_ty.kind() {
1244 // We know these types are trivially drop
1250 | ty::Infer(ty::IntVar(_))
1251 | ty::Infer(ty::FloatVar(_))
1258 | ty::Foreign(_) => {}
1260 // `ManuallyDrop` is trivially drop
1261 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().manually_drop() => {}
1263 // These types are built-in, so we can fast-track by registering
1264 // nested predicates for their constituent type(s)
1265 ty::Array(ty, _) | ty::Slice(ty) => {
1269 stack.extend(tys.iter());
1271 ty::Closure(_, substs) => {
1272 stack.push(substs.as_closure().tupled_upvars_ty());
1274 ty::Generator(_, substs, _) => {
1275 let generator = substs.as_generator();
1276 stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1278 ty::GeneratorWitness(tys) => {
1279 stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1282 // If we have a projection type, make sure to normalize it so we replace it
1283 // with a fresh infer variable
1284 ty::Projection(..) => {
1285 let predicate = normalize_with_depth_to(
1287 obligation.param_env,
1289 obligation.recursion_depth + 1,
1290 self_ty.rebind(ty::TraitPredicate {
1294 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1295 constness: ty::BoundConstness::ConstIfConst,
1296 polarity: ty::ImplPolarity::Positive,
1301 nested.push(Obligation::with_depth(
1304 obligation.recursion_depth + 1,
1305 obligation.param_env,
1310 // If we have any other type (e.g. an ADT), just register a nested obligation
1311 // since it's either not `const Drop` (and we raise an error during selection),
1312 // or it's an ADT (and we need to check for a custom impl during selection)
1314 let predicate = self_ty.rebind(ty::TraitPredicate {
1318 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1319 constness: ty::BoundConstness::ConstIfConst,
1320 polarity: ty::ImplPolarity::Positive,
1323 nested.push(Obligation::with_depth(
1326 obligation.recursion_depth + 1,
1327 obligation.param_env,
1334 Ok(ImplSourceConstDestructData { nested })