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