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::Alias(_, ty::AliasTy { def_id, substs, .. }) => (def_id, substs),
159 _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
162 let candidate_predicate =
163 tcx.bound_item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs);
164 let candidate = candidate_predicate
165 .to_opt_poly_trait_pred()
166 .expect("projection candidate is not a trait predicate")
167 .map_bound(|t| t.trait_ref);
168 let mut obligations = Vec::new();
169 let candidate = normalize_with_depth_to(
171 obligation.param_env,
172 obligation.cause.clone(),
173 obligation.recursion_depth + 1,
178 obligations.extend(self.infcx.commit_if_ok(|_| {
180 .at(&obligation.cause, obligation.param_env)
181 .sup(placeholder_trait_predicate, candidate)
182 .map(|InferOk { obligations, .. }| obligations)
183 .map_err(|_| Unimplemented)
186 if let ty::Alias(ty::Projection, ..) = placeholder_self_ty.kind() {
187 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates;
188 debug!(?predicates, "projection predicates");
189 for predicate in predicates {
190 let normalized = normalize_with_depth_to(
192 obligation.param_env,
193 obligation.cause.clone(),
194 obligation.recursion_depth + 1,
198 obligations.push(Obligation::with_depth(
200 obligation.cause.clone(),
201 obligation.recursion_depth + 1,
202 obligation.param_env,
211 fn confirm_param_candidate(
213 obligation: &TraitObligation<'tcx>,
214 param: ty::PolyTraitRef<'tcx>,
215 ) -> Vec<PredicateObligation<'tcx>> {
216 debug!(?obligation, ?param, "confirm_param_candidate");
218 // During evaluation, we already checked that this
219 // where-clause trait-ref could be unified with the obligation
220 // trait-ref. Repeat that unification now without any
221 // transactional boundary; it should not fail.
222 match self.match_where_clause_trait_ref(obligation, param) {
223 Ok(obligations) => obligations,
226 "Where clause `{:?}` was applicable to `{:?}` but now is not",
234 fn confirm_builtin_candidate(
236 obligation: &TraitObligation<'tcx>,
238 ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
239 debug!(?obligation, ?has_nested, "confirm_builtin_candidate");
241 let lang_items = self.tcx().lang_items();
242 let obligations = if has_nested {
243 let trait_def = obligation.predicate.def_id();
244 let conditions = if Some(trait_def) == lang_items.sized_trait() {
245 self.sized_conditions(obligation)
246 } else if Some(trait_def) == lang_items.copy_trait() {
247 self.copy_clone_conditions(obligation)
248 } else if Some(trait_def) == lang_items.clone_trait() {
249 self.copy_clone_conditions(obligation)
251 bug!("unexpected builtin trait {:?}", trait_def)
253 let BuiltinImplConditions::Where(nested) = conditions else {
254 bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
257 let cause = obligation.derived_cause(BuiltinDerivedObligation);
258 ensure_sufficient_stack(|| {
259 self.collect_predicates_for_types(
260 obligation.param_env,
262 obligation.recursion_depth + 1,
271 debug!(?obligations);
273 ImplSourceBuiltinData { nested: obligations }
276 fn confirm_transmutability_candidate(
278 obligation: &TraitObligation<'tcx>,
279 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
280 debug!(?obligation, "confirm_transmutability_candidate");
282 let predicate = obligation.predicate;
284 let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i));
285 let const_at = |i| predicate.skip_binder().trait_ref.substs.const_at(i);
287 let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types {
288 dst: p.trait_ref.substs.type_at(0),
289 src: p.trait_ref.substs.type_at(1),
292 let scope = type_at(2).skip_binder();
295 rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, const_at(3)) else {
296 return Err(Unimplemented);
299 let cause = obligation.cause.clone();
301 let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
303 let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume);
305 use rustc_transmute::Answer;
307 match maybe_transmutable {
308 Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }),
309 _ => Err(Unimplemented),
313 /// This handles the case where an `auto trait Foo` impl is being used.
314 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
316 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
317 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
318 fn confirm_auto_impl_candidate(
320 obligation: &TraitObligation<'tcx>,
321 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
322 debug!(?obligation, "confirm_auto_impl_candidate");
324 let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
325 let types = self.constituent_types_for_ty(self_ty);
326 self.vtable_auto_impl(obligation, obligation.predicate.def_id(), types)
329 /// See `confirm_auto_impl_candidate`.
332 obligation: &TraitObligation<'tcx>,
334 nested: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
335 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
336 debug!(?nested, "vtable_auto_impl");
337 ensure_sufficient_stack(|| {
338 let cause = obligation.derived_cause(BuiltinDerivedObligation);
340 let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
341 let trait_ref = self.infcx.replace_bound_vars_with_placeholders(poly_trait_ref);
342 let trait_obligations: Vec<PredicateObligation<'_>> = self.impl_or_trait_obligations(
344 obligation.recursion_depth + 1,
345 obligation.param_env,
348 obligation.predicate,
351 let mut obligations = self.collect_predicates_for_types(
352 obligation.param_env,
354 obligation.recursion_depth + 1,
359 // Adds the predicates from the trait. Note that this contains a `Self: Trait`
360 // predicate as usual. It won't have any effect since auto traits are coinductive.
361 obligations.extend(trait_obligations);
363 debug!(?obligations, "vtable_auto_impl");
365 ImplSourceAutoImplData { trait_def_id, nested: obligations }
369 fn confirm_impl_candidate(
371 obligation: &TraitObligation<'tcx>,
373 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
374 debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");
376 // First, create the substitutions by matching the impl again,
377 // this time not in a probe.
378 let substs = self.rematch_impl(impl_def_id, obligation);
379 debug!(?substs, "impl substs");
380 ensure_sufficient_stack(|| {
385 obligation.recursion_depth + 1,
386 obligation.param_env,
387 obligation.predicate,
395 substs: Normalized<'tcx, SubstsRef<'tcx>>,
396 cause: &ObligationCause<'tcx>,
397 recursion_depth: usize,
398 param_env: ty::ParamEnv<'tcx>,
399 parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
400 ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
401 debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl");
403 let mut impl_obligations = self.impl_or_trait_obligations(
412 debug!(?impl_obligations, "vtable_impl");
414 // Because of RFC447, the impl-trait-ref and obligations
415 // are sufficient to determine the impl substs, without
416 // relying on projections in the impl-trait-ref.
418 // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
419 impl_obligations.extend(substs.obligations);
421 ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations }
424 fn confirm_object_candidate(
426 obligation: &TraitObligation<'tcx>,
428 ) -> Result<ImplSourceObjectData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
429 let tcx = self.tcx();
430 debug!(?obligation, ?index, "confirm_object_candidate");
432 let trait_predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
433 let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
434 let obligation_trait_ref = ty::Binder::dummy(trait_predicate.trait_ref);
435 let ty::Dynamic(data, ..) = *self_ty.kind() else {
436 span_bug!(obligation.cause.span, "object candidate with non-object");
439 let object_trait_ref = data.principal().unwrap_or_else(|| {
440 span_bug!(obligation.cause.span, "object candidate with no principal")
442 let object_trait_ref = self.infcx.replace_bound_vars_with_fresh_vars(
443 obligation.cause.span,
447 let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);
449 let mut nested = vec![];
451 let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
452 let unnormalized_upcast_trait_ref =
453 supertraits.nth(index).expect("supertraits iterator no longer has as many elements");
455 let upcast_trait_ref = normalize_with_depth_to(
457 obligation.param_env,
458 obligation.cause.clone(),
459 obligation.recursion_depth + 1,
460 unnormalized_upcast_trait_ref,
464 nested.extend(self.infcx.commit_if_ok(|_| {
466 .at(&obligation.cause, obligation.param_env)
467 .sup(obligation_trait_ref, upcast_trait_ref)
468 .map(|InferOk { obligations, .. }| obligations)
469 .map_err(|_| Unimplemented)
472 // Check supertraits hold. This is so that their associated type bounds
473 // will be checked in the code below.
474 for super_trait in tcx
475 .super_predicates_of(trait_predicate.def_id())
476 .instantiate(tcx, trait_predicate.trait_ref.substs)
480 let normalized_super_trait = normalize_with_depth_to(
482 obligation.param_env,
483 obligation.cause.clone(),
484 obligation.recursion_depth + 1,
488 nested.push(obligation.with(tcx, normalized_super_trait));
491 let assoc_types: Vec<_> = tcx
492 .associated_items(trait_predicate.def_id())
493 .in_definition_order()
495 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
499 for assoc_type in assoc_types {
500 let defs: &ty::Generics = tcx.generics_of(assoc_type);
502 if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
503 tcx.sess.delay_span_bug(
504 obligation.cause.span,
505 "GATs in trait object shouldn't have been considered",
507 return Err(SelectionError::Unimplemented);
510 // This maybe belongs in wf, but that can't (doesn't) handle
511 // higher-ranked things.
512 // Prevent, e.g., `dyn Iterator<Item = str>`.
513 for bound in self.tcx().bound_item_bounds(assoc_type).transpose_iter() {
515 if defs.count() == 0 {
516 bound.subst(tcx, trait_predicate.trait_ref.substs)
518 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
519 substs.extend(trait_predicate.trait_ref.substs.iter());
520 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
521 smallvec::SmallVec::with_capacity(
522 bound.0.kind().bound_vars().len() + defs.count(),
524 bound_vars.extend(bound.0.kind().bound_vars().into_iter());
525 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
528 GenericParamDefKind::Type { .. } => {
529 let kind = ty::BoundTyKind::Param(param.name);
530 let bound_var = ty::BoundVariableKind::Ty(kind);
531 bound_vars.push(bound_var);
535 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
541 GenericParamDefKind::Lifetime => {
542 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
543 let bound_var = ty::BoundVariableKind::Region(kind);
544 bound_vars.push(bound_var);
545 tcx.mk_region(ty::ReLateBound(
548 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
554 GenericParamDefKind::Const { .. } => {
555 let bound_var = ty::BoundVariableKind::Const;
556 bound_vars.push(bound_var);
558 ty::ConstKind::Bound(
560 ty::BoundVar::from_usize(bound_vars.len() - 1),
562 tcx.type_of(param.def_id),
567 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
568 let assoc_ty_substs = tcx.intern_substs(&substs);
570 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
572 bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs);
573 tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
575 let normalized_bound = normalize_with_depth_to(
577 obligation.param_env,
578 obligation.cause.clone(),
579 obligation.recursion_depth + 1,
583 nested.push(obligation.with(tcx, normalized_bound));
587 debug!(?nested, "object nested obligations");
589 let vtable_base = vtable_trait_first_method_offset(
591 (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
594 Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
597 fn confirm_fn_pointer_candidate(
599 obligation: &TraitObligation<'tcx>,
600 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
602 debug!(?obligation, "confirm_fn_pointer_candidate");
606 .shallow_resolve(obligation.self_ty().no_bound_vars())
607 .expect("fn pointer should not capture bound vars from predicate");
608 let sig = self_ty.fn_sig(self.tcx());
609 let trait_ref = closure_trait_ref_and_return_type(
611 obligation.predicate.def_id(),
614 util::TupleArgumentsFlag::Yes,
616 .map_bound(|(trait_ref, _)| trait_ref);
618 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
620 // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
621 let cause = obligation.derived_cause(BuiltinDerivedObligation);
622 let output_ty = self.infcx.replace_bound_vars_with_placeholders(sig.output());
623 let output_ty = normalize_with_depth_to(
625 obligation.param_env,
627 obligation.recursion_depth,
632 ty::Binder::dummy(self.tcx().at(cause.span).mk_trait_ref(LangItem::Sized, [output_ty]));
633 nested.push(Obligation::new(self.infcx.tcx, cause, obligation.param_env, tr));
635 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
638 fn confirm_trait_alias_candidate(
640 obligation: &TraitObligation<'tcx>,
641 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
642 debug!(?obligation, "confirm_trait_alias_candidate");
644 let alias_def_id = obligation.predicate.def_id();
645 let predicate = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate);
646 let trait_ref = predicate.trait_ref;
647 let trait_def_id = trait_ref.def_id;
648 let substs = trait_ref.substs;
650 let trait_obligations = self.impl_or_trait_obligations(
652 obligation.recursion_depth,
653 obligation.param_env,
656 obligation.predicate,
659 debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
661 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
664 fn confirm_generator_candidate(
666 obligation: &TraitObligation<'tcx>,
667 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
669 // Okay to skip binder because the substs on generator types never
670 // touch bound regions, they just capture the in-scope
671 // type/region parameters.
672 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
673 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
674 bug!("closure candidate for non-closure {:?}", obligation);
677 debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
679 let gen_sig = substs.as_generator().poly_sig();
681 // NOTE: The self-type is a generator type and hence is
682 // in fact unparameterized (or at least does not reference any
683 // regions bound in the obligation).
684 let self_ty = obligation
688 .expect("unboxed closure type should not capture bound vars from the predicate");
690 let trait_ref = super::util::generator_trait_ref_and_outputs(
692 obligation.predicate.def_id(),
696 .map_bound(|(trait_ref, ..)| trait_ref);
698 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
699 debug!(?trait_ref, ?nested, "generator candidate obligations");
701 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
704 fn confirm_future_candidate(
706 obligation: &TraitObligation<'tcx>,
707 ) -> Result<ImplSourceFutureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
708 // Okay to skip binder because the substs on generator types never
709 // touch bound regions, they just capture the in-scope
710 // type/region parameters.
711 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
712 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
713 bug!("closure candidate for non-closure {:?}", obligation);
716 debug!(?obligation, ?generator_def_id, ?substs, "confirm_future_candidate");
718 let gen_sig = substs.as_generator().poly_sig();
720 let trait_ref = super::util::future_trait_ref_and_outputs(
722 obligation.predicate.def_id(),
723 obligation.predicate.no_bound_vars().expect("future has no bound vars").self_ty(),
726 .map_bound(|(trait_ref, ..)| trait_ref);
728 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
729 debug!(?trait_ref, ?nested, "future candidate obligations");
731 Ok(ImplSourceFutureData { generator_def_id, substs, nested })
734 #[instrument(skip(self), level = "debug")]
735 fn confirm_closure_candidate(
737 obligation: &TraitObligation<'tcx>,
738 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
741 .fn_trait_kind_from_def_id(obligation.predicate.def_id())
742 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
744 // Okay to skip binder because the substs on closure types never
745 // touch bound regions, they just capture the in-scope
746 // type/region parameters.
747 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
748 let ty::Closure(closure_def_id, substs) = *self_ty.kind() else {
749 bug!("closure candidate for non-closure {:?}", obligation);
752 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
753 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
755 debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
759 if !self.tcx().sess.opts.unstable_opts.chalk {
760 nested.push(obligation.with(
762 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind)),
766 Ok(ImplSourceClosureData { closure_def_id, substs, nested })
769 /// In the case of closure types and fn pointers,
770 /// we currently treat the input type parameters on the trait as
771 /// outputs. This means that when we have a match we have only
772 /// considered the self type, so we have to go back and make sure
773 /// to relate the argument types too. This is kind of wrong, but
774 /// since we control the full set of impls, also not that wrong,
775 /// and it DOES yield better error messages (since we don't report
776 /// errors as if there is no applicable impl, but rather report
777 /// errors are about mismatched argument types.
779 /// Here is an example. Imagine we have a closure expression
780 /// and we desugared it so that the type of the expression is
781 /// `Closure`, and `Closure` expects `i32` as argument. Then it
782 /// is "as if" the compiler generated this impl:
783 /// ```ignore (illustrative)
784 /// impl Fn(i32) for Closure { ... }
786 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
787 /// we have matched the self type `Closure`. At this point we'll
788 /// compare the `i32` to `usize` and generate an error.
790 /// Note that this checking occurs *after* the impl has selected,
791 /// because these output type parameters should not affect the
792 /// selection of the impl. Therefore, if there is a mismatch, we
793 /// report an error to the user.
794 #[instrument(skip(self), level = "trace")]
795 fn confirm_poly_trait_refs(
797 obligation: &TraitObligation<'tcx>,
798 expected_trait_ref: ty::PolyTraitRef<'tcx>,
799 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
800 let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
801 // Normalize the obligation and expected trait refs together, because why not
802 let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
803 ensure_sufficient_stack(|| {
804 normalize_with_depth(
806 obligation.param_env,
807 obligation.cause.clone(),
808 obligation.recursion_depth + 1,
809 (obligation_trait_ref, expected_trait_ref),
814 .at(&obligation.cause, obligation.param_env)
815 .sup(obligation_trait_ref, expected_trait_ref)
816 .map(|InferOk { mut obligations, .. }| {
817 obligations.extend(nested);
820 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
823 fn confirm_trait_upcasting_unsize_candidate(
825 obligation: &TraitObligation<'tcx>,
827 ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
829 let tcx = self.tcx();
831 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
832 // regions here. See the comment there for more details.
833 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
834 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
835 let target = self.infcx.shallow_resolve(target);
837 debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
839 let mut nested = vec![];
840 let source_trait_ref;
841 let upcast_trait_ref;
842 match (source.kind(), target.kind()) {
843 // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
845 &ty::Dynamic(ref data_a, r_a, repr_a @ ty::Dyn),
846 &ty::Dynamic(ref data_b, r_b, ty::Dyn),
848 // See `assemble_candidates_for_unsizing` for more info.
849 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
850 let principal_a = data_a.principal().unwrap();
851 source_trait_ref = principal_a.with_self_ty(tcx, source);
852 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
853 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
854 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
855 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
859 let iter = Some(existential_predicate)
864 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
869 .map(ty::ExistentialPredicate::AutoTrait)
870 .map(ty::Binder::dummy),
872 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
873 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, repr_a);
875 // Require that the traits involved in this upcast are **equal**;
876 // only the **lifetime bound** is changed.
877 let InferOk { obligations, .. } = self
879 .at(&obligation.cause, obligation.param_env)
880 .sup(target, source_trait)
881 .map_err(|_| Unimplemented)?;
882 nested.extend(obligations);
884 // Register one obligation for 'a: 'b.
885 let cause = ObligationCause::new(
886 obligation.cause.span,
887 obligation.cause.body_id,
888 ObjectCastObligation(source, target),
890 let outlives = ty::OutlivesPredicate(r_a, r_b);
891 nested.push(Obligation::with_depth(
894 obligation.recursion_depth + 1,
895 obligation.param_env,
896 obligation.predicate.rebind(outlives),
902 let vtable_segment_callback = {
903 let mut vptr_offset = 0;
906 VtblSegment::MetadataDSA => {
907 vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
909 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
910 vptr_offset += count_own_vtable_entries(tcx, trait_ref);
911 if trait_ref == upcast_trait_ref {
913 return ControlFlow::Break(Some(vptr_offset));
915 return ControlFlow::Break(None);
924 ControlFlow::Continue(())
928 let vtable_vptr_slot =
929 prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback).unwrap();
931 Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
934 fn confirm_builtin_unsize_candidate(
936 obligation: &TraitObligation<'tcx>,
937 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
938 let tcx = self.tcx();
940 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
941 // regions here. See the comment there for more details.
942 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
943 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
944 let target = self.infcx.shallow_resolve(target);
946 debug!(?source, ?target, "confirm_builtin_unsize_candidate");
948 let mut nested = vec![];
949 match (source.kind(), target.kind()) {
950 // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
951 (&ty::Dynamic(ref data_a, r_a, dyn_a), &ty::Dynamic(ref data_b, r_b, dyn_b))
954 // See `assemble_candidates_for_unsizing` for more info.
955 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
958 .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
963 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
968 .map(ty::ExistentialPredicate::AutoTrait)
969 .map(ty::Binder::dummy),
971 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
972 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, dyn_a);
974 // Require that the traits involved in this upcast are **equal**;
975 // only the **lifetime bound** is changed.
976 let InferOk { obligations, .. } = self
978 .at(&obligation.cause, obligation.param_env)
979 .sup(target, source_trait)
980 .map_err(|_| Unimplemented)?;
981 nested.extend(obligations);
983 // Register one obligation for 'a: 'b.
984 let cause = ObligationCause::new(
985 obligation.cause.span,
986 obligation.cause.body_id,
987 ObjectCastObligation(source, target),
989 let outlives = ty::OutlivesPredicate(r_a, r_b);
990 nested.push(Obligation::with_depth(
993 obligation.recursion_depth + 1,
994 obligation.param_env,
995 obligation.predicate.rebind(outlives),
1000 (_, &ty::Dynamic(ref data, r, ty::Dyn)) => {
1001 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
1002 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
1003 return Err(TraitNotObjectSafe(did));
1006 let cause = ObligationCause::new(
1007 obligation.cause.span,
1008 obligation.cause.body_id,
1009 ObjectCastObligation(source, target),
1012 let predicate_to_obligation = |predicate| {
1013 Obligation::with_depth(
1016 obligation.recursion_depth + 1,
1017 obligation.param_env,
1022 // Create obligations:
1023 // - Casting `T` to `Trait`
1024 // - For all the various builtin bounds attached to the object cast. (In other
1025 // words, if the object type is `Foo + Send`, this would create an obligation for
1026 // the `Send` check.)
1027 // - Projection predicates
1029 data.iter().map(|predicate| {
1030 predicate_to_obligation(predicate.with_self_ty(tcx, source))
1034 // We can only make objects from sized types.
1036 ty::Binder::dummy(tcx.at(cause.span).mk_trait_ref(LangItem::Sized, [source]));
1037 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
1039 // If the type is `Foo + 'a`, ensure that the type
1040 // being cast to `Foo + 'a` outlives `'a`:
1041 let outlives = ty::OutlivesPredicate(source, r);
1042 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
1045 // `[T; n]` -> `[T]`
1046 (&ty::Array(a, _), &ty::Slice(b)) => {
1047 let InferOk { obligations, .. } = self
1049 .at(&obligation.cause, obligation.param_env)
1051 .map_err(|_| Unimplemented)?;
1052 nested.extend(obligations);
1055 // `Struct<T>` -> `Struct<U>`
1056 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
1057 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
1058 GenericArgKind::Type(ty) => match ty.kind() {
1059 ty::Param(p) => Some(p.index),
1063 // Lifetimes aren't allowed to change during unsizing.
1064 GenericArgKind::Lifetime(_) => None,
1066 GenericArgKind::Const(ct) => match ct.kind() {
1067 ty::ConstKind::Param(p) => Some(p.index),
1072 // FIXME(eddyb) cache this (including computing `unsizing_params`)
1073 // by putting it in a query; it would only need the `DefId` as it
1074 // looks at declared field types, not anything substituted.
1076 // The last field of the structure has to exist and contain type/const parameters.
1077 let (tail_field, prefix_fields) =
1078 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
1079 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1081 let mut unsizing_params = GrowableBitSet::new_empty();
1082 for arg in tail_field_ty.0.walk() {
1083 if let Some(i) = maybe_unsizing_param_idx(arg) {
1084 unsizing_params.insert(i);
1088 // Ensure none of the other fields mention the parameters used
1090 for field in prefix_fields {
1091 for arg in tcx.type_of(field.did).walk() {
1092 if let Some(i) = maybe_unsizing_param_idx(arg) {
1093 unsizing_params.remove(i);
1098 if unsizing_params.is_empty() {
1099 return Err(Unimplemented);
1102 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
1103 // normalizing in the process, since `type_of` returns something directly from
1104 // astconv (which means it's un-normalized).
1105 let source_tail = normalize_with_depth_to(
1107 obligation.param_env,
1108 obligation.cause.clone(),
1109 obligation.recursion_depth + 1,
1110 tail_field_ty.subst(tcx, substs_a),
1113 let target_tail = normalize_with_depth_to(
1115 obligation.param_env,
1116 obligation.cause.clone(),
1117 obligation.recursion_depth + 1,
1118 tail_field_ty.subst(tcx, substs_b),
1122 // Check that the source struct with the target's
1123 // unsizing parameters is equal to the target.
1124 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1125 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1127 let new_struct = tcx.mk_adt(def, substs);
1128 let InferOk { obligations, .. } = self
1130 .at(&obligation.cause, obligation.param_env)
1131 .eq(target, new_struct)
1132 .map_err(|_| Unimplemented)?;
1133 nested.extend(obligations);
1135 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1136 nested.push(predicate_for_trait_def(
1138 obligation.param_env,
1139 obligation.cause.clone(),
1140 obligation.predicate.def_id(),
1141 obligation.recursion_depth + 1,
1142 [source_tail, target_tail],
1146 // `(.., T)` -> `(.., U)`
1147 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1148 assert_eq!(tys_a.len(), tys_b.len());
1150 // The last field of the tuple has to exist.
1151 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1152 let &b_last = tys_b.last().unwrap();
1154 // Check that the source tuple with the target's
1155 // last element is equal to the target.
1156 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1157 let InferOk { obligations, .. } = self
1159 .at(&obligation.cause, obligation.param_env)
1160 .eq(target, new_tuple)
1161 .map_err(|_| Unimplemented)?;
1162 nested.extend(obligations);
1164 // Construct the nested `T: Unsize<U>` predicate.
1165 nested.push(ensure_sufficient_stack(|| {
1166 predicate_for_trait_def(
1168 obligation.param_env,
1169 obligation.cause.clone(),
1170 obligation.predicate.def_id(),
1171 obligation.recursion_depth + 1,
1177 _ => bug!("source: {source}, target: {target}"),
1180 Ok(ImplSourceBuiltinData { nested })
1183 fn confirm_const_destruct_candidate(
1185 obligation: &TraitObligation<'tcx>,
1186 impl_def_id: Option<DefId>,
1187 ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1188 // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1189 if !obligation.is_const() {
1190 return Ok(ImplSourceConstDestructData { nested: vec![] });
1193 let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1195 let tcx = self.tcx();
1196 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1198 let mut nested = vec![];
1199 let cause = obligation.derived_cause(BuiltinDerivedObligation);
1201 // If we have a custom `impl const Drop`, then
1202 // first check it like a regular impl candidate.
1203 // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1204 if let Some(impl_def_id) = impl_def_id {
1205 let mut new_obligation = obligation.clone();
1206 new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1207 trait_pred.trait_ref.def_id = drop_trait;
1210 let substs = self.rematch_impl(impl_def_id, &new_obligation);
1211 debug!(?substs, "impl substs");
1213 let cause = obligation.derived_cause(|derived| {
1214 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1217 span: obligation.cause.span,
1220 let obligations = ensure_sufficient_stack(|| {
1225 new_obligation.recursion_depth + 1,
1226 new_obligation.param_env,
1227 obligation.predicate,
1230 nested.extend(obligations.nested);
1233 // We want to confirm the ADT's fields if we have an ADT
1234 let mut stack = match *self_ty.skip_binder().kind() {
1235 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1236 _ => vec![self_ty.skip_binder()],
1239 while let Some(nested_ty) = stack.pop() {
1240 match *nested_ty.kind() {
1241 // We know these types are trivially drop
1247 | ty::Infer(ty::IntVar(_))
1248 | ty::Infer(ty::FloatVar(_))
1255 | ty::Foreign(_) => {}
1257 // `ManuallyDrop` is trivially drop
1258 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().manually_drop() => {}
1260 // These types are built-in, so we can fast-track by registering
1261 // nested predicates for their constituent type(s)
1262 ty::Array(ty, _) | ty::Slice(ty) => {
1266 stack.extend(tys.iter());
1268 ty::Closure(_, substs) => {
1269 stack.push(substs.as_closure().tupled_upvars_ty());
1271 ty::Generator(_, substs, _) => {
1272 let generator = substs.as_generator();
1273 stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1275 ty::GeneratorWitness(tys) => {
1276 stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1279 // If we have a projection type, make sure to normalize it so we replace it
1280 // with a fresh infer variable
1281 ty::Alias(ty::Projection, ..) => {
1282 let predicate = normalize_with_depth_to(
1284 obligation.param_env,
1286 obligation.recursion_depth + 1,
1287 self_ty.rebind(ty::TraitPredicate {
1291 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1292 constness: ty::BoundConstness::ConstIfConst,
1293 polarity: ty::ImplPolarity::Positive,
1298 nested.push(Obligation::with_depth(
1301 obligation.recursion_depth + 1,
1302 obligation.param_env,
1307 // If we have any other type (e.g. an ADT), just register a nested obligation
1308 // since it's either not `const Drop` (and we raise an error during selection),
1309 // or it's an ADT (and we need to check for a custom impl during selection)
1311 let predicate = self_ty.rebind(ty::TraitPredicate {
1315 .mk_trait_ref(LangItem::Destruct, [nested_ty]),
1316 constness: ty::BoundConstness::ConstIfConst,
1317 polarity: ty::ImplPolarity::Positive,
1320 nested.push(Obligation::with_depth(
1323 obligation.recursion_depth + 1,
1324 obligation.param_env,
1331 Ok(ImplSourceConstDestructData { nested })