]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/upvar.rs
Auto merge of #26876 - liigo:patch-3, r=Gankro
[rust.git] / src / librustc_typeck / check / upvar.rs
1 // Copyright 2012-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 //! ### Inferring borrow kinds for upvars
12 //!
13 //! Whenever there is a closure expression, we need to determine how each
14 //! upvar is used. We do this by initially assigning each upvar an
15 //! immutable "borrow kind" (see `ty::BorrowKind` for details) and then
16 //! "escalating" the kind as needed. The borrow kind proceeds according to
17 //! the following lattice:
18 //!
19 //!     ty::ImmBorrow -> ty::UniqueImmBorrow -> ty::MutBorrow
20 //!
21 //! So, for example, if we see an assignment `x = 5` to an upvar `x`, we
22 //! will promote its borrow kind to mutable borrow. If we see an `&mut x`
23 //! we'll do the same. Naturally, this applies not just to the upvar, but
24 //! to everything owned by `x`, so the result is the same for something
25 //! like `x.f = 5` and so on (presuming `x` is not a borrowed pointer to a
26 //! struct). These adjustments are performed in
27 //! `adjust_upvar_borrow_kind()` (you can trace backwards through the code
28 //! from there).
29 //!
30 //! The fact that we are inferring borrow kinds as we go results in a
31 //! semi-hacky interaction with mem-categorization. In particular,
32 //! mem-categorization will query the current borrow kind as it
33 //! categorizes, and we'll return the *current* value, but this may get
34 //! adjusted later. Therefore, in this module, we generally ignore the
35 //! borrow kind (and derived mutabilities) that are returned from
36 //! mem-categorization, since they may be inaccurate. (Another option
37 //! would be to use a unification scheme, where instead of returning a
38 //! concrete borrow kind like `ty::ImmBorrow`, we return a
39 //! `ty::InferBorrow(upvar_id)` or something like that, but this would
40 //! then mean that all later passes would have to check for these figments
41 //! and report an error, and it just seems like more mess in the end.)
42
43 use super::FnCtxt;
44
45 use check::demand;
46 use middle::expr_use_visitor as euv;
47 use middle::mem_categorization as mc;
48 use middle::ty::{self, Ty};
49 use middle::infer::{InferCtxt, UpvarRegion};
50 use std::collections::HashSet;
51 use syntax::ast;
52 use syntax::ast_util;
53 use syntax::codemap::Span;
54 use syntax::visit::{self, Visitor};
55
56 ///////////////////////////////////////////////////////////////////////////
57 // PUBLIC ENTRY POINTS
58
59 pub fn closure_analyze_fn(fcx: &FnCtxt,
60                           _id: ast::NodeId,
61                           _decl: &ast::FnDecl,
62                           body: &ast::Block)
63 {
64     let mut seed = SeedBorrowKind::new(fcx);
65     seed.visit_block(body);
66     let closures_with_inferred_kinds = seed.closures_with_inferred_kinds;
67
68     let mut adjust = AdjustBorrowKind::new(fcx, &closures_with_inferred_kinds);
69     adjust.visit_block(body);
70
71     // it's our job to process these.
72     assert!(fcx.inh.deferred_call_resolutions.borrow().is_empty());
73 }
74
75 ///////////////////////////////////////////////////////////////////////////
76 // SEED BORROW KIND
77
78 struct SeedBorrowKind<'a,'tcx:'a> {
79     fcx: &'a FnCtxt<'a,'tcx>,
80     closures_with_inferred_kinds: HashSet<ast::NodeId>,
81 }
82
83 impl<'a, 'tcx, 'v> Visitor<'v> for SeedBorrowKind<'a, 'tcx> {
84     fn visit_expr(&mut self, expr: &ast::Expr) {
85         match expr.node {
86             ast::ExprClosure(cc, _, ref body) => {
87                 self.check_closure(expr, cc, &**body);
88             }
89
90             _ => { }
91         }
92
93         visit::walk_expr(self, expr);
94     }
95
96     // Skip all items; they aren't in the same context.
97     fn visit_item(&mut self, _: &'v ast::Item) { }
98 }
99
100 impl<'a,'tcx> SeedBorrowKind<'a,'tcx> {
101     fn new(fcx: &'a FnCtxt<'a,'tcx>) -> SeedBorrowKind<'a,'tcx> {
102         SeedBorrowKind { fcx: fcx, closures_with_inferred_kinds: HashSet::new() }
103     }
104
105     fn tcx(&self) -> &'a ty::ctxt<'tcx> {
106         self.fcx.tcx()
107     }
108
109     fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
110         self.fcx.infcx()
111     }
112
113     fn check_closure(&mut self,
114                      expr: &ast::Expr,
115                      capture_clause: ast::CaptureClause,
116                      _body: &ast::Block)
117     {
118         let closure_def_id = ast_util::local_def(expr.id);
119         if !self.fcx.inh.tables.borrow().closure_kinds.contains_key(&closure_def_id) {
120             self.closures_with_inferred_kinds.insert(expr.id);
121             self.fcx.inh.tables.borrow_mut().closure_kinds
122                                             .insert(closure_def_id, ty::FnClosureKind);
123             debug!("check_closure: adding closure_id={:?} to closures_with_inferred_kinds",
124                    closure_def_id);
125         }
126
127         self.tcx().with_freevars(expr.id, |freevars| {
128             for freevar in freevars {
129                 let var_node_id = freevar.def.local_node_id();
130                 let upvar_id = ty::UpvarId { var_id: var_node_id,
131                                              closure_expr_id: expr.id };
132                 debug!("seed upvar_id {:?}", upvar_id);
133
134                 let capture_kind = match capture_clause {
135                     ast::CaptureByValue => {
136                         ty::UpvarCapture::ByValue
137                     }
138                     ast::CaptureByRef => {
139                         let origin = UpvarRegion(upvar_id, expr.span);
140                         let freevar_region = self.infcx().next_region_var(origin);
141                         let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
142                                                              region: freevar_region };
143                         ty::UpvarCapture::ByRef(upvar_borrow)
144                     }
145                 };
146
147                 self.fcx.inh.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
148             }
149         });
150     }
151 }
152
153 ///////////////////////////////////////////////////////////////////////////
154 // ADJUST BORROW KIND
155
156 struct AdjustBorrowKind<'a,'tcx:'a> {
157     fcx: &'a FnCtxt<'a,'tcx>,
158     closures_with_inferred_kinds: &'a HashSet<ast::NodeId>,
159 }
160
161 impl<'a,'tcx> AdjustBorrowKind<'a,'tcx> {
162     fn new(fcx: &'a FnCtxt<'a,'tcx>,
163            closures_with_inferred_kinds: &'a HashSet<ast::NodeId>)
164            -> AdjustBorrowKind<'a,'tcx> {
165         AdjustBorrowKind { fcx: fcx, closures_with_inferred_kinds: closures_with_inferred_kinds }
166     }
167
168     fn analyze_closure(&mut self,
169                        id: ast::NodeId,
170                        span: Span,
171                        decl: &ast::FnDecl,
172                        body: &ast::Block) {
173         /*!
174          * Analysis starting point.
175          */
176
177         debug!("analyze_closure(id={:?}, body.id={:?})", id, body.id);
178
179         {
180             let mut euv = euv::ExprUseVisitor::new(self, self.fcx.infcx());
181             euv.walk_fn(decl, body);
182         }
183
184         // Now that we've analyzed the closure, we know how each
185         // variable is borrowed, and we know what traits the closure
186         // implements (Fn vs FnMut etc). We now have some updates to do
187         // with that information.
188         //
189         // Note that no closure type C may have an upvar of type C
190         // (though it may reference itself via a trait object). This
191         // results from the desugaring of closures to a struct like
192         // `Foo<..., UV0...UVn>`. If one of those upvars referenced
193         // C, then the type would have infinite size (and the
194         // inference algorithm will reject it).
195
196         // Extract the type variables UV0...UVn.
197         let closure_substs = match self.fcx.node_ty(id).sty {
198             ty::TyClosure(_, ref substs) => substs,
199             ref t => {
200                 self.fcx.tcx().sess.span_bug(
201                     span,
202                     &format!("type of closure expr {:?} is not a closure {:?}",
203                              id, t));
204             }
205         };
206
207         // Equate the type variables with the actual types.
208         let final_upvar_tys = self.final_upvar_tys(id);
209         debug!("analyze_closure: id={:?} closure_substs={:?} final_upvar_tys={:?}",
210                id, closure_substs, final_upvar_tys);
211         for (&upvar_ty, final_upvar_ty) in closure_substs.upvar_tys.iter().zip(final_upvar_tys) {
212             demand::eqtype(self.fcx, span, final_upvar_ty, upvar_ty);
213         }
214
215         // Now we must process and remove any deferred resolutions,
216         // since we have a concrete closure kind.
217         let closure_def_id = ast_util::local_def(id);
218         if self.closures_with_inferred_kinds.contains(&id) {
219             let mut deferred_call_resolutions =
220                 self.fcx.remove_deferred_call_resolutions(closure_def_id);
221             for deferred_call_resolution in &mut deferred_call_resolutions {
222                 deferred_call_resolution.resolve(self.fcx);
223             }
224         }
225     }
226
227     // Returns a list of `ClosureUpvar`s for each upvar.
228     fn final_upvar_tys(&mut self, closure_id: ast::NodeId) -> Vec<Ty<'tcx>> {
229         // Presently an unboxed closure type cannot "escape" out of a
230         // function, so we will only encounter ones that originated in the
231         // local crate or were inlined into it along with some function.
232         // This may change if abstract return types of some sort are
233         // implemented.
234         let tcx = self.fcx.tcx();
235         tcx.with_freevars(closure_id, |freevars| {
236             freevars.iter()
237                     .map(|freevar| {
238                         let freevar_def_id = freevar.def.def_id();
239                         let freevar_ty = self.fcx.node_ty(freevar_def_id.node);
240                         let upvar_id = ty::UpvarId {
241                             var_id: freevar_def_id.node,
242                             closure_expr_id: closure_id
243                         };
244                         let capture = self.fcx.infcx().upvar_capture(upvar_id).unwrap();
245
246                         debug!("freevar_def_id={:?} freevar_ty={:?} capture={:?}",
247                                freevar_def_id, freevar_ty, capture);
248
249                         match capture {
250                             ty::UpvarCapture::ByValue => freevar_ty,
251                             ty::UpvarCapture::ByRef(borrow) =>
252                                 tcx.mk_ref(tcx.mk_region(borrow.region),
253                                            ty::TypeAndMut {
254                                                ty: freevar_ty,
255                                                mutbl: borrow.kind.to_mutbl_lossy(),
256                                            }),
257                         }
258                     })
259                     .collect()
260             })
261     }
262
263     fn adjust_upvar_borrow_kind_for_consume(&self,
264                                             cmt: mc::cmt<'tcx>,
265                                             mode: euv::ConsumeMode)
266     {
267         debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
268                cmt, mode);
269
270         // we only care about moves
271         match mode {
272             euv::Copy => { return; }
273             euv::Move(_) => { }
274         }
275
276         // watch out for a move of the deref of a borrowed pointer;
277         // for that to be legal, the upvar would have to be borrowed
278         // by value instead
279         let guarantor = cmt.guarantor();
280         debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
281                guarantor);
282         match guarantor.cat {
283             mc::cat_deref(_, _, mc::BorrowedPtr(..)) |
284             mc::cat_deref(_, _, mc::Implicit(..)) => {
285                 match cmt.note {
286                     mc::NoteUpvarRef(upvar_id) => {
287                         debug!("adjust_upvar_borrow_kind_for_consume: \
288                                 setting upvar_id={:?} to by value",
289                                upvar_id);
290
291                         // to move out of an upvar, this must be a FnOnce closure
292                         self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
293
294                         let upvar_capture_map =
295                             &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
296                         upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
297                     }
298                     mc::NoteClosureEnv(upvar_id) => {
299                         // we get just a closureenv ref if this is a
300                         // `move` closure, or if the upvar has already
301                         // been inferred to by-value. In any case, we
302                         // must still adjust the kind of the closure
303                         // to be a FnOnce closure to permit moves out
304                         // of the environment.
305                         self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
306                     }
307                     mc::NoteNone => {
308                     }
309                 }
310             }
311             _ => { }
312         }
313     }
314
315     /// Indicates that `cmt` is being directly mutated (e.g., assigned
316     /// to). If cmt contains any by-ref upvars, this implies that
317     /// those upvars must be borrowed using an `&mut` borrow.
318     fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
319         debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
320                cmt);
321
322         match cmt.cat.clone() {
323             mc::cat_deref(base, _, mc::Unique) |
324             mc::cat_interior(base, _) |
325             mc::cat_downcast(base, _) => {
326                 // Interior or owned data is mutable if base is
327                 // mutable, so iterate to the base.
328                 self.adjust_upvar_borrow_kind_for_mut(base);
329             }
330
331             mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
332             mc::cat_deref(base, _, mc::Implicit(..)) => {
333                 if !self.try_adjust_upvar_deref(&cmt.note, ty::MutBorrow) {
334                     // assignment to deref of an `&mut`
335                     // borrowed pointer implies that the
336                     // pointer itself must be unique, but not
337                     // necessarily *mutable*
338                     self.adjust_upvar_borrow_kind_for_unique(base);
339                 }
340             }
341
342             mc::cat_deref(_, _, mc::UnsafePtr(..)) |
343             mc::cat_static_item |
344             mc::cat_rvalue(_) |
345             mc::cat_local(_) |
346             mc::cat_upvar(..) => {
347                 return;
348             }
349         }
350     }
351
352     fn adjust_upvar_borrow_kind_for_unique(&self, cmt: mc::cmt<'tcx>) {
353         debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
354                cmt);
355
356         match cmt.cat.clone() {
357             mc::cat_deref(base, _, mc::Unique) |
358             mc::cat_interior(base, _) |
359             mc::cat_downcast(base, _) => {
360                 // Interior or owned data is unique if base is
361                 // unique.
362                 self.adjust_upvar_borrow_kind_for_unique(base);
363             }
364
365             mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
366             mc::cat_deref(base, _, mc::Implicit(..)) => {
367                 if !self.try_adjust_upvar_deref(&cmt.note, ty::UniqueImmBorrow) {
368                     // for a borrowed pointer to be unique, its
369                     // base must be unique
370                     self.adjust_upvar_borrow_kind_for_unique(base);
371                 }
372             }
373
374             mc::cat_deref(_, _, mc::UnsafePtr(..)) |
375             mc::cat_static_item |
376             mc::cat_rvalue(_) |
377             mc::cat_local(_) |
378             mc::cat_upvar(..) => {
379             }
380         }
381     }
382
383     fn try_adjust_upvar_deref(&self,
384                               note: &mc::Note,
385                               borrow_kind: ty::BorrowKind)
386                               -> bool
387     {
388         assert!(match borrow_kind {
389             ty::MutBorrow => true,
390             ty::UniqueImmBorrow => true,
391
392             // imm borrows never require adjusting any kinds, so we don't wind up here
393             ty::ImmBorrow => false,
394         });
395
396         match *note {
397             mc::NoteUpvarRef(upvar_id) => {
398                 // if this is an implicit deref of an
399                 // upvar, then we need to modify the
400                 // borrow_kind of the upvar to make sure it
401                 // is inferred to mutable if necessary
402                 {
403                     let upvar_capture_map = &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
404                     let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
405                     self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
406                 }
407
408                 // also need to be in an FnMut closure since this is not an ImmBorrow
409                 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
410
411                 true
412             }
413             mc::NoteClosureEnv(upvar_id) => {
414                 // this kind of deref occurs in a `move` closure, or
415                 // for a by-value upvar; in either case, to mutate an
416                 // upvar, we need to be an FnMut closure
417                 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
418
419                 true
420             }
421             mc::NoteNone => {
422                 false
423             }
424         }
425     }
426
427     /// We infer the borrow_kind with which to borrow upvars in a stack closure. The borrow_kind
428     /// basically follows a lattice of `imm < unique-imm < mut`, moving from left to right as needed
429     /// (but never right to left). Here the argument `mutbl` is the borrow_kind that is required by
430     /// some particular use.
431     fn adjust_upvar_borrow_kind(&self,
432                                 upvar_id: ty::UpvarId,
433                                 upvar_capture: &mut ty::UpvarCapture,
434                                 kind: ty::BorrowKind) {
435         debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
436                upvar_id, upvar_capture, kind);
437
438         match *upvar_capture {
439             ty::UpvarCapture::ByValue => {
440                 // Upvar is already by-value, the strongest criteria.
441             }
442             ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
443                 match (upvar_borrow.kind, kind) {
444                     // Take RHS:
445                     (ty::ImmBorrow, ty::UniqueImmBorrow) |
446                     (ty::ImmBorrow, ty::MutBorrow) |
447                     (ty::UniqueImmBorrow, ty::MutBorrow) => {
448                         upvar_borrow.kind = kind;
449                     }
450                     // Take LHS:
451                     (ty::ImmBorrow, ty::ImmBorrow) |
452                     (ty::UniqueImmBorrow, ty::ImmBorrow) |
453                     (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
454                     (ty::MutBorrow, _) => {
455                     }
456                 }
457             }
458         }
459     }
460
461     fn adjust_closure_kind(&self,
462                            closure_id: ast::NodeId,
463                            new_kind: ty::ClosureKind) {
464         debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
465                closure_id, new_kind);
466
467         if !self.closures_with_inferred_kinds.contains(&closure_id) {
468             return;
469         }
470
471         let closure_def_id = ast_util::local_def(closure_id);
472         let closure_kinds = &mut self.fcx.inh.tables.borrow_mut().closure_kinds;
473         let existing_kind = *closure_kinds.get(&closure_def_id).unwrap();
474
475         debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
476                closure_id, existing_kind, new_kind);
477
478         match (existing_kind, new_kind) {
479             (ty::FnClosureKind, ty::FnClosureKind) |
480             (ty::FnMutClosureKind, ty::FnClosureKind) |
481             (ty::FnMutClosureKind, ty::FnMutClosureKind) |
482             (ty::FnOnceClosureKind, _) => {
483                 // no change needed
484             }
485
486             (ty::FnClosureKind, ty::FnMutClosureKind) |
487             (ty::FnClosureKind, ty::FnOnceClosureKind) |
488             (ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
489                 // new kind is stronger than the old kind
490                 closure_kinds.insert(closure_def_id, new_kind);
491             }
492         }
493     }
494 }
495
496 impl<'a, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'tcx> {
497     fn visit_fn(&mut self,
498                 fn_kind: visit::FnKind<'v>,
499                 decl: &'v ast::FnDecl,
500                 body: &'v ast::Block,
501                 span: Span,
502                 id: ast::NodeId)
503     {
504         visit::walk_fn(self, fn_kind, decl, body, span);
505         self.analyze_closure(id, span, decl, body);
506     }
507
508     // Skip all items; they aren't in the same context.
509     fn visit_item(&mut self, _: &'v ast::Item) { }
510 }
511
512 impl<'a,'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a,'tcx> {
513     fn consume(&mut self,
514                _consume_id: ast::NodeId,
515                _consume_span: Span,
516                cmt: mc::cmt<'tcx>,
517                mode: euv::ConsumeMode)
518     {
519         debug!("consume(cmt={:?},mode={:?})", cmt, mode);
520         self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
521     }
522
523     fn matched_pat(&mut self,
524                    _matched_pat: &ast::Pat,
525                    _cmt: mc::cmt<'tcx>,
526                    _mode: euv::MatchMode)
527     {}
528
529     fn consume_pat(&mut self,
530                    _consume_pat: &ast::Pat,
531                    cmt: mc::cmt<'tcx>,
532                    mode: euv::ConsumeMode)
533     {
534         debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
535         self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
536     }
537
538     fn borrow(&mut self,
539               borrow_id: ast::NodeId,
540               _borrow_span: Span,
541               cmt: mc::cmt<'tcx>,
542               _loan_region: ty::Region,
543               bk: ty::BorrowKind,
544               _loan_cause: euv::LoanCause)
545     {
546         debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
547                borrow_id, cmt, bk);
548
549         match bk {
550             ty::ImmBorrow => { }
551             ty::UniqueImmBorrow => {
552                 self.adjust_upvar_borrow_kind_for_unique(cmt);
553             }
554             ty::MutBorrow => {
555                 self.adjust_upvar_borrow_kind_for_mut(cmt);
556             }
557         }
558     }
559
560     fn decl_without_init(&mut self,
561                          _id: ast::NodeId,
562                          _span: Span)
563     {}
564
565     fn mutate(&mut self,
566               _assignment_id: ast::NodeId,
567               _assignment_span: Span,
568               assignee_cmt: mc::cmt<'tcx>,
569               _mode: euv::MutateMode)
570     {
571         debug!("mutate(assignee_cmt={:?})",
572                assignee_cmt);
573
574         self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);
575     }
576 }