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