1 //! Inference of closure parameter types based on the closure's expected type.
3 use chalk_ir::{cast::Cast, AliasEq, AliasTy, FnSubst, WhereClause};
4 use hir_def::{expr::ExprId, HasModule};
5 use smallvec::SmallVec;
8 to_chalk_trait_id, utils, ChalkTraitId, DynTy, FnPointer, FnSig, Interner, Substitution, Ty,
12 use super::{Expectation, InferenceContext};
14 impl InferenceContext<'_> {
15 pub(super) fn deduce_closure_type_from_expectations(
20 expectation: &Expectation,
22 let expected_ty = match expectation.to_option(&mut self.table) {
27 // Deduction from where-clauses in scope, as well as fn-pointer coercion are handled here.
28 let _ = self.coerce(Some(closure_expr), closure_ty, &expected_ty);
30 // Deduction based on the expected `dyn Fn` is done separately.
31 if let TyKind::Dyn(dyn_ty) = expected_ty.kind(Interner) {
32 if let Some(sig) = self.deduce_sig_from_dyn_ty(dyn_ty) {
33 let expected_sig_ty = TyKind::Function(sig).intern(Interner);
35 self.unify(sig_ty, &expected_sig_ty);
40 fn deduce_sig_from_dyn_ty(&self, dyn_ty: &DynTy) -> Option<FnPointer> {
41 // Search for a predicate like `<$self as FnX<Args>>::Output == Ret`
43 let fn_traits: SmallVec<[ChalkTraitId; 3]> =
44 utils::fn_traits(self.db.upcast(), self.owner.module(self.db.upcast()).krate())
45 .map(to_chalk_trait_id)
48 let self_ty = TyKind::Error.intern(Interner);
49 let bounds = dyn_ty.bounds.clone().substitute(Interner, &[self_ty.cast(Interner)]);
50 for bound in bounds.iter(Interner) {
51 // NOTE(skip_binders): the extracted types are rebound by the returned `FnPointer`
52 if let WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection), ty }) =
55 let assoc_data = self.db.associated_ty_data(projection.associated_ty_id);
56 if !fn_traits.contains(&assoc_data.trait_id) {
60 // Skip `Self`, get the type argument.
61 let arg = projection.substitution.as_slice(Interner).get(1)?;
62 if let Some(subst) = arg.ty(Interner)?.as_tuple() {
63 let generic_args = subst.as_slice(Interner);
64 let mut sig_tys = Vec::new();
65 for arg in generic_args {
66 sig_tys.push(arg.ty(Interner)?.clone());
68 sig_tys.push(ty.clone());
70 cov_mark::hit!(dyn_fn_param_informs_call_site_closure_signature);
71 return Some(FnPointer {
72 num_binders: bound.len(Interner),
73 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
74 substitution: FnSubst(Substitution::from_iter(Interner, sig_tys)),