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;
11 use rustc_index::bit_set::GrowableBitSet;
12 use rustc_infer::infer::InferOk;
13 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst, SubstsRef};
14 use rustc_middle::ty::{self, Ty};
15 use rustc_middle::ty::{ToPolyTraitRef, ToPredicate, WithConstness};
16 use rustc_span::def_id::DefId;
18 use crate::traits::project::{self, normalize_with_depth};
19 use crate::traits::select::TraitObligationExt;
20 use crate::traits::util;
21 use crate::traits::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
22 use crate::traits::Normalized;
23 use crate::traits::OutputTypeParameterMismatch;
24 use crate::traits::Selection;
25 use crate::traits::TraitNotObjectSafe;
26 use crate::traits::{BuiltinDerivedObligation, ImplDerivedObligation};
28 ImplSourceAutoImpl, ImplSourceBuiltin, ImplSourceClosure, ImplSourceDiscriminantKind,
29 ImplSourceFnPointer, ImplSourceGenerator, ImplSourceObject, ImplSourceParam,
30 ImplSourceTraitAlias, ImplSourceUserDefined,
33 ImplSourceAutoImplData, ImplSourceBuiltinData, ImplSourceClosureData,
34 ImplSourceDiscriminantKindData, ImplSourceFnPointerData, ImplSourceGeneratorData,
35 ImplSourceObjectData, ImplSourceTraitAliasData, ImplSourceUserDefinedData,
37 use crate::traits::{ObjectCastObligation, PredicateObligation, TraitObligation};
38 use crate::traits::{Obligation, ObligationCause};
39 use crate::traits::{SelectionError, Unimplemented};
41 use super::BuiltinImplConditions;
42 use super::SelectionCandidate::{self, *};
43 use super::SelectionContext;
47 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
48 pub(super) fn confirm_candidate(
50 obligation: &TraitObligation<'tcx>,
51 candidate: SelectionCandidate<'tcx>,
52 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
53 debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
56 BuiltinCandidate { has_nested } => {
57 let data = self.confirm_builtin_candidate(obligation, has_nested);
58 Ok(ImplSourceBuiltin(data))
61 ParamCandidate(param) => {
62 let obligations = self.confirm_param_candidate(obligation, param);
63 Ok(ImplSourceParam(obligations))
66 ImplCandidate(impl_def_id) => {
67 Ok(ImplSourceUserDefined(self.confirm_impl_candidate(obligation, impl_def_id)))
70 AutoImplCandidate(trait_def_id) => {
71 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
72 Ok(ImplSourceAutoImpl(data))
75 ProjectionCandidate => {
76 self.confirm_projection_candidate(obligation);
77 Ok(ImplSourceParam(Vec::new()))
81 let vtable_closure = self.confirm_closure_candidate(obligation)?;
82 Ok(ImplSourceClosure(vtable_closure))
85 GeneratorCandidate => {
86 let vtable_generator = self.confirm_generator_candidate(obligation)?;
87 Ok(ImplSourceGenerator(vtable_generator))
90 FnPointerCandidate => {
91 let data = self.confirm_fn_pointer_candidate(obligation)?;
92 Ok(ImplSourceFnPointer(data))
95 DiscriminantKindCandidate => {
96 Ok(ImplSourceDiscriminantKind(ImplSourceDiscriminantKindData))
99 TraitAliasCandidate(alias_def_id) => {
100 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
101 Ok(ImplSourceTraitAlias(data))
105 let data = self.confirm_object_candidate(obligation);
106 Ok(ImplSourceObject(data))
109 BuiltinObjectCandidate => {
110 // This indicates something like `Trait + Send: Send`. In this case, we know that
111 // this holds because that's what the object type is telling us, and there's really
112 // no additional obligations to prove and no types in particular to unify, etc.
113 Ok(ImplSourceParam(Vec::new()))
116 BuiltinUnsizeCandidate => {
117 let data = self.confirm_builtin_unsize_candidate(obligation)?;
118 Ok(ImplSourceBuiltin(data))
123 fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
124 self.infcx.commit_unconditionally(|snapshot| {
126 self.match_projection_obligation_against_definition_bounds(obligation, snapshot);
131 fn confirm_param_candidate(
133 obligation: &TraitObligation<'tcx>,
134 param: ty::PolyTraitRef<'tcx>,
135 ) -> Vec<PredicateObligation<'tcx>> {
136 debug!("confirm_param_candidate({:?},{:?})", obligation, param);
138 // During evaluation, we already checked that this
139 // where-clause trait-ref could be unified with the obligation
140 // trait-ref. Repeat that unification now without any
141 // transactional boundary; it should not fail.
142 match self.match_where_clause_trait_ref(obligation, param) {
143 Ok(obligations) => obligations,
146 "Where clause `{:?}` was applicable to `{:?}` but now is not",
154 fn confirm_builtin_candidate(
156 obligation: &TraitObligation<'tcx>,
158 ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
159 debug!("confirm_builtin_candidate({:?}, {:?})", obligation, has_nested);
161 let lang_items = self.tcx().lang_items();
162 let obligations = if has_nested {
163 let trait_def = obligation.predicate.def_id();
164 let conditions = if Some(trait_def) == lang_items.sized_trait() {
165 self.sized_conditions(obligation)
166 } else if Some(trait_def) == lang_items.copy_trait() {
167 self.copy_clone_conditions(obligation)
168 } else if Some(trait_def) == lang_items.clone_trait() {
169 self.copy_clone_conditions(obligation)
171 bug!("unexpected builtin trait {:?}", trait_def)
173 let nested = match conditions {
174 BuiltinImplConditions::Where(nested) => nested,
175 _ => bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation),
178 let cause = obligation.derived_cause(BuiltinDerivedObligation);
179 ensure_sufficient_stack(|| {
180 self.collect_predicates_for_types(
181 obligation.param_env,
183 obligation.recursion_depth + 1,
192 debug!("confirm_builtin_candidate: obligations={:?}", obligations);
194 ImplSourceBuiltinData { nested: obligations }
197 /// This handles the case where a `auto trait Foo` impl is being used.
198 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
200 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
201 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
202 fn confirm_auto_impl_candidate(
204 obligation: &TraitObligation<'tcx>,
206 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
207 debug!("confirm_auto_impl_candidate({:?}, {:?})", obligation, trait_def_id);
209 let types = obligation.predicate.map_bound(|inner| {
210 let self_ty = self.infcx.shallow_resolve(inner.self_ty());
211 self.constituent_types_for_ty(self_ty)
213 self.vtable_auto_impl(obligation, trait_def_id, types)
216 /// See `confirm_auto_impl_candidate`.
219 obligation: &TraitObligation<'tcx>,
221 nested: ty::Binder<Vec<Ty<'tcx>>>,
222 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
223 debug!("vtable_auto_impl: nested={:?}", nested);
224 ensure_sufficient_stack(|| {
225 let cause = obligation.derived_cause(BuiltinDerivedObligation);
226 let mut obligations = self.collect_predicates_for_types(
227 obligation.param_env,
229 obligation.recursion_depth + 1,
234 let trait_obligations: Vec<PredicateObligation<'_>> =
235 self.infcx.commit_unconditionally(|_| {
236 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
238 self.infcx.replace_bound_vars_with_placeholders(&poly_trait_ref);
239 let cause = obligation.derived_cause(ImplDerivedObligation);
240 self.impl_or_trait_obligations(
242 obligation.recursion_depth + 1,
243 obligation.param_env,
249 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
250 // predicate as usual. It won't have any effect since auto traits are coinductive.
251 obligations.extend(trait_obligations);
253 debug!("vtable_auto_impl: obligations={:?}", obligations);
255 ImplSourceAutoImplData { trait_def_id, nested: obligations }
259 fn confirm_impl_candidate(
261 obligation: &TraitObligation<'tcx>,
263 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
264 debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
266 // First, create the substitutions by matching the impl again,
267 // this time not in a probe.
268 self.infcx.commit_unconditionally(|snapshot| {
269 let substs = self.rematch_impl(impl_def_id, obligation, snapshot);
270 debug!("confirm_impl_candidate: substs={:?}", substs);
271 let cause = obligation.derived_cause(ImplDerivedObligation);
272 ensure_sufficient_stack(|| {
277 obligation.recursion_depth + 1,
278 obligation.param_env,
287 mut substs: Normalized<'tcx, SubstsRef<'tcx>>,
288 cause: ObligationCause<'tcx>,
289 recursion_depth: usize,
290 param_env: ty::ParamEnv<'tcx>,
291 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
293 "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={})",
294 impl_def_id, substs, recursion_depth,
297 let mut impl_obligations = self.impl_or_trait_obligations(
306 "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
307 impl_def_id, impl_obligations
310 // Because of RFC447, the impl-trait-ref and obligations
311 // are sufficient to determine the impl substs, without
312 // relying on projections in the impl-trait-ref.
314 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
315 impl_obligations.append(&mut substs.obligations);
317 ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations }
320 fn confirm_object_candidate(
322 obligation: &TraitObligation<'tcx>,
323 ) -> ImplSourceObjectData<'tcx, PredicateObligation<'tcx>> {
324 debug!("confirm_object_candidate({:?})", obligation);
326 // FIXME(nmatsakis) skipping binder here seems wrong -- we should
327 // probably flatten the binder from the obligation and the binder
328 // from the object. Have to try to make a broken test case that
330 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
331 let poly_trait_ref = match self_ty.kind {
332 ty::Dynamic(ref data, ..) => data
335 span_bug!(obligation.cause.span, "object candidate with no principal")
337 .with_self_ty(self.tcx(), self_ty),
338 _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
341 let mut upcast_trait_ref = None;
342 let mut nested = vec![];
346 let tcx = self.tcx();
348 // We want to find the first supertrait in the list of
349 // supertraits that we can unify with, and do that
350 // unification. We know that there is exactly one in the list
351 // where we can unify, because otherwise select would have
352 // reported an ambiguity. (When we do find a match, also
353 // record it for later.)
354 let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(|&t| {
355 match self.infcx.commit_if_ok(|_| self.match_poly_trait_ref(obligation, t)) {
357 upcast_trait_ref = Some(t);
358 nested.extend(obligations);
365 // Additionally, for each of the non-matching predicates that
366 // we pass over, we sum up the set of number of vtable
367 // entries, so that we can compute the offset for the selected
369 vtable_base = nonmatching.map(|t| super::util::count_own_vtable_entries(tcx, t)).sum();
372 ImplSourceObjectData { upcast_trait_ref: upcast_trait_ref.unwrap(), vtable_base, nested }
375 fn confirm_fn_pointer_candidate(
377 obligation: &TraitObligation<'tcx>,
378 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
380 debug!("confirm_fn_pointer_candidate({:?})", obligation);
382 // Okay to skip binder; it is reintroduced below.
383 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
384 let sig = self_ty.fn_sig(self.tcx());
385 let trait_ref = closure_trait_ref_and_return_type(
387 obligation.predicate.def_id(),
390 util::TupleArgumentsFlag::Yes,
392 .map_bound(|(trait_ref, _)| trait_ref);
394 let Normalized { value: trait_ref, obligations } = ensure_sufficient_stack(|| {
395 project::normalize_with_depth(
397 obligation.param_env,
398 obligation.cause.clone(),
399 obligation.recursion_depth + 1,
404 self.confirm_poly_trait_refs(
405 obligation.cause.clone(),
406 obligation.param_env,
407 obligation.predicate.to_poly_trait_ref(),
410 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested: obligations })
413 fn confirm_trait_alias_candidate(
415 obligation: &TraitObligation<'tcx>,
417 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
418 debug!("confirm_trait_alias_candidate({:?}, {:?})", obligation, alias_def_id);
420 self.infcx.commit_unconditionally(|_| {
422 self.infcx().replace_bound_vars_with_placeholders(&obligation.predicate);
423 let trait_ref = predicate.trait_ref;
424 let trait_def_id = trait_ref.def_id;
425 let substs = trait_ref.substs;
427 let trait_obligations = self.impl_or_trait_obligations(
428 obligation.cause.clone(),
429 obligation.recursion_depth,
430 obligation.param_env,
436 "confirm_trait_alias_candidate: trait_def_id={:?} trait_obligations={:?}",
437 trait_def_id, trait_obligations
440 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
444 fn confirm_generator_candidate(
446 obligation: &TraitObligation<'tcx>,
447 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
449 // Okay to skip binder because the substs on generator types never
450 // touch bound regions, they just capture the in-scope
451 // type/region parameters.
452 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
453 let (generator_def_id, substs) = match self_ty.kind {
454 ty::Generator(id, substs, _) => (id, substs),
455 _ => bug!("closure candidate for non-closure {:?}", obligation),
458 debug!("confirm_generator_candidate({:?},{:?},{:?})", obligation, generator_def_id, substs);
460 let trait_ref = self.generator_trait_ref_unnormalized(obligation, substs);
461 let Normalized { value: trait_ref, mut obligations } = ensure_sufficient_stack(|| {
462 normalize_with_depth(
464 obligation.param_env,
465 obligation.cause.clone(),
466 obligation.recursion_depth + 1,
472 "confirm_generator_candidate(generator_def_id={:?}, \
473 trait_ref={:?}, obligations={:?})",
474 generator_def_id, trait_ref, obligations
477 obligations.extend(self.confirm_poly_trait_refs(
478 obligation.cause.clone(),
479 obligation.param_env,
480 obligation.predicate.to_poly_trait_ref(),
484 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested: obligations })
487 fn confirm_closure_candidate(
489 obligation: &TraitObligation<'tcx>,
490 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
491 debug!("confirm_closure_candidate({:?})", obligation);
495 .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
496 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
498 // Okay to skip binder because the substs on closure types never
499 // touch bound regions, they just capture the in-scope
500 // type/region parameters.
501 let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
502 let (closure_def_id, substs) = match self_ty.kind {
503 ty::Closure(id, substs) => (id, substs),
504 _ => bug!("closure candidate for non-closure {:?}", obligation),
507 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
508 let Normalized { value: trait_ref, mut obligations } = ensure_sufficient_stack(|| {
509 normalize_with_depth(
511 obligation.param_env,
512 obligation.cause.clone(),
513 obligation.recursion_depth + 1,
519 "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
520 closure_def_id, trait_ref, obligations
523 obligations.extend(self.confirm_poly_trait_refs(
524 obligation.cause.clone(),
525 obligation.param_env,
526 obligation.predicate.to_poly_trait_ref(),
532 if !self.tcx().sess.opts.debugging_opts.chalk {
533 obligations.push(Obligation::new(
534 obligation.cause.clone(),
535 obligation.param_env,
536 ty::PredicateKind::ClosureKind(closure_def_id, substs, kind)
537 .to_predicate(self.tcx()),
541 Ok(ImplSourceClosureData { closure_def_id, substs, nested: obligations })
544 /// In the case of closure types and fn pointers,
545 /// we currently treat the input type parameters on the trait as
546 /// outputs. This means that when we have a match we have only
547 /// considered the self type, so we have to go back and make sure
548 /// to relate the argument types too. This is kind of wrong, but
549 /// since we control the full set of impls, also not that wrong,
550 /// and it DOES yield better error messages (since we don't report
551 /// errors as if there is no applicable impl, but rather report
552 /// errors are about mismatched argument types.
554 /// Here is an example. Imagine we have a closure expression
555 /// and we desugared it so that the type of the expression is
556 /// `Closure`, and `Closure` expects `i32` as argument. Then it
557 /// is "as if" the compiler generated this impl:
559 /// impl Fn(i32) for Closure { ... }
561 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
562 /// we have matched the self type `Closure`. At this point we'll
563 /// compare the `i32` to `usize` and generate an error.
565 /// Note that this checking occurs *after* the impl has selected,
566 /// because these output type parameters should not affect the
567 /// selection of the impl. Therefore, if there is a mismatch, we
568 /// report an error to the user.
569 fn confirm_poly_trait_refs(
571 obligation_cause: ObligationCause<'tcx>,
572 obligation_param_env: ty::ParamEnv<'tcx>,
573 obligation_trait_ref: ty::PolyTraitRef<'tcx>,
574 expected_trait_ref: ty::PolyTraitRef<'tcx>,
575 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
577 .at(&obligation_cause, obligation_param_env)
578 .sup(obligation_trait_ref, expected_trait_ref)
579 .map(|InferOk { obligations, .. }| obligations)
580 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
583 fn confirm_builtin_unsize_candidate(
585 obligation: &TraitObligation<'tcx>,
586 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
587 let tcx = self.tcx();
589 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
590 // regions here. See the comment there for more details.
591 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
592 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
593 let target = self.infcx.shallow_resolve(target);
595 debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})", source, target);
597 let mut nested = vec![];
598 match (&source.kind, &target.kind) {
599 // Trait+Kx+'a -> Trait+Ky+'b (upcasts).
600 (&ty::Dynamic(ref data_a, r_a), &ty::Dynamic(ref data_b, r_b)) => {
601 // See `assemble_candidates_for_unsizing` for more info.
602 let existential_predicates = data_a.map_bound(|data_a| {
605 .map(ty::ExistentialPredicate::Trait)
607 .chain(data_a.projection_bounds().map(ty::ExistentialPredicate::Projection))
608 .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
609 tcx.mk_existential_predicates(iter)
611 let source_trait = tcx.mk_dynamic(existential_predicates, r_b);
613 // Require that the traits involved in this upcast are **equal**;
614 // only the **lifetime bound** is changed.
616 // FIXME: This condition is arguably too strong -- it would
617 // suffice for the source trait to be a *subtype* of the target
618 // trait. In particular, changing from something like
619 // `for<'a, 'b> Foo<'a, 'b>` to `for<'a> Foo<'a, 'a>` should be
620 // permitted. And, indeed, in the in commit
621 // 904a0bde93f0348f69914ee90b1f8b6e4e0d7cbc, this
622 // condition was loosened. However, when the leak check was
623 // added back, using subtype here actually guides the coercion
624 // code in such a way that it accepts `old-lub-glb-object.rs`.
625 // This is probably a good thing, but I've modified this to `.eq`
626 // because I want to continue rejecting that test (as we have
627 // done for quite some time) before we are firmly comfortable
628 // with what our behavior should be there. -nikomatsakis
629 let InferOk { obligations, .. } = self
631 .at(&obligation.cause, obligation.param_env)
632 .eq(target, source_trait) // FIXME -- see below
633 .map_err(|_| Unimplemented)?;
634 nested.extend(obligations);
636 // Register one obligation for 'a: 'b.
637 let cause = ObligationCause::new(
638 obligation.cause.span,
639 obligation.cause.body_id,
640 ObjectCastObligation(target),
642 let outlives = ty::OutlivesPredicate(r_a, r_b);
643 nested.push(Obligation::with_depth(
645 obligation.recursion_depth + 1,
646 obligation.param_env,
647 ty::Binder::bind(outlives).to_predicate(tcx),
652 (_, &ty::Dynamic(ref data, r)) => {
653 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
654 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
655 return Err(TraitNotObjectSafe(did));
658 let cause = ObligationCause::new(
659 obligation.cause.span,
660 obligation.cause.body_id,
661 ObjectCastObligation(target),
664 let predicate_to_obligation = |predicate| {
665 Obligation::with_depth(
667 obligation.recursion_depth + 1,
668 obligation.param_env,
673 // Create obligations:
674 // - Casting `T` to `Trait`
675 // - For all the various builtin bounds attached to the object cast. (In other
676 // words, if the object type is `Foo + Send`, this would create an obligation for
677 // the `Send` check.)
678 // - Projection predicates
680 data.iter().map(|predicate| {
681 predicate_to_obligation(predicate.with_self_ty(tcx, source))
685 // We can only make objects from sized types.
686 let tr = ty::TraitRef::new(
687 tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
688 tcx.mk_substs_trait(source, &[]),
690 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
692 // If the type is `Foo + 'a`, ensure that the type
693 // being cast to `Foo + 'a` outlives `'a`:
694 let outlives = ty::OutlivesPredicate(source, r);
695 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
699 (&ty::Array(a, _), &ty::Slice(b)) => {
700 let InferOk { obligations, .. } = self
702 .at(&obligation.cause, obligation.param_env)
704 .map_err(|_| Unimplemented)?;
705 nested.extend(obligations);
708 // `Struct<T>` -> `Struct<U>`
709 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
710 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
711 GenericArgKind::Type(ty) => match ty.kind {
712 ty::Param(p) => Some(p.index),
716 // Lifetimes aren't allowed to change during unsizing.
717 GenericArgKind::Lifetime(_) => None,
719 GenericArgKind::Const(ct) => match ct.val {
720 ty::ConstKind::Param(p) => Some(p.index),
725 // The last field of the structure has to exist and contain type/const parameters.
726 let (tail_field, prefix_fields) =
727 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
728 let tail_field_ty = tcx.type_of(tail_field.did);
730 let mut unsizing_params = GrowableBitSet::new_empty();
731 let mut found = false;
732 for arg in tail_field_ty.walk() {
733 if let Some(i) = maybe_unsizing_param_idx(arg) {
734 unsizing_params.insert(i);
739 return Err(Unimplemented);
742 // Ensure none of the other fields mention the parameters used
744 // FIXME(eddyb) cache this (including computing `unsizing_params`)
745 // by putting it in a query; it would only need the `DefId` as it
746 // looks at declared field types, not anything substituted.
747 for field in prefix_fields {
748 for arg in tcx.type_of(field.did).walk() {
749 if let Some(i) = maybe_unsizing_param_idx(arg) {
750 if unsizing_params.contains(i) {
751 return Err(Unimplemented);
757 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`.
758 let source_tail = tail_field_ty.subst(tcx, substs_a);
759 let target_tail = tail_field_ty.subst(tcx, substs_b);
761 // Check that the source struct with the target's
762 // unsizing parameters is equal to the target.
763 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
764 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
766 let new_struct = tcx.mk_adt(def, substs);
767 let InferOk { obligations, .. } = self
769 .at(&obligation.cause, obligation.param_env)
770 .eq(target, new_struct)
771 .map_err(|_| Unimplemented)?;
772 nested.extend(obligations);
774 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
775 nested.push(predicate_for_trait_def(
777 obligation.param_env,
778 obligation.cause.clone(),
779 obligation.predicate.def_id(),
780 obligation.recursion_depth + 1,
782 &[target_tail.into()],
786 // `(.., T)` -> `(.., U)`
787 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
788 assert_eq!(tys_a.len(), tys_b.len());
790 // The last field of the tuple has to exist.
791 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
792 let &b_last = tys_b.last().unwrap();
794 // Check that the source tuple with the target's
795 // last element is equal to the target.
796 let new_tuple = tcx.mk_tup(
797 a_mid.iter().map(|k| k.expect_ty()).chain(iter::once(b_last.expect_ty())),
799 let InferOk { obligations, .. } = self
801 .at(&obligation.cause, obligation.param_env)
802 .eq(target, new_tuple)
803 .map_err(|_| Unimplemented)?;
804 nested.extend(obligations);
806 // Construct the nested `T: Unsize<U>` predicate.
807 nested.push(ensure_sufficient_stack(|| {
808 predicate_for_trait_def(
810 obligation.param_env,
811 obligation.cause.clone(),
812 obligation.predicate.def_id(),
813 obligation.recursion_depth + 1,
823 Ok(ImplSourceBuiltinData { nested })