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