3 //! Confirmation unifies the output type parameters of the trait
4 //! with the values found in the obligation, possibly yielding a
5 //! type error. See the [rustc dev guide] for more details.
8 //! https://rustc-dev-guide.rust-lang.org/traits/resolution.html#confirmation
9 use rustc_data_structures::stack::ensure_sufficient_stack;
10 use rustc_hir::lang_items::LangItem;
11 use rustc_index::bit_set::GrowableBitSet;
12 use rustc_infer::infer::InferOk;
13 use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType;
14 use rustc_middle::ty::{
15 self, GenericArg, GenericArgKind, GenericParamDefKind, InternalSubsts, SubstsRef,
16 ToPolyTraitRef, ToPredicate, Ty, TyCtxt,
18 use rustc_span::def_id::DefId;
20 use crate::traits::project::{normalize_with_depth, normalize_with_depth_to};
21 use crate::traits::util::{self, closure_trait_ref_and_return_type, predicate_for_trait_def};
23 BuiltinDerivedObligation, ImplDerivedObligation, ImplDerivedObligationCause, ImplSource,
24 ImplSourceAutoImplData, ImplSourceBuiltinData, ImplSourceClosureData,
25 ImplSourceConstDestructData, ImplSourceDiscriminantKindData, ImplSourceFnPointerData,
26 ImplSourceGeneratorData, ImplSourceObjectData, ImplSourcePointeeData, ImplSourceTraitAliasData,
27 ImplSourceTraitUpcastingData, ImplSourceUserDefinedData, Normalized, ObjectCastObligation,
28 Obligation, ObligationCause, OutputTypeParameterMismatch, PredicateObligation, Selection,
29 SelectionError, TraitNotObjectSafe, TraitObligation, Unimplemented, VtblSegment,
32 use super::BuiltinImplConditions;
33 use super::SelectionCandidate::{self, *};
34 use super::SelectionContext;
37 use std::ops::ControlFlow;
39 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
40 #[instrument(level = "debug", skip(self))]
41 pub(super) fn confirm_candidate(
43 obligation: &TraitObligation<'tcx>,
44 candidate: SelectionCandidate<'tcx>,
45 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
46 let mut impl_src = match candidate {
47 BuiltinCandidate { has_nested } => {
48 let data = self.confirm_builtin_candidate(obligation, has_nested);
49 ImplSource::Builtin(data)
52 TransmutabilityCandidate => {
53 let data = self.confirm_transmutability_candidate(obligation)?;
54 ImplSource::Builtin(data)
57 ParamCandidate(param) => {
59 self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref));
60 ImplSource::Param(obligations, param.skip_binder().constness)
63 ImplCandidate(impl_def_id) => {
64 ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id))
67 AutoImplCandidate => {
68 let data = self.confirm_auto_impl_candidate(obligation);
69 ImplSource::AutoImpl(data)
72 ProjectionCandidate(idx, constness) => {
73 let obligations = self.confirm_projection_candidate(obligation, idx)?;
74 ImplSource::Param(obligations, constness)
77 ObjectCandidate(idx) => {
78 let data = self.confirm_object_candidate(obligation, idx)?;
79 ImplSource::Object(data)
83 let vtable_closure = self.confirm_closure_candidate(obligation)?;
84 ImplSource::Closure(vtable_closure)
87 GeneratorCandidate => {
88 let vtable_generator = self.confirm_generator_candidate(obligation)?;
89 ImplSource::Generator(vtable_generator)
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 => {
104 let data = self.confirm_trait_alias_candidate(obligation);
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)
131 if !obligation.predicate.is_const_if_const() {
132 // normalize nested predicates according to parent predicate's constness.
133 impl_src = impl_src.map(|mut o| {
134 o.predicate = o.predicate.without_const(self.tcx());
142 fn confirm_projection_candidate(
144 obligation: &TraitObligation<'tcx>,
146 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
147 let tcx = self.tcx();
149 let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
150 let placeholder_trait_predicate =
151 self.infcx().replace_bound_vars_with_placeholders(trait_predicate).trait_ref;
152 let placeholder_self_ty = placeholder_trait_predicate.self_ty();
153 let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate);
154 let (def_id, substs) = match *placeholder_self_ty.kind() {
155 ty::Projection(proj) => (proj.item_def_id, proj.substs),
156 ty::Opaque(def_id, substs) => (def_id, substs),
157 _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
160 let candidate_predicate =
161 tcx.bound_item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs);
162 let candidate = candidate_predicate
163 .to_opt_poly_trait_pred()
164 .expect("projection candidate is not a trait predicate")
165 .map_bound(|t| t.trait_ref);
166 let mut obligations = Vec::new();
167 let candidate = normalize_with_depth_to(
169 obligation.param_env,
170 obligation.cause.clone(),
171 obligation.recursion_depth + 1,
176 obligations.extend(self.infcx.commit_if_ok(|_| {
178 .at(&obligation.cause, obligation.param_env)
179 .sup(placeholder_trait_predicate, candidate)
180 .map(|InferOk { obligations, .. }| obligations)
181 .map_err(|_| Unimplemented)
184 if let ty::Projection(..) = placeholder_self_ty.kind() {
185 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates;
186 debug!(?predicates, "projection predicates");
187 for predicate in predicates {
188 let normalized = normalize_with_depth_to(
190 obligation.param_env,
191 obligation.cause.clone(),
192 obligation.recursion_depth + 1,
196 obligations.push(Obligation::with_depth(
198 obligation.cause.clone(),
199 obligation.recursion_depth + 1,
200 obligation.param_env,
209 fn confirm_param_candidate(
211 obligation: &TraitObligation<'tcx>,
212 param: ty::PolyTraitRef<'tcx>,
213 ) -> Vec<PredicateObligation<'tcx>> {
214 debug!(?obligation, ?param, "confirm_param_candidate");
216 // During evaluation, we already checked that this
217 // where-clause trait-ref could be unified with the obligation
218 // trait-ref. Repeat that unification now without any
219 // transactional boundary; it should not fail.
220 match self.match_where_clause_trait_ref(obligation, param) {
221 Ok(obligations) => obligations,
224 "Where clause `{:?}` was applicable to `{:?}` but now is not",
232 fn confirm_builtin_candidate(
234 obligation: &TraitObligation<'tcx>,
236 ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
237 debug!(?obligation, ?has_nested, "confirm_builtin_candidate");
239 let lang_items = self.tcx().lang_items();
240 let obligations = if has_nested {
241 let trait_def = obligation.predicate.def_id();
242 let conditions = if Some(trait_def) == lang_items.sized_trait() {
243 self.sized_conditions(obligation)
244 } else if Some(trait_def) == lang_items.copy_trait() {
245 self.copy_clone_conditions(obligation)
246 } else if Some(trait_def) == lang_items.clone_trait() {
247 self.copy_clone_conditions(obligation)
249 bug!("unexpected builtin trait {:?}", trait_def)
251 let BuiltinImplConditions::Where(nested) = conditions else {
252 bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
255 let cause = obligation.derived_cause(BuiltinDerivedObligation);
256 ensure_sufficient_stack(|| {
257 self.collect_predicates_for_types(
258 obligation.param_env,
260 obligation.recursion_depth + 1,
269 debug!(?obligations);
271 ImplSourceBuiltinData { nested: obligations }
274 fn confirm_transmutability_candidate(
276 obligation: &TraitObligation<'tcx>,
277 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
278 debug!(?obligation, "confirm_transmutability_candidate");
280 let predicate = obligation.predicate;
282 let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i));
283 let const_at = |i| predicate.skip_binder().trait_ref.substs.const_at(i);
285 let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types {
286 dst: p.trait_ref.substs.type_at(0),
287 src: p.trait_ref.substs.type_at(1),
290 let scope = type_at(2).skip_binder();
293 rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, const_at(3)) else {
294 return Err(Unimplemented);
297 let cause = obligation.cause.clone();
299 let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
301 let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume);
303 use rustc_transmute::Answer;
305 match maybe_transmutable {
306 Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }),
307 _ => Err(Unimplemented),
311 /// This handles the case where an `auto trait Foo` impl is being used.
312 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
314 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
315 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
316 fn confirm_auto_impl_candidate(
318 obligation: &TraitObligation<'tcx>,
319 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
320 debug!(?obligation, "confirm_auto_impl_candidate");
322 let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
323 let types = self.constituent_types_for_ty(self_ty);
324 self.vtable_auto_impl(obligation, obligation.predicate.def_id(), types)
327 /// See `confirm_auto_impl_candidate`.
330 obligation: &TraitObligation<'tcx>,
332 nested: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
333 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
334 debug!(?nested, "vtable_auto_impl");
335 ensure_sufficient_stack(|| {
336 let cause = obligation.derived_cause(BuiltinDerivedObligation);
338 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
339 let trait_ref = self.infcx.replace_bound_vars_with_placeholders(poly_trait_ref);
340 let trait_obligations: Vec<PredicateObligation<'_>> = self.impl_or_trait_obligations(
342 obligation.recursion_depth + 1,
343 obligation.param_env,
346 obligation.predicate,
349 let mut obligations = self.collect_predicates_for_types(
350 obligation.param_env,
352 obligation.recursion_depth + 1,
357 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
358 // predicate as usual. It won't have any effect since auto traits are coinductive.
359 obligations.extend(trait_obligations);
361 debug!(?obligations, "vtable_auto_impl");
363 ImplSourceAutoImplData { trait_def_id, nested: obligations }
367 fn confirm_impl_candidate(
369 obligation: &TraitObligation<'tcx>,
371 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
372 debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");
374 // First, create the substitutions by matching the impl again,
375 // this time not in a probe.
376 let substs = self.rematch_impl(impl_def_id, obligation);
377 debug!(?substs, "impl substs");
378 ensure_sufficient_stack(|| {
383 obligation.recursion_depth + 1,
384 obligation.param_env,
385 obligation.predicate,
393 substs: Normalized<'tcx, SubstsRef<'tcx>>,
394 cause: &ObligationCause<'tcx>,
395 recursion_depth: usize,
396 param_env: ty::ParamEnv<'tcx>,
397 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
398 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
399 debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl");
401 let mut impl_obligations = self.impl_or_trait_obligations(
410 debug!(?impl_obligations, "vtable_impl");
412 // Because of RFC447, the impl-trait-ref and obligations
413 // are sufficient to determine the impl substs, without
414 // relying on projections in the impl-trait-ref.
416 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
417 impl_obligations.extend(substs.obligations);
419 ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations }
422 fn confirm_object_candidate(
424 obligation: &TraitObligation<'tcx>,
426 ) -> Result<ImplSourceObjectData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
427 let tcx = self.tcx();
428 debug!(?obligation, ?index, "confirm_object_candidate");
430 let trait_predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
431 let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
432 let obligation_trait_ref = ty::Binder::dummy(trait_predicate.trait_ref);
433 let ty::Dynamic(data, ..) = *self_ty.kind() else {
434 span_bug!(obligation.cause.span, "object candidate with non-object");
437 let object_trait_ref = data.principal().unwrap_or_else(|| {
438 span_bug!(obligation.cause.span, "object candidate with no principal")
440 let object_trait_ref = self.infcx.replace_bound_vars_with_fresh_vars(
441 obligation.cause.span,
445 let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);
447 let mut nested = vec![];
449 let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
450 let unnormalized_upcast_trait_ref =
451 supertraits.nth(index).expect("supertraits iterator no longer has as many elements");
453 let upcast_trait_ref = normalize_with_depth_to(
455 obligation.param_env,
456 obligation.cause.clone(),
457 obligation.recursion_depth + 1,
458 unnormalized_upcast_trait_ref,
462 nested.extend(self.infcx.commit_if_ok(|_| {
464 .at(&obligation.cause, obligation.param_env)
465 .sup(obligation_trait_ref, upcast_trait_ref)
466 .map(|InferOk { obligations, .. }| obligations)
467 .map_err(|_| Unimplemented)
470 // Check supertraits hold. This is so that their associated type bounds
471 // will be checked in the code below.
472 for super_trait in tcx
473 .super_predicates_of(trait_predicate.def_id())
474 .instantiate(tcx, trait_predicate.trait_ref.substs)
478 let normalized_super_trait = normalize_with_depth_to(
480 obligation.param_env,
481 obligation.cause.clone(),
482 obligation.recursion_depth + 1,
486 nested.push(obligation.with(tcx, normalized_super_trait));
489 let assoc_types: Vec<_> = tcx
490 .associated_items(trait_predicate.def_id())
491 .in_definition_order()
493 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
497 for assoc_type in assoc_types {
498 let defs: &ty::Generics = tcx.generics_of(assoc_type);
500 if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
501 tcx.sess.delay_span_bug(
502 obligation.cause.span,
503 "GATs in trait object shouldn't have been considered",
505 return Err(SelectionError::Unimplemented);
508 // This maybe belongs in wf, but that can't (doesn't) handle
509 // higher-ranked things.
510 // Prevent, e.g., `dyn Iterator<Item = str>`.
511 for bound in self.tcx().bound_item_bounds(assoc_type).transpose_iter() {
513 if defs.count() == 0 {
514 bound.subst(tcx, trait_predicate.trait_ref.substs)
516 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
517 substs.extend(trait_predicate.trait_ref.substs.iter());
518 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
519 smallvec::SmallVec::with_capacity(
520 bound.0.kind().bound_vars().len() + defs.count(),
522 bound_vars.extend(bound.0.kind().bound_vars().into_iter());
523 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
526 GenericParamDefKind::Type { .. } => {
527 let kind = ty::BoundTyKind::Param(param.name);
528 let bound_var = ty::BoundVariableKind::Ty(kind);
529 bound_vars.push(bound_var);
533 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
539 GenericParamDefKind::Lifetime => {
540 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
541 let bound_var = ty::BoundVariableKind::Region(kind);
542 bound_vars.push(bound_var);
543 tcx.mk_region(ty::ReLateBound(
546 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
552 GenericParamDefKind::Const { .. } => {
553 let bound_var = ty::BoundVariableKind::Const;
554 bound_vars.push(bound_var);
556 ty::ConstKind::Bound(
558 ty::BoundVar::from_usize(bound_vars.len() - 1),
560 tcx.type_of(param.def_id),
565 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
566 let assoc_ty_substs = tcx.intern_substs(&substs);
568 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
570 bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs);
571 tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
573 let normalized_bound = normalize_with_depth_to(
575 obligation.param_env,
576 obligation.cause.clone(),
577 obligation.recursion_depth + 1,
581 nested.push(obligation.with(tcx, normalized_bound));
585 debug!(?nested, "object nested obligations");
587 let vtable_base = super::super::vtable_trait_first_method_offset(
589 (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
592 Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
595 fn confirm_fn_pointer_candidate(
597 obligation: &TraitObligation<'tcx>,
598 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
600 debug!(?obligation, "confirm_fn_pointer_candidate");
602 // Okay to skip binder; it is reintroduced below.
603 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
604 let sig = self_ty.fn_sig(self.tcx());
605 let trait_ref = closure_trait_ref_and_return_type(
607 obligation.predicate.def_id(),
610 util::TupleArgumentsFlag::Yes,
612 .map_bound(|(trait_ref, _)| trait_ref);
614 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
616 // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
617 let cause = obligation.derived_cause(BuiltinDerivedObligation);
618 // The binder on the Fn obligation is "less" important than the one on
619 // the signature, as evidenced by how we treat it during projection.
620 // The safe thing to do here is to liberate it, though, which should
621 // have no worse effect than skipping the binder here.
622 let liberated_fn_ty =
623 self.infcx.replace_bound_vars_with_placeholders(obligation.predicate.rebind(self_ty));
626 .replace_bound_vars_with_placeholders(liberated_fn_ty.fn_sig(self.tcx()).output());
627 let output_ty = normalize_with_depth_to(
629 obligation.param_env,
631 obligation.recursion_depth,
636 ty::Binder::dummy(self.tcx().at(cause.span).mk_trait_ref(LangItem::Sized, [output_ty]));
637 nested.push(Obligation::new(
640 obligation.param_env,
641 tr.to_poly_trait_predicate(),
644 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
647 fn confirm_trait_alias_candidate(
649 obligation: &TraitObligation<'tcx>,
650 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
651 debug!(?obligation, "confirm_trait_alias_candidate");
653 let alias_def_id = obligation.predicate.def_id();
654 let predicate = self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
655 let trait_ref = predicate.trait_ref;
656 let trait_def_id = trait_ref.def_id;
657 let substs = trait_ref.substs;
659 let trait_obligations = self.impl_or_trait_obligations(
661 obligation.recursion_depth,
662 obligation.param_env,
665 obligation.predicate,
668 debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
670 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
673 fn confirm_generator_candidate(
675 obligation: &TraitObligation<'tcx>,
676 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
678 // Okay to skip binder because the substs on generator types never
679 // touch bound regions, they just capture the in-scope
680 // type/region parameters.
681 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
682 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
683 bug!("closure candidate for non-closure {:?}", obligation);
686 debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
688 let trait_ref = self.generator_trait_ref_unnormalized(obligation, substs);
690 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
691 debug!(?trait_ref, ?nested, "generator candidate obligations");
693 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
696 #[instrument(skip(self), level = "debug")]
697 fn confirm_closure_candidate(
699 obligation: &TraitObligation<'tcx>,
700 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
703 .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
704 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
706 // Okay to skip binder because the substs on closure types never
707 // touch bound regions, they just capture the in-scope
708 // type/region parameters.
709 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
710 let ty::Closure(closure_def_id, substs) = *self_ty.kind() else {
711 bug!("closure candidate for non-closure {:?}", obligation);
714 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
715 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
717 debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
721 if !self.tcx().sess.opts.unstable_opts.chalk {
722 nested.push(obligation.with(
724 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind)),
728 Ok(ImplSourceClosureData { closure_def_id, substs, nested })
731 /// In the case of closure types and fn pointers,
732 /// we currently treat the input type parameters on the trait as
733 /// outputs. This means that when we have a match we have only
734 /// considered the self type, so we have to go back and make sure
735 /// to relate the argument types too. This is kind of wrong, but
736 /// since we control the full set of impls, also not that wrong,
737 /// and it DOES yield better error messages (since we don't report
738 /// errors as if there is no applicable impl, but rather report
739 /// errors are about mismatched argument types.
741 /// Here is an example. Imagine we have a closure expression
742 /// and we desugared it so that the type of the expression is
743 /// `Closure`, and `Closure` expects `i32` as argument. Then it
744 /// is "as if" the compiler generated this impl:
745 /// ```ignore (illustrative)
746 /// impl Fn(i32) for Closure { ... }
748 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
749 /// we have matched the self type `Closure`. At this point we'll
750 /// compare the `i32` to `usize` and generate an error.
752 /// Note that this checking occurs *after* the impl has selected,
753 /// because these output type parameters should not affect the
754 /// selection of the impl. Therefore, if there is a mismatch, we
755 /// report an error to the user.
756 #[instrument(skip(self), level = "trace")]
757 fn confirm_poly_trait_refs(
759 obligation: &TraitObligation<'tcx>,
760 expected_trait_ref: ty::PolyTraitRef<'tcx>,
761 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
762 let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
763 // Normalize the obligation and expected trait refs together, because why not
764 let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
765 ensure_sufficient_stack(|| {
766 normalize_with_depth(
768 obligation.param_env,
769 obligation.cause.clone(),
770 obligation.recursion_depth + 1,
771 (obligation_trait_ref, expected_trait_ref),
776 .at(&obligation.cause, obligation.param_env)
777 .sup(obligation_trait_ref, expected_trait_ref)
778 .map(|InferOk { mut obligations, .. }| {
779 obligations.extend(nested);
782 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
785 fn confirm_trait_upcasting_unsize_candidate(
787 obligation: &TraitObligation<'tcx>,
789 ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
791 let tcx = self.tcx();
793 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
794 // regions here. See the comment there for more details.
795 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
796 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
797 let target = self.infcx.shallow_resolve(target);
799 debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
801 let mut nested = vec![];
802 let source_trait_ref;
803 let upcast_trait_ref;
804 match (source.kind(), target.kind()) {
805 // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
807 &ty::Dynamic(ref data_a, r_a, repr_a @ ty::Dyn),
808 &ty::Dynamic(ref data_b, r_b, ty::Dyn),
810 // See `assemble_candidates_for_unsizing` for more info.
811 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
812 let principal_a = data_a.principal().unwrap();
813 source_trait_ref = principal_a.with_self_ty(tcx, source);
814 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
815 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
816 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
817 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
821 let iter = Some(existential_predicate)
826 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
831 .map(ty::ExistentialPredicate::AutoTrait)
832 .map(ty::Binder::dummy),
834 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
835 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, repr_a);
837 // Require that the traits involved in this upcast are **equal**;
838 // only the **lifetime bound** is changed.
839 let InferOk { obligations, .. } = self
841 .at(&obligation.cause, obligation.param_env)
842 .sup(target, source_trait)
843 .map_err(|_| Unimplemented)?;
844 nested.extend(obligations);
846 // Register one obligation for 'a: 'b.
847 let cause = ObligationCause::new(
848 obligation.cause.span,
849 obligation.cause.body_id,
850 ObjectCastObligation(source, target),
852 let outlives = ty::OutlivesPredicate(r_a, r_b);
853 nested.push(Obligation::with_depth(
856 obligation.recursion_depth + 1,
857 obligation.param_env,
858 obligation.predicate.rebind(outlives),
864 let vtable_segment_callback = {
865 let mut vptr_offset = 0;
868 VtblSegment::MetadataDSA => {
869 vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
871 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
872 vptr_offset += util::count_own_vtable_entries(tcx, trait_ref);
873 if trait_ref == upcast_trait_ref {
875 return ControlFlow::Break(Some(vptr_offset));
877 return ControlFlow::Break(None);
886 ControlFlow::Continue(())
890 let vtable_vptr_slot =
891 super::super::prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback)
894 Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
897 fn confirm_builtin_unsize_candidate(
899 obligation: &TraitObligation<'tcx>,
900 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
901 let tcx = self.tcx();
903 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
904 // regions here. See the comment there for more details.
905 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
906 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
907 let target = self.infcx.shallow_resolve(target);
909 debug!(?source, ?target, "confirm_builtin_unsize_candidate");
911 let mut nested = vec![];
912 match (source.kind(), target.kind()) {
913 // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
914 (&ty::Dynamic(ref data_a, r_a, dyn_a), &ty::Dynamic(ref data_b, r_b, dyn_b))
917 // See `assemble_candidates_for_unsizing` for more info.
918 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
921 .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
926 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
931 .map(ty::ExistentialPredicate::AutoTrait)
932 .map(ty::Binder::dummy),
934 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
935 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, dyn_a);
937 // Require that the traits involved in this upcast are **equal**;
938 // only the **lifetime bound** is changed.
939 let InferOk { obligations, .. } = self
941 .at(&obligation.cause, obligation.param_env)
942 .sup(target, source_trait)
943 .map_err(|_| Unimplemented)?;
944 nested.extend(obligations);
946 // Register one obligation for 'a: 'b.
947 let cause = ObligationCause::new(
948 obligation.cause.span,
949 obligation.cause.body_id,
950 ObjectCastObligation(source, target),
952 let outlives = ty::OutlivesPredicate(r_a, r_b);
953 nested.push(Obligation::with_depth(
956 obligation.recursion_depth + 1,
957 obligation.param_env,
958 obligation.predicate.rebind(outlives),
963 (_, &ty::Dynamic(ref data, r, ty::Dyn)) => {
964 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
965 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
966 return Err(TraitNotObjectSafe(did));
969 let cause = ObligationCause::new(
970 obligation.cause.span,
971 obligation.cause.body_id,
972 ObjectCastObligation(source, target),
975 let predicate_to_obligation = |predicate| {
976 Obligation::with_depth(
979 obligation.recursion_depth + 1,
980 obligation.param_env,
985 // Create obligations:
986 // - Casting `T` to `Trait`
987 // - For all the various builtin bounds attached to the object cast. (In other
988 // words, if the object type is `Foo + Send`, this would create an obligation for
989 // the `Send` check.)
990 // - Projection predicates
992 data.iter().map(|predicate| {
993 predicate_to_obligation(predicate.with_self_ty(tcx, source))
997 // We can only make objects from sized types.
999 ty::Binder::dummy(tcx.at(cause.span).mk_trait_ref(LangItem::Sized, [source]));
1000 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
1002 // If the type is `Foo + 'a`, ensure that the type
1003 // being cast to `Foo + 'a` outlives `'a`:
1004 let outlives = ty::OutlivesPredicate(source, r);
1005 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
1008 // `[T; n]` -> `[T]`
1009 (&ty::Array(a, _), &ty::Slice(b)) => {
1010 let InferOk { obligations, .. } = self
1012 .at(&obligation.cause, obligation.param_env)
1014 .map_err(|_| Unimplemented)?;
1015 nested.extend(obligations);
1018 // `Struct<T>` -> `Struct<U>`
1019 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
1020 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
1021 GenericArgKind::Type(ty) => match ty.kind() {
1022 ty::Param(p) => Some(p.index),
1026 // Lifetimes aren't allowed to change during unsizing.
1027 GenericArgKind::Lifetime(_) => None,
1029 GenericArgKind::Const(ct) => match ct.kind() {
1030 ty::ConstKind::Param(p) => Some(p.index),
1035 // FIXME(eddyb) cache this (including computing `unsizing_params`)
1036 // by putting it in a query; it would only need the `DefId` as it
1037 // looks at declared field types, not anything substituted.
1039 // The last field of the structure has to exist and contain type/const parameters.
1040 let (tail_field, prefix_fields) =
1041 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
1042 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1044 let mut unsizing_params = GrowableBitSet::new_empty();
1045 for arg in tail_field_ty.0.walk() {
1046 if let Some(i) = maybe_unsizing_param_idx(arg) {
1047 unsizing_params.insert(i);
1051 // Ensure none of the other fields mention the parameters used
1053 for field in prefix_fields {
1054 for arg in tcx.type_of(field.did).walk() {
1055 if let Some(i) = maybe_unsizing_param_idx(arg) {
1056 unsizing_params.remove(i);
1061 if unsizing_params.is_empty() {
1062 return Err(Unimplemented);
1065 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
1066 // normalizing in the process, since `type_of` returns something directly from
1067 // astconv (which means it's un-normalized).
1068 let source_tail = normalize_with_depth_to(
1070 obligation.param_env,
1071 obligation.cause.clone(),
1072 obligation.recursion_depth + 1,
1073 tail_field_ty.subst(tcx, substs_a),
1076 let target_tail = normalize_with_depth_to(
1078 obligation.param_env,
1079 obligation.cause.clone(),
1080 obligation.recursion_depth + 1,
1081 tail_field_ty.subst(tcx, substs_b),
1085 // Check that the source struct with the target's
1086 // unsizing parameters is equal to the target.
1087 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1088 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1090 let new_struct = tcx.mk_adt(def, substs);
1091 let InferOk { obligations, .. } = self
1093 .at(&obligation.cause, obligation.param_env)
1094 .eq(target, new_struct)
1095 .map_err(|_| Unimplemented)?;
1096 nested.extend(obligations);
1098 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1099 nested.push(predicate_for_trait_def(
1101 obligation.param_env,
1102 obligation.cause.clone(),
1103 obligation.predicate.def_id(),
1104 obligation.recursion_depth + 1,
1105 [source_tail, target_tail],
1109 // `(.., T)` -> `(.., U)`
1110 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1111 assert_eq!(tys_a.len(), tys_b.len());
1113 // The last field of the tuple has to exist.
1114 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1115 let &b_last = tys_b.last().unwrap();
1117 // Check that the source tuple with the target's
1118 // last element is equal to the target.
1119 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1120 let InferOk { obligations, .. } = self
1122 .at(&obligation.cause, obligation.param_env)
1123 .eq(target, new_tuple)
1124 .map_err(|_| Unimplemented)?;
1125 nested.extend(obligations);
1127 // Construct the nested `T: Unsize<U>` predicate.
1128 nested.push(ensure_sufficient_stack(|| {
1129 predicate_for_trait_def(
1131 obligation.param_env,
1132 obligation.cause.clone(),
1133 obligation.predicate.def_id(),
1134 obligation.recursion_depth + 1,
1140 _ => bug!("source: {source}, target: {target}"),
1143 Ok(ImplSourceBuiltinData { nested })
1146 fn confirm_const_destruct_candidate(
1148 obligation: &TraitObligation<'tcx>,
1149 impl_def_id: Option<DefId>,
1150 ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1151 // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1152 if !obligation.is_const() {
1153 return Ok(ImplSourceConstDestructData { nested: vec![] });
1156 let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1158 let tcx = self.tcx();
1159 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1161 let mut nested = vec![];
1162 let cause = obligation.derived_cause(BuiltinDerivedObligation);
1164 // If we have a custom `impl const Drop`, then
1165 // first check it like a regular impl candidate.
1166 // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1167 if let Some(impl_def_id) = impl_def_id {
1168 let mut new_obligation = obligation.clone();
1169 new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1170 trait_pred.trait_ref.def_id = drop_trait;
1173 let substs = self.rematch_impl(impl_def_id, &new_obligation);
1174 debug!(?substs, "impl substs");
1176 let cause = obligation.derived_cause(|derived| {
1177 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1180 span: obligation.cause.span,
1183 let obligations = ensure_sufficient_stack(|| {
1188 new_obligation.recursion_depth + 1,
1189 new_obligation.param_env,
1190 obligation.predicate,
1193 nested.extend(obligations.nested);
1196 // We want to confirm the ADT's fields if we have an ADT
1197 let mut stack = match *self_ty.skip_binder().kind() {
1198 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1199 _ => vec![self_ty.skip_binder()],
1202 while let Some(nested_ty) = stack.pop() {
1203 match *nested_ty.kind() {
1204 // We know these types are trivially drop
1210 | ty::Infer(ty::IntVar(_))
1211 | ty::Infer(ty::FloatVar(_))
1218 | ty::Foreign(_) => {}
1220 // `ManuallyDrop` is trivially drop
1221 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().manually_drop() => {}
1223 // These types are built-in, so we can fast-track by registering
1224 // nested predicates for their constituent type(s)
1225 ty::Array(ty, _) | ty::Slice(ty) => {
1229 stack.extend(tys.iter());
1231 ty::Closure(_, substs) => {
1232 stack.push(substs.as_closure().tupled_upvars_ty());
1234 ty::Generator(_, substs, _) => {
1235 let generator = substs.as_generator();
1236 stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1238 ty::GeneratorWitness(tys) => {
1239 stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1242 // If we have a projection type, make sure to normalize it so we replace it
1243 // with a fresh infer variable
1244 ty::Projection(..) => {
1245 let predicate = normalize_with_depth_to(
1247 obligation.param_env,
1249 obligation.recursion_depth + 1,
1250 self_ty.rebind(ty::TraitPredicate {
1254 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1255 constness: ty::BoundConstness::ConstIfConst,
1256 polarity: ty::ImplPolarity::Positive,
1261 nested.push(Obligation::with_depth(
1264 obligation.recursion_depth + 1,
1265 obligation.param_env,
1270 // If we have any other type (e.g. an ADT), just register a nested obligation
1271 // since it's either not `const Drop` (and we raise an error during selection),
1272 // or it's an ADT (and we need to check for a custom impl during selection)
1274 let predicate = self_ty.rebind(ty::TraitPredicate {
1278 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1279 constness: ty::BoundConstness::ConstIfConst,
1280 polarity: ty::ImplPolarity::Positive,
1283 nested.push(Obligation::with_depth(
1286 obligation.recursion_depth + 1,
1287 obligation.param_env,
1294 Ok(ImplSourceConstDestructData { nested })