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