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