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(trait_def_id) => {
68 let data = self.confirm_auto_impl_candidate(obligation, trait_def_id);
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(alias_def_id) => {
104 let data = self.confirm_trait_alias_candidate(obligation, alias_def_id);
105 ImplSource::TraitAlias(data)
108 BuiltinObjectCandidate => {
109 // This indicates something like `Trait + Send: Send`. In this case, we know that
110 // this holds because that's what the object type is telling us, and there's really
111 // no additional obligations to prove and no types in particular to unify, etc.
112 ImplSource::Param(Vec::new(), ty::BoundConstness::NotConst)
115 BuiltinUnsizeCandidate => {
116 let data = self.confirm_builtin_unsize_candidate(obligation)?;
117 ImplSource::Builtin(data)
120 TraitUpcastingUnsizeCandidate(idx) => {
121 let data = self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?;
122 ImplSource::TraitUpcasting(data)
125 ConstDestructCandidate(def_id) => {
126 let data = self.confirm_const_destruct_candidate(obligation, def_id)?;
127 ImplSource::ConstDestruct(data)
130 TupleCandidate => ImplSource::Tuple,
133 if !obligation.predicate.is_const_if_const() {
134 // normalize nested predicates according to parent predicate's constness.
135 impl_src = impl_src.map(|mut o| {
136 o.predicate = o.predicate.without_const(self.tcx());
144 fn confirm_projection_candidate(
146 obligation: &TraitObligation<'tcx>,
148 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
149 let tcx = self.tcx();
151 let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
152 let placeholder_trait_predicate =
153 self.infcx().replace_bound_vars_with_placeholders(trait_predicate).trait_ref;
154 let placeholder_self_ty = placeholder_trait_predicate.self_ty();
155 let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate);
156 let (def_id, substs) = match *placeholder_self_ty.kind() {
157 ty::Projection(proj) => (proj.item_def_id, proj.substs),
158 ty::Opaque(def_id, substs) => (def_id, substs),
159 _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty),
162 let candidate_predicate =
163 tcx.bound_item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs);
164 let candidate = candidate_predicate
165 .to_opt_poly_trait_pred()
166 .expect("projection candidate is not a trait predicate")
167 .map_bound(|t| t.trait_ref);
168 let mut obligations = Vec::new();
169 let candidate = normalize_with_depth_to(
171 obligation.param_env,
172 obligation.cause.clone(),
173 obligation.recursion_depth + 1,
178 obligations.extend(self.infcx.commit_if_ok(|_| {
180 .at(&obligation.cause, obligation.param_env)
181 .sup(placeholder_trait_predicate, candidate)
182 .map(|InferOk { obligations, .. }| obligations)
183 .map_err(|_| Unimplemented)
186 if let ty::Projection(..) = placeholder_self_ty.kind() {
187 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs).predicates;
188 debug!(?predicates, "projection predicates");
189 for predicate in predicates {
190 let normalized = normalize_with_depth_to(
192 obligation.param_env,
193 obligation.cause.clone(),
194 obligation.recursion_depth + 1,
198 obligations.push(Obligation::with_depth(
199 obligation.cause.clone(),
200 obligation.recursion_depth + 1,
201 obligation.param_env,
210 fn confirm_param_candidate(
212 obligation: &TraitObligation<'tcx>,
213 param: ty::PolyTraitRef<'tcx>,
214 ) -> Vec<PredicateObligation<'tcx>> {
215 debug!(?obligation, ?param, "confirm_param_candidate");
217 // During evaluation, we already checked that this
218 // where-clause trait-ref could be unified with the obligation
219 // trait-ref. Repeat that unification now without any
220 // transactional boundary; it should not fail.
221 match self.match_where_clause_trait_ref(obligation, param) {
222 Ok(obligations) => obligations,
225 "Where clause `{:?}` was applicable to `{:?}` but now is not",
233 fn confirm_builtin_candidate(
235 obligation: &TraitObligation<'tcx>,
237 ) -> ImplSourceBuiltinData<PredicateObligation<'tcx>> {
238 debug!(?obligation, ?has_nested, "confirm_builtin_candidate");
240 let lang_items = self.tcx().lang_items();
241 let obligations = if has_nested {
242 let trait_def = obligation.predicate.def_id();
243 let conditions = if Some(trait_def) == lang_items.sized_trait() {
244 self.sized_conditions(obligation)
245 } else if Some(trait_def) == lang_items.copy_trait() {
246 self.copy_clone_conditions(obligation)
247 } else if Some(trait_def) == lang_items.clone_trait() {
248 self.copy_clone_conditions(obligation)
250 bug!("unexpected builtin trait {:?}", trait_def)
252 let BuiltinImplConditions::Where(nested) = conditions else {
253 bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
256 let cause = obligation.derived_cause(BuiltinDerivedObligation);
257 ensure_sufficient_stack(|| {
258 self.collect_predicates_for_types(
259 obligation.param_env,
261 obligation.recursion_depth + 1,
270 debug!(?obligations);
272 ImplSourceBuiltinData { nested: obligations }
275 fn confirm_transmutability_candidate(
277 obligation: &TraitObligation<'tcx>,
278 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
279 debug!(?obligation, "confirm_transmutability_candidate");
281 let predicate = obligation.predicate;
283 let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i));
284 let const_at = |i| predicate.skip_binder().trait_ref.substs.const_at(i);
286 let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types {
287 dst: p.trait_ref.substs.type_at(0),
288 src: p.trait_ref.substs.type_at(1),
291 let scope = type_at(2).skip_binder();
294 rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, const_at(3)) else {
295 return Err(Unimplemented);
298 let cause = obligation.cause.clone();
300 let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
302 let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume);
304 use rustc_transmute::Answer;
306 match maybe_transmutable {
307 Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }),
308 _ => Err(Unimplemented),
312 /// This handles the case where an `auto trait Foo` impl is being used.
313 /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
315 /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
316 /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
317 fn confirm_auto_impl_candidate(
319 obligation: &TraitObligation<'tcx>,
321 ) -> ImplSourceAutoImplData<PredicateObligation<'tcx>> {
322 debug!(?obligation, ?trait_def_id, "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, trait_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::new(
489 obligation.cause.clone(),
490 obligation.param_env,
491 normalized_super_trait,
495 let assoc_types: Vec<_> = tcx
496 .associated_items(trait_predicate.def_id())
497 .in_definition_order()
499 |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
503 for assoc_type in assoc_types {
504 let defs: &ty::Generics = tcx.generics_of(assoc_type);
506 if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
507 tcx.sess.delay_span_bug(
508 obligation.cause.span,
509 "GATs in trait object shouldn't have been considered",
511 return Err(SelectionError::Unimplemented);
514 // This maybe belongs in wf, but that can't (doesn't) handle
515 // higher-ranked things.
516 // Prevent, e.g., `dyn Iterator<Item = str>`.
517 for bound in self.tcx().bound_item_bounds(assoc_type).transpose_iter() {
519 if defs.count() == 0 {
520 bound.subst(tcx, trait_predicate.trait_ref.substs)
522 let mut substs = smallvec::SmallVec::with_capacity(defs.count());
523 substs.extend(trait_predicate.trait_ref.substs.iter());
524 let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
525 smallvec::SmallVec::with_capacity(
526 bound.0.kind().bound_vars().len() + defs.count(),
528 bound_vars.extend(bound.0.kind().bound_vars().into_iter());
529 InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param
532 GenericParamDefKind::Type { .. } => {
533 let kind = ty::BoundTyKind::Param(param.name);
534 let bound_var = ty::BoundVariableKind::Ty(kind);
535 bound_vars.push(bound_var);
539 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
545 GenericParamDefKind::Lifetime => {
546 let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
547 let bound_var = ty::BoundVariableKind::Region(kind);
548 bound_vars.push(bound_var);
549 tcx.mk_region(ty::ReLateBound(
552 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
558 GenericParamDefKind::Const { .. } => {
559 let bound_var = ty::BoundVariableKind::Const;
560 bound_vars.push(bound_var);
561 tcx.mk_const(ty::ConstS {
562 ty: tcx.type_of(param.def_id),
563 kind: ty::ConstKind::Bound(
565 ty::BoundVar::from_usize(bound_vars.len() - 1),
571 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
572 let assoc_ty_substs = tcx.intern_substs(&substs);
574 let bound_vars = tcx.mk_bound_variable_kinds(bound_vars.into_iter());
576 bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs);
577 tcx.mk_predicate(ty::Binder::bind_with_vars(bound, bound_vars))
579 let normalized_bound = normalize_with_depth_to(
581 obligation.param_env,
582 obligation.cause.clone(),
583 obligation.recursion_depth + 1,
587 nested.push(Obligation::new(
588 obligation.cause.clone(),
589 obligation.param_env,
595 debug!(?nested, "object nested obligations");
597 let vtable_base = super::super::vtable_trait_first_method_offset(
599 (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
602 Ok(ImplSourceObjectData { upcast_trait_ref, vtable_base, nested })
605 fn confirm_fn_pointer_candidate(
607 obligation: &TraitObligation<'tcx>,
608 ) -> Result<ImplSourceFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
610 debug!(?obligation, "confirm_fn_pointer_candidate");
612 // Okay to skip binder; it is reintroduced below.
613 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
614 let sig = self_ty.fn_sig(self.tcx());
615 let trait_ref = closure_trait_ref_and_return_type(
617 obligation.predicate.def_id(),
620 util::TupleArgumentsFlag::Yes,
622 .map_bound(|(trait_ref, _)| trait_ref);
624 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
626 // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
627 let cause = obligation.derived_cause(BuiltinDerivedObligation);
628 // The binder on the Fn obligation is "less" important than the one on
629 // the signature, as evidenced by how we treat it during projection.
630 // The safe thing to do here is to liberate it, though, which should
631 // have no worse effect than skipping the binder here.
632 let liberated_fn_ty =
633 self.infcx.replace_bound_vars_with_placeholders(obligation.predicate.rebind(self_ty));
636 .replace_bound_vars_with_placeholders(liberated_fn_ty.fn_sig(self.tcx()).output());
637 let output_ty = normalize_with_depth_to(
639 obligation.param_env,
641 obligation.recursion_depth,
645 let tr = ty::Binder::dummy(ty::TraitRef::new(
646 self.tcx().require_lang_item(LangItem::Sized, None),
647 self.tcx().mk_substs_trait(output_ty, &[]),
649 nested.push(Obligation::new(
651 obligation.param_env,
652 tr.to_poly_trait_predicate().to_predicate(self.tcx()),
655 Ok(ImplSourceFnPointerData { fn_ty: self_ty, nested })
658 fn confirm_trait_alias_candidate(
660 obligation: &TraitObligation<'tcx>,
662 ) -> ImplSourceTraitAliasData<'tcx, PredicateObligation<'tcx>> {
663 debug!(?obligation, ?alias_def_id, "confirm_trait_alias_candidate");
665 let predicate = self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
666 let trait_ref = predicate.trait_ref;
667 let trait_def_id = trait_ref.def_id;
668 let substs = trait_ref.substs;
670 let trait_obligations = self.impl_or_trait_obligations(
672 obligation.recursion_depth,
673 obligation.param_env,
676 obligation.predicate,
679 debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");
681 ImplSourceTraitAliasData { alias_def_id, substs, nested: trait_obligations }
684 fn confirm_generator_candidate(
686 obligation: &TraitObligation<'tcx>,
687 ) -> Result<ImplSourceGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
689 // Okay to skip binder because the substs on generator types never
690 // touch bound regions, they just capture the in-scope
691 // type/region parameters.
692 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
693 let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else {
694 bug!("closure candidate for non-closure {:?}", obligation);
697 debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate");
699 let trait_ref = self.generator_trait_ref_unnormalized(obligation, substs);
701 let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
702 debug!(?trait_ref, ?nested, "generator candidate obligations");
704 Ok(ImplSourceGeneratorData { generator_def_id, substs, nested })
707 #[instrument(skip(self), level = "debug")]
708 fn confirm_closure_candidate(
710 obligation: &TraitObligation<'tcx>,
711 ) -> Result<ImplSourceClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
714 .fn_trait_kind_from_lang_item(obligation.predicate.def_id())
715 .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
717 // Okay to skip binder because the substs on closure types never
718 // touch bound regions, they just capture the in-scope
719 // type/region parameters.
720 let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
721 let ty::Closure(closure_def_id, substs) = *self_ty.kind() else {
722 bug!("closure candidate for non-closure {:?}", obligation);
725 let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs);
726 let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
728 debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations");
732 if !self.tcx().sess.opts.unstable_opts.chalk {
733 nested.push(Obligation::new(
734 obligation.cause.clone(),
735 obligation.param_env,
736 ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind))
737 .to_predicate(self.tcx()),
741 Ok(ImplSourceClosureData { closure_def_id, substs, nested })
744 /// In the case of closure types and fn pointers,
745 /// we currently treat the input type parameters on the trait as
746 /// outputs. This means that when we have a match we have only
747 /// considered the self type, so we have to go back and make sure
748 /// to relate the argument types too. This is kind of wrong, but
749 /// since we control the full set of impls, also not that wrong,
750 /// and it DOES yield better error messages (since we don't report
751 /// errors as if there is no applicable impl, but rather report
752 /// errors are about mismatched argument types.
754 /// Here is an example. Imagine we have a closure expression
755 /// and we desugared it so that the type of the expression is
756 /// `Closure`, and `Closure` expects `i32` as argument. Then it
757 /// is "as if" the compiler generated this impl:
758 /// ```ignore (illustrative)
759 /// impl Fn(i32) for Closure { ... }
761 /// Now imagine our obligation is `Closure: Fn(usize)`. So far
762 /// we have matched the self type `Closure`. At this point we'll
763 /// compare the `i32` to `usize` and generate an error.
765 /// Note that this checking occurs *after* the impl has selected,
766 /// because these output type parameters should not affect the
767 /// selection of the impl. Therefore, if there is a mismatch, we
768 /// report an error to the user.
769 #[instrument(skip(self), level = "trace")]
770 fn confirm_poly_trait_refs(
772 obligation: &TraitObligation<'tcx>,
773 expected_trait_ref: ty::PolyTraitRef<'tcx>,
774 ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
775 let obligation_trait_ref = obligation.predicate.to_poly_trait_ref();
776 // Normalize the obligation and expected trait refs together, because why not
777 let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
778 ensure_sufficient_stack(|| {
779 normalize_with_depth(
781 obligation.param_env,
782 obligation.cause.clone(),
783 obligation.recursion_depth + 1,
784 (obligation_trait_ref, expected_trait_ref),
789 .at(&obligation.cause, obligation.param_env)
790 .sup(obligation_trait_ref, expected_trait_ref)
791 .map(|InferOk { mut obligations, .. }| {
792 obligations.extend(nested);
795 .map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
798 fn confirm_trait_upcasting_unsize_candidate(
800 obligation: &TraitObligation<'tcx>,
802 ) -> Result<ImplSourceTraitUpcastingData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
804 let tcx = self.tcx();
806 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
807 // regions here. See the comment there for more details.
808 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
809 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
810 let target = self.infcx.shallow_resolve(target);
812 debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate");
814 let mut nested = vec![];
815 let source_trait_ref;
816 let upcast_trait_ref;
817 match (source.kind(), target.kind()) {
818 // TraitA+Kx+'a -> TraitB+Ky+'b (trait upcasting coercion).
819 (&ty::Dynamic(ref data_a, r_a, repr_a), &ty::Dynamic(ref data_b, r_b, repr_b))
820 if repr_a == repr_b =>
822 // See `assemble_candidates_for_unsizing` for more info.
823 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
824 let principal_a = data_a.principal().unwrap();
825 source_trait_ref = principal_a.with_self_ty(tcx, source);
826 upcast_trait_ref = util::supertraits(tcx, source_trait_ref).nth(idx).unwrap();
827 assert_eq!(data_b.principal_def_id(), Some(upcast_trait_ref.def_id()));
828 let existential_predicate = upcast_trait_ref.map_bound(|trait_ref| {
829 ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::erase_self_ty(
833 let iter = Some(existential_predicate)
838 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
843 .map(ty::ExistentialPredicate::AutoTrait)
844 .map(ty::Binder::dummy),
846 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
847 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, repr_b);
849 // Require that the traits involved in this upcast are **equal**;
850 // only the **lifetime bound** is changed.
851 let InferOk { obligations, .. } = self
853 .at(&obligation.cause, obligation.param_env)
854 .sup(target, source_trait)
855 .map_err(|_| Unimplemented)?;
856 nested.extend(obligations);
858 // Register one obligation for 'a: 'b.
859 let cause = ObligationCause::new(
860 obligation.cause.span,
861 obligation.cause.body_id,
862 ObjectCastObligation(source, target),
864 let outlives = ty::OutlivesPredicate(r_a, r_b);
865 nested.push(Obligation::with_depth(
867 obligation.recursion_depth + 1,
868 obligation.param_env,
869 obligation.predicate.rebind(outlives).to_predicate(tcx),
875 let vtable_segment_callback = {
876 let mut vptr_offset = 0;
879 VtblSegment::MetadataDSA => {
880 vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
882 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
883 vptr_offset += util::count_own_vtable_entries(tcx, trait_ref);
884 if trait_ref == upcast_trait_ref {
886 return ControlFlow::Break(Some(vptr_offset));
888 return ControlFlow::Break(None);
897 ControlFlow::Continue(())
901 let vtable_vptr_slot =
902 super::super::prepare_vtable_segments(tcx, source_trait_ref, vtable_segment_callback)
905 Ok(ImplSourceTraitUpcastingData { upcast_trait_ref, vtable_vptr_slot, nested })
908 fn confirm_builtin_unsize_candidate(
910 obligation: &TraitObligation<'tcx>,
911 ) -> Result<ImplSourceBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
912 let tcx = self.tcx();
914 // `assemble_candidates_for_unsizing` should ensure there are no late-bound
915 // regions here. See the comment there for more details.
916 let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
917 let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
918 let target = self.infcx.shallow_resolve(target);
920 debug!(?source, ?target, "confirm_builtin_unsize_candidate");
922 let mut nested = vec![];
923 match (source.kind(), target.kind()) {
924 // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
925 (&ty::Dynamic(ref data_a, r_a, ty::Dyn), &ty::Dynamic(ref data_b, r_b, ty::Dyn)) => {
926 // See `assemble_candidates_for_unsizing` for more info.
927 // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
930 .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
935 .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
940 .map(ty::ExistentialPredicate::AutoTrait)
941 .map(ty::Binder::dummy),
943 let existential_predicates = tcx.mk_poly_existential_predicates(iter);
944 let source_trait = tcx.mk_dynamic(existential_predicates, r_b, ty::Dyn);
946 // Require that the traits involved in this upcast are **equal**;
947 // only the **lifetime bound** is changed.
948 let InferOk { obligations, .. } = self
950 .at(&obligation.cause, obligation.param_env)
951 .sup(target, source_trait)
952 .map_err(|_| Unimplemented)?;
953 nested.extend(obligations);
955 // Register one obligation for 'a: 'b.
956 let cause = ObligationCause::new(
957 obligation.cause.span,
958 obligation.cause.body_id,
959 ObjectCastObligation(source, target),
961 let outlives = ty::OutlivesPredicate(r_a, r_b);
962 nested.push(Obligation::with_depth(
964 obligation.recursion_depth + 1,
965 obligation.param_env,
966 obligation.predicate.rebind(outlives).to_predicate(tcx),
971 (_, &ty::Dynamic(ref data, r, ty::Dyn)) => {
972 let mut object_dids = data.auto_traits().chain(data.principal_def_id());
973 if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
974 return Err(TraitNotObjectSafe(did));
977 let cause = ObligationCause::new(
978 obligation.cause.span,
979 obligation.cause.body_id,
980 ObjectCastObligation(source, target),
983 let predicate_to_obligation = |predicate| {
984 Obligation::with_depth(
986 obligation.recursion_depth + 1,
987 obligation.param_env,
992 // Create obligations:
993 // - Casting `T` to `Trait`
994 // - For all the various builtin bounds attached to the object cast. (In other
995 // words, if the object type is `Foo + Send`, this would create an obligation for
996 // the `Send` check.)
997 // - Projection predicates
999 data.iter().map(|predicate| {
1000 predicate_to_obligation(predicate.with_self_ty(tcx, source))
1004 // We can only make objects from sized types.
1005 let tr = ty::Binder::dummy(ty::TraitRef::new(
1006 tcx.require_lang_item(LangItem::Sized, None),
1007 tcx.mk_substs_trait(source, &[]),
1009 nested.push(predicate_to_obligation(tr.without_const().to_predicate(tcx)));
1011 // If the type is `Foo + 'a`, ensure that the type
1012 // being cast to `Foo + 'a` outlives `'a`:
1013 let outlives = ty::OutlivesPredicate(source, r);
1014 nested.push(predicate_to_obligation(ty::Binder::dummy(outlives).to_predicate(tcx)));
1017 // `[T; n]` -> `[T]`
1018 (&ty::Array(a, _), &ty::Slice(b)) => {
1019 let InferOk { obligations, .. } = self
1021 .at(&obligation.cause, obligation.param_env)
1023 .map_err(|_| Unimplemented)?;
1024 nested.extend(obligations);
1027 // `Struct<T>` -> `Struct<U>`
1028 (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
1029 let maybe_unsizing_param_idx = |arg: GenericArg<'tcx>| match arg.unpack() {
1030 GenericArgKind::Type(ty) => match ty.kind() {
1031 ty::Param(p) => Some(p.index),
1035 // Lifetimes aren't allowed to change during unsizing.
1036 GenericArgKind::Lifetime(_) => None,
1038 GenericArgKind::Const(ct) => match ct.kind() {
1039 ty::ConstKind::Param(p) => Some(p.index),
1044 // FIXME(eddyb) cache this (including computing `unsizing_params`)
1045 // by putting it in a query; it would only need the `DefId` as it
1046 // looks at declared field types, not anything substituted.
1048 // The last field of the structure has to exist and contain type/const parameters.
1049 let (tail_field, prefix_fields) =
1050 def.non_enum_variant().fields.split_last().ok_or(Unimplemented)?;
1051 let tail_field_ty = tcx.bound_type_of(tail_field.did);
1053 let mut unsizing_params = GrowableBitSet::new_empty();
1054 for arg in tail_field_ty.0.walk() {
1055 if let Some(i) = maybe_unsizing_param_idx(arg) {
1056 unsizing_params.insert(i);
1060 // Ensure none of the other fields mention the parameters used
1062 for field in prefix_fields {
1063 for arg in tcx.type_of(field.did).walk() {
1064 if let Some(i) = maybe_unsizing_param_idx(arg) {
1065 unsizing_params.remove(i);
1070 if unsizing_params.is_empty() {
1071 return Err(Unimplemented);
1074 // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
1075 // normalizing in the process, since `type_of` returns something directly from
1076 // astconv (which means it's un-normalized).
1077 let source_tail = normalize_with_depth_to(
1079 obligation.param_env,
1080 obligation.cause.clone(),
1081 obligation.recursion_depth + 1,
1082 tail_field_ty.subst(tcx, substs_a),
1085 let target_tail = normalize_with_depth_to(
1087 obligation.param_env,
1088 obligation.cause.clone(),
1089 obligation.recursion_depth + 1,
1090 tail_field_ty.subst(tcx, substs_b),
1094 // Check that the source struct with the target's
1095 // unsizing parameters is equal to the target.
1096 let substs = tcx.mk_substs(substs_a.iter().enumerate().map(|(i, k)| {
1097 if unsizing_params.contains(i as u32) { substs_b[i] } else { k }
1099 let new_struct = tcx.mk_adt(def, substs);
1100 let InferOk { obligations, .. } = self
1102 .at(&obligation.cause, obligation.param_env)
1103 .eq(target, new_struct)
1104 .map_err(|_| Unimplemented)?;
1105 nested.extend(obligations);
1107 // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
1108 nested.push(predicate_for_trait_def(
1110 obligation.param_env,
1111 obligation.cause.clone(),
1112 obligation.predicate.def_id(),
1113 obligation.recursion_depth + 1,
1115 &[target_tail.into()],
1119 // `(.., T)` -> `(.., U)`
1120 (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
1121 assert_eq!(tys_a.len(), tys_b.len());
1123 // The last field of the tuple has to exist.
1124 let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
1125 let &b_last = tys_b.last().unwrap();
1127 // Check that the source tuple with the target's
1128 // last element is equal to the target.
1129 let new_tuple = tcx.mk_tup(a_mid.iter().copied().chain(iter::once(b_last)));
1130 let InferOk { obligations, .. } = self
1132 .at(&obligation.cause, obligation.param_env)
1133 .eq(target, new_tuple)
1134 .map_err(|_| Unimplemented)?;
1135 nested.extend(obligations);
1137 // Construct the nested `T: Unsize<U>` predicate.
1138 nested.push(ensure_sufficient_stack(|| {
1139 predicate_for_trait_def(
1141 obligation.param_env,
1142 obligation.cause.clone(),
1143 obligation.predicate.def_id(),
1144 obligation.recursion_depth + 1,
1154 Ok(ImplSourceBuiltinData { nested })
1157 fn confirm_const_destruct_candidate(
1159 obligation: &TraitObligation<'tcx>,
1160 impl_def_id: Option<DefId>,
1161 ) -> Result<ImplSourceConstDestructData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
1162 // `~const Destruct` in a non-const environment is always trivially true, since our type is `Drop`
1163 if !obligation.is_const() {
1164 return Ok(ImplSourceConstDestructData { nested: vec![] });
1167 let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);
1169 let tcx = self.tcx();
1170 let self_ty = self.infcx.shallow_resolve(obligation.self_ty());
1172 let mut nested = vec![];
1173 let cause = obligation.derived_cause(BuiltinDerivedObligation);
1175 // If we have a custom `impl const Drop`, then
1176 // first check it like a regular impl candidate.
1177 // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
1178 if let Some(impl_def_id) = impl_def_id {
1179 let mut new_obligation = obligation.clone();
1180 new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
1181 trait_pred.trait_ref.def_id = drop_trait;
1184 let substs = self.rematch_impl(impl_def_id, &new_obligation);
1185 debug!(?substs, "impl substs");
1187 let cause = obligation.derived_cause(|derived| {
1188 ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
1191 span: obligation.cause.span,
1194 let obligations = ensure_sufficient_stack(|| {
1199 new_obligation.recursion_depth + 1,
1200 new_obligation.param_env,
1201 obligation.predicate,
1204 nested.extend(obligations.nested);
1207 // We want to confirm the ADT's fields if we have an ADT
1208 let mut stack = match *self_ty.skip_binder().kind() {
1209 ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(),
1210 _ => vec![self_ty.skip_binder()],
1213 while let Some(nested_ty) = stack.pop() {
1214 match *nested_ty.kind() {
1215 // We know these types are trivially drop
1221 | ty::Infer(ty::IntVar(_))
1222 | ty::Infer(ty::FloatVar(_))
1229 | ty::Foreign(_) => {}
1231 // `ManuallyDrop` is trivially drop
1232 ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().manually_drop() => {}
1234 // These types are built-in, so we can fast-track by registering
1235 // nested predicates for their constituent type(s)
1236 ty::Array(ty, _) | ty::Slice(ty) => {
1240 stack.extend(tys.iter());
1242 ty::Closure(_, substs) => {
1243 stack.push(substs.as_closure().tupled_upvars_ty());
1245 ty::Generator(_, substs, _) => {
1246 let generator = substs.as_generator();
1247 stack.extend([generator.tupled_upvars_ty(), generator.witness()]);
1249 ty::GeneratorWitness(tys) => {
1250 stack.extend(tcx.erase_late_bound_regions(tys).to_vec());
1253 // If we have a projection type, make sure to normalize it so we replace it
1254 // with a fresh infer variable
1255 ty::Projection(..) => {
1256 let predicate = normalize_with_depth_to(
1258 obligation.param_env,
1260 obligation.recursion_depth + 1,
1262 .rebind(ty::TraitPredicate {
1263 trait_ref: ty::TraitRef {
1264 def_id: self.tcx().require_lang_item(LangItem::Destruct, None),
1265 substs: self.tcx().mk_substs_trait(nested_ty, &[]),
1267 constness: ty::BoundConstness::ConstIfConst,
1268 polarity: ty::ImplPolarity::Positive,
1274 nested.push(Obligation::with_depth(
1276 obligation.recursion_depth + 1,
1277 obligation.param_env,
1282 // If we have any other type (e.g. an ADT), just register a nested obligation
1283 // since it's either not `const Drop` (and we raise an error during selection),
1284 // or it's an ADT (and we need to check for a custom impl during selection)
1286 let predicate = self_ty
1287 .rebind(ty::TraitPredicate {
1288 trait_ref: ty::TraitRef {
1289 def_id: self.tcx().require_lang_item(LangItem::Destruct, None),
1290 substs: self.tcx().mk_substs_trait(nested_ty, &[]),
1292 constness: ty::BoundConstness::ConstIfConst,
1293 polarity: ty::ImplPolarity::Positive,
1297 nested.push(Obligation::with_depth(
1299 obligation.recursion_depth + 1,
1300 obligation.param_env,
1307 Ok(ImplSourceConstDestructData { nested })