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};
22 use crate::traits::vtable::{
23 count_own_vtable_entries, prepare_vtable_segments, vtable_trait_first_method_offset,
27 BuiltinDerivedObligation, ImplDerivedObligation, ImplDerivedObligationCause, ImplSource,
28 ImplSourceAutoImplData, ImplSourceBuiltinData, ImplSourceClosureData,
29 ImplSourceConstDestructData, ImplSourceFnPointerData, ImplSourceFutureData,
30 ImplSourceGeneratorData, ImplSourceObjectData, ImplSourceTraitAliasData,
31 ImplSourceTraitUpcastingData, ImplSourceUserDefinedData, Normalized, ObjectCastObligation,
32 Obligation, ObligationCause, OutputTypeParameterMismatch, PredicateObligation, Selection,
33 SelectionError, TraitNotObjectSafe, TraitObligation, Unimplemented,
36 use super::BuiltinImplConditions;
37 use super::SelectionCandidate::{self, *};
38 use super::SelectionContext;
41 use std::ops::ControlFlow;
43 impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
44 #[instrument(level = "debug", skip(self))]
45 pub(super) fn confirm_candidate(
47 obligation: &TraitObligation<'tcx>,
48 candidate: SelectionCandidate<'tcx>,
49 ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
50 let mut impl_src = match candidate {
51 BuiltinCandidate { has_nested } => {
52 let data = self.confirm_builtin_candidate(obligation, has_nested);
53 ImplSource::Builtin(data)
56 TransmutabilityCandidate => {
57 let data = self.confirm_transmutability_candidate(obligation)?;
58 ImplSource::Builtin(data)
61 ParamCandidate(param) => {
63 self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref));
64 ImplSource::Param(obligations, param.skip_binder().constness)
67 ImplCandidate(impl_def_id) => {
68 ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id))
71 AutoImplCandidate => {
72 let data = self.confirm_auto_impl_candidate(obligation);
73 ImplSource::AutoImpl(data)
76 ProjectionCandidate(idx, constness) => {
77 let obligations = self.confirm_projection_candidate(obligation, idx)?;
78 ImplSource::Param(obligations, constness)
81 ObjectCandidate(idx) => {
82 let data = self.confirm_object_candidate(obligation, idx)?;
83 ImplSource::Object(data)
87 let vtable_closure = self.confirm_closure_candidate(obligation)?;
88 ImplSource::Closure(vtable_closure)
91 GeneratorCandidate => {
92 let vtable_generator = self.confirm_generator_candidate(obligation)?;
93 ImplSource::Generator(vtable_generator)
97 let vtable_future = self.confirm_future_candidate(obligation)?;
98 ImplSource::Future(vtable_future)
101 FnPointerCandidate { .. } => {
102 let data = self.confirm_fn_pointer_candidate(obligation)?;
103 ImplSource::FnPointer(data)
106 TraitAliasCandidate => {
107 let data = self.confirm_trait_alias_candidate(obligation);
108 ImplSource::TraitAlias(data)
111 BuiltinObjectCandidate => {
112 // This indicates something like `Trait + Send: Send`. In this case, we know that
113 // this holds because that's what the object type is telling us, and there's really
114 // no additional obligations to prove and no types in particular to unify, etc.
115 ImplSource::Param(Vec::new(), ty::BoundConstness::NotConst)
118 BuiltinUnsizeCandidate => {
119 let data = self.confirm_builtin_unsize_candidate(obligation)?;
120 ImplSource::Builtin(data)
123 TraitUpcastingUnsizeCandidate(idx) => {
124 let data = self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?;
125 ImplSource::TraitUpcasting(data)
128 ConstDestructCandidate(def_id) => {
129 let data = self.confirm_const_destruct_candidate(obligation, def_id)?;
130 ImplSource::ConstDestruct(data)
134 if !obligation.predicate.is_const_if_const() {
135 // normalize nested predicates according to parent predicate's constness.
136 impl_src = impl_src.map(|mut o| {
137 o.predicate = o.predicate.without_const(self.tcx());
145 fn confirm_projection_candidate(
147 obligation: &TraitObligation<'tcx>,
149 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
150 let tcx = self.tcx();
152 let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
153 let placeholder_trait_predicate =
154 self.infcx.replace_bound_vars_with_placeholders(trait_predicate).trait_ref;
155 let placeholder_self_ty = placeholder_trait_predicate.self_ty();
156 let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate);
157 let (def_id, substs) = match *placeholder_self_ty.kind() {
158 ty::Projection(proj) => (proj.item_def_id, proj.substs),
159 ty::Opaque(def_id, substs) => (def_id, substs),
160 _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
163 let candidate_predicate =
164 tcx.bound_item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs);
165 let candidate = candidate_predicate
166 .to_opt_poly_trait_pred()
167 .expect("projection candidate is not a trait predicate")
168 .map_bound(|t| t.trait_ref);
169 let mut obligations = Vec::new();
170 let candidate = normalize_with_depth_to(
172 obligation.param_env,
173 obligation.cause.clone(),
174 obligation.recursion_depth + 1,
179 obligations.extend(self.infcx.commit_if_ok(|_| {
181 .at(&obligation.cause, obligation.param_env)
182 .sup(placeholder_trait_predicate, candidate)
183 .map(|InferOk { obligations, .. }| obligations)
184 .map_err(|_| Unimplemented)
187 if let ty::Projection(..) = placeholder_self_ty.kind() {
188 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates;
189 debug!(?predicates, "projection predicates");
190 for predicate in predicates {
191 let normalized = normalize_with_depth_to(
193 obligation.param_env,
194 obligation.cause.clone(),
195 obligation.recursion_depth + 1,
199 obligations.push(Obligation::with_depth(
201 obligation.cause.clone(),
202 obligation.recursion_depth + 1,
203 obligation.param_env,
212 fn confirm_param_candidate(
214 obligation: &TraitObligation<'tcx>,
215 param: ty::PolyTraitRef<'tcx>,
216 ) -> Vec<PredicateObligation<'tcx>> {
217 debug!(?obligation, ?param, "confirm_param_candidate");
219 // During evaluation, we already checked that this
220 // where-clause trait-ref could be unified with the obligation
221 // trait-ref. Repeat that unification now without any
222 // transactional boundary; it should not fail.
223 match self.match_where_clause_trait_ref(obligation, param) {
224 Ok(obligations) => obligations,
227 "Where clause `{:?}` was applicable to `{:?}` but now is not",
235 fn confirm_builtin_candidate(
237 obligation: &TraitObligation<'tcx>,
239 ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
240 debug!(?obligation, ?has_nested, "confirm_builtin_candidate");
242 let lang_items = self.tcx().lang_items();
243 let obligations = if has_nested {
244 let trait_def = obligation.predicate.def_id();
245 let conditions = if Some(trait_def) == lang_items.sized_trait() {
246 self.sized_conditions(obligation)
247 } else if Some(trait_def) == lang_items.copy_trait() {
248 self.copy_clone_conditions(obligation)
249 } else if Some(trait_def) == lang_items.clone_trait() {
250 self.copy_clone_conditions(obligation)
252 bug!("unexpected builtin trait {:?}", trait_def)
254 let BuiltinImplConditions::Where(nested) = conditions else {
255 bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
258 let cause = obligation.derived_cause(BuiltinDerivedObligation);
259 ensure_sufficient_stack(|| {
260 self.collect_predicates_for_types(
261 obligation.param_env,
263 obligation.recursion_depth + 1,
272 debug!(?obligations);
274 ImplSourceBuiltinData { nested: obligations }
277 fn confirm_transmutability_candidate(
279 obligation: &TraitObligation<'tcx>,
280 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
281 debug!(?obligation, "confirm_transmutability_candidate");
283 let predicate = obligation.predicate;
285 let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i));
286 let const_at = |i| predicate.skip_binder().trait_ref.substs.const_at(i);
288 let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types {
289 dst: p.trait_ref.substs.type_at(0),
290 src: p.trait_ref.substs.type_at(1),
293 let scope = type_at(2).skip_binder();
296 rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, const_at(3)) else {
297 return Err(Unimplemented);
300 let cause = obligation.cause.clone();
302 let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
304 let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume);
306 use rustc_transmute::Answer;
308 match maybe_transmutable {
309 Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }),
310 _ => Err(Unimplemented),
314 /// This handles the case where an `auto trait Foo` impl is being used.
315 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
317 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
318 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
319 fn confirm_auto_impl_candidate(
321 obligation: &TraitObligation<'tcx>,
322 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
323 debug!(?obligation, "confirm_auto_impl_candidate");
325 let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
326 let types = self.constituent_types_for_ty(self_ty);
327 self.vtable_auto_impl(obligation, obligation.predicate.def_id(), types)
330 /// See `confirm_auto_impl_candidate`.
333 obligation: &TraitObligation<'tcx>,
335 nested: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
336 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
337 debug!(?nested, "vtable_auto_impl");
338 ensure_sufficient_stack(|| {
339 let cause = obligation.derived_cause(BuiltinDerivedObligation);
341 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
342 let trait_ref = self.infcx.replace_bound_vars_with_placeholders(poly_trait_ref);
343 let trait_obligations: Vec<PredicateObligation<'_>> = self.impl_or_trait_obligations(
345 obligation.recursion_depth + 1,
346 obligation.param_env,
349 obligation.predicate,
352 let mut obligations = self.collect_predicates_for_types(
353 obligation.param_env,
355 obligation.recursion_depth + 1,
360 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
361 // predicate as usual. It won't have any effect since auto traits are coinductive.
362 obligations.extend(trait_obligations);
364 debug!(?obligations, "vtable_auto_impl");
366 ImplSourceAutoImplData { trait_def_id, nested: obligations }
370 fn confirm_impl_candidate(
372 obligation: &TraitObligation<'tcx>,
374 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
375 debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");
377 // First, create the substitutions by matching the impl again,
378 // this time not in a probe.
379 let substs = self.rematch_impl(impl_def_id, obligation);
380 debug!(?substs, "impl substs");
381 ensure_sufficient_stack(|| {
386 obligation.recursion_depth + 1,
387 obligation.param_env,
388 obligation.predicate,
396 substs: Normalized<'tcx, SubstsRef<'tcx>>,
397 cause: &ObligationCause<'tcx>,
398 recursion_depth: usize,
399 param_env: ty::ParamEnv<'tcx>,
400 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
401 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
402 debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl");
404 let mut impl_obligations = self.impl_or_trait_obligations(
413 debug!(?impl_obligations, "vtable_impl");
415 // Because of RFC447, the impl-trait-ref and obligations
416 // are sufficient to determine the impl substs, without
417 // relying on projections in the impl-trait-ref.
419 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
420 impl_obligations.extend(substs.obligations);
422 ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations }
425 fn confirm_object_candidate(
427 obligation: &TraitObligation<'tcx>,
429 ) -> Result<ImplSourceObjectData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
430 let tcx = self.tcx();
431 debug!(?obligation, ?index, "confirm_object_candidate");
433 let trait_predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
434 let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
435 let obligation_trait_ref = ty::Binder::dummy(trait_predicate.trait_ref);
436 let ty::Dynamic(data, ..) = *self_ty.kind() else {
437 span_bug!(obligation.cause.span, "object candidate with non-object");
440 let object_trait_ref = data.principal().unwrap_or_else(|| {
441 span_bug!(obligation.cause.span, "object candidate with no principal")
443 let object_trait_ref = self.infcx.replace_bound_vars_with_fresh_vars(
444 obligation.cause.span,
448 let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);
450 let mut nested = vec![];
452 let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
453 let unnormalized_upcast_trait_ref =
454 supertraits.nth(index).expect("supertraits iterator no longer has as many elements");
456 let upcast_trait_ref = normalize_with_depth_to(
458 obligation.param_env,
459 obligation.cause.clone(),
460 obligation.recursion_depth + 1,
461 unnormalized_upcast_trait_ref,
465 nested.extend(self.infcx.commit_if_ok(|_| {
467 .at(&obligation.cause, obligation.param_env)
468 .sup(obligation_trait_ref, upcast_trait_ref)
469 .map(|InferOk { obligations, .. }| obligations)
470 .map_err(|_| Unimplemented)
473 // Check supertraits hold. This is so that their associated type bounds
474 // will be checked in the code below.
475 for super_trait in tcx
476 .super_predicates_of(trait_predicate.def_id())
477 .instantiate(tcx, trait_predicate.trait_ref.substs)
481 let normalized_super_trait = normalize_with_depth_to(
483 obligation.param_env,
484 obligation.cause.clone(),
485 obligation.recursion_depth + 1,
489 nested.push(obligation.with(tcx, normalized_super_trait));
492 let assoc_types: Vec<_> = tcx
493 .associated_items(trait_predicate.def_id())
494 .in_definition_order()
496 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
500 for assoc_type in assoc_types {
501 let defs: &ty::Generics = tcx.generics_of(assoc_type);
503 if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
504 tcx.sess.delay_span_bug(
505 obligation.cause.span,
506 "GATs in trait object shouldn't have been considered",
508 return Err(SelectionError::Unimplemented);
511 // This maybe belongs in wf, but that can't (doesn't) handle
512 // higher-ranked things.
513 // Prevent, e.g., `dyn Iterator<Item = str>`.
514 for bound in self.tcx().bound_item_bounds(assoc_type).transpose_iter() {
516 if defs.count() == 0 {
517 bound.subst(tcx, trait_predicate.trait_ref.substs)
519 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
520 substs.extend(trait_predicate.trait_ref.substs.iter());
521 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
522 smallvec::SmallVec::with_capacity(
523 bound.0.kind().bound_vars().len() + defs.count(),
525 bound_vars.extend(bound.0.kind().bound_vars().into_iter());
526 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
529 GenericParamDefKind::Type { .. } => {
530 let kind = ty::BoundTyKind::Param(param.name);
531 let bound_var = ty::BoundVariableKind::Ty(kind);
532 bound_vars.push(bound_var);
536 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
542 GenericParamDefKind::Lifetime => {
543 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
544 let bound_var = ty::BoundVariableKind::Region(kind);
545 bound_vars.push(bound_var);
546 tcx.mk_region(ty::ReLateBound(
549 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
555 GenericParamDefKind::Const { .. } => {
556 let bound_var = ty::BoundVariableKind::Const;
557 bound_vars.push(bound_var);
559 ty::ConstKind::Bound(
561 ty::BoundVar::from_usize(bound_vars.len() - 1),
563 tcx.type_of(param.def_id),
568 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
569 let assoc_ty_substs = tcx.intern_substs(&substs);
571 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
573 bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs);
574 tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
576 let normalized_bound = normalize_with_depth_to(
578 obligation.param_env,
579 obligation.cause.clone(),
580 obligation.recursion_depth + 1,
584 nested.push(obligation.with(tcx, normalized_bound));
588 debug!(?nested, "object nested obligations");
590 let vtable_base = vtable_trait_first_method_offset(
592 (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
595 Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
598 fn confirm_fn_pointer_candidate(
600 obligation: &TraitObligation<'tcx>,
601 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
603 debug!(?obligation, "confirm_fn_pointer_candidate");
607 .shallow_resolve(obligation.self_ty().no_bound_vars())
608 .expect("fn pointer should not capture bound vars from predicate");
609 let sig = self_ty.fn_sig(self.tcx());
610 let trait_ref = closure_trait_ref_and_return_type(
612 obligation.predicate.def_id(),
615 util::TupleArgumentsFlag::Yes,
617 .map_bound(|(trait_ref, _)| trait_ref);
619 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
621 // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
622 let cause = obligation.derived_cause(BuiltinDerivedObligation);
623 let output_ty = self.infcx.replace_bound_vars_with_placeholders(sig.output());
624 let output_ty = normalize_with_depth_to(
626 obligation.param_env,
628 obligation.recursion_depth,
633 ty::Binder::dummy(self.tcx().at(cause.span).mk_trait_ref(LangItem::Sized, [output_ty]));
634 nested.push(Obligation::new(self.infcx.tcx, cause, obligation.param_env, tr));
636 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
639 fn confirm_trait_alias_candidate(
641 obligation: &TraitObligation<'tcx>,
642 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
643 debug!(?obligation, "confirm_trait_alias_candidate");
645 let alias_def_id = obligation.predicate.def_id();
646 let predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
647 let trait_ref = predicate.trait_ref;
648 let trait_def_id = trait_ref.def_id;
649 let substs = trait_ref.substs;
651 let trait_obligations = self.impl_or_trait_obligations(
653 obligation.recursion_depth,
654 obligation.param_env,
657 obligation.predicate,
660 debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
662 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
665 fn confirm_generator_candidate(
667 obligation: &TraitObligation<'tcx>,
668 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
670 // Okay to skip binder because the substs on generator types never
671 // touch bound regions, they just capture the in-scope
672 // type/region parameters.
673 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
674 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
675 bug!("closure candidate for non-closure {:?}", obligation);
678 debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
680 let gen_sig = substs.as_generator().poly_sig();
682 // NOTE: The self-type is a generator type and hence is
683 // in fact unparameterized (or at least does not reference any
684 // regions bound in the obligation).
685 let self_ty = obligation
689 .expect("unboxed closure type should not capture bound vars from the predicate");
691 let trait_ref = super::util::generator_trait_ref_and_outputs(
693 obligation.predicate.def_id(),
697 .map_bound(|(trait_ref, ..)| trait_ref);
699 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
700 debug!(?trait_ref, ?nested, "generator candidate obligations");
702 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
705 fn confirm_future_candidate(
707 obligation: &TraitObligation<'tcx>,
708 ) -> Result<ImplSourceFutureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
709 // Okay to skip binder because the substs on generator types never
710 // touch bound regions, they just capture the in-scope
711 // type/region parameters.
712 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
713 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
714 bug!("closure candidate for non-closure {:?}", obligation);
717 debug!(?obligation, ?generator_def_id, ?substs, "confirm_future_candidate");
719 let gen_sig = substs.as_generator().poly_sig();
721 let trait_ref = super::util::future_trait_ref_and_outputs(
723 obligation.predicate.def_id(),
724 obligation.predicate.no_bound_vars().expect("future has no bound vars").self_ty(),
727 .map_bound(|(trait_ref, ..)| trait_ref);
729 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
730 debug!(?trait_ref, ?nested, "future candidate obligations");
732 Ok(ImplSourceFutureData { generator_def_id, substs, nested })
735 #[instrument(skip(self), level = "debug")]
736 fn confirm_closure_candidate(
738 obligation: &TraitObligation<'tcx>,
739 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
742 .fn_trait_kind_from_def_id(obligation.predicate.def_id())
743 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
745 // Okay to skip binder because the substs on closure types never
746 // touch bound regions, they just capture the in-scope
747 // type/region parameters.
748 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
749 let ty::Closure(closure_def_id, substs) = *self_ty.kind() else {
750 bug!("closure candidate for non-closure {:?}", obligation);
753 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
754 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
756 debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
760 if !self.tcx().sess.opts.unstable_opts.chalk {
761 nested.push(obligation.with(
763 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind)),
767 Ok(ImplSourceClosureData { closure_def_id, substs, nested })
770 /// In the case of closure types and fn pointers,
771 /// we currently treat the input type parameters on the trait as
772 /// outputs. This means that when we have a match we have only
773 /// considered the self type, so we have to go back and make sure
774 /// to relate the argument types too. This is kind of wrong, but
775 /// since we control the full set of impls, also not that wrong,
776 /// and it DOES yield better error messages (since we don't report
777 /// errors as if there is no applicable impl, but rather report
778 /// errors are about mismatched argument types.
780 /// Here is an example. Imagine we have a closure expression
781 /// and we desugared it so that the type of the expression is
782 /// `Closure`, and `Closure` expects `i32` as argument. Then it
783 /// is "as if" the compiler generated this impl:
784 /// ```ignore (illustrative)
785 /// impl Fn(i32) for Closure { ... }
787 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
788 /// we have matched the self type `Closure`. At this point we'll
789 /// compare the `i32` to `usize` and generate an error.
791 /// Note that this checking occurs *after* the impl has selected,
792 /// because these output type parameters should not affect the
793 /// selection of the impl. Therefore, if there is a mismatch, we
794 /// report an error to the user.
795 #[instrument(skip(self), level = "trace")]
796 fn confirm_poly_trait_refs(
798 obligation: &TraitObligation<'tcx>,
799 expected_trait_ref: ty::PolyTraitRef<'tcx>,
800 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
801 let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
802 // Normalize the obligation and expected trait refs together, because why not
803 let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
804 ensure_sufficient_stack(|| {
805 normalize_with_depth(
807 obligation.param_env,
808 obligation.cause.clone(),
809 obligation.recursion_depth + 1,
810 (obligation_trait_ref, expected_trait_ref),
815 .at(&obligation.cause, obligation.param_env)
816 .sup(obligation_trait_ref, expected_trait_ref)
817 .map(|InferOk { mut obligations, .. }| {
818 obligations.extend(nested);
821 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
824 fn confirm_trait_upcasting_unsize_candidate(
826 obligation: &TraitObligation<'tcx>,
828 ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
830 let tcx = self.tcx();
832 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
833 // regions here. See the comment there for more details.
834 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
835 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
836 let target = self.infcx.shallow_resolve(target);
838 debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
840 let mut nested = vec![];
841 let source_trait_ref;
842 let upcast_trait_ref;
843 match (source.kind(), target.kind()) {
844 // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
846 &ty::Dynamic(ref data_a, r_a, repr_a @ ty::Dyn),
847 &ty::Dynamic(ref data_b, r_b, ty::Dyn),
849 // See `assemble_candidates_for_unsizing` for more info.
850 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
851 let principal_a = data_a.principal().unwrap();
852 source_trait_ref = principal_a.with_self_ty(tcx, source);
853 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
854 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
855 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
856 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
860 let iter = Some(existential_predicate)
865 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
870 .map(ty::ExistentialPredicate::AutoTrait)
871 .map(ty::Binder::dummy),
873 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
874 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, repr_a);
876 // Require that the traits involved in this upcast are **equal**;
877 // only the **lifetime bound** is changed.
878 let InferOk { obligations, .. } = self
880 .at(&obligation.cause, obligation.param_env)
881 .sup(target, source_trait)
882 .map_err(|_| Unimplemented)?;
883 nested.extend(obligations);
885 // Register one obligation for 'a: 'b.
886 let cause = ObligationCause::new(
887 obligation.cause.span,
888 obligation.cause.body_id,
889 ObjectCastObligation(source, target),
891 let outlives = ty::OutlivesPredicate(r_a, r_b);
892 nested.push(Obligation::with_depth(
895 obligation.recursion_depth + 1,
896 obligation.param_env,
897 obligation.predicate.rebind(outlives),
903 let vtable_segment_callback = {
904 let mut vptr_offset = 0;
907 VtblSegment::MetadataDSA => {
908 vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
910 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
911 vptr_offset += count_own_vtable_entries(tcx, trait_ref);
912 if trait_ref == upcast_trait_ref {
914 return ControlFlow::Break(Some(vptr_offset));
916 return ControlFlow::Break(None);
925 ControlFlow::Continue(())
929 let vtable_vptr_slot =
930 prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback).unwrap();
932 Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
935 fn confirm_builtin_unsize_candidate(
937 obligation: &TraitObligation<'tcx>,
938 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
939 let tcx = self.tcx();
941 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
942 // regions here. See the comment there for more details.
943 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
944 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
945 let target = self.infcx.shallow_resolve(target);
947 debug!(?source, ?target, "confirm_builtin_unsize_candidate");
949 let mut nested = vec![];
950 match (source.kind(), target.kind()) {
951 // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
952 (&ty::Dynamic(ref data_a, r_a, dyn_a), &ty::Dynamic(ref data_b, r_b, dyn_b))
955 // See `assemble_candidates_for_unsizing` for more info.
956 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
959 .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
964 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
969 .map(ty::ExistentialPredicate::AutoTrait)
970 .map(ty::Binder::dummy),
972 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
973 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, dyn_a);
975 // Require that the traits involved in this upcast are **equal**;
976 // only the **lifetime bound** is changed.
977 let InferOk { obligations, .. } = self
979 .at(&obligation.cause, obligation.param_env)
980 .sup(target, source_trait)
981 .map_err(|_| Unimplemented)?;
982 nested.extend(obligations);
984 // Register one obligation for 'a: 'b.
985 let cause = ObligationCause::new(
986 obligation.cause.span,
987 obligation.cause.body_id,
988 ObjectCastObligation(source, target),
990 let outlives = ty::OutlivesPredicate(r_a, r_b);
991 nested.push(Obligation::with_depth(
994 obligation.recursion_depth + 1,
995 obligation.param_env,
996 obligation.predicate.rebind(outlives),
1001 (_, &ty::Dynamic(ref data, r, ty::Dyn)) => {
1002 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
1003 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
1004 return Err(TraitNotObjectSafe(did));
1007 let cause = ObligationCause::new(
1008 obligation.cause.span,
1009 obligation.cause.body_id,
1010 ObjectCastObligation(source, target),
1013 let predicate_to_obligation = |predicate| {
1014 Obligation::with_depth(
1017 obligation.recursion_depth + 1,
1018 obligation.param_env,
1023 // Create obligations:
1024 // - Casting `T` to `Trait`
1025 // - For all the various builtin bounds attached to the object cast. (In other
1026 // words, if the object type is `Foo + Send`, this would create an obligation for
1027 // the `Send` check.)
1028 // - Projection predicates
1030 data.iter().map(|predicate| {
1031 predicate_to_obligation(predicate.with_self_ty(tcx, source))
1035 // We can only make objects from sized types.
1037 ty::Binder::dummy(tcx.at(cause.span).mk_trait_ref(LangItem::Sized, [source]));
1038 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
1040 // If the type is `Foo + 'a`, ensure that the type
1041 // being cast to `Foo + 'a` outlives `'a`:
1042 let outlives = ty::OutlivesPredicate(source, r);
1043 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
1046 // `[T; n]` -> `[T]`
1047 (&ty::Array(a, _), &ty::Slice(b)) => {
1048 let InferOk { obligations, .. } = self
1050 .at(&obligation.cause, obligation.param_env)
1052 .map_err(|_| Unimplemented)?;
1053 nested.extend(obligations);
1056 // `Struct<T>` -> `Struct<U>`
1057 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
1058 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
1059 GenericArgKind::Type(ty) => match ty.kind() {
1060 ty::Param(p) => Some(p.index),
1064 // Lifetimes aren't allowed to change during unsizing.
1065 GenericArgKind::Lifetime(_) => None,
1067 GenericArgKind::Const(ct) => match ct.kind() {
1068 ty::ConstKind::Param(p) => Some(p.index),
1073 // FIXME(eddyb) cache this (including computing `unsizing_params`)
1074 // by putting it in a query; it would only need the `DefId` as it
1075 // looks at declared field types, not anything substituted.
1077 // The last field of the structure has to exist and contain type/const parameters.
1078 let (tail_field, prefix_fields) =
1079 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
1080 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1082 let mut unsizing_params = GrowableBitSet::new_empty();
1083 for arg in tail_field_ty.0.walk() {
1084 if let Some(i) = maybe_unsizing_param_idx(arg) {
1085 unsizing_params.insert(i);
1089 // Ensure none of the other fields mention the parameters used
1091 for field in prefix_fields {
1092 for arg in tcx.type_of(field.did).walk() {
1093 if let Some(i) = maybe_unsizing_param_idx(arg) {
1094 unsizing_params.remove(i);
1099 if unsizing_params.is_empty() {
1100 return Err(Unimplemented);
1103 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
1104 // normalizing in the process, since `type_of` returns something directly from
1105 // astconv (which means it's un-normalized).
1106 let source_tail = normalize_with_depth_to(
1108 obligation.param_env,
1109 obligation.cause.clone(),
1110 obligation.recursion_depth + 1,
1111 tail_field_ty.subst(tcx, substs_a),
1114 let target_tail = normalize_with_depth_to(
1116 obligation.param_env,
1117 obligation.cause.clone(),
1118 obligation.recursion_depth + 1,
1119 tail_field_ty.subst(tcx, substs_b),
1123 // Check that the source struct with the target's
1124 // unsizing parameters is equal to the target.
1125 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1126 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1128 let new_struct = tcx.mk_adt(def, substs);
1129 let InferOk { obligations, .. } = self
1131 .at(&obligation.cause, obligation.param_env)
1132 .eq(target, new_struct)
1133 .map_err(|_| Unimplemented)?;
1134 nested.extend(obligations);
1136 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1137 nested.push(predicate_for_trait_def(
1139 obligation.param_env,
1140 obligation.cause.clone(),
1141 obligation.predicate.def_id(),
1142 obligation.recursion_depth + 1,
1143 [source_tail, target_tail],
1147 // `(.., T)` -> `(.., U)`
1148 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1149 assert_eq!(tys_a.len(), tys_b.len());
1151 // The last field of the tuple has to exist.
1152 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1153 let &b_last = tys_b.last().unwrap();
1155 // Check that the source tuple with the target's
1156 // last element is equal to the target.
1157 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1158 let InferOk { obligations, .. } = self
1160 .at(&obligation.cause, obligation.param_env)
1161 .eq(target, new_tuple)
1162 .map_err(|_| Unimplemented)?;
1163 nested.extend(obligations);
1165 // Construct the nested `T: Unsize<U>` predicate.
1166 nested.push(ensure_sufficient_stack(|| {
1167 predicate_for_trait_def(
1169 obligation.param_env,
1170 obligation.cause.clone(),
1171 obligation.predicate.def_id(),
1172 obligation.recursion_depth + 1,
1178 _ => bug!("source: {source}, target: {target}"),
1181 Ok(ImplSourceBuiltinData { nested })
1184 fn confirm_const_destruct_candidate(
1186 obligation: &TraitObligation<'tcx>,
1187 impl_def_id: Option<DefId>,
1188 ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1189 // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1190 if !obligation.is_const() {
1191 return Ok(ImplSourceConstDestructData { nested: vec![] });
1194 let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1196 let tcx = self.tcx();
1197 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1199 let mut nested = vec![];
1200 let cause = obligation.derived_cause(BuiltinDerivedObligation);
1202 // If we have a custom `impl const Drop`, then
1203 // first check it like a regular impl candidate.
1204 // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1205 if let Some(impl_def_id) = impl_def_id {
1206 let mut new_obligation = obligation.clone();
1207 new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1208 trait_pred.trait_ref.def_id = drop_trait;
1211 let substs = self.rematch_impl(impl_def_id, &new_obligation);
1212 debug!(?substs, "impl substs");
1214 let cause = obligation.derived_cause(|derived| {
1215 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1218 span: obligation.cause.span,
1221 let obligations = ensure_sufficient_stack(|| {
1226 new_obligation.recursion_depth + 1,
1227 new_obligation.param_env,
1228 obligation.predicate,
1231 nested.extend(obligations.nested);
1234 // We want to confirm the ADT's fields if we have an ADT
1235 let mut stack = match *self_ty.skip_binder().kind() {
1236 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1237 _ => vec![self_ty.skip_binder()],
1240 while let Some(nested_ty) = stack.pop() {
1241 match *nested_ty.kind() {
1242 // We know these types are trivially drop
1248 | ty::Infer(ty::IntVar(_))
1249 | ty::Infer(ty::FloatVar(_))
1256 | ty::Foreign(_) => {}
1258 // `ManuallyDrop` is trivially drop
1259 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().manually_drop() => {}
1261 // These types are built-in, so we can fast-track by registering
1262 // nested predicates for their constituent type(s)
1263 ty::Array(ty, _) | ty::Slice(ty) => {
1267 stack.extend(tys.iter());
1269 ty::Closure(_, substs) => {
1270 stack.push(substs.as_closure().tupled_upvars_ty());
1272 ty::Generator(_, substs, _) => {
1273 let generator = substs.as_generator();
1274 stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1276 ty::GeneratorWitness(tys) => {
1277 stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1280 // If we have a projection type, make sure to normalize it so we replace it
1281 // with a fresh infer variable
1282 ty::Projection(..) => {
1283 let predicate = normalize_with_depth_to(
1285 obligation.param_env,
1287 obligation.recursion_depth + 1,
1288 self_ty.rebind(ty::TraitPredicate {
1292 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1293 constness: ty::BoundConstness::ConstIfConst,
1294 polarity: ty::ImplPolarity::Positive,
1299 nested.push(Obligation::with_depth(
1302 obligation.recursion_depth + 1,
1303 obligation.param_env,
1308 // If we have any other type (e.g. an ADT), just register a nested obligation
1309 // since it's either not `const Drop` (and we raise an error during selection),
1310 // or it's an ADT (and we need to check for a custom impl during selection)
1312 let predicate = self_ty.rebind(ty::TraitPredicate {
1316 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1317 constness: ty::BoundConstness::ConstIfConst,
1318 polarity: ty::ImplPolarity::Positive,
1321 nested.push(Obligation::with_depth(
1324 obligation.recursion_depth + 1,
1325 obligation.param_env,
1332 Ok(ImplSourceConstDestructData { nested })