]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/upvar.rs
Rollup merge of #26834 - tshepang:space, r=brson
[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 middle::expr_use_visitor as euv;
46 use middle::mem_categorization as mc;
47 use middle::ty::{self};
48 use middle::infer::{InferCtxt, UpvarRegion};
49 use std::collections::HashSet;
50 use syntax::ast;
51 use syntax::ast_util;
52 use syntax::codemap::Span;
53 use syntax::visit::{self, Visitor};
54
55 ///////////////////////////////////////////////////////////////////////////
56 // PUBLIC ENTRY POINTS
57
58 pub fn closure_analyze_fn(fcx: &FnCtxt,
59                           _id: ast::NodeId,
60                           _decl: &ast::FnDecl,
61                           body: &ast::Block)
62 {
63     let mut seed = SeedBorrowKind::new(fcx);
64     seed.visit_block(body);
65     let closures_with_inferred_kinds = seed.closures_with_inferred_kinds;
66
67     let mut adjust = AdjustBorrowKind::new(fcx, &closures_with_inferred_kinds);
68     adjust.visit_block(body);
69
70     // it's our job to process these.
71     assert!(fcx.inh.deferred_call_resolutions.borrow().is_empty());
72 }
73
74 ///////////////////////////////////////////////////////////////////////////
75 // SEED BORROW KIND
76
77 struct SeedBorrowKind<'a,'tcx:'a> {
78     fcx: &'a FnCtxt<'a,'tcx>,
79     closures_with_inferred_kinds: HashSet<ast::NodeId>,
80 }
81
82 impl<'a, 'tcx, 'v> Visitor<'v> for SeedBorrowKind<'a, 'tcx> {
83     fn visit_expr(&mut self, expr: &ast::Expr) {
84         match expr.node {
85             ast::ExprClosure(cc, _, ref body) => {
86                 self.check_closure(expr, cc, &**body);
87             }
88
89             _ => { }
90         }
91
92         visit::walk_expr(self, expr);
93     }
94
95     fn visit_fn(&mut self,
96                 fn_kind: visit::FnKind<'v>,
97                 decl: &'v ast::FnDecl,
98                 block: &'v ast::Block,
99                 span: Span,
100                 _id: ast::NodeId)
101     {
102         match fn_kind {
103             visit::FkItemFn(..) | visit::FkMethod(..) => {
104                 // ignore nested fn items
105             }
106             visit::FkFnBlock => {
107                 visit::walk_fn(self, fn_kind, decl, block, span);
108             }
109         }
110     }
111 }
112
113 impl<'a,'tcx> SeedBorrowKind<'a,'tcx> {
114     fn new(fcx: &'a FnCtxt<'a,'tcx>) -> SeedBorrowKind<'a,'tcx> {
115         SeedBorrowKind { fcx: fcx, closures_with_inferred_kinds: HashSet::new() }
116     }
117
118     fn tcx(&self) -> &'a ty::ctxt<'tcx> {
119         self.fcx.tcx()
120     }
121
122     fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
123         self.fcx.infcx()
124     }
125
126     fn check_closure(&mut self,
127                      expr: &ast::Expr,
128                      capture_clause: ast::CaptureClause,
129                      _body: &ast::Block)
130     {
131         let closure_def_id = ast_util::local_def(expr.id);
132         if !self.fcx.inh.tables.borrow().closure_kinds.contains_key(&closure_def_id) {
133             self.closures_with_inferred_kinds.insert(expr.id);
134             self.fcx.inh.tables.borrow_mut().closure_kinds
135                                             .insert(closure_def_id, ty::FnClosureKind);
136             debug!("check_closure: adding closure_id={:?} to closures_with_inferred_kinds",
137                    closure_def_id);
138         }
139
140         self.tcx().with_freevars(expr.id, |freevars| {
141             for freevar in freevars {
142                 let var_node_id = freevar.def.local_node_id();
143                 let upvar_id = ty::UpvarId { var_id: var_node_id,
144                                              closure_expr_id: expr.id };
145                 debug!("seed upvar_id {:?}", upvar_id);
146
147                 let capture_kind = match capture_clause {
148                     ast::CaptureByValue => {
149                         ty::UpvarCapture::ByValue
150                     }
151                     ast::CaptureByRef => {
152                         let origin = UpvarRegion(upvar_id, expr.span);
153                         let freevar_region = self.infcx().next_region_var(origin);
154                         let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow,
155                                                              region: freevar_region };
156                         ty::UpvarCapture::ByRef(upvar_borrow)
157                     }
158                 };
159
160                 self.fcx.inh.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind);
161             }
162         });
163     }
164 }
165
166 ///////////////////////////////////////////////////////////////////////////
167 // ADJUST BORROW KIND
168
169 struct AdjustBorrowKind<'a,'tcx:'a> {
170     fcx: &'a FnCtxt<'a,'tcx>,
171     closures_with_inferred_kinds: &'a HashSet<ast::NodeId>,
172 }
173
174 impl<'a,'tcx> AdjustBorrowKind<'a,'tcx> {
175     fn new(fcx: &'a FnCtxt<'a,'tcx>,
176            closures_with_inferred_kinds: &'a HashSet<ast::NodeId>)
177            -> AdjustBorrowKind<'a,'tcx> {
178         AdjustBorrowKind { fcx: fcx, closures_with_inferred_kinds: closures_with_inferred_kinds }
179     }
180
181     fn analyze_closure(&mut self, id: ast::NodeId, decl: &ast::FnDecl, body: &ast::Block) {
182         /*!
183          * Analysis starting point.
184          */
185
186         self.visit_block(body);
187
188         debug!("analyzing closure `{}` with fn body id `{}`", id, body.id);
189
190         let mut euv = euv::ExprUseVisitor::new(self, self.fcx.infcx());
191         euv.walk_fn(decl, body);
192
193         // If we had not yet settled on a closure kind for this closure,
194         // then we should have by now. Process and remove any deferred resolutions.
195         //
196         // Interesting fact: all calls to this closure must come
197         // *after* its definition.  Initially, I thought that some
198         // kind of fixed-point iteration would be required, due to the
199         // possibility of twisted examples like this one:
200         //
201         // ```rust
202         // let mut closure0 = None;
203         // let vec = vec!(1, 2, 3);
204         //
205         // loop {
206         //     {
207         //         let closure1 = || {
208         //             match closure0.take() {
209         //                 Some(c) => {
210         //                     return c(); // (*) call to `closure0` before it is defined
211         //                 }
212         //                 None => { }
213         //             }
214         //         };
215         //         closure1();
216         //     }
217         //
218         //     closure0 = || vec;
219         // }
220         // ```
221         //
222         // However, this turns out to be wrong. Examples like this
223         // fail to compile because the type of the variable `c` above
224         // is an inference variable.  And in fact since closure types
225         // cannot be written, there is no way to make this example
226         // work without a boxed closure. This implies that we can't
227         // have two closures that recursively call one another without
228         // some form of boxing (and hence explicit writing of a
229         // closure kind) involved. Huzzah. -nmatsakis
230         let closure_def_id = ast_util::local_def(id);
231         if self.closures_with_inferred_kinds.contains(&id) {
232             let mut deferred_call_resolutions =
233                 self.fcx.remove_deferred_call_resolutions(closure_def_id);
234             for deferred_call_resolution in &mut deferred_call_resolutions {
235                 deferred_call_resolution.resolve(self.fcx);
236             }
237         }
238     }
239
240     fn adjust_upvar_borrow_kind_for_consume(&self,
241                                             cmt: mc::cmt<'tcx>,
242                                             mode: euv::ConsumeMode)
243     {
244         debug!("adjust_upvar_borrow_kind_for_consume(cmt={:?}, mode={:?})",
245                cmt, mode);
246
247         // we only care about moves
248         match mode {
249             euv::Copy => { return; }
250             euv::Move(_) => { }
251         }
252
253         // watch out for a move of the deref of a borrowed pointer;
254         // for that to be legal, the upvar would have to be borrowed
255         // by value instead
256         let guarantor = cmt.guarantor();
257         debug!("adjust_upvar_borrow_kind_for_consume: guarantor={:?}",
258                guarantor);
259         match guarantor.cat {
260             mc::cat_deref(_, _, mc::BorrowedPtr(..)) |
261             mc::cat_deref(_, _, mc::Implicit(..)) => {
262                 match cmt.note {
263                     mc::NoteUpvarRef(upvar_id) => {
264                         debug!("adjust_upvar_borrow_kind_for_consume: \
265                                 setting upvar_id={:?} to by value",
266                                upvar_id);
267
268                         // to move out of an upvar, this must be a FnOnce closure
269                         self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
270
271                         let upvar_capture_map = &mut self.fcx
272                                                          .inh
273                                                          .tables.borrow_mut()
274                                                          .upvar_capture_map;
275                         upvar_capture_map.insert(upvar_id, ty::UpvarCapture::ByValue);
276                     }
277                     mc::NoteClosureEnv(upvar_id) => {
278                         // we get just a closureenv ref if this is a
279                         // `move` closure, or if the upvar has already
280                         // been inferred to by-value. In any case, we
281                         // must still adjust the kind of the closure
282                         // to be a FnOnce closure to permit moves out
283                         // of the environment.
284                         self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnOnceClosureKind);
285                     }
286                     mc::NoteNone => {
287                     }
288                 }
289             }
290             _ => { }
291         }
292     }
293
294     /// Indicates that `cmt` is being directly mutated (e.g., assigned
295     /// to). If cmt contains any by-ref upvars, this implies that
296     /// those upvars must be borrowed using an `&mut` borrow.
297     fn adjust_upvar_borrow_kind_for_mut(&mut self, cmt: mc::cmt<'tcx>) {
298         debug!("adjust_upvar_borrow_kind_for_mut(cmt={:?})",
299                cmt);
300
301         match cmt.cat.clone() {
302             mc::cat_deref(base, _, mc::Unique) |
303             mc::cat_interior(base, _) |
304             mc::cat_downcast(base, _) => {
305                 // Interior or owned data is mutable if base is
306                 // mutable, so iterate to the base.
307                 self.adjust_upvar_borrow_kind_for_mut(base);
308             }
309
310             mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
311             mc::cat_deref(base, _, mc::Implicit(..)) => {
312                 if !self.try_adjust_upvar_deref(&cmt.note, ty::MutBorrow) {
313                     // assignment to deref of an `&mut`
314                     // borrowed pointer implies that the
315                     // pointer itself must be unique, but not
316                     // necessarily *mutable*
317                     self.adjust_upvar_borrow_kind_for_unique(base);
318                 }
319             }
320
321             mc::cat_deref(_, _, mc::UnsafePtr(..)) |
322             mc::cat_static_item |
323             mc::cat_rvalue(_) |
324             mc::cat_local(_) |
325             mc::cat_upvar(..) => {
326                 return;
327             }
328         }
329     }
330
331     fn adjust_upvar_borrow_kind_for_unique(&self, cmt: mc::cmt<'tcx>) {
332         debug!("adjust_upvar_borrow_kind_for_unique(cmt={:?})",
333                cmt);
334
335         match cmt.cat.clone() {
336             mc::cat_deref(base, _, mc::Unique) |
337             mc::cat_interior(base, _) |
338             mc::cat_downcast(base, _) => {
339                 // Interior or owned data is unique if base is
340                 // unique.
341                 self.adjust_upvar_borrow_kind_for_unique(base);
342             }
343
344             mc::cat_deref(base, _, mc::BorrowedPtr(..)) |
345             mc::cat_deref(base, _, mc::Implicit(..)) => {
346                 if !self.try_adjust_upvar_deref(&cmt.note, ty::UniqueImmBorrow) {
347                     // for a borrowed pointer to be unique, its
348                     // base must be unique
349                     self.adjust_upvar_borrow_kind_for_unique(base);
350                 }
351             }
352
353             mc::cat_deref(_, _, mc::UnsafePtr(..)) |
354             mc::cat_static_item |
355             mc::cat_rvalue(_) |
356             mc::cat_local(_) |
357             mc::cat_upvar(..) => {
358             }
359         }
360     }
361
362     fn try_adjust_upvar_deref(&self,
363                               note: &mc::Note,
364                               borrow_kind: ty::BorrowKind)
365                               -> bool
366     {
367         assert!(match borrow_kind {
368             ty::MutBorrow => true,
369             ty::UniqueImmBorrow => true,
370
371             // imm borrows never require adjusting any kinds, so we don't wind up here
372             ty::ImmBorrow => false,
373         });
374
375         match *note {
376             mc::NoteUpvarRef(upvar_id) => {
377                 // if this is an implicit deref of an
378                 // upvar, then we need to modify the
379                 // borrow_kind of the upvar to make sure it
380                 // is inferred to mutable if necessary
381                 {
382                     let upvar_capture_map = &mut self.fcx.inh.tables.borrow_mut().upvar_capture_map;
383                     let ub = upvar_capture_map.get_mut(&upvar_id).unwrap();
384                     self.adjust_upvar_borrow_kind(upvar_id, ub, borrow_kind);
385                 }
386
387                 // also need to be in an FnMut closure since this is not an ImmBorrow
388                 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
389
390                 true
391             }
392             mc::NoteClosureEnv(upvar_id) => {
393                 // this kind of deref occurs in a `move` closure, or
394                 // for a by-value upvar; in either case, to mutate an
395                 // upvar, we need to be an FnMut closure
396                 self.adjust_closure_kind(upvar_id.closure_expr_id, ty::FnMutClosureKind);
397
398                 true
399             }
400             mc::NoteNone => {
401                 false
402             }
403         }
404     }
405
406     /// We infer the borrow_kind with which to borrow upvars in a stack closure. The borrow_kind
407     /// basically follows a lattice of `imm < unique-imm < mut`, moving from left to right as needed
408     /// (but never right to left). Here the argument `mutbl` is the borrow_kind that is required by
409     /// some particular use.
410     fn adjust_upvar_borrow_kind(&self,
411                                 upvar_id: ty::UpvarId,
412                                 upvar_capture: &mut ty::UpvarCapture,
413                                 kind: ty::BorrowKind) {
414         debug!("adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})",
415                upvar_id, upvar_capture, kind);
416
417         match *upvar_capture {
418             ty::UpvarCapture::ByValue => {
419                 // Upvar is already by-value, the strongest criteria.
420             }
421             ty::UpvarCapture::ByRef(ref mut upvar_borrow) => {
422                 match (upvar_borrow.kind, kind) {
423                     // Take RHS:
424                     (ty::ImmBorrow, ty::UniqueImmBorrow) |
425                     (ty::ImmBorrow, ty::MutBorrow) |
426                     (ty::UniqueImmBorrow, ty::MutBorrow) => {
427                         upvar_borrow.kind = kind;
428                     }
429                     // Take LHS:
430                     (ty::ImmBorrow, ty::ImmBorrow) |
431                     (ty::UniqueImmBorrow, ty::ImmBorrow) |
432                     (ty::UniqueImmBorrow, ty::UniqueImmBorrow) |
433                     (ty::MutBorrow, _) => {
434                     }
435                 }
436             }
437         }
438     }
439
440     fn adjust_closure_kind(&self,
441                            closure_id: ast::NodeId,
442                            new_kind: ty::ClosureKind) {
443         debug!("adjust_closure_kind(closure_id={}, new_kind={:?})",
444                closure_id, new_kind);
445
446         if !self.closures_with_inferred_kinds.contains(&closure_id) {
447             return;
448         }
449
450         let closure_def_id = ast_util::local_def(closure_id);
451         let closure_kinds = &mut self.fcx.inh.tables.borrow_mut().closure_kinds;
452         let existing_kind = *closure_kinds.get(&closure_def_id).unwrap();
453
454         debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}",
455                closure_id, existing_kind, new_kind);
456
457         match (existing_kind, new_kind) {
458             (ty::FnClosureKind, ty::FnClosureKind) |
459             (ty::FnMutClosureKind, ty::FnClosureKind) |
460             (ty::FnMutClosureKind, ty::FnMutClosureKind) |
461             (ty::FnOnceClosureKind, _) => {
462                 // no change needed
463             }
464
465             (ty::FnClosureKind, ty::FnMutClosureKind) |
466             (ty::FnClosureKind, ty::FnOnceClosureKind) |
467             (ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
468                 // new kind is stronger than the old kind
469                 closure_kinds.insert(closure_def_id, new_kind);
470             }
471         }
472     }
473 }
474
475 impl<'a, 'tcx, 'v> Visitor<'v> for AdjustBorrowKind<'a, 'tcx> {
476     fn visit_fn(&mut self,
477                 fn_kind: visit::FnKind<'v>,
478                 decl: &'v ast::FnDecl,
479                 body: &'v ast::Block,
480                 span: Span,
481                 id: ast::NodeId)
482     {
483         match fn_kind {
484             visit::FkItemFn(..) | visit::FkMethod(..) => {
485                 // ignore nested fn items
486             }
487             visit::FkFnBlock => {
488                 self.analyze_closure(id, decl, body);
489                 visit::walk_fn(self, fn_kind, decl, body, span);
490             }
491         }
492     }
493 }
494
495 impl<'a,'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a,'tcx> {
496     fn consume(&mut self,
497                _consume_id: ast::NodeId,
498                _consume_span: Span,
499                cmt: mc::cmt<'tcx>,
500                mode: euv::ConsumeMode)
501     {
502         debug!("consume(cmt={:?},mode={:?})", cmt, mode);
503         self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
504     }
505
506     fn matched_pat(&mut self,
507                    _matched_pat: &ast::Pat,
508                    _cmt: mc::cmt<'tcx>,
509                    _mode: euv::MatchMode)
510     {}
511
512     fn consume_pat(&mut self,
513                    _consume_pat: &ast::Pat,
514                    cmt: mc::cmt<'tcx>,
515                    mode: euv::ConsumeMode)
516     {
517         debug!("consume_pat(cmt={:?},mode={:?})", cmt, mode);
518         self.adjust_upvar_borrow_kind_for_consume(cmt, mode);
519     }
520
521     fn borrow(&mut self,
522               borrow_id: ast::NodeId,
523               _borrow_span: Span,
524               cmt: mc::cmt<'tcx>,
525               _loan_region: ty::Region,
526               bk: ty::BorrowKind,
527               _loan_cause: euv::LoanCause)
528     {
529         debug!("borrow(borrow_id={}, cmt={:?}, bk={:?})",
530                borrow_id, cmt, bk);
531
532         match bk {
533             ty::ImmBorrow => { }
534             ty::UniqueImmBorrow => {
535                 self.adjust_upvar_borrow_kind_for_unique(cmt);
536             }
537             ty::MutBorrow => {
538                 self.adjust_upvar_borrow_kind_for_mut(cmt);
539             }
540         }
541     }
542
543     fn decl_without_init(&mut self,
544                          _id: ast::NodeId,
545                          _span: Span)
546     {}
547
548     fn mutate(&mut self,
549               _assignment_id: ast::NodeId,
550               _assignment_span: Span,
551               assignee_cmt: mc::cmt<'tcx>,
552               _mode: euv::MutateMode)
553     {
554         debug!("mutate(assignee_cmt={:?})",
555                assignee_cmt);
556
557         self.adjust_upvar_borrow_kind_for_mut(assignee_cmt);
558     }
559 }