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 // This function handles both closures and generators.
16 pub(super) fn deduce_closure_type_from_expectations(
21 expectation: &Expectation,
23 let expected_ty = match expectation.to_option(&mut self.table) {
28 // Deduction from where-clauses in scope, as well as fn-pointer coercion are handled here.
29 let _ = self.coerce(Some(closure_expr), closure_ty, &expected_ty);
31 // Generators are not Fn* so return early.
32 if matches!(closure_ty.kind(Interner), TyKind::Generator(..)) {
36 // Deduction based on the expected `dyn Fn` is done separately.
37 if let TyKind::Dyn(dyn_ty) = expected_ty.kind(Interner) {
38 if let Some(sig) = self.deduce_sig_from_dyn_ty(dyn_ty) {
39 let expected_sig_ty = TyKind::Function(sig).intern(Interner);
41 self.unify(sig_ty, &expected_sig_ty);
46 fn deduce_sig_from_dyn_ty(&self, dyn_ty: &DynTy) -> Option<FnPointer> {
47 // Search for a predicate like `<$self as FnX<Args>>::Output == Ret`
49 let fn_traits: SmallVec<[ChalkTraitId; 3]> =
50 utils::fn_traits(self.db.upcast(), self.owner.module(self.db.upcast()).krate())
51 .map(to_chalk_trait_id)
54 let self_ty = TyKind::Error.intern(Interner);
55 let bounds = dyn_ty.bounds.clone().substitute(Interner, &[self_ty.cast(Interner)]);
56 for bound in bounds.iter(Interner) {
57 // NOTE(skip_binders): the extracted types are rebound by the returned `FnPointer`
58 if let WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection), ty }) =
61 let assoc_data = self.db.associated_ty_data(projection.associated_ty_id);
62 if !fn_traits.contains(&assoc_data.trait_id) {
66 // Skip `Self`, get the type argument.
67 let arg = projection.substitution.as_slice(Interner).get(1)?;
68 if let Some(subst) = arg.ty(Interner)?.as_tuple() {
69 let generic_args = subst.as_slice(Interner);
70 let mut sig_tys = Vec::new();
71 for arg in generic_args {
72 sig_tys.push(arg.ty(Interner)?.clone());
74 sig_tys.push(ty.clone());
76 cov_mark::hit!(dyn_fn_param_informs_call_site_closure_signature);
77 return Some(FnPointer {
78 num_binders: bound.len(Interner),
79 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
80 substitution: FnSubst(Substitution::from_iter(Interner, sig_tys)),