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, 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 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) => {
72 let obligations = self.confirm_projection_candidate(obligation, idx)?;
73 // FIXME(jschievink): constness
74 ImplSource::Param(obligations, ty::BoundConstness::NotConst)
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)
92 FnPointerCandidate { .. } => {
93 let data = self.confirm_fn_pointer_candidate(obligation)?;
94 ImplSource::FnPointer(data)
97 DiscriminantKindCandidate => {
98 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
101 PointeeCandidate => ImplSource::Pointee(ImplSourcePointeeData),
103 TraitAliasCandidate(alias_def_id) => {
104 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
105 ImplSource::TraitAlias(data)
108 BuiltinObjectCandidate => {
109 // This indicates something like `Trait + Send: Send`. In this case, we know that
110 // this holds because that's what the object type is telling us, and there's really
111 // no additional obligations to prove and no types in particular to unify, etc.
112 ImplSource::Param(Vec::new(), ty::BoundConstness::NotConst)
115 BuiltinUnsizeCandidate => {
116 let data = self.confirm_builtin_unsize_candidate(obligation)?;
117 ImplSource::Builtin(data)
120 TraitUpcastingUnsizeCandidate(idx) => {
121 let data = self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?;
122 ImplSource::TraitUpcasting(data)
125 ConstDestructCandidate(def_id) => {
126 let data = self.confirm_const_destruct_candidate(obligation, def_id)?;
127 ImplSource::ConstDestruct(data)
130 TupleCandidate => ImplSource::Tuple,
133 if !obligation.predicate.is_const_if_const() {
134 // normalize nested predicates according to parent predicate's constness.
135 impl_src = impl_src.map(|mut o| {
136 o.predicate = o.predicate.without_const(self.tcx());
144 fn confirm_projection_candidate(
146 obligation: &TraitObligation<'tcx>,
148 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
149 let tcx = self.tcx();
151 let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
152 let placeholder_trait_predicate =
153 self.infcx().replace_bound_vars_with_placeholders(trait_predicate).trait_ref;
154 let placeholder_self_ty = placeholder_trait_predicate.self_ty();
155 let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate);
156 let (def_id, substs) = match *placeholder_self_ty.kind() {
157 ty::Projection(proj) => (proj.item_def_id, proj.substs),
158 ty::Opaque(def_id, substs) => (def_id, substs),
159 _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
162 let candidate_predicate =
163 tcx.bound_item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs);
164 let candidate = candidate_predicate
165 .to_opt_poly_trait_pred()
166 .expect("projection candidate is not a trait predicate")
167 .map_bound(|t| t.trait_ref);
168 let mut obligations = Vec::new();
169 let candidate = normalize_with_depth_to(
171 obligation.param_env,
172 obligation.cause.clone(),
173 obligation.recursion_depth + 1,
178 obligations.extend(self.infcx.commit_if_ok(|_| {
180 .at(&obligation.cause, obligation.param_env)
181 .sup(placeholder_trait_predicate, candidate)
182 .map(|InferOk { obligations, .. }| obligations)
183 .map_err(|_| Unimplemented)
186 if let ty::Projection(..) = placeholder_self_ty.kind() {
187 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates;
188 debug!(?predicates, "projection predicates");
189 for predicate in predicates {
190 let normalized = normalize_with_depth_to(
192 obligation.param_env,
193 obligation.cause.clone(),
194 obligation.recursion_depth + 1,
198 obligations.push(Obligation::with_depth(
199 obligation.cause.clone(),
200 obligation.recursion_depth + 1,
201 obligation.param_env,
210 fn confirm_param_candidate(
212 obligation: &TraitObligation<'tcx>,
213 param: ty::PolyTraitRef<'tcx>,
214 ) -> Vec<PredicateObligation<'tcx>> {
215 debug!(?obligation, ?param, "confirm_param_candidate");
217 // During evaluation, we already checked that this
218 // where-clause trait-ref could be unified with the obligation
219 // trait-ref. Repeat that unification now without any
220 // transactional boundary; it should not fail.
221 match self.match_where_clause_trait_ref(obligation, param) {
222 Ok(obligations) => obligations,
225 "Where clause `{:?}` was applicable to `{:?}` but now is not",
233 fn confirm_builtin_candidate(
235 obligation: &TraitObligation<'tcx>,
237 ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
238 debug!(?obligation, ?has_nested, "confirm_builtin_candidate");
240 let lang_items = self.tcx().lang_items();
241 let obligations = if has_nested {
242 let trait_def = obligation.predicate.def_id();
243 let conditions = if Some(trait_def) == lang_items.sized_trait() {
244 self.sized_conditions(obligation)
245 } else if Some(trait_def) == lang_items.copy_trait() {
246 self.copy_clone_conditions(obligation)
247 } else if Some(trait_def) == lang_items.clone_trait() {
248 self.copy_clone_conditions(obligation)
250 bug!("unexpected builtin trait {:?}", trait_def)
252 let BuiltinImplConditions::Where(nested) = conditions else {
253 bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
256 let cause = obligation.derived_cause(BuiltinDerivedObligation);
257 ensure_sufficient_stack(|| {
258 self.collect_predicates_for_types(
259 obligation.param_env,
261 obligation.recursion_depth + 1,
270 debug!(?obligations);
272 ImplSourceBuiltinData { nested: obligations }
275 fn confirm_transmutability_candidate(
277 obligation: &TraitObligation<'tcx>,
278 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
279 debug!(?obligation, "confirm_transmutability_candidate");
281 let predicate = obligation.predicate;
283 let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i));
290 .try_eval_bool(self.tcx(), obligation.param_env)
294 let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types {
295 src: p.trait_ref.substs.type_at(1),
296 dst: p.trait_ref.substs.type_at(0),
299 let scope = type_at(2).skip_binder();
301 let assume = rustc_transmute::Assume {
302 alignment: bool_at(3),
303 lifetimes: bool_at(4),
304 validity: bool_at(5),
305 visibility: bool_at(6),
308 let cause = obligation.cause.clone();
310 let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
312 let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume);
314 use rustc_transmute::Answer;
316 match maybe_transmutable {
317 Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }),
318 _ => Err(Unimplemented),
322 /// This handles the case where an `auto trait Foo` impl is being used.
323 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
325 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
326 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
327 fn confirm_auto_impl_candidate(
329 obligation: &TraitObligation<'tcx>,
331 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
332 debug!(?obligation, ?trait_def_id, "confirm_auto_impl_candidate");
334 let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
335 let types = self.constituent_types_for_ty(self_ty);
336 self.vtable_auto_impl(obligation, trait_def_id, types)
339 /// See `confirm_auto_impl_candidate`.
342 obligation: &TraitObligation<'tcx>,
344 nested: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
345 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
346 debug!(?nested, "vtable_auto_impl");
347 ensure_sufficient_stack(|| {
348 let cause = obligation.derived_cause(BuiltinDerivedObligation);
350 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
351 let trait_ref = self.infcx.replace_bound_vars_with_placeholders(poly_trait_ref);
352 let trait_obligations: Vec<PredicateObligation<'_>> = self.impl_or_trait_obligations(
354 obligation.recursion_depth + 1,
355 obligation.param_env,
358 obligation.predicate,
361 let mut obligations = self.collect_predicates_for_types(
362 obligation.param_env,
364 obligation.recursion_depth + 1,
369 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
370 // predicate as usual. It won't have any effect since auto traits are coinductive.
371 obligations.extend(trait_obligations);
373 debug!(?obligations, "vtable_auto_impl");
375 ImplSourceAutoImplData { trait_def_id, nested: obligations }
379 fn confirm_impl_candidate(
381 obligation: &TraitObligation<'tcx>,
383 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
384 debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");
386 // First, create the substitutions by matching the impl again,
387 // this time not in a probe.
388 let substs = self.rematch_impl(impl_def_id, obligation);
389 debug!(?substs, "impl substs");
390 ensure_sufficient_stack(|| {
395 obligation.recursion_depth + 1,
396 obligation.param_env,
397 obligation.predicate,
405 substs: Normalized<'tcx, SubstsRef<'tcx>>,
406 cause: &ObligationCause<'tcx>,
407 recursion_depth: usize,
408 param_env: ty::ParamEnv<'tcx>,
409 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
410 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
411 debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl");
413 let mut impl_obligations = self.impl_or_trait_obligations(
422 debug!(?impl_obligations, "vtable_impl");
424 // Because of RFC447, the impl-trait-ref and obligations
425 // are sufficient to determine the impl substs, without
426 // relying on projections in the impl-trait-ref.
428 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
429 impl_obligations.extend(substs.obligations);
431 ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations }
434 fn confirm_object_candidate(
436 obligation: &TraitObligation<'tcx>,
438 ) -> Result<ImplSourceObjectData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
439 let tcx = self.tcx();
440 debug!(?obligation, ?index, "confirm_object_candidate");
442 let trait_predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
443 let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
444 let obligation_trait_ref = ty::Binder::dummy(trait_predicate.trait_ref);
445 let ty::Dynamic(data, ..) = *self_ty.kind() else {
446 span_bug!(obligation.cause.span, "object candidate with non-object");
449 let object_trait_ref = data.principal().unwrap_or_else(|| {
450 span_bug!(obligation.cause.span, "object candidate with no principal")
452 let object_trait_ref = self.infcx.replace_bound_vars_with_fresh_vars(
453 obligation.cause.span,
457 let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);
459 let mut nested = vec![];
461 let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
462 let unnormalized_upcast_trait_ref =
463 supertraits.nth(index).expect("supertraits iterator no longer has as many elements");
465 let upcast_trait_ref = normalize_with_depth_to(
467 obligation.param_env,
468 obligation.cause.clone(),
469 obligation.recursion_depth + 1,
470 unnormalized_upcast_trait_ref,
474 nested.extend(self.infcx.commit_if_ok(|_| {
476 .at(&obligation.cause, obligation.param_env)
477 .sup(obligation_trait_ref, upcast_trait_ref)
478 .map(|InferOk { obligations, .. }| obligations)
479 .map_err(|_| Unimplemented)
482 // Check supertraits hold. This is so that their associated type bounds
483 // will be checked in the code below.
484 for super_trait in tcx
485 .super_predicates_of(trait_predicate.def_id())
486 .instantiate(tcx, trait_predicate.trait_ref.substs)
490 let normalized_super_trait = normalize_with_depth_to(
492 obligation.param_env,
493 obligation.cause.clone(),
494 obligation.recursion_depth + 1,
498 nested.push(Obligation::new(
499 obligation.cause.clone(),
500 obligation.param_env,
501 normalized_super_trait,
505 let assoc_types: Vec<_> = tcx
506 .associated_items(trait_predicate.def_id())
507 .in_definition_order()
509 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
513 for assoc_type in assoc_types {
514 let defs: &ty::Generics = tcx.generics_of(assoc_type);
516 if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
517 tcx.sess.delay_span_bug(
518 obligation.cause.span,
519 "GATs in trait object shouldn't have been considered",
521 return Err(SelectionError::Unimplemented);
524 // This maybe belongs in wf, but that can't (doesn't) handle
525 // higher-ranked things.
526 // Prevent, e.g., `dyn Iterator<Item = str>`.
527 for bound in self.tcx().bound_item_bounds(assoc_type).transpose_iter() {
529 if defs.count() == 0 {
530 bound.subst(tcx, trait_predicate.trait_ref.substs)
532 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
533 substs.extend(trait_predicate.trait_ref.substs.iter());
534 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
535 smallvec::SmallVec::with_capacity(
536 bound.0.kind().bound_vars().len() + defs.count(),
538 bound_vars.extend(bound.0.kind().bound_vars().into_iter());
539 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
542 GenericParamDefKind::Type { .. } => {
543 let kind = ty::BoundTyKind::Param(param.name);
544 let bound_var = ty::BoundVariableKind::Ty(kind);
545 bound_vars.push(bound_var);
549 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
555 GenericParamDefKind::Lifetime => {
556 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
557 let bound_var = ty::BoundVariableKind::Region(kind);
558 bound_vars.push(bound_var);
559 tcx.mk_region(ty::ReLateBound(
562 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
568 GenericParamDefKind::Const { .. } => {
569 let bound_var = ty::BoundVariableKind::Const;
570 bound_vars.push(bound_var);
571 tcx.mk_const(ty::ConstS {
572 ty: tcx.type_of(param.def_id),
573 kind: ty::ConstKind::Bound(
575 ty::BoundVar::from_usize(bound_vars.len() - 1),
581 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
582 let assoc_ty_substs = tcx.intern_substs(&substs);
584 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
586 bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs);
587 tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
589 let normalized_bound = normalize_with_depth_to(
591 obligation.param_env,
592 obligation.cause.clone(),
593 obligation.recursion_depth + 1,
597 nested.push(Obligation::new(
598 obligation.cause.clone(),
599 obligation.param_env,
605 debug!(?nested, "object nested obligations");
607 let vtable_base = super::super::vtable_trait_first_method_offset(
609 (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
612 Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
615 fn confirm_fn_pointer_candidate(
617 obligation: &TraitObligation<'tcx>,
618 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
620 debug!(?obligation, "confirm_fn_pointer_candidate");
622 // Okay to skip binder; it is reintroduced below.
623 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
624 let sig = self_ty.fn_sig(self.tcx());
625 let trait_ref = closure_trait_ref_and_return_type(
627 obligation.predicate.def_id(),
630 util::TupleArgumentsFlag::Yes,
632 .map_bound(|(trait_ref, _)| trait_ref);
634 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
635 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
638 fn confirm_trait_alias_candidate(
640 obligation: &TraitObligation<'tcx>,
642 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
643 debug!(?obligation, ?alias_def_id, "confirm_trait_alias_candidate");
645 let predicate = self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
646 let trait_ref = predicate.trait_ref;
647 let trait_def_id = trait_ref.def_id;
648 let substs = trait_ref.substs;
650 let trait_obligations = self.impl_or_trait_obligations(
652 obligation.recursion_depth,
653 obligation.param_env,
656 obligation.predicate,
659 debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
661 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
664 fn confirm_generator_candidate(
666 obligation: &TraitObligation<'tcx>,
667 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
669 // Okay to skip binder because the substs on generator types never
670 // touch bound regions, they just capture the in-scope
671 // type/region parameters.
672 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
673 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
674 bug!("closure candidate for non-closure {:?}", obligation);
677 debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
679 let trait_ref = self.generator_trait_ref_unnormalized(obligation, substs);
681 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
682 debug!(?trait_ref, ?nested, "generator candidate obligations");
684 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
687 #[instrument(skip(self), level = "debug")]
688 fn confirm_closure_candidate(
690 obligation: &TraitObligation<'tcx>,
691 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
694 .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
695 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
697 // Okay to skip binder because the substs on closure types never
698 // touch bound regions, they just capture the in-scope
699 // type/region parameters.
700 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
701 let ty::Closure(closure_def_id, substs) = *self_ty.kind() else {
702 bug!("closure candidate for non-closure {:?}", obligation);
705 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
706 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
708 debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
712 if !self.tcx().sess.opts.unstable_opts.chalk {
713 nested.push(Obligation::new(
714 obligation.cause.clone(),
715 obligation.param_env,
716 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind))
717 .to_predicate(self.tcx()),
721 Ok(ImplSourceClosureData { closure_def_id, substs, nested })
724 /// In the case of closure types and fn pointers,
725 /// we currently treat the input type parameters on the trait as
726 /// outputs. This means that when we have a match we have only
727 /// considered the self type, so we have to go back and make sure
728 /// to relate the argument types too. This is kind of wrong, but
729 /// since we control the full set of impls, also not that wrong,
730 /// and it DOES yield better error messages (since we don't report
731 /// errors as if there is no applicable impl, but rather report
732 /// errors are about mismatched argument types.
734 /// Here is an example. Imagine we have a closure expression
735 /// and we desugared it so that the type of the expression is
736 /// `Closure`, and `Closure` expects `i32` as argument. Then it
737 /// is "as if" the compiler generated this impl:
738 /// ```ignore (illustrative)
739 /// impl Fn(i32) for Closure { ... }
741 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
742 /// we have matched the self type `Closure`. At this point we'll
743 /// compare the `i32` to `usize` and generate an error.
745 /// Note that this checking occurs *after* the impl has selected,
746 /// because these output type parameters should not affect the
747 /// selection of the impl. Therefore, if there is a mismatch, we
748 /// report an error to the user.
749 #[instrument(skip(self), level = "trace")]
750 fn confirm_poly_trait_refs(
752 obligation: &TraitObligation<'tcx>,
753 expected_trait_ref: ty::PolyTraitRef<'tcx>,
754 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
755 let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
756 // Normalize the obligation and expected trait refs together, because why not
757 let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
758 ensure_sufficient_stack(|| {
759 normalize_with_depth(
761 obligation.param_env,
762 obligation.cause.clone(),
763 obligation.recursion_depth + 1,
764 (obligation_trait_ref, expected_trait_ref),
769 .at(&obligation.cause, obligation.param_env)
770 .sup(obligation_trait_ref, expected_trait_ref)
771 .map(|InferOk { mut obligations, .. }| {
772 obligations.extend(nested);
775 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
778 fn confirm_trait_upcasting_unsize_candidate(
780 obligation: &TraitObligation<'tcx>,
782 ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
784 let tcx = self.tcx();
786 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
787 // regions here. See the comment there for more details.
788 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
789 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
790 let target = self.infcx.shallow_resolve(target);
792 debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
794 let mut nested = vec![];
795 let source_trait_ref;
796 let upcast_trait_ref;
797 match (source.kind(), target.kind()) {
798 // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
799 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
800 // See `assemble_candidates_for_unsizing` for more info.
801 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
802 let principal_a = data_a.principal().unwrap();
803 source_trait_ref = principal_a.with_self_ty(tcx, source);
804 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
805 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
806 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
807 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
811 let iter = Some(existential_predicate)
816 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
821 .map(ty::ExistentialPredicate::AutoTrait)
822 .map(ty::Binder::dummy),
824 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
825 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
827 // Require that the traits involved in this upcast are **equal**;
828 // only the **lifetime bound** is changed.
829 let InferOk { obligations, .. } = self
831 .at(&obligation.cause, obligation.param_env)
832 .sup(target, source_trait)
833 .map_err(|_| Unimplemented)?;
834 nested.extend(obligations);
836 // Register one obligation for 'a: 'b.
837 let cause = ObligationCause::new(
838 obligation.cause.span,
839 obligation.cause.body_id,
840 ObjectCastObligation(source, target),
842 let outlives = ty::OutlivesPredicate(r_a, r_b);
843 nested.push(Obligation::with_depth(
845 obligation.recursion_depth + 1,
846 obligation.param_env,
847 obligation.predicate.rebind(outlives).to_predicate(tcx),
853 let vtable_segment_callback = {
854 let mut vptr_offset = 0;
857 VtblSegment::MetadataDSA => {
858 vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
860 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
861 vptr_offset += util::count_own_vtable_entries(tcx, trait_ref);
862 if trait_ref == upcast_trait_ref {
864 return ControlFlow::Break(Some(vptr_offset));
866 return ControlFlow::Break(None);
875 ControlFlow::Continue(())
879 let vtable_vptr_slot =
880 super::super::prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback)
883 Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
886 fn confirm_builtin_unsize_candidate(
888 obligation: &TraitObligation<'tcx>,
889 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
890 let tcx = self.tcx();
892 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
893 // regions here. See the comment there for more details.
894 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
895 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
896 let target = self.infcx.shallow_resolve(target);
898 debug!(?source, ?target, "confirm_builtin_unsize_candidate");
900 let mut nested = vec![];
901 match (source.kind(), target.kind()) {
902 // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
903 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
904 // See `assemble_candidates_for_unsizing` for more info.
905 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
908 .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
913 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
918 .map(ty::ExistentialPredicate::AutoTrait)
919 .map(ty::Binder::dummy),
921 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
922 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
924 // Require that the traits involved in this upcast are **equal**;
925 // only the **lifetime bound** is changed.
926 let InferOk { obligations, .. } = self
928 .at(&obligation.cause, obligation.param_env)
929 .sup(target, source_trait)
930 .map_err(|_| Unimplemented)?;
931 nested.extend(obligations);
933 // Register one obligation for 'a: 'b.
934 let cause = ObligationCause::new(
935 obligation.cause.span,
936 obligation.cause.body_id,
937 ObjectCastObligation(source, target),
939 let outlives = ty::OutlivesPredicate(r_a, r_b);
940 nested.push(Obligation::with_depth(
942 obligation.recursion_depth + 1,
943 obligation.param_env,
944 obligation.predicate.rebind(outlives).to_predicate(tcx),
949 (_, &ty::Dynamic(ref data, r)) => {
950 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
951 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
952 return Err(TraitNotObjectSafe(did));
955 let cause = ObligationCause::new(
956 obligation.cause.span,
957 obligation.cause.body_id,
958 ObjectCastObligation(source, target),
961 let predicate_to_obligation = |predicate| {
962 Obligation::with_depth(
964 obligation.recursion_depth + 1,
965 obligation.param_env,
970 // Create obligations:
971 // - Casting `T` to `Trait`
972 // - For all the various builtin bounds attached to the object cast. (In other
973 // words, if the object type is `Foo + Send`, this would create an obligation for
974 // the `Send` check.)
975 // - Projection predicates
977 data.iter().map(|predicate| {
978 predicate_to_obligation(predicate.with_self_ty(tcx, source))
982 // We can only make objects from sized types.
983 let tr = ty::Binder::dummy(ty::TraitRef::new(
984 tcx.require_lang_item(LangItem::Sized, None),
985 tcx.mk_substs_trait(source, &[]),
987 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
989 // If the type is `Foo + 'a`, ensure that the type
990 // being cast to `Foo + 'a` outlives `'a`:
991 let outlives = ty::OutlivesPredicate(source, r);
992 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
996 (&ty::Array(a, _), &ty::Slice(b)) => {
997 let InferOk { obligations, .. } = self
999 .at(&obligation.cause, obligation.param_env)
1001 .map_err(|_| Unimplemented)?;
1002 nested.extend(obligations);
1005 // `Struct<T>` -> `Struct<U>`
1006 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
1007 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
1008 GenericArgKind::Type(ty) => match ty.kind() {
1009 ty::Param(p) => Some(p.index),
1013 // Lifetimes aren't allowed to change during unsizing.
1014 GenericArgKind::Lifetime(_) => None,
1016 GenericArgKind::Const(ct) => match ct.kind() {
1017 ty::ConstKind::Param(p) => Some(p.index),
1022 // FIXME(eddyb) cache this (including computing `unsizing_params`)
1023 // by putting it in a query; it would only need the `DefId` as it
1024 // looks at declared field types, not anything substituted.
1026 // The last field of the structure has to exist and contain type/const parameters.
1027 let (tail_field, prefix_fields) =
1028 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
1029 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1031 let mut unsizing_params = GrowableBitSet::new_empty();
1032 for arg in tail_field_ty.0.walk() {
1033 if let Some(i) = maybe_unsizing_param_idx(arg) {
1034 unsizing_params.insert(i);
1038 // Ensure none of the other fields mention the parameters used
1040 for field in prefix_fields {
1041 for arg in tcx.type_of(field.did).walk() {
1042 if let Some(i) = maybe_unsizing_param_idx(arg) {
1043 unsizing_params.remove(i);
1048 if unsizing_params.is_empty() {
1049 return Err(Unimplemented);
1052 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`.
1053 let source_tail = tail_field_ty.subst(tcx, substs_a);
1054 let target_tail = tail_field_ty.subst(tcx, substs_b);
1056 // Check that the source struct with the target's
1057 // unsizing parameters is equal to the target.
1058 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1059 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1061 let new_struct = tcx.mk_adt(def, substs);
1062 let InferOk { obligations, .. } = self
1064 .at(&obligation.cause, obligation.param_env)
1065 .eq(target, new_struct)
1066 .map_err(|_| Unimplemented)?;
1067 nested.extend(obligations);
1069 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1070 nested.push(predicate_for_trait_def(
1072 obligation.param_env,
1073 obligation.cause.clone(),
1074 obligation.predicate.def_id(),
1075 obligation.recursion_depth + 1,
1077 &[target_tail.into()],
1081 // `(.., T)` -> `(.., U)`
1082 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1083 assert_eq!(tys_a.len(), tys_b.len());
1085 // The last field of the tuple has to exist.
1086 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1087 let &b_last = tys_b.last().unwrap();
1089 // Check that the source tuple with the target's
1090 // last element is equal to the target.
1091 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1092 let InferOk { obligations, .. } = self
1094 .at(&obligation.cause, obligation.param_env)
1095 .eq(target, new_tuple)
1096 .map_err(|_| Unimplemented)?;
1097 nested.extend(obligations);
1099 // Construct the nested `T: Unsize<U>` predicate.
1100 nested.push(ensure_sufficient_stack(|| {
1101 predicate_for_trait_def(
1103 obligation.param_env,
1104 obligation.cause.clone(),
1105 obligation.predicate.def_id(),
1106 obligation.recursion_depth + 1,
1116 Ok(ImplSourceBuiltinData { nested })
1119 fn confirm_const_destruct_candidate(
1121 obligation: &TraitObligation<'tcx>,
1122 impl_def_id: Option<DefId>,
1123 ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1124 // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1125 if !obligation.is_const() {
1126 return Ok(ImplSourceConstDestructData { nested: vec![] });
1129 let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1131 let tcx = self.tcx();
1132 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1134 let mut nested = vec![];
1135 let cause = obligation.derived_cause(BuiltinDerivedObligation);
1137 // If we have a custom `impl const Drop`, then
1138 // first check it like a regular impl candidate.
1139 // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1140 if let Some(impl_def_id) = impl_def_id {
1141 let mut new_obligation = obligation.clone();
1142 new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1143 trait_pred.trait_ref.def_id = drop_trait;
1146 let substs = self.rematch_impl(impl_def_id, &new_obligation);
1147 debug!(?substs, "impl substs");
1149 let cause = obligation.derived_cause(|derived| {
1150 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1153 span: obligation.cause.span,
1156 let obligations = ensure_sufficient_stack(|| {
1161 new_obligation.recursion_depth + 1,
1162 new_obligation.param_env,
1163 obligation.predicate,
1166 nested.extend(obligations.nested);
1169 // We want to confirm the ADT's fields if we have an ADT
1170 let mut stack = match *self_ty.skip_binder().kind() {
1171 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1172 _ => vec![self_ty.skip_binder()],
1175 while let Some(nested_ty) = stack.pop() {
1176 match *nested_ty.kind() {
1177 // We know these types are trivially drop
1183 | ty::Infer(ty::IntVar(_))
1184 | ty::Infer(ty::FloatVar(_))
1191 | ty::Foreign(_) => {}
1193 // These types are built-in, so we can fast-track by registering
1194 // nested predicates for their constituent type(s)
1195 ty::Array(ty, _) | ty::Slice(ty) => {
1199 stack.extend(tys.iter());
1201 ty::Closure(_, substs) => {
1202 stack.push(substs.as_closure().tupled_upvars_ty());
1204 ty::Generator(_, substs, _) => {
1205 let generator = substs.as_generator();
1206 stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1208 ty::GeneratorWitness(tys) => {
1209 stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1212 // If we have a projection type, make sure to normalize it so we replace it
1213 // with a fresh infer variable
1214 ty::Projection(..) => {
1215 let predicate = normalize_with_depth_to(
1217 obligation.param_env,
1219 obligation.recursion_depth + 1,
1221 .rebind(ty::TraitPredicate {
1222 trait_ref: ty::TraitRef {
1223 def_id: self.tcx().require_lang_item(LangItem::Destruct, None),
1224 substs: self.tcx().mk_substs_trait(nested_ty, &[]),
1226 constness: ty::BoundConstness::ConstIfConst,
1227 polarity: ty::ImplPolarity::Positive,
1233 nested.push(Obligation::with_depth(
1235 obligation.recursion_depth + 1,
1236 obligation.param_env,
1241 // If we have any other type (e.g. an ADT), just register a nested obligation
1242 // since it's either not `const Drop` (and we raise an error during selection),
1243 // or it's an ADT (and we need to check for a custom impl during selection)
1245 let predicate = self_ty
1246 .rebind(ty::TraitPredicate {
1247 trait_ref: ty::TraitRef {
1248 def_id: self.tcx().require_lang_item(LangItem::Destruct, None),
1249 substs: self.tcx().mk_substs_trait(nested_ty, &[]),
1251 constness: ty::BoundConstness::ConstIfConst,
1252 polarity: ty::ImplPolarity::Positive,
1256 nested.push(Obligation::with_depth(
1258 obligation.recursion_depth + 1,
1259 obligation.param_env,
1266 Ok(ImplSourceConstDestructData { nested })