]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/closure.rs
Auto merge of #28393 - arielb1:required-because-it-appears, r=nikomatsakis
[rust.git] / src / librustc_typeck / check / closure.rs
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.
4 //
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.
10
11 //! Code for type-checking closure expressions.
12
13 use super::{check_fn, Expectation, FnCtxt};
14
15 use astconv;
16 use middle::def_id::DefId;
17 use middle::subst;
18 use middle::ty::{self, ToPolyTraitRef, Ty};
19 use std::cmp;
20 use syntax::abi;
21 use rustc_front::hir;
22
23 pub fn check_expr_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
24                                    expr: &hir::Expr,
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={:?})",
30            expr,
31            expected);
32
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),
38         None => (None, None)
39     };
40     check_closure(fcx, expr, expected_kind, decl, body, expected_sig)
41 }
42
43 fn check_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
44                           expr: &hir::Expr,
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);
50
51     debug!("check_closure opt_kind={:?} expected_sig={:?}",
52            opt_kind,
53            expected_sig);
54
55     let mut fn_ty = astconv::ty_of_closure(fcx,
56                                            hir::Unsafety::Normal,
57                                            decl,
58                                            abi::RustCall,
59                                            expected_sig);
60
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);
66
67     debug!("check_closure: expr.id={:?} upvar_tys={:?}",
68            expr.id, upvar_tys);
69
70     let closure_type =
71         fcx.ccx.tcx.mk_closure(
72             expr_def_id,
73             fcx.ccx.tcx.mk_substs(fcx.inh.infcx.parameter_environment.free_substs.clone()),
74             upvar_tys);
75
76     fcx.write_ty(expr.id, closure_type);
77
78     let fn_sig = fcx.tcx().liberate_late_bound_regions(
79         fcx.tcx().region_maps.item_extent(body.id), &fn_ty.sig);
80
81     check_fn(fcx.ccx,
82              hir::Unsafety::Normal,
83              expr.id,
84              &fn_sig,
85              decl,
86              expr.id,
87              &*body,
88              fcx.inh);
89
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)];
93
94     debug!("closure for {:?} --> sig={:?} opt_kind={:?}",
95            expr_def_id,
96            fn_ty.sig,
97            opt_kind);
98
99     fcx.inh.tables.borrow_mut().closure_tys.insert(expr_def_id, fn_ty);
100     match opt_kind {
101         Some(kind) => { fcx.inh.tables.borrow_mut().closure_kinds.insert(expr_def_id, kind); }
102         None => { }
103     }
104 }
105
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>)
110 {
111     debug!("deduce_expectations_from_expected_type(expected_ty={:?})",
112            expected_ty);
113
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))
120                                  .next();
121             let kind = fcx.tcx().lang_items.fn_trait_kind(object_type.principal_def_id());
122             (sig, kind)
123         }
124         ty::TyInfer(ty::TyVar(vid)) => {
125             deduce_expectations_from_obligations(fcx, vid)
126         }
127         _ => {
128             (None, None)
129         }
130     }
131 }
132
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>)
137 {
138     let fulfillment_cx = fcx.inh.infcx.fulfillment_cx.borrow();
139     // Here `expected_ty` is known to be a type inference variable.
140
141     let expected_sig =
142         fulfillment_cx
143         .pending_obligations()
144         .iter()
145         .filter_map(|obligation| {
146             debug!("deduce_expectations_from_obligations: obligation.predicate={:?}",
147                    obligation.predicate);
148
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))
156                 }
157                 _ => {
158                     None
159                 }
160             }
161         })
162         .next();
163
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.
168     let expected_kind =
169         fulfillment_cx
170         .pending_obligations()
171         .iter()
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,
181             };
182             opt_trait_ref
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()))
185         })
186         .fold(None, pick_most_restrictive_closure_kind);
187
188     (expected_sig, expected_kind)
189 }
190
191 fn pick_most_restrictive_closure_kind(best: Option<ty::ClosureKind>,
192                                       cur: ty::ClosureKind)
193                                       -> Option<ty::ClosureKind>
194 {
195     match best {
196         None => Some(cur),
197         Some(best) => Some(cmp::min(best, cur))
198     }
199 }
200
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>>
207 {
208     let tcx = fcx.tcx();
209
210     debug!("deduce_sig_from_projection({:?})",
211            projection);
212
213     let trait_ref = projection.to_poly_trait_ref();
214
215     if tcx.lang_items.fn_trait_kind(trait_ref.def_id()).is_none() {
216         return None;
217     }
218
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);
222
223     let input_tys = match arg_param_ty.sty {
224         ty::TyTuple(ref tys) => { (*tys).clone() }
225         _ => { return None; }
226     };
227     debug!("deduce_sig_from_projection: input_tys {:?}", input_tys);
228
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);
232
233     let fn_sig = ty::FnSig {
234         inputs: input_tys,
235         output: ty::FnConverging(ret_param_ty),
236         variadic: false
237     };
238     debug!("deduce_sig_from_projection: fn_sig {:?}", fn_sig);
239
240     Some(fn_sig)
241 }
242
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>>
248 {
249     let self_ty = fcx.infcx().shallow_resolve(trait_ref.self_ty());
250     debug!("self_type_matches_expected_vid(trait_ref={:?}, self_ty={:?})",
251            trait_ref,
252            self_ty);
253     match self_ty.sty {
254         ty::TyInfer(ty::TyVar(v)) if expected_vid == v => Some(trait_ref),
255         _ => None,
256     }
257 }