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