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