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