1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Code for type-checking closure expressions.
13 use super::{check_fn, Expectation, FnCtxt};
16 use middle::def_id::DefId;
18 use middle::ty::{self, ToPolyTraitRef, Ty};
23 pub fn check_expr_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
25 _capture: hir::CaptureClause,
26 decl: &'tcx hir::FnDecl,
27 body: &'tcx hir::Block,
28 expected: Expectation<'tcx>) {
29 debug!("check_expr_closure(expr={:?},expected={:?})",
33 // It's always helpful for inference if we know the kind of
34 // closure sooner rather than later, so first examine the expected
35 // type, and see if can glean a closure kind from there.
36 let (expected_sig,expected_kind) = match expected.to_option(fcx) {
37 Some(ty) => deduce_expectations_from_expected_type(fcx, ty),
40 check_closure(fcx, expr, expected_kind, decl, body, expected_sig)
43 fn check_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
45 opt_kind: Option<ty::ClosureKind>,
46 decl: &'tcx hir::FnDecl,
47 body: &'tcx hir::Block,
48 expected_sig: Option<ty::FnSig<'tcx>>) {
49 let expr_def_id = DefId::local(expr.id);
51 debug!("check_closure opt_kind={:?} expected_sig={:?}",
55 let mut fn_ty = astconv::ty_of_closure(fcx,
56 hir::Unsafety::Normal,
61 // Create type variables (for now) to represent the transformed
62 // types of upvars. These will be unified during the upvar
63 // inference phase (`upvar.rs`).
64 let num_upvars = fcx.tcx().with_freevars(expr.id, |fv| fv.len());
65 let upvar_tys = fcx.infcx().next_ty_vars(num_upvars);
67 debug!("check_closure: expr.id={:?} upvar_tys={:?}",
71 fcx.ccx.tcx.mk_closure(
73 fcx.ccx.tcx.mk_substs(fcx.inh.infcx.parameter_environment.free_substs.clone()),
76 fcx.write_ty(expr.id, closure_type);
78 let fn_sig = fcx.tcx().liberate_late_bound_regions(
79 fcx.tcx().region_maps.item_extent(body.id), &fn_ty.sig);
82 hir::Unsafety::Normal,
90 // Tuple up the arguments and insert the resulting function type into
91 // the `closures` table.
92 fn_ty.sig.0.inputs = vec![fcx.tcx().mk_tup(fn_ty.sig.0.inputs)];
94 debug!("closure for {:?} --> sig={:?} opt_kind={:?}",
99 fcx.inh.tables.borrow_mut().closure_tys.insert(expr_def_id, fn_ty);
101 Some(kind) => { fcx.inh.tables.borrow_mut().closure_kinds.insert(expr_def_id, kind); }
106 fn deduce_expectations_from_expected_type<'a,'tcx>(
107 fcx: &FnCtxt<'a,'tcx>,
108 expected_ty: Ty<'tcx>)
109 -> (Option<ty::FnSig<'tcx>>,Option<ty::ClosureKind>)
111 debug!("deduce_expectations_from_expected_type(expected_ty={:?})",
114 match expected_ty.sty {
115 ty::TyTrait(ref object_type) => {
116 let proj_bounds = object_type.projection_bounds_with_self_ty(fcx.tcx(),
117 fcx.tcx().types.err);
118 let sig = proj_bounds.iter()
119 .filter_map(|pb| deduce_sig_from_projection(fcx, pb))
121 let kind = fcx.tcx().lang_items.fn_trait_kind(object_type.principal_def_id());
124 ty::TyInfer(ty::TyVar(vid)) => {
125 deduce_expectations_from_obligations(fcx, vid)
133 fn deduce_expectations_from_obligations<'a,'tcx>(
134 fcx: &FnCtxt<'a,'tcx>,
135 expected_vid: ty::TyVid)
136 -> (Option<ty::FnSig<'tcx>>, Option<ty::ClosureKind>)
138 let fulfillment_cx = fcx.inh.infcx.fulfillment_cx.borrow();
139 // Here `expected_ty` is known to be a type inference variable.
143 .pending_obligations()
145 .filter_map(|obligation| {
146 debug!("deduce_expectations_from_obligations: obligation.predicate={:?}",
147 obligation.predicate);
149 match obligation.predicate {
150 // Given a Projection predicate, we can potentially infer
151 // the complete signature.
152 ty::Predicate::Projection(ref proj_predicate) => {
153 let trait_ref = proj_predicate.to_poly_trait_ref();
154 self_type_matches_expected_vid(fcx, trait_ref, expected_vid)
155 .and_then(|_| deduce_sig_from_projection(fcx, proj_predicate))
164 // Even if we can't infer the full signature, we may be able to
165 // infer the kind. This can occur if there is a trait-reference
166 // like `F : Fn<A>`. Note that due to subtyping we could encounter
167 // many viable options, so pick the most restrictive.
170 .pending_obligations()
172 .filter_map(|obligation| {
173 let opt_trait_ref = match obligation.predicate {
174 ty::Predicate::Projection(ref data) => Some(data.to_poly_trait_ref()),
175 ty::Predicate::Trait(ref data) => Some(data.to_poly_trait_ref()),
176 ty::Predicate::Equate(..) => None,
177 ty::Predicate::RegionOutlives(..) => None,
178 ty::Predicate::TypeOutlives(..) => None,
179 ty::Predicate::WellFormed(..) => None,
180 ty::Predicate::ObjectSafe(..) => None,
183 .and_then(|trait_ref| self_type_matches_expected_vid(fcx, trait_ref, expected_vid))
184 .and_then(|trait_ref| fcx.tcx().lang_items.fn_trait_kind(trait_ref.def_id()))
186 .fold(None, pick_most_restrictive_closure_kind);
188 (expected_sig, expected_kind)
191 fn pick_most_restrictive_closure_kind(best: Option<ty::ClosureKind>,
192 cur: ty::ClosureKind)
193 -> Option<ty::ClosureKind>
197 Some(best) => Some(cmp::min(best, cur))
201 /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
202 /// everything we need to know about a closure.
203 fn deduce_sig_from_projection<'a,'tcx>(
204 fcx: &FnCtxt<'a,'tcx>,
205 projection: &ty::PolyProjectionPredicate<'tcx>)
206 -> Option<ty::FnSig<'tcx>>
210 debug!("deduce_sig_from_projection({:?})",
213 let trait_ref = projection.to_poly_trait_ref();
215 if tcx.lang_items.fn_trait_kind(trait_ref.def_id()).is_none() {
219 let arg_param_ty = *trait_ref.substs().types.get(subst::TypeSpace, 0);
220 let arg_param_ty = fcx.infcx().resolve_type_vars_if_possible(&arg_param_ty);
221 debug!("deduce_sig_from_projection: arg_param_ty {:?}", arg_param_ty);
223 let input_tys = match arg_param_ty.sty {
224 ty::TyTuple(ref tys) => { (*tys).clone() }
225 _ => { return None; }
227 debug!("deduce_sig_from_projection: input_tys {:?}", input_tys);
229 let ret_param_ty = projection.0.ty;
230 let ret_param_ty = fcx.infcx().resolve_type_vars_if_possible(&ret_param_ty);
231 debug!("deduce_sig_from_projection: ret_param_ty {:?}", ret_param_ty);
233 let fn_sig = ty::FnSig {
235 output: ty::FnConverging(ret_param_ty),
238 debug!("deduce_sig_from_projection: fn_sig {:?}", fn_sig);
243 fn self_type_matches_expected_vid<'a,'tcx>(
244 fcx: &FnCtxt<'a,'tcx>,
245 trait_ref: ty::PolyTraitRef<'tcx>,
246 expected_vid: ty::TyVid)
247 -> Option<ty::PolyTraitRef<'tcx>>
249 let self_ty = fcx.infcx().shallow_resolve(trait_ref.self_ty());
250 debug!("self_type_matches_expected_vid(trait_ref={:?}, self_ty={:?})",
254 ty::TyInfer(ty::TyVar(v)) if expected_vid == v => Some(trait_ref),