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