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::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef};
15 use rustc_middle::ty::{self, EarlyBinder, GenericParamDefKind, Ty, TyCtxt};
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 obligation = obligation;
48 // HACK(const_trait_impl): the surrounding environment is remapped to a non-const context
49 // because nested obligations might be actually `~const` then (incorrectly) requiring
50 // const impls. for example:
53 // pub trait Sub: Super {}
55 // impl<A> const Super for &A where A: ~const Super {}
56 // impl<A> const Sub for &A where A: ~const Sub {}
59 // The procedure to check the code above without the remapping code is as follows:
61 // CheckWf(impl const Sub for &A where A: ~const Sub) // <- const env
62 // CheckPredicate(&A: Super)
63 // CheckPredicate(A: ~const Super) // <- still const env, failure
65 if obligation.param_env.is_const() && !obligation.predicate.is_const_if_const() {
66 new_obligation = TraitObligation {
67 cause: obligation.cause.clone(),
68 param_env: obligation.param_env.without_const(),
71 obligation = &new_obligation;
75 BuiltinCandidate { has_nested } => {
76 let data = self.confirm_builtin_candidate(obligation, has_nested);
77 Ok(ImplSource::Builtin(data))
80 ParamCandidate(param) => {
82 self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref));
83 Ok(ImplSource::Param(obligations, param.skip_binder().constness))
86 ImplCandidate(impl_def_id) => {
87 Ok(ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id)))
90 AutoImplCandidate(trait_def_id) => {
91 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
92 Ok(ImplSource::AutoImpl(data))
95 ProjectionCandidate(idx) => {
96 let obligations = self.confirm_projection_candidate(obligation, idx)?;
97 // FIXME(jschievink): constness
98 Ok(ImplSource::Param(obligations, ty::BoundConstness::NotConst))
101 ObjectCandidate(idx) => {
102 let data = self.confirm_object_candidate(obligation, idx)?;
103 Ok(ImplSource::Object(data))
106 ClosureCandidate => {
107 let vtable_closure = self.confirm_closure_candidate(obligation)?;
108 Ok(ImplSource::Closure(vtable_closure))
111 GeneratorCandidate => {
112 let vtable_generator = self.confirm_generator_candidate(obligation)?;
113 Ok(ImplSource::Generator(vtable_generator))
116 FnPointerCandidate { .. } => {
117 let data = self.confirm_fn_pointer_candidate(obligation)?;
118 Ok(ImplSource::FnPointer(data))
121 DiscriminantKindCandidate => {
122 Ok(ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData))
125 PointeeCandidate => Ok(ImplSource::Pointee(ImplSourcePointeeData)),
127 TraitAliasCandidate(alias_def_id) => {
128 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
129 Ok(ImplSource::TraitAlias(data))
132 BuiltinObjectCandidate => {
133 // This indicates something like `Trait + Send: Send`. In this case, we know that
134 // this holds because that's what the object type is telling us, and there's really
135 // no additional obligations to prove and no types in particular to unify, etc.
136 Ok(ImplSource::Param(Vec::new(), ty::BoundConstness::NotConst))
139 BuiltinUnsizeCandidate => {
140 let data = self.confirm_builtin_unsize_candidate(obligation)?;
141 Ok(ImplSource::Builtin(data))
144 TraitUpcastingUnsizeCandidate(idx) => {
145 let data = self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?;
146 Ok(ImplSource::TraitUpcasting(data))
149 ConstDestructCandidate(def_id) => {
150 let data = self.confirm_const_destruct_candidate(obligation, def_id)?;
151 Ok(ImplSource::ConstDestruct(data))
156 fn confirm_projection_candidate(
158 obligation: &TraitObligation<'tcx>,
160 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
161 self.infcx.commit_unconditionally(|_| {
162 let tcx = self.tcx();
164 let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
165 let placeholder_trait_predicate =
166 self.infcx().replace_bound_vars_with_placeholders(trait_predicate).trait_ref;
167 let placeholder_self_ty = placeholder_trait_predicate.self_ty();
168 let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate);
169 let (def_id, substs) = match *placeholder_self_ty.kind() {
170 ty::Projection(proj) => (proj.item_def_id, proj.substs),
171 ty::Opaque(def_id, substs) => (def_id, substs),
172 _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
175 let candidate_predicate =
176 tcx.bound_item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs);
177 let candidate = candidate_predicate
178 .to_opt_poly_trait_pred()
179 .expect("projection candidate is not a trait predicate")
180 .map_bound(|t| t.trait_ref);
181 let mut obligations = Vec::new();
182 let candidate = normalize_with_depth_to(
184 obligation.param_env,
185 obligation.cause.clone(),
186 obligation.recursion_depth + 1,
191 obligations.extend(self.infcx.commit_if_ok(|_| {
193 .at(&obligation.cause, obligation.param_env)
194 .sup(placeholder_trait_predicate, candidate)
195 .map(|InferOk { obligations, .. }| obligations)
196 .map_err(|_| Unimplemented)
199 if let ty::Projection(..) = placeholder_self_ty.kind() {
200 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates;
201 debug!(?predicates, "projection predicates");
202 for predicate in predicates {
203 let normalized = normalize_with_depth_to(
205 obligation.param_env,
206 obligation.cause.clone(),
207 obligation.recursion_depth + 1,
211 obligations.push(Obligation::with_depth(
212 obligation.cause.clone(),
213 obligation.recursion_depth + 1,
214 obligation.param_env,
224 fn confirm_param_candidate(
226 obligation: &TraitObligation<'tcx>,
227 param: ty::PolyTraitRef<'tcx>,
228 ) -> Vec<PredicateObligation<'tcx>> {
229 debug!(?obligation, ?param, "confirm_param_candidate");
231 // During evaluation, we already checked that this
232 // where-clause trait-ref could be unified with the obligation
233 // trait-ref. Repeat that unification now without any
234 // transactional boundary; it should not fail.
235 match self.match_where_clause_trait_ref(obligation, param) {
236 Ok(obligations) => obligations,
239 "Where clause `{:?}` was applicable to `{:?}` but now is not",
247 fn confirm_builtin_candidate(
249 obligation: &TraitObligation<'tcx>,
251 ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
252 debug!(?obligation, ?has_nested, "confirm_builtin_candidate");
254 let lang_items = self.tcx().lang_items();
255 let obligations = if has_nested {
256 let trait_def = obligation.predicate.def_id();
257 let conditions = if Some(trait_def) == lang_items.sized_trait() {
258 self.sized_conditions(obligation)
259 } else if Some(trait_def) == lang_items.copy_trait() {
260 self.copy_clone_conditions(obligation)
261 } else if Some(trait_def) == lang_items.clone_trait() {
262 self.copy_clone_conditions(obligation)
264 bug!("unexpected builtin trait {:?}", trait_def)
266 let BuiltinImplConditions::Where(nested) = conditions else {
267 bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
270 let cause = obligation.derived_cause(BuiltinDerivedObligation);
271 ensure_sufficient_stack(|| {
272 self.collect_predicates_for_types(
273 obligation.param_env,
275 obligation.recursion_depth + 1,
284 debug!(?obligations);
286 ImplSourceBuiltinData { nested: obligations }
289 /// This handles the case where an `auto trait Foo` impl is being used.
290 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
292 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
293 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
294 fn confirm_auto_impl_candidate(
296 obligation: &TraitObligation<'tcx>,
298 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
299 debug!(?obligation, ?trait_def_id, "confirm_auto_impl_candidate");
301 let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
302 let types = self.constituent_types_for_ty(self_ty);
303 self.vtable_auto_impl(obligation, trait_def_id, types)
306 /// See `confirm_auto_impl_candidate`.
309 obligation: &TraitObligation<'tcx>,
311 nested: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
312 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
313 debug!(?nested, "vtable_auto_impl");
314 ensure_sufficient_stack(|| {
315 let cause = obligation.derived_cause(BuiltinDerivedObligation);
317 let trait_obligations: Vec<PredicateObligation<'_>> =
318 self.infcx.commit_unconditionally(|_| {
319 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
320 let trait_ref = self.infcx.replace_bound_vars_with_placeholders(poly_trait_ref);
321 self.impl_or_trait_obligations(
323 obligation.recursion_depth + 1,
324 obligation.param_env,
327 obligation.predicate,
331 let mut obligations = self.collect_predicates_for_types(
332 obligation.param_env,
334 obligation.recursion_depth + 1,
339 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
340 // predicate as usual. It won't have any effect since auto traits are coinductive.
341 obligations.extend(trait_obligations);
343 debug!(?obligations, "vtable_auto_impl");
345 ImplSourceAutoImplData { trait_def_id, nested: obligations }
349 fn confirm_impl_candidate(
351 obligation: &TraitObligation<'tcx>,
353 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
354 debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");
356 // First, create the substitutions by matching the impl again,
357 // this time not in a probe.
358 self.infcx.commit_unconditionally(|_| {
359 let substs = self.rematch_impl(impl_def_id, obligation);
360 debug!(?substs, "impl substs");
361 ensure_sufficient_stack(|| {
366 obligation.recursion_depth + 1,
367 obligation.param_env,
368 obligation.predicate,
377 substs: Normalized<'tcx, SubstsRef<'tcx>>,
378 cause: &ObligationCause<'tcx>,
379 recursion_depth: usize,
380 param_env: ty::ParamEnv<'tcx>,
381 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
382 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
383 debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl");
385 let mut impl_obligations = self.impl_or_trait_obligations(
394 debug!(?impl_obligations, "vtable_impl");
396 // Because of RFC447, the impl-trait-ref and obligations
397 // are sufficient to determine the impl substs, without
398 // relying on projections in the impl-trait-ref.
400 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
401 impl_obligations.extend(substs.obligations);
403 ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations }
406 fn confirm_object_candidate(
408 obligation: &TraitObligation<'tcx>,
410 ) -> Result<ImplSourceObjectData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
411 let tcx = self.tcx();
412 debug!(?obligation, ?index, "confirm_object_candidate");
414 let trait_predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
415 let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
416 let obligation_trait_ref = ty::Binder::dummy(trait_predicate.trait_ref);
417 let ty::Dynamic(data, ..) = *self_ty.kind() else {
418 span_bug!(obligation.cause.span, "object candidate with non-object");
421 let object_trait_ref = data.principal().unwrap_or_else(|| {
422 span_bug!(obligation.cause.span, "object candidate with no principal")
424 let object_trait_ref = self.infcx.replace_bound_vars_with_fresh_vars(
425 obligation.cause.span,
429 let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);
431 let mut nested = vec![];
433 let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
434 let unnormalized_upcast_trait_ref =
435 supertraits.nth(index).expect("supertraits iterator no longer has as many elements");
437 let upcast_trait_ref = normalize_with_depth_to(
439 obligation.param_env,
440 obligation.cause.clone(),
441 obligation.recursion_depth + 1,
442 unnormalized_upcast_trait_ref,
446 nested.extend(self.infcx.commit_if_ok(|_| {
448 .at(&obligation.cause, obligation.param_env)
449 .sup(obligation_trait_ref, upcast_trait_ref)
450 .map(|InferOk { obligations, .. }| obligations)
451 .map_err(|_| Unimplemented)
454 // Check supertraits hold. This is so that their associated type bounds
455 // will be checked in the code below.
456 for super_trait in tcx
457 .super_predicates_of(trait_predicate.def_id())
458 .instantiate(tcx, trait_predicate.trait_ref.substs)
462 let normalized_super_trait = normalize_with_depth_to(
464 obligation.param_env,
465 obligation.cause.clone(),
466 obligation.recursion_depth + 1,
470 nested.push(Obligation::new(
471 obligation.cause.clone(),
472 obligation.param_env,
473 normalized_super_trait,
477 let assoc_types: Vec<_> = tcx
478 .associated_items(trait_predicate.def_id())
479 .in_definition_order()
481 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
485 for assoc_type in assoc_types {
486 let defs: &ty::Generics = tcx.generics_of(assoc_type);
488 if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
489 tcx.sess.delay_span_bug(
490 obligation.cause.span,
491 "GATs in trait object shouldn't have been considered",
493 return Err(SelectionError::Unimplemented);
496 // This maybe belongs in wf, but that can't (doesn't) handle
497 // higher-ranked things.
498 // Prevent, e.g., `dyn Iterator<Item = str>`.
499 for bound in self.tcx().bound_item_bounds(assoc_type).transpose_iter() {
501 if defs.count() == 0 {
502 bound.subst(tcx, trait_predicate.trait_ref.substs)
504 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
505 substs.extend(trait_predicate.trait_ref.substs.iter());
506 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
507 smallvec::SmallVec::with_capacity(
508 bound.0.kind().bound_vars().len() + defs.count(),
510 bound_vars.extend(bound.0.kind().bound_vars().into_iter());
511 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
514 GenericParamDefKind::Type { .. } => {
515 let kind = ty::BoundTyKind::Param(param.name);
516 let bound_var = ty::BoundVariableKind::Ty(kind);
517 bound_vars.push(bound_var);
521 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
527 GenericParamDefKind::Lifetime => {
528 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
529 let bound_var = ty::BoundVariableKind::Region(kind);
530 bound_vars.push(bound_var);
531 tcx.mk_region(ty::ReLateBound(
534 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
540 GenericParamDefKind::Const { .. } => {
541 let bound_var = ty::BoundVariableKind::Const;
542 bound_vars.push(bound_var);
543 tcx.mk_const(ty::ConstS {
544 ty: tcx.type_of(param.def_id),
545 kind: ty::ConstKind::Bound(
547 ty::BoundVar::from_usize(bound_vars.len() - 1),
553 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
554 let assoc_ty_substs = tcx.intern_substs(&substs);
556 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
558 EarlyBinder(bound.0.kind().skip_binder()).subst(tcx, assoc_ty_substs);
559 tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
561 let normalized_bound = normalize_with_depth_to(
563 obligation.param_env,
564 obligation.cause.clone(),
565 obligation.recursion_depth + 1,
569 nested.push(Obligation::new(
570 obligation.cause.clone(),
571 obligation.param_env,
577 debug!(?nested, "object nested obligations");
579 let vtable_base = super::super::vtable_trait_first_method_offset(
581 (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
584 Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
587 fn confirm_fn_pointer_candidate(
589 obligation: &TraitObligation<'tcx>,
590 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
592 debug!(?obligation, "confirm_fn_pointer_candidate");
594 // Okay to skip binder; it is reintroduced below.
595 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
596 let sig = self_ty.fn_sig(self.tcx());
597 let trait_ref = closure_trait_ref_and_return_type(
599 obligation.predicate.def_id(),
602 util::TupleArgumentsFlag::Yes,
604 .map_bound(|(trait_ref, _)| trait_ref);
606 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
607 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
610 fn confirm_trait_alias_candidate(
612 obligation: &TraitObligation<'tcx>,
614 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
615 debug!(?obligation, ?alias_def_id, "confirm_trait_alias_candidate");
617 self.infcx.commit_unconditionally(|_| {
618 let predicate = self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
619 let trait_ref = predicate.trait_ref;
620 let trait_def_id = trait_ref.def_id;
621 let substs = trait_ref.substs;
623 let trait_obligations = self.impl_or_trait_obligations(
625 obligation.recursion_depth,
626 obligation.param_env,
629 obligation.predicate,
632 debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
634 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
638 fn confirm_generator_candidate(
640 obligation: &TraitObligation<'tcx>,
641 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
643 // Okay to skip binder because the substs on generator types never
644 // touch bound regions, they just capture the in-scope
645 // type/region parameters.
646 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
647 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
648 bug!("closure candidate for non-closure {:?}", obligation);
651 debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
653 let trait_ref = self.generator_trait_ref_unnormalized(obligation, substs);
655 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
656 debug!(?trait_ref, ?nested, "generator candidate obligations");
658 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
661 #[instrument(skip(self), level = "debug")]
662 fn confirm_closure_candidate(
664 obligation: &TraitObligation<'tcx>,
665 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
668 .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
669 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
671 // Okay to skip binder because the substs on closure 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::Closure(closure_def_id, substs) = *self_ty.kind() else {
676 bug!("closure candidate for non-closure {:?}", obligation);
679 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
680 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
682 debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
686 if !self.tcx().sess.opts.debugging_opts.chalk {
687 nested.push(Obligation::new(
688 obligation.cause.clone(),
689 obligation.param_env,
690 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind))
691 .to_predicate(self.tcx()),
695 Ok(ImplSourceClosureData { closure_def_id, substs, nested })
698 /// In the case of closure types and fn pointers,
699 /// we currently treat the input type parameters on the trait as
700 /// outputs. This means that when we have a match we have only
701 /// considered the self type, so we have to go back and make sure
702 /// to relate the argument types too. This is kind of wrong, but
703 /// since we control the full set of impls, also not that wrong,
704 /// and it DOES yield better error messages (since we don't report
705 /// errors as if there is no applicable impl, but rather report
706 /// errors are about mismatched argument types.
708 /// Here is an example. Imagine we have a closure expression
709 /// and we desugared it so that the type of the expression is
710 /// `Closure`, and `Closure` expects `i32` as argument. Then it
711 /// is "as if" the compiler generated this impl:
712 /// ```ignore (illustrative)
713 /// impl Fn(i32) for Closure { ... }
715 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
716 /// we have matched the self type `Closure`. At this point we'll
717 /// compare the `i32` to `usize` and generate an error.
719 /// Note that this checking occurs *after* the impl has selected,
720 /// because these output type parameters should not affect the
721 /// selection of the impl. Therefore, if there is a mismatch, we
722 /// report an error to the user.
723 #[instrument(skip(self), level = "trace")]
724 fn confirm_poly_trait_refs(
726 obligation: &TraitObligation<'tcx>,
727 expected_trait_ref: ty::PolyTraitRef<'tcx>,
728 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
729 let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
730 // Normalize the obligation and expected trait refs together, because why not
731 let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
732 ensure_sufficient_stack(|| {
733 self.infcx.commit_unconditionally(|_| {
734 normalize_with_depth(
736 obligation.param_env,
737 obligation.cause.clone(),
738 obligation.recursion_depth + 1,
739 (obligation_trait_ref, expected_trait_ref),
745 .at(&obligation.cause, obligation.param_env)
746 .sup(obligation_trait_ref, expected_trait_ref)
747 .map(|InferOk { mut obligations, .. }| {
748 obligations.extend(nested);
751 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
754 fn confirm_trait_upcasting_unsize_candidate(
756 obligation: &TraitObligation<'tcx>,
758 ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
760 let tcx = self.tcx();
762 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
763 // regions here. See the comment there for more details.
764 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
765 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
766 let target = self.infcx.shallow_resolve(target);
768 debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
770 let mut nested = vec![];
771 let source_trait_ref;
772 let upcast_trait_ref;
773 match (source.kind(), target.kind()) {
774 // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
775 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
776 // See `assemble_candidates_for_unsizing` for more info.
777 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
778 let principal_a = data_a.principal().unwrap();
779 source_trait_ref = principal_a.with_self_ty(tcx, source);
780 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
781 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
782 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
783 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
787 let iter = Some(existential_predicate)
792 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
797 .map(ty::ExistentialPredicate::AutoTrait)
798 .map(ty::Binder::dummy),
800 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
801 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
803 // Require that the traits involved in this upcast are **equal**;
804 // only the **lifetime bound** is changed.
805 let InferOk { obligations, .. } = self
807 .at(&obligation.cause, obligation.param_env)
808 .sup(target, source_trait)
809 .map_err(|_| Unimplemented)?;
810 nested.extend(obligations);
812 // Register one obligation for 'a: 'b.
813 let cause = ObligationCause::new(
814 obligation.cause.span,
815 obligation.cause.body_id,
816 ObjectCastObligation(source, target),
818 let outlives = ty::OutlivesPredicate(r_a, r_b);
819 nested.push(Obligation::with_depth(
821 obligation.recursion_depth + 1,
822 obligation.param_env,
823 obligation.predicate.rebind(outlives).to_predicate(tcx),
829 let vtable_segment_callback = {
830 let mut vptr_offset = 0;
833 VtblSegment::MetadataDSA => {
834 vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
836 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
837 vptr_offset += util::count_own_vtable_entries(tcx, trait_ref);
838 if trait_ref == upcast_trait_ref {
840 return ControlFlow::Break(Some(vptr_offset));
842 return ControlFlow::Break(None);
851 ControlFlow::Continue(())
855 let vtable_vptr_slot =
856 super::super::prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback)
859 Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
862 fn confirm_builtin_unsize_candidate(
864 obligation: &TraitObligation<'tcx>,
865 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
866 let tcx = self.tcx();
868 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
869 // regions here. See the comment there for more details.
870 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
871 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
872 let target = self.infcx.shallow_resolve(target);
874 debug!(?source, ?target, "confirm_builtin_unsize_candidate");
876 let mut nested = vec![];
877 match (source.kind(), target.kind()) {
878 // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
879 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
880 // See `assemble_candidates_for_unsizing` for more info.
881 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
884 .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
889 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
894 .map(ty::ExistentialPredicate::AutoTrait)
895 .map(ty::Binder::dummy),
897 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
898 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
900 // Require that the traits involved in this upcast are **equal**;
901 // only the **lifetime bound** is changed.
902 let InferOk { obligations, .. } = self
904 .at(&obligation.cause, obligation.param_env)
905 .sup(target, source_trait)
906 .map_err(|_| Unimplemented)?;
907 nested.extend(obligations);
909 // Register one obligation for 'a: 'b.
910 let cause = ObligationCause::new(
911 obligation.cause.span,
912 obligation.cause.body_id,
913 ObjectCastObligation(source, target),
915 let outlives = ty::OutlivesPredicate(r_a, r_b);
916 nested.push(Obligation::with_depth(
918 obligation.recursion_depth + 1,
919 obligation.param_env,
920 obligation.predicate.rebind(outlives).to_predicate(tcx),
925 (_, &ty::Dynamic(ref data, r)) => {
926 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
927 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
928 return Err(TraitNotObjectSafe(did));
931 let cause = ObligationCause::new(
932 obligation.cause.span,
933 obligation.cause.body_id,
934 ObjectCastObligation(source, target),
937 let predicate_to_obligation = |predicate| {
938 Obligation::with_depth(
940 obligation.recursion_depth + 1,
941 obligation.param_env,
946 // Create obligations:
947 // - Casting `T` to `Trait`
948 // - For all the various builtin bounds attached to the object cast. (In other
949 // words, if the object type is `Foo + Send`, this would create an obligation for
950 // the `Send` check.)
951 // - Projection predicates
953 data.iter().map(|predicate| {
954 predicate_to_obligation(predicate.with_self_ty(tcx, source))
958 // We can only make objects from sized types.
959 let tr = ty::Binder::dummy(ty::TraitRef::new(
960 tcx.require_lang_item(LangItem::Sized, None),
961 tcx.mk_substs_trait(source, &[]),
963 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
965 // If the type is `Foo + 'a`, ensure that the type
966 // being cast to `Foo + 'a` outlives `'a`:
967 let outlives = ty::OutlivesPredicate(source, r);
968 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
972 (&ty::Array(a, _), &ty::Slice(b)) => {
973 let InferOk { obligations, .. } = self
975 .at(&obligation.cause, obligation.param_env)
977 .map_err(|_| Unimplemented)?;
978 nested.extend(obligations);
981 // `Struct<T>` -> `Struct<U>`
982 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
983 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
984 GenericArgKind::Type(ty) => match ty.kind() {
985 ty::Param(p) => Some(p.index),
989 // Lifetimes aren't allowed to change during unsizing.
990 GenericArgKind::Lifetime(_) => None,
992 GenericArgKind::Const(ct) => match ct.kind() {
993 ty::ConstKind::Param(p) => Some(p.index),
998 // FIXME(eddyb) cache this (including computing `unsizing_params`)
999 // by putting it in a query; it would only need the `DefId` as it
1000 // looks at declared field types, not anything substituted.
1002 // The last field of the structure has to exist and contain type/const parameters.
1003 let (tail_field, prefix_fields) =
1004 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
1005 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1007 let mut unsizing_params = GrowableBitSet::new_empty();
1008 for arg in tail_field_ty.0.walk() {
1009 if let Some(i) = maybe_unsizing_param_idx(arg) {
1010 unsizing_params.insert(i);
1014 // Ensure none of the other fields mention the parameters used
1016 for field in prefix_fields {
1017 for arg in tcx.type_of(field.did).walk() {
1018 if let Some(i) = maybe_unsizing_param_idx(arg) {
1019 unsizing_params.remove(i);
1024 if unsizing_params.is_empty() {
1025 return Err(Unimplemented);
1028 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`.
1029 let source_tail = tail_field_ty.subst(tcx, substs_a);
1030 let target_tail = tail_field_ty.subst(tcx, substs_b);
1032 // Check that the source struct with the target's
1033 // unsizing parameters is equal to the target.
1034 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1035 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1037 let new_struct = tcx.mk_adt(def, substs);
1038 let InferOk { obligations, .. } = self
1040 .at(&obligation.cause, obligation.param_env)
1041 .eq(target, new_struct)
1042 .map_err(|_| Unimplemented)?;
1043 nested.extend(obligations);
1045 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1046 nested.push(predicate_for_trait_def(
1048 obligation.param_env,
1049 obligation.cause.clone(),
1050 obligation.predicate.def_id(),
1051 obligation.recursion_depth + 1,
1053 &[target_tail.into()],
1057 // `(.., T)` -> `(.., U)`
1058 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1059 assert_eq!(tys_a.len(), tys_b.len());
1061 // The last field of the tuple has to exist.
1062 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1063 let &b_last = tys_b.last().unwrap();
1065 // Check that the source tuple with the target's
1066 // last element is equal to the target.
1067 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1068 let InferOk { obligations, .. } = self
1070 .at(&obligation.cause, obligation.param_env)
1071 .eq(target, new_tuple)
1072 .map_err(|_| Unimplemented)?;
1073 nested.extend(obligations);
1075 // Construct the nested `T: Unsize<U>` predicate.
1076 nested.push(ensure_sufficient_stack(|| {
1077 predicate_for_trait_def(
1079 obligation.param_env,
1080 obligation.cause.clone(),
1081 obligation.predicate.def_id(),
1082 obligation.recursion_depth + 1,
1092 Ok(ImplSourceBuiltinData { nested })
1095 fn confirm_const_destruct_candidate(
1097 obligation: &TraitObligation<'tcx>,
1098 impl_def_id: Option<DefId>,
1099 ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1100 // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1101 if !obligation.is_const() {
1102 return Ok(ImplSourceConstDestructData { nested: vec![] });
1105 let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1107 let tcx = self.tcx();
1108 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1110 let mut nested = vec![];
1111 let cause = obligation.derived_cause(BuiltinDerivedObligation);
1113 // If we have a custom `impl const Drop`, then
1114 // first check it like a regular impl candidate.
1115 // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1116 if let Some(impl_def_id) = impl_def_id {
1117 let obligations = self.infcx.commit_unconditionally(|_| {
1118 let mut new_obligation = obligation.clone();
1119 new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1120 trait_pred.trait_ref.def_id = drop_trait;
1123 let substs = self.rematch_impl(impl_def_id, &new_obligation);
1124 debug!(?substs, "impl substs");
1126 let cause = obligation.derived_cause(|derived| {
1127 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1130 span: obligation.cause.span,
1133 ensure_sufficient_stack(|| {
1138 new_obligation.recursion_depth + 1,
1139 new_obligation.param_env,
1140 obligation.predicate,
1144 nested.extend(obligations.nested);
1147 // We want to confirm the ADT's fields if we have an ADT
1148 let mut stack = match *self_ty.skip_binder().kind() {
1149 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1150 _ => vec![self_ty.skip_binder()],
1153 while let Some(nested_ty) = stack.pop() {
1154 match *nested_ty.kind() {
1155 // We know these types are trivially drop
1161 | ty::Infer(ty::IntVar(_))
1162 | ty::Infer(ty::FloatVar(_))
1169 | ty::Foreign(_) => {}
1171 // These types are built-in, so we can fast-track by registering
1172 // nested predicates for their constituent type(s)
1173 ty::Array(ty, _) | ty::Slice(ty) => {
1177 stack.extend(tys.iter());
1179 ty::Closure(_, substs) => {
1180 stack.push(substs.as_closure().tupled_upvars_ty());
1182 ty::Generator(_, substs, _) => {
1183 let generator = substs.as_generator();
1184 stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1186 ty::GeneratorWitness(tys) => {
1187 stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1190 // If we have a projection type, make sure to normalize it so we replace it
1191 // with a fresh infer variable
1192 ty::Projection(..) => {
1193 self.infcx.commit_unconditionally(|_| {
1194 let predicate = normalize_with_depth_to(
1196 obligation.param_env,
1198 obligation.recursion_depth + 1,
1200 .rebind(ty::TraitPredicate {
1201 trait_ref: ty::TraitRef {
1204 .require_lang_item(LangItem::Destruct, None),
1205 substs: self.tcx().mk_substs_trait(nested_ty, &[]),
1207 constness: ty::BoundConstness::ConstIfConst,
1208 polarity: ty::ImplPolarity::Positive,
1214 nested.push(Obligation::with_depth(
1216 obligation.recursion_depth + 1,
1217 obligation.param_env,
1223 // If we have any other type (e.g. an ADT), just register a nested obligation
1224 // since it's either not `const Drop` (and we raise an error during selection),
1225 // or it's an ADT (and we need to check for a custom impl during selection)
1227 let predicate = self_ty
1228 .rebind(ty::TraitPredicate {
1229 trait_ref: ty::TraitRef {
1230 def_id: self.tcx().require_lang_item(LangItem::Destruct, None),
1231 substs: self.tcx().mk_substs_trait(nested_ty, &[]),
1233 constness: ty::BoundConstness::ConstIfConst,
1234 polarity: ty::ImplPolarity::Positive,
1238 nested.push(Obligation::with_depth(
1240 obligation.recursion_depth + 1,
1241 obligation.param_env,
1248 Ok(ImplSourceConstDestructData { nested })