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::{self, GenericParamDefKind, Ty, TyCtxt};
15 use rustc_middle::ty::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
16 use rustc_middle::ty::{ToPolyTraitRef, ToPredicate};
17 use rustc_span::def_id::DefId;
19 use crate::traits::project::{normalize_with_depth, normalize_with_depth_to};
20 use crate::traits::util::{self, closure_trait_ref_and_return_type, predicate_for_trait_def};
22 BuiltinDerivedObligation, ImplDerivedObligation, ImplDerivedObligationCause, ImplSource,
23 ImplSourceAutoImplData, ImplSourceBuiltinData, ImplSourceClosureData,
24 ImplSourceConstDestructData, ImplSourceDiscriminantKindData, ImplSourceFnPointerData,
25 ImplSourceGeneratorData, ImplSourceObjectData, ImplSourcePointeeData, ImplSourceTraitAliasData,
26 ImplSourceTraitUpcastingData, ImplSourceUserDefinedData, Normalized, ObjectCastObligation,
27 Obligation, ObligationCause, OutputTypeParameterMismatch, PredicateObligation, Selection,
28 SelectionError, TraitNotObjectSafe, TraitObligation, Unimplemented, VtblSegment,
31 use super::BuiltinImplConditions;
32 use super::SelectionCandidate::{self, *};
33 use super::SelectionContext;
36 use std::ops::ControlFlow;
38 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
39 #[instrument(level = "debug", skip(self))]
40 pub(super) fn confirm_candidate(
42 obligation: &TraitObligation<'tcx>,
43 candidate: SelectionCandidate<'tcx>,
44 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
45 let mut impl_src = match candidate {
46 BuiltinCandidate { has_nested } => {
47 let data = self.confirm_builtin_candidate(obligation, has_nested);
48 ImplSource::Builtin(data)
51 TransmutabilityCandidate => {
52 let data = self.confirm_transmutability_candidate(obligation)?;
53 ImplSource::Builtin(data)
56 ParamCandidate(param) => {
58 self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref));
59 ImplSource::Param(obligations, param.skip_binder().constness)
62 ImplCandidate(impl_def_id) => {
63 ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id))
66 AutoImplCandidate(trait_def_id) => {
67 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
68 ImplSource::AutoImpl(data)
71 ProjectionCandidate(idx, constness) => {
72 let obligations = self.confirm_projection_candidate(obligation, idx)?;
73 ImplSource::Param(obligations, constness)
76 ObjectCandidate(idx) => {
77 let data = self.confirm_object_candidate(obligation, idx)?;
78 ImplSource::Object(data)
82 let vtable_closure = self.confirm_closure_candidate(obligation)?;
83 ImplSource::Closure(vtable_closure)
86 GeneratorCandidate => {
87 let vtable_generator = self.confirm_generator_candidate(obligation)?;
88 ImplSource::Generator(vtable_generator)
91 FnPointerCandidate { .. } => {
92 let data = self.confirm_fn_pointer_candidate(obligation)?;
93 ImplSource::FnPointer(data)
96 DiscriminantKindCandidate => {
97 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
100 PointeeCandidate => ImplSource::Pointee(ImplSourcePointeeData),
102 TraitAliasCandidate(alias_def_id) => {
103 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
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)
129 TupleCandidate => ImplSource::Tuple,
132 if !obligation.predicate.is_const_if_const() {
133 // normalize nested predicates according to parent predicate's constness.
134 impl_src = impl_src.map(|mut o| {
135 o.predicate = o.predicate.without_const(self.tcx());
143 fn confirm_projection_candidate(
145 obligation: &TraitObligation<'tcx>,
147 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
148 let tcx = self.tcx();
150 let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
151 let placeholder_trait_predicate =
152 self.infcx().replace_bound_vars_with_placeholders(trait_predicate).trait_ref;
153 let placeholder_self_ty = placeholder_trait_predicate.self_ty();
154 let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate);
155 let (def_id, substs) = match *placeholder_self_ty.kind() {
156 ty::Projection(proj) => (proj.item_def_id, proj.substs),
157 ty::Opaque(def_id, substs) => (def_id, substs),
158 _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
161 let candidate_predicate =
162 tcx.bound_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::Projection(..) = placeholder_self_ty.kind() {
186 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates;
187 debug!(?predicates, "projection predicates");
188 for predicate in predicates {
189 let normalized = normalize_with_depth_to(
191 obligation.param_env,
192 obligation.cause.clone(),
193 obligation.recursion_depth + 1,
197 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));
295 let cause = obligation.cause.clone();
297 let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
299 let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume);
301 use rustc_transmute::Answer;
303 match maybe_transmutable {
304 Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }),
305 _ => Err(Unimplemented),
309 /// This handles the case where an `auto trait Foo` impl is being used.
310 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
312 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
313 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
314 fn confirm_auto_impl_candidate(
316 obligation: &TraitObligation<'tcx>,
318 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
319 debug!(?obligation, ?trait_def_id, "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, trait_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::new(
486 obligation.cause.clone(),
487 obligation.param_env,
488 normalized_super_trait,
492 let assoc_types: Vec<_> = tcx
493 .associated_items(trait_predicate.def_id())
494 .in_definition_order()
496 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
500 for assoc_type in assoc_types {
501 let defs: &ty::Generics = tcx.generics_of(assoc_type);
503 if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
504 tcx.sess.delay_span_bug(
505 obligation.cause.span,
506 "GATs in trait object shouldn't have been considered",
508 return Err(SelectionError::Unimplemented);
511 // This maybe belongs in wf, but that can't (doesn't) handle
512 // higher-ranked things.
513 // Prevent, e.g., `dyn Iterator<Item = str>`.
514 for bound in self.tcx().bound_item_bounds(assoc_type).transpose_iter() {
516 if defs.count() == 0 {
517 bound.subst(tcx, trait_predicate.trait_ref.substs)
519 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
520 substs.extend(trait_predicate.trait_ref.substs.iter());
521 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
522 smallvec::SmallVec::with_capacity(
523 bound.0.kind().bound_vars().len() + defs.count(),
525 bound_vars.extend(bound.0.kind().bound_vars().into_iter());
526 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
529 GenericParamDefKind::Type { .. } => {
530 let kind = ty::BoundTyKind::Param(param.name);
531 let bound_var = ty::BoundVariableKind::Ty(kind);
532 bound_vars.push(bound_var);
536 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
542 GenericParamDefKind::Lifetime => {
543 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
544 let bound_var = ty::BoundVariableKind::Region(kind);
545 bound_vars.push(bound_var);
546 tcx.mk_region(ty::ReLateBound(
549 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
555 GenericParamDefKind::Const { .. } => {
556 let bound_var = ty::BoundVariableKind::Const;
557 bound_vars.push(bound_var);
558 tcx.mk_const(ty::ConstS {
559 ty: tcx.type_of(param.def_id),
560 kind: ty::ConstKind::Bound(
562 ty::BoundVar::from_usize(bound_vars.len() - 1),
568 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
569 let assoc_ty_substs = tcx.intern_substs(&substs);
571 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
573 bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs);
574 tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
576 let normalized_bound = normalize_with_depth_to(
578 obligation.param_env,
579 obligation.cause.clone(),
580 obligation.recursion_depth + 1,
584 nested.push(Obligation::new(
585 obligation.cause.clone(),
586 obligation.param_env,
592 debug!(?nested, "object nested obligations");
594 let vtable_base = super::super::vtable_trait_first_method_offset(
596 (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
599 Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
602 fn confirm_fn_pointer_candidate(
604 obligation: &TraitObligation<'tcx>,
605 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
607 debug!(?obligation, "confirm_fn_pointer_candidate");
609 // Okay to skip binder; it is reintroduced below.
610 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
611 let sig = self_ty.fn_sig(self.tcx());
612 let trait_ref = closure_trait_ref_and_return_type(
614 obligation.predicate.def_id(),
617 util::TupleArgumentsFlag::Yes,
619 .map_bound(|(trait_ref, _)| trait_ref);
621 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
623 // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
624 let cause = obligation.derived_cause(BuiltinDerivedObligation);
625 // The binder on the Fn obligation is "less" important than the one on
626 // the signature, as evidenced by how we treat it during projection.
627 // The safe thing to do here is to liberate it, though, which should
628 // have no worse effect than skipping the binder here.
629 let liberated_fn_ty =
630 self.infcx.replace_bound_vars_with_placeholders(obligation.predicate.rebind(self_ty));
633 .replace_bound_vars_with_placeholders(liberated_fn_ty.fn_sig(self.tcx()).output());
634 let output_ty = normalize_with_depth_to(
636 obligation.param_env,
638 obligation.recursion_depth,
642 let tr = ty::Binder::dummy(ty::TraitRef::new(
643 self.tcx().require_lang_item(LangItem::Sized, None),
644 self.tcx().mk_substs_trait(output_ty, &[]),
646 nested.push(Obligation::new(
648 obligation.param_env,
649 tr.to_poly_trait_predicate().to_predicate(self.tcx()),
652 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
655 fn confirm_trait_alias_candidate(
657 obligation: &TraitObligation<'tcx>,
659 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
660 debug!(?obligation, ?alias_def_id, "confirm_trait_alias_candidate");
662 let predicate = self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
663 let trait_ref = predicate.trait_ref;
664 let trait_def_id = trait_ref.def_id;
665 let substs = trait_ref.substs;
667 let trait_obligations = self.impl_or_trait_obligations(
669 obligation.recursion_depth,
670 obligation.param_env,
673 obligation.predicate,
676 debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
678 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
681 fn confirm_generator_candidate(
683 obligation: &TraitObligation<'tcx>,
684 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
686 // Okay to skip binder because the substs on generator types never
687 // touch bound regions, they just capture the in-scope
688 // type/region parameters.
689 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
690 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
691 bug!("closure candidate for non-closure {:?}", obligation);
694 debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
696 let trait_ref = self.generator_trait_ref_unnormalized(obligation, substs);
698 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
699 debug!(?trait_ref, ?nested, "generator candidate obligations");
701 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
704 #[instrument(skip(self), level = "debug")]
705 fn confirm_closure_candidate(
707 obligation: &TraitObligation<'tcx>,
708 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
711 .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
712 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
714 // Okay to skip binder because the substs on closure types never
715 // touch bound regions, they just capture the in-scope
716 // type/region parameters.
717 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
718 let ty::Closure(closure_def_id, substs) = *self_ty.kind() else {
719 bug!("closure candidate for non-closure {:?}", obligation);
722 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
723 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
725 debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
729 if !self.tcx().sess.opts.unstable_opts.chalk {
730 nested.push(Obligation::new(
731 obligation.cause.clone(),
732 obligation.param_env,
733 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind))
734 .to_predicate(self.tcx()),
738 Ok(ImplSourceClosureData { closure_def_id, substs, nested })
741 /// In the case of closure types and fn pointers,
742 /// we currently treat the input type parameters on the trait as
743 /// outputs. This means that when we have a match we have only
744 /// considered the self type, so we have to go back and make sure
745 /// to relate the argument types too. This is kind of wrong, but
746 /// since we control the full set of impls, also not that wrong,
747 /// and it DOES yield better error messages (since we don't report
748 /// errors as if there is no applicable impl, but rather report
749 /// errors are about mismatched argument types.
751 /// Here is an example. Imagine we have a closure expression
752 /// and we desugared it so that the type of the expression is
753 /// `Closure`, and `Closure` expects `i32` as argument. Then it
754 /// is "as if" the compiler generated this impl:
755 /// ```ignore (illustrative)
756 /// impl Fn(i32) for Closure { ... }
758 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
759 /// we have matched the self type `Closure`. At this point we'll
760 /// compare the `i32` to `usize` and generate an error.
762 /// Note that this checking occurs *after* the impl has selected,
763 /// because these output type parameters should not affect the
764 /// selection of the impl. Therefore, if there is a mismatch, we
765 /// report an error to the user.
766 #[instrument(skip(self), level = "trace")]
767 fn confirm_poly_trait_refs(
769 obligation: &TraitObligation<'tcx>,
770 expected_trait_ref: ty::PolyTraitRef<'tcx>,
771 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
772 let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
773 // Normalize the obligation and expected trait refs together, because why not
774 let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
775 ensure_sufficient_stack(|| {
776 normalize_with_depth(
778 obligation.param_env,
779 obligation.cause.clone(),
780 obligation.recursion_depth + 1,
781 (obligation_trait_ref, expected_trait_ref),
786 .at(&obligation.cause, obligation.param_env)
787 .sup(obligation_trait_ref, expected_trait_ref)
788 .map(|InferOk { mut obligations, .. }| {
789 obligations.extend(nested);
792 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
795 fn confirm_trait_upcasting_unsize_candidate(
797 obligation: &TraitObligation<'tcx>,
799 ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
801 let tcx = self.tcx();
803 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
804 // regions here. See the comment there for more details.
805 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
806 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
807 let target = self.infcx.shallow_resolve(target);
809 debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
811 let mut nested = vec![];
812 let source_trait_ref;
813 let upcast_trait_ref;
814 match (source.kind(), target.kind()) {
815 // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
816 (&ty::Dynamic(ref data_a, r_a, repr_a), &ty::Dynamic(ref data_b, r_b, repr_b))
817 if repr_a == repr_b =>
819 // See `assemble_candidates_for_unsizing` for more info.
820 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
821 let principal_a = data_a.principal().unwrap();
822 source_trait_ref = principal_a.with_self_ty(tcx, source);
823 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
824 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
825 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
826 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
830 let iter = Some(existential_predicate)
835 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
840 .map(ty::ExistentialPredicate::AutoTrait)
841 .map(ty::Binder::dummy),
843 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
844 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, repr_b);
846 // Require that the traits involved in this upcast are **equal**;
847 // only the **lifetime bound** is changed.
848 let InferOk { obligations, .. } = self
850 .at(&obligation.cause, obligation.param_env)
851 .sup(target, source_trait)
852 .map_err(|_| Unimplemented)?;
853 nested.extend(obligations);
855 // Register one obligation for 'a: 'b.
856 let cause = ObligationCause::new(
857 obligation.cause.span,
858 obligation.cause.body_id,
859 ObjectCastObligation(source, target),
861 let outlives = ty::OutlivesPredicate(r_a, r_b);
862 nested.push(Obligation::with_depth(
864 obligation.recursion_depth + 1,
865 obligation.param_env,
866 obligation.predicate.rebind(outlives).to_predicate(tcx),
872 let vtable_segment_callback = {
873 let mut vptr_offset = 0;
876 VtblSegment::MetadataDSA => {
877 vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
879 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
880 vptr_offset += util::count_own_vtable_entries(tcx, trait_ref);
881 if trait_ref == upcast_trait_ref {
883 return ControlFlow::Break(Some(vptr_offset));
885 return ControlFlow::Break(None);
894 ControlFlow::Continue(())
898 let vtable_vptr_slot =
899 super::super::prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback)
902 Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
905 fn confirm_builtin_unsize_candidate(
907 obligation: &TraitObligation<'tcx>,
908 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
909 let tcx = self.tcx();
911 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
912 // regions here. See the comment there for more details.
913 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
914 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
915 let target = self.infcx.shallow_resolve(target);
917 debug!(?source, ?target, "confirm_builtin_unsize_candidate");
919 let mut nested = vec![];
920 match (source.kind(), target.kind()) {
921 // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
922 (&ty::Dynamic(ref data_a, r_a, ty::Dyn), &ty::Dynamic(ref data_b, r_b, ty::Dyn)) => {
923 // See `assemble_candidates_for_unsizing` for more info.
924 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
927 .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
932 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
937 .map(ty::ExistentialPredicate::AutoTrait)
938 .map(ty::Binder::dummy),
940 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
941 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, ty::Dyn);
943 // Require that the traits involved in this upcast are **equal**;
944 // only the **lifetime bound** is changed.
945 let InferOk { obligations, .. } = self
947 .at(&obligation.cause, obligation.param_env)
948 .sup(target, source_trait)
949 .map_err(|_| Unimplemented)?;
950 nested.extend(obligations);
952 // Register one obligation for 'a: 'b.
953 let cause = ObligationCause::new(
954 obligation.cause.span,
955 obligation.cause.body_id,
956 ObjectCastObligation(source, target),
958 let outlives = ty::OutlivesPredicate(r_a, r_b);
959 nested.push(Obligation::with_depth(
961 obligation.recursion_depth + 1,
962 obligation.param_env,
963 obligation.predicate.rebind(outlives).to_predicate(tcx),
968 (_, &ty::Dynamic(ref data, r, ty::Dyn)) => {
969 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
970 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
971 return Err(TraitNotObjectSafe(did));
974 let cause = ObligationCause::new(
975 obligation.cause.span,
976 obligation.cause.body_id,
977 ObjectCastObligation(source, target),
980 let predicate_to_obligation = |predicate| {
981 Obligation::with_depth(
983 obligation.recursion_depth + 1,
984 obligation.param_env,
989 // Create obligations:
990 // - Casting `T` to `Trait`
991 // - For all the various builtin bounds attached to the object cast. (In other
992 // words, if the object type is `Foo + Send`, this would create an obligation for
993 // the `Send` check.)
994 // - Projection predicates
996 data.iter().map(|predicate| {
997 predicate_to_obligation(predicate.with_self_ty(tcx, source))
1001 // We can only make objects from sized types.
1002 let tr = ty::Binder::dummy(ty::TraitRef::new(
1003 tcx.require_lang_item(LangItem::Sized, None),
1004 tcx.mk_substs_trait(source, &[]),
1006 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
1008 // If the type is `Foo + 'a`, ensure that the type
1009 // being cast to `Foo + 'a` outlives `'a`:
1010 let outlives = ty::OutlivesPredicate(source, r);
1011 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
1014 // `[T; n]` -> `[T]`
1015 (&ty::Array(a, _), &ty::Slice(b)) => {
1016 let InferOk { obligations, .. } = self
1018 .at(&obligation.cause, obligation.param_env)
1020 .map_err(|_| Unimplemented)?;
1021 nested.extend(obligations);
1024 // `Struct<T>` -> `Struct<U>`
1025 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
1026 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
1027 GenericArgKind::Type(ty) => match ty.kind() {
1028 ty::Param(p) => Some(p.index),
1032 // Lifetimes aren't allowed to change during unsizing.
1033 GenericArgKind::Lifetime(_) => None,
1035 GenericArgKind::Const(ct) => match ct.kind() {
1036 ty::ConstKind::Param(p) => Some(p.index),
1041 // FIXME(eddyb) cache this (including computing `unsizing_params`)
1042 // by putting it in a query; it would only need the `DefId` as it
1043 // looks at declared field types, not anything substituted.
1045 // The last field of the structure has to exist and contain type/const parameters.
1046 let (tail_field, prefix_fields) =
1047 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
1048 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1050 let mut unsizing_params = GrowableBitSet::new_empty();
1051 for arg in tail_field_ty.0.walk() {
1052 if let Some(i) = maybe_unsizing_param_idx(arg) {
1053 unsizing_params.insert(i);
1057 // Ensure none of the other fields mention the parameters used
1059 for field in prefix_fields {
1060 for arg in tcx.type_of(field.did).walk() {
1061 if let Some(i) = maybe_unsizing_param_idx(arg) {
1062 unsizing_params.remove(i);
1067 if unsizing_params.is_empty() {
1068 return Err(Unimplemented);
1071 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
1072 // normalizing in the process, since `type_of` returns something directly from
1073 // astconv (which means it's un-normalized).
1074 let source_tail = normalize_with_depth_to(
1076 obligation.param_env,
1077 obligation.cause.clone(),
1078 obligation.recursion_depth + 1,
1079 tail_field_ty.subst(tcx, substs_a),
1082 let target_tail = normalize_with_depth_to(
1084 obligation.param_env,
1085 obligation.cause.clone(),
1086 obligation.recursion_depth + 1,
1087 tail_field_ty.subst(tcx, substs_b),
1091 // Check that the source struct with the target's
1092 // unsizing parameters is equal to the target.
1093 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1094 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1096 let new_struct = tcx.mk_adt(def, substs);
1097 let InferOk { obligations, .. } = self
1099 .at(&obligation.cause, obligation.param_env)
1100 .eq(target, new_struct)
1101 .map_err(|_| Unimplemented)?;
1102 nested.extend(obligations);
1104 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1105 nested.push(predicate_for_trait_def(
1107 obligation.param_env,
1108 obligation.cause.clone(),
1109 obligation.predicate.def_id(),
1110 obligation.recursion_depth + 1,
1112 &[target_tail.into()],
1116 // `(.., T)` -> `(.., U)`
1117 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1118 assert_eq!(tys_a.len(), tys_b.len());
1120 // The last field of the tuple has to exist.
1121 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1122 let &b_last = tys_b.last().unwrap();
1124 // Check that the source tuple with the target's
1125 // last element is equal to the target.
1126 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1127 let InferOk { obligations, .. } = self
1129 .at(&obligation.cause, obligation.param_env)
1130 .eq(target, new_tuple)
1131 .map_err(|_| Unimplemented)?;
1132 nested.extend(obligations);
1134 // Construct the nested `T: Unsize<U>` predicate.
1135 nested.push(ensure_sufficient_stack(|| {
1136 predicate_for_trait_def(
1138 obligation.param_env,
1139 obligation.cause.clone(),
1140 obligation.predicate.def_id(),
1141 obligation.recursion_depth + 1,
1151 Ok(ImplSourceBuiltinData { nested })
1154 fn confirm_const_destruct_candidate(
1156 obligation: &TraitObligation<'tcx>,
1157 impl_def_id: Option<DefId>,
1158 ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1159 // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1160 if !obligation.is_const() {
1161 return Ok(ImplSourceConstDestructData { nested: vec![] });
1164 let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1166 let tcx = self.tcx();
1167 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1169 let mut nested = vec![];
1170 let cause = obligation.derived_cause(BuiltinDerivedObligation);
1172 // If we have a custom `impl const Drop`, then
1173 // first check it like a regular impl candidate.
1174 // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1175 if let Some(impl_def_id) = impl_def_id {
1176 let mut new_obligation = obligation.clone();
1177 new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1178 trait_pred.trait_ref.def_id = drop_trait;
1181 let substs = self.rematch_impl(impl_def_id, &new_obligation);
1182 debug!(?substs, "impl substs");
1184 let cause = obligation.derived_cause(|derived| {
1185 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1188 span: obligation.cause.span,
1191 let obligations = ensure_sufficient_stack(|| {
1196 new_obligation.recursion_depth + 1,
1197 new_obligation.param_env,
1198 obligation.predicate,
1201 nested.extend(obligations.nested);
1204 // We want to confirm the ADT's fields if we have an ADT
1205 let mut stack = match *self_ty.skip_binder().kind() {
1206 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1207 _ => vec![self_ty.skip_binder()],
1210 while let Some(nested_ty) = stack.pop() {
1211 match *nested_ty.kind() {
1212 // We know these types are trivially drop
1218 | ty::Infer(ty::IntVar(_))
1219 | ty::Infer(ty::FloatVar(_))
1226 | ty::Foreign(_) => {}
1228 // `ManuallyDrop` is trivially drop
1229 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().manually_drop() => {}
1231 // These types are built-in, so we can fast-track by registering
1232 // nested predicates for their constituent type(s)
1233 ty::Array(ty, _) | ty::Slice(ty) => {
1237 stack.extend(tys.iter());
1239 ty::Closure(_, substs) => {
1240 stack.push(substs.as_closure().tupled_upvars_ty());
1242 ty::Generator(_, substs, _) => {
1243 let generator = substs.as_generator();
1244 stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1246 ty::GeneratorWitness(tys) => {
1247 stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1250 // If we have a projection type, make sure to normalize it so we replace it
1251 // with a fresh infer variable
1252 ty::Projection(..) => {
1253 let predicate = normalize_with_depth_to(
1255 obligation.param_env,
1257 obligation.recursion_depth + 1,
1259 .rebind(ty::TraitPredicate {
1260 trait_ref: ty::TraitRef {
1261 def_id: self.tcx().require_lang_item(LangItem::Destruct, None),
1262 substs: self.tcx().mk_substs_trait(nested_ty, &[]),
1264 constness: ty::BoundConstness::ConstIfConst,
1265 polarity: ty::ImplPolarity::Positive,
1271 nested.push(Obligation::with_depth(
1273 obligation.recursion_depth + 1,
1274 obligation.param_env,
1279 // If we have any other type (e.g. an ADT), just register a nested obligation
1280 // since it's either not `const Drop` (and we raise an error during selection),
1281 // or it's an ADT (and we need to check for a custom impl during selection)
1283 let predicate = self_ty
1284 .rebind(ty::TraitPredicate {
1285 trait_ref: ty::TraitRef {
1286 def_id: self.tcx().require_lang_item(LangItem::Destruct, None),
1287 substs: self.tcx().mk_substs_trait(nested_ty, &[]),
1289 constness: ty::BoundConstness::ConstIfConst,
1290 polarity: ty::ImplPolarity::Positive,
1294 nested.push(Obligation::with_depth(
1296 obligation.recursion_depth + 1,
1297 obligation.param_env,
1304 Ok(ImplSourceConstDestructData { nested })