]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/regionck.rs
Remove Ty prefix from Ty{Adt|Array|Slice|RawPtr|Ref|FnDef|FnPtr|Dynamic|Closure|Gener...
[rust.git] / src / librustc_typeck / check / regionck.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 //! The region check is a final pass that runs over the AST after we have
12 //! inferred the type constraints but before we have actually finalized
13 //! the types.  Its purpose is to embed a variety of region constraints.
14 //! Inserting these constraints as a separate pass is good because (1) it
15 //! localizes the code that has to do with region inference and (2) often
16 //! we cannot know what constraints are needed until the basic types have
17 //! been inferred.
18 //!
19 //! ### Interaction with the borrow checker
20 //!
21 //! In general, the job of the borrowck module (which runs later) is to
22 //! check that all soundness criteria are met, given a particular set of
23 //! regions. The job of *this* module is to anticipate the needs of the
24 //! borrow checker and infer regions that will satisfy its requirements.
25 //! It is generally true that the inference doesn't need to be sound,
26 //! meaning that if there is a bug and we inferred bad regions, the borrow
27 //! checker should catch it. This is not entirely true though; for
28 //! example, the borrow checker doesn't check subtyping, and it doesn't
29 //! check that region pointers are always live when they are used. It
30 //! might be worthwhile to fix this so that borrowck serves as a kind of
31 //! verification step -- that would add confidence in the overall
32 //! correctness of the compiler, at the cost of duplicating some type
33 //! checks and effort.
34 //!
35 //! ### Inferring the duration of borrows, automatic and otherwise
36 //!
37 //! Whenever we introduce a borrowed pointer, for example as the result of
38 //! a borrow expression `let x = &data`, the lifetime of the pointer `x`
39 //! is always specified as a region inference variable. `regionck` has the
40 //! job of adding constraints such that this inference variable is as
41 //! narrow as possible while still accommodating all uses (that is, every
42 //! dereference of the resulting pointer must be within the lifetime).
43 //!
44 //! #### Reborrows
45 //!
46 //! Generally speaking, `regionck` does NOT try to ensure that the data
47 //! `data` will outlive the pointer `x`. That is the job of borrowck.  The
48 //! one exception is when "re-borrowing" the contents of another borrowed
49 //! pointer. For example, imagine you have a borrowed pointer `b` with
50 //! lifetime L1 and you have an expression `&*b`. The result of this
51 //! expression will be another borrowed pointer with lifetime L2 (which is
52 //! an inference variable). The borrow checker is going to enforce the
53 //! constraint that L2 < L1, because otherwise you are re-borrowing data
54 //! for a lifetime larger than the original loan.  However, without the
55 //! routines in this module, the region inferencer would not know of this
56 //! dependency and thus it might infer the lifetime of L2 to be greater
57 //! than L1 (issue #3148).
58 //!
59 //! There are a number of troublesome scenarios in the tests
60 //! `region-dependent-*.rs`, but here is one example:
61 //!
62 //!     struct Foo { i: i32 }
63 //!     struct Bar { foo: Foo  }
64 //!     fn get_i<'a>(x: &'a Bar) -> &'a i32 {
65 //!        let foo = &x.foo; // Lifetime L1
66 //!        &foo.i            // Lifetime L2
67 //!     }
68 //!
69 //! Note that this comes up either with `&` expressions, `ref`
70 //! bindings, and `autorefs`, which are the three ways to introduce
71 //! a borrow.
72 //!
73 //! The key point here is that when you are borrowing a value that
74 //! is "guaranteed" by a borrowed pointer, you must link the
75 //! lifetime of that borrowed pointer (L1, here) to the lifetime of
76 //! the borrow itself (L2).  What do I mean by "guaranteed" by a
77 //! borrowed pointer? I mean any data that is reached by first
78 //! dereferencing a borrowed pointer and then either traversing
79 //! interior offsets or boxes.  We say that the guarantor
80 //! of such data is the region of the borrowed pointer that was
81 //! traversed.  This is essentially the same as the ownership
82 //! relation, except that a borrowed pointer never owns its
83 //! contents.
84
85 use check::dropck;
86 use check::FnCtxt;
87 use middle::mem_categorization as mc;
88 use middle::mem_categorization::Categorization;
89 use middle::region;
90 use rustc::hir::def_id::DefId;
91 use rustc::ty::subst::Substs;
92 use rustc::ty::{self, Ty};
93 use rustc::infer;
94 use rustc::infer::outlives::env::OutlivesEnvironment;
95 use rustc::ty::adjustment;
96
97 use std::mem;
98 use std::ops::Deref;
99 use std::rc::Rc;
100 use rustc_data_structures::sync::Lrc;
101 use syntax::ast;
102 use syntax_pos::Span;
103 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
104 use rustc::hir::{self, PatKind};
105
106 // a variation on try that just returns unit
107 macro_rules! ignore_err {
108     ($e:expr) => (match $e { Ok(e) => e, Err(_) => {
109         debug!("ignoring mem-categorization error!");
110         return ()
111     }})
112 }
113
114 ///////////////////////////////////////////////////////////////////////////
115 // PUBLIC ENTRY POINTS
116
117 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
118     pub fn regionck_expr(&self, body: &'gcx hir::Body) {
119         let subject = self.tcx.hir.body_owner_def_id(body.id());
120         let id = body.value.id;
121         let mut rcx = RegionCtxt::new(self,
122                                       RepeatingScope(id),
123                                       id,
124                                       Subject(subject),
125                                       self.param_env);
126         if self.err_count_since_creation() == 0 {
127             // regionck assumes typeck succeeded
128             rcx.visit_body(body);
129             rcx.visit_region_obligations(id);
130         }
131         rcx.resolve_regions_and_report_errors_unless_nll();
132
133         assert!(self.tables.borrow().free_region_map.is_empty());
134         self.tables.borrow_mut().free_region_map = rcx.outlives_environment.into_free_region_map();
135     }
136
137     /// Region checking during the WF phase for items. `wf_tys` are the
138     /// types from which we should derive implied bounds, if any.
139     pub fn regionck_item(&self,
140                          item_id: ast::NodeId,
141                          span: Span,
142                          wf_tys: &[Ty<'tcx>]) {
143         debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys);
144         let subject = self.tcx.hir.local_def_id(item_id);
145         let mut rcx = RegionCtxt::new(self,
146                                       RepeatingScope(item_id),
147                                       item_id,
148                                       Subject(subject),
149                                       self.param_env);
150         rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span);
151         rcx.visit_region_obligations(item_id);
152         rcx.resolve_regions_and_report_errors();
153     }
154
155     /// Region check a function body. Not invoked on closures, but
156     /// only on the "root" fn item (in which closures may be
157     /// embedded). Walks the function body and adds various add'l
158     /// constraints that are needed for region inference. This is
159     /// separated both to isolate "pure" region constraints from the
160     /// rest of type check and because sometimes we need type
161     /// inference to have completed before we can determine which
162     /// constraints to add.
163     pub fn regionck_fn(&self,
164                        fn_id: ast::NodeId,
165                        body: &'gcx hir::Body) {
166         debug!("regionck_fn(id={})", fn_id);
167         let subject = self.tcx.hir.body_owner_def_id(body.id());
168         let node_id = body.value.id;
169         let mut rcx = RegionCtxt::new(self,
170                                       RepeatingScope(node_id),
171                                       node_id,
172                                       Subject(subject),
173                                       self.param_env);
174
175         if self.err_count_since_creation() == 0 {
176             // regionck assumes typeck succeeded
177             rcx.visit_fn_body(fn_id, body, self.tcx.hir.span(fn_id));
178         }
179
180         rcx.resolve_regions_and_report_errors_unless_nll();
181
182         // In this mode, we also copy the free-region-map into the
183         // tables of the enclosing fcx. In the other regionck modes
184         // (e.g., `regionck_item`), we don't have an enclosing tables.
185         assert!(self.tables.borrow().free_region_map.is_empty());
186         self.tables.borrow_mut().free_region_map = rcx.outlives_environment.into_free_region_map();
187     }
188 }
189
190 ///////////////////////////////////////////////////////////////////////////
191 // INTERNALS
192
193 pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
194     pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
195
196     pub region_scope_tree: Lrc<region::ScopeTree>,
197
198     outlives_environment: OutlivesEnvironment<'tcx>,
199
200     // id of innermost fn body id
201     body_id: ast::NodeId,
202
203     // call_site scope of innermost fn
204     call_site_scope: Option<region::Scope>,
205
206     // id of innermost fn or loop
207     repeating_scope: ast::NodeId,
208
209     // id of AST node being analyzed (the subject of the analysis).
210     subject_def_id: DefId,
211
212 }
213
214 impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> {
215     type Target = FnCtxt<'a, 'gcx, 'tcx>;
216     fn deref(&self) -> &Self::Target {
217         &self.fcx
218     }
219 }
220
221 pub struct RepeatingScope(ast::NodeId);
222 pub struct Subject(DefId);
223
224 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
225     pub fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
226                RepeatingScope(initial_repeating_scope): RepeatingScope,
227                initial_body_id: ast::NodeId,
228                Subject(subject): Subject,
229                param_env: ty::ParamEnv<'tcx>)
230                -> RegionCtxt<'a, 'gcx, 'tcx> {
231         let region_scope_tree = fcx.tcx.region_scope_tree(subject);
232         let outlives_environment = OutlivesEnvironment::new(param_env);
233         RegionCtxt {
234             fcx,
235             region_scope_tree,
236             repeating_scope: initial_repeating_scope,
237             body_id: initial_body_id,
238             call_site_scope: None,
239             subject_def_id: subject,
240             outlives_environment,
241         }
242     }
243
244     fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
245         mem::replace(&mut self.repeating_scope, scope)
246     }
247
248     /// Try to resolve the type for the given node, returning t_err if an error results.  Note that
249     /// we never care about the details of the error, the same error will be detected and reported
250     /// in the writeback phase.
251     ///
252     /// Note one important point: we do not attempt to resolve *region variables* here.  This is
253     /// because regionck is essentially adding constraints to those region variables and so may yet
254     /// influence how they are resolved.
255     ///
256     /// Consider this silly example:
257     ///
258     /// ```
259     /// fn borrow(x: &i32) -> &i32 {x}
260     /// fn foo(x: @i32) -> i32 {  // block: B
261     ///     let b = borrow(x);    // region: <R0>
262     ///     *b
263     /// }
264     /// ```
265     ///
266     /// Here, the region of `b` will be `<R0>`.  `<R0>` is constrained to be some subregion of the
267     /// block B and some superregion of the call.  If we forced it now, we'd choose the smaller
268     /// region (the call).  But that would make the *b illegal.  Since we don't resolve, the type
269     /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
270     /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
271     pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
272         self.resolve_type_vars_if_possible(&unresolved_ty)
273     }
274
275     /// Try to resolve the type for the given node.
276     fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> {
277         let t = self.node_ty(id);
278         self.resolve_type(t)
279     }
280
281     /// Try to resolve the type for the given node.
282     pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> {
283         let ty = self.tables.borrow().expr_ty_adjusted(expr);
284         self.resolve_type(ty)
285     }
286
287     /// This is the "main" function when region-checking a function item or a closure
288     /// within a function item. It begins by updating various fields (e.g., `call_site_scope`
289     /// and `outlives_environment`) to be appropriate to the function and then adds constraints
290     /// derived from the function body.
291     ///
292     /// Note that it does **not** restore the state of the fields that
293     /// it updates! This is intentional, since -- for the main
294     /// function -- we wish to be able to read the final
295     /// `outlives_environment` and other fields from the caller. For
296     /// closures, however, we save and restore any "scoped state"
297     /// before we invoke this function. (See `visit_fn` in the
298     /// `intravisit::Visitor` impl below.)
299     fn visit_fn_body(&mut self,
300                      id: ast::NodeId, // the id of the fn itself
301                      body: &'gcx hir::Body,
302                      span: Span)
303     {
304         // When we enter a function, we can derive
305         debug!("visit_fn_body(id={})", id);
306
307         let body_id = body.id();
308         self.body_id = body_id.node_id;
309
310         let call_site = region::Scope::CallSite(body.value.hir_id.local_id);
311         self.call_site_scope = Some(call_site);
312
313         let fn_sig = {
314             let fn_hir_id = self.tcx.hir.node_to_hir_id(id);
315             match self.tables.borrow().liberated_fn_sigs().get(fn_hir_id) {
316                 Some(f) => f.clone(),
317                 None => {
318                     bug!("No fn-sig entry for id={}", id);
319                 }
320             }
321         };
322
323         // Collect the types from which we create inferred bounds.
324         // For the return type, if diverging, substitute `bool` just
325         // because it will have no effect.
326         //
327         // FIXME(#27579) return types should not be implied bounds
328         let fn_sig_tys: Vec<_> =
329             fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
330
331         self.outlives_environment.add_implied_bounds(
332             self.fcx,
333             &fn_sig_tys[..],
334             body_id.node_id,
335             span);
336         self.link_fn_args(region::Scope::Node(body.value.hir_id.local_id), &body.arguments);
337         self.visit_body(body);
338         self.visit_region_obligations(body_id.node_id);
339
340         let call_site_scope = self.call_site_scope.unwrap();
341         debug!("visit_fn_body body.id {:?} call_site_scope: {:?}",
342                body.id(), call_site_scope);
343         let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
344
345         let body_hir_id = self.tcx.hir.node_to_hir_id(body_id.node_id);
346         self.type_of_node_must_outlive(infer::CallReturn(span),
347                                        body_hir_id,
348                                        call_site_region);
349
350         self.constrain_anon_types(
351             &self.fcx.anon_types.borrow(),
352             self.outlives_environment.free_region_map(),
353         );
354     }
355
356     fn visit_region_obligations(&mut self, node_id: ast::NodeId)
357     {
358         debug!("visit_region_obligations: node_id={}", node_id);
359
360         // region checking can introduce new pending obligations
361         // which, when processed, might generate new region
362         // obligations. So make sure we process those.
363         self.select_all_obligations_or_error();
364
365         self.infcx.process_registered_region_obligations(
366             self.outlives_environment.region_bound_pairs(),
367             self.implicit_region_bound,
368             self.param_env,
369             self.body_id);
370     }
371
372     fn resolve_regions_and_report_errors(&self) {
373         self.fcx.resolve_regions_and_report_errors(self.subject_def_id,
374                                                    &self.region_scope_tree,
375                                                    &self.outlives_environment);
376     }
377
378     fn resolve_regions_and_report_errors_unless_nll(&self) {
379         self.fcx.resolve_regions_and_report_errors_unless_nll(self.subject_def_id,
380                                                               &self.region_scope_tree,
381                                                               &self.outlives_environment);
382     }
383
384     fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) {
385         debug!("regionck::visit_pat(pat={:?})", pat);
386         pat.each_binding(|_, hir_id, span, _| {
387             // If we have a variable that contains region'd data, that
388             // data will be accessible from anywhere that the variable is
389             // accessed. We must be wary of loops like this:
390             //
391             //     // from src/test/compile-fail/borrowck-lend-flow.rs
392             //     let mut v = box 3, w = box 4;
393             //     let mut x = &mut w;
394             //     loop {
395             //         **x += 1;   // (2)
396             //         borrow(v);  //~ ERROR cannot borrow
397             //         x = &mut v; // (1)
398             //     }
399             //
400             // Typically, we try to determine the region of a borrow from
401             // those points where it is dereferenced. In this case, one
402             // might imagine that the lifetime of `x` need only be the
403             // body of the loop. But of course this is incorrect because
404             // the pointer that is created at point (1) is consumed at
405             // point (2), meaning that it must be live across the loop
406             // iteration. The easiest way to guarantee this is to require
407             // that the lifetime of any regions that appear in a
408             // variable's type enclose at least the variable's scope.
409             let var_scope = self.region_scope_tree.var_scope(hir_id.local_id);
410             let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
411
412             let origin = infer::BindingTypeIsNotValidAtDecl(span);
413             self.type_of_node_must_outlive(origin, hir_id, var_region);
414
415             let typ = self.resolve_node_type(hir_id);
416             let body_id = self.body_id;
417             let _ = dropck::check_safety_of_destructor_if_necessary(
418                 self, typ, span, body_id, var_scope);
419         })
420     }
421 }
422
423 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for RegionCtxt<'a, 'gcx, 'tcx> {
424     // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
425     // However, right now we run into an issue whereby some free
426     // regions are not properly related if they appear within the
427     // types of arguments that must be inferred. This could be
428     // addressed by deferring the construction of the region
429     // hierarchy, and in particular the relationships between free
430     // regions, until regionck, as described in #3238.
431
432     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
433         NestedVisitorMap::None
434     }
435
436     fn visit_fn(&mut self,
437                 fk: intravisit::FnKind<'gcx>,
438                 _: &'gcx hir::FnDecl,
439                 body_id: hir::BodyId,
440                 span: Span,
441                 id: ast::NodeId) {
442         assert!(match fk { intravisit::FnKind::Closure(..) => true, _ => false },
443                 "visit_fn invoked for something other than a closure");
444
445         // Save state of current function before invoking
446         // `visit_fn_body`.  We will restore afterwards.
447         let old_body_id = self.body_id;
448         let old_call_site_scope = self.call_site_scope;
449         let env_snapshot = self.outlives_environment.push_snapshot_pre_closure();
450
451         let body = self.tcx.hir.body(body_id);
452         self.visit_fn_body(id, body, span);
453
454         // Restore state from previous function.
455         self.outlives_environment.pop_snapshot_post_closure(env_snapshot);
456         self.call_site_scope = old_call_site_scope;
457         self.body_id = old_body_id;
458     }
459
460     //visit_pat: visit_pat, // (..) see above
461
462     fn visit_arm(&mut self, arm: &'gcx hir::Arm) {
463         // see above
464         for p in &arm.pats {
465             self.constrain_bindings_in_pat(p);
466         }
467         intravisit::walk_arm(self, arm);
468     }
469
470     fn visit_local(&mut self, l: &'gcx hir::Local) {
471         // see above
472         self.constrain_bindings_in_pat(&l.pat);
473         self.link_local(l);
474         intravisit::walk_local(self, l);
475     }
476
477     fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
478         debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
479                expr, self.repeating_scope);
480
481         // No matter what, the type of each expression must outlive the
482         // scope of that expression. This also guarantees basic WF.
483         let expr_ty = self.resolve_node_type(expr.hir_id);
484         // the region corresponding to this expression
485         let expr_region = self.tcx.mk_region(ty::ReScope(
486             region::Scope::Node(expr.hir_id.local_id)));
487         self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span),
488                                expr_ty, expr_region);
489
490         let is_method_call = self.tables.borrow().is_method_call(expr);
491
492         // If we are calling a method (either explicitly or via an
493         // overloaded operator), check that all of the types provided as
494         // arguments for its type parameters are well-formed, and all the regions
495         // provided as arguments outlive the call.
496         if is_method_call {
497             let origin = match expr.node {
498                 hir::ExprKind::MethodCall(..) =>
499                     infer::ParameterOrigin::MethodCall,
500                 hir::ExprKind::Unary(op, _) if op == hir::UnDeref =>
501                     infer::ParameterOrigin::OverloadedDeref,
502                 _ =>
503                     infer::ParameterOrigin::OverloadedOperator
504             };
505
506             let substs = self.tables.borrow().node_substs(expr.hir_id);
507             self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
508             // Arguments (sub-expressions) are checked via `constrain_call`, below.
509         }
510
511         // Check any autoderefs or autorefs that appear.
512         let cmt_result = self.constrain_adjustments(expr);
513
514         // If necessary, constrain destructors in this expression. This will be
515         // the adjusted form if there is an adjustment.
516         match cmt_result {
517             Ok(head_cmt) => {
518                 self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span);
519             }
520             Err(..) => {
521                 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
522             }
523         }
524
525         debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
526                expr, self.repeating_scope);
527         match expr.node {
528             hir::ExprKind::Path(_) => {
529                 let substs = self.tables.borrow().node_substs(expr.hir_id);
530                 let origin = infer::ParameterOrigin::Path;
531                 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
532             }
533
534             hir::ExprKind::Call(ref callee, ref args) => {
535                 if is_method_call {
536                     self.constrain_call(expr, Some(&callee), args.iter().map(|e| &*e));
537                 } else {
538                     self.constrain_callee(&callee);
539                     self.constrain_call(expr, None, args.iter().map(|e| &*e));
540                 }
541
542                 intravisit::walk_expr(self, expr);
543             }
544
545             hir::ExprKind::MethodCall(.., ref args) => {
546                 self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &*e));
547
548                 intravisit::walk_expr(self, expr);
549             }
550
551             hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
552                 if is_method_call {
553                     self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
554                 }
555
556                 intravisit::walk_expr(self, expr);
557             }
558
559             hir::ExprKind::Index(ref lhs, ref rhs) if is_method_call => {
560                 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
561
562                 intravisit::walk_expr(self, expr);
563             },
564
565             hir::ExprKind::Binary(_, ref lhs, ref rhs) if is_method_call => {
566                 // As `ExprKind::MethodCall`, but the call is via an overloaded op.
567                 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
568
569                 intravisit::walk_expr(self, expr);
570             }
571
572             hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
573                 // If you do `x OP y`, then the types of `x` and `y` must
574                 // outlive the operation you are performing.
575                 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
576                 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
577                 for &ty in &[lhs_ty, rhs_ty] {
578                     self.type_must_outlive(infer::Operand(expr.span),
579                                            ty, expr_region);
580                 }
581                 intravisit::walk_expr(self, expr);
582             }
583
584             hir::ExprKind::Unary(hir::UnDeref, ref base) => {
585                 // For *a, the lifetime of a must enclose the deref
586                 if is_method_call {
587                     self.constrain_call(expr, Some(base), None::<hir::Expr>.iter());
588                 }
589                 // For overloaded derefs, base_ty is the input to `Deref::deref`,
590                 // but it's a reference type uing the same region as the output.
591                 let base_ty = self.resolve_expr_type_adjusted(base);
592                 if let ty::Ref(r_ptr, _, _) = base_ty.sty {
593                     self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
594                 }
595
596                 intravisit::walk_expr(self, expr);
597             }
598
599             hir::ExprKind::Unary(_, ref lhs) if is_method_call => {
600                 // As above.
601                 self.constrain_call(expr, Some(&lhs), None::<hir::Expr>.iter());
602
603                 intravisit::walk_expr(self, expr);
604             }
605
606             hir::ExprKind::Index(ref vec_expr, _) => {
607                 // For a[b], the lifetime of a must enclose the deref
608                 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
609                 self.constrain_index(expr, vec_type);
610
611                 intravisit::walk_expr(self, expr);
612             }
613
614             hir::ExprKind::Cast(ref source, _) => {
615                 // Determine if we are casting `source` to a trait
616                 // instance.  If so, we have to be sure that the type of
617                 // the source obeys the trait's region bound.
618                 self.constrain_cast(expr, &source);
619                 intravisit::walk_expr(self, expr);
620             }
621
622             hir::ExprKind::AddrOf(m, ref base) => {
623                 self.link_addr_of(expr, m, &base);
624
625                 // Require that when you write a `&expr` expression, the
626                 // resulting pointer has a lifetime that encompasses the
627                 // `&expr` expression itself. Note that we constraining
628                 // the type of the node expr.id here *before applying
629                 // adjustments*.
630                 //
631                 // FIXME(https://github.com/rust-lang/rfcs/issues/811)
632                 // nested method calls requires that this rule change
633                 let ty0 = self.resolve_node_type(expr.hir_id);
634                 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
635                 intravisit::walk_expr(self, expr);
636             }
637
638             hir::ExprKind::Match(ref discr, ref arms, _) => {
639                 self.link_match(&discr, &arms[..]);
640
641                 intravisit::walk_expr(self, expr);
642             }
643
644             hir::ExprKind::Closure(.., body_id, _, _) => {
645                 self.check_expr_fn_block(expr, body_id);
646             }
647
648             hir::ExprKind::Loop(ref body, _, _) => {
649                 let repeating_scope = self.set_repeating_scope(body.id);
650                 intravisit::walk_expr(self, expr);
651                 self.set_repeating_scope(repeating_scope);
652             }
653
654             hir::ExprKind::While(ref cond, ref body, _) => {
655                 let repeating_scope = self.set_repeating_scope(cond.id);
656                 self.visit_expr(&cond);
657
658                 self.set_repeating_scope(body.id);
659                 self.visit_block(&body);
660
661                 self.set_repeating_scope(repeating_scope);
662             }
663
664             hir::ExprKind::Ret(Some(ref ret_expr)) => {
665                 let call_site_scope = self.call_site_scope;
666                 debug!("visit_expr ExprKind::Ret ret_expr.id {} call_site_scope: {:?}",
667                        ret_expr.id, call_site_scope);
668                 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
669                 self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span),
670                                                ret_expr.hir_id,
671                                                call_site_region);
672                 intravisit::walk_expr(self, expr);
673             }
674
675             _ => {
676                 intravisit::walk_expr(self, expr);
677             }
678         }
679     }
680 }
681
682 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
683     fn constrain_cast(&mut self,
684                       cast_expr: &hir::Expr,
685                       source_expr: &hir::Expr)
686     {
687         debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
688                cast_expr,
689                source_expr);
690
691         let source_ty = self.resolve_node_type(source_expr.hir_id);
692         let target_ty = self.resolve_node_type(cast_expr.hir_id);
693
694         self.walk_cast(cast_expr, source_ty, target_ty);
695     }
696
697     fn walk_cast(&mut self,
698                  cast_expr: &hir::Expr,
699                  from_ty: Ty<'tcx>,
700                  to_ty: Ty<'tcx>) {
701         debug!("walk_cast(from_ty={:?}, to_ty={:?})",
702                from_ty,
703                to_ty);
704         match (&from_ty.sty, &to_ty.sty) {
705             /*From:*/ (&ty::Ref(from_r, from_ty, _),
706             /*To:  */  &ty::Ref(to_r, to_ty, _)) => {
707                 // Target cannot outlive source, naturally.
708                 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
709                 self.walk_cast(cast_expr, from_ty, to_ty);
710             }
711
712             /*From:*/ (_,
713             /*To:  */  &ty::Dynamic(.., r)) => {
714                 // When T is existentially quantified as a trait
715                 // `Foo+'to`, it must outlive the region bound `'to`.
716                 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
717             }
718
719             /*From:*/ (&ty::Adt(from_def, _),
720             /*To:  */  &ty::Adt(to_def, _)) if from_def.is_box() && to_def.is_box() => {
721                 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
722             }
723
724             _ => { }
725         }
726     }
727
728     fn check_expr_fn_block(&mut self,
729                            expr: &'gcx hir::Expr,
730                            body_id: hir::BodyId) {
731         let repeating_scope = self.set_repeating_scope(body_id.node_id);
732         intravisit::walk_expr(self, expr);
733         self.set_repeating_scope(repeating_scope);
734     }
735
736     fn constrain_callee(&mut self, callee_expr: &hir::Expr) {
737         let callee_ty = self.resolve_node_type(callee_expr.hir_id);
738         match callee_ty.sty {
739             ty::FnDef(..) | ty::FnPtr(_) => { }
740             _ => {
741                 // this should not happen, but it does if the program is
742                 // erroneous
743                 //
744                 // bug!(
745                 //     callee_expr.span,
746                 //     "Calling non-function: {}",
747                 //     callee_ty);
748             }
749         }
750     }
751
752     fn constrain_call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
753                                                            call_expr: &hir::Expr,
754                                                            receiver: Option<&hir::Expr>,
755                                                            arg_exprs: I) {
756         //! Invoked on every call site (i.e., normal calls, method calls,
757         //! and overloaded operators). Constrains the regions which appear
758         //! in the type of the function. Also constrains the regions that
759         //! appear in the arguments appropriately.
760
761         debug!("constrain_call(call_expr={:?}, receiver={:?})",
762                 call_expr,
763                 receiver);
764
765         // `callee_region` is the scope representing the time in which the
766         // call occurs.
767         //
768         // FIXME(#6268) to support nested method calls, should be callee_id
769         let callee_scope = region::Scope::Node(call_expr.hir_id.local_id);
770         let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
771
772         debug!("callee_region={:?}", callee_region);
773
774         for arg_expr in arg_exprs {
775             debug!("Argument: {:?}", arg_expr);
776
777             // ensure that any regions appearing in the argument type are
778             // valid for at least the lifetime of the function:
779             self.type_of_node_must_outlive(infer::CallArg(arg_expr.span),
780                                            arg_expr.hir_id,
781                                            callee_region);
782         }
783
784         // as loop above, but for receiver
785         if let Some(r) = receiver {
786             debug!("receiver: {:?}", r);
787             self.type_of_node_must_outlive(infer::CallRcvr(r.span),
788                                            r.hir_id,
789                                            callee_region);
790         }
791     }
792
793     /// Create a temporary `MemCategorizationContext` and pass it to the closure.
794     fn with_mc<F, R>(&self, f: F) -> R
795         where F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'gcx, 'tcx>) -> R
796     {
797         f(mc::MemCategorizationContext::with_infer(&self.infcx,
798                                                    &self.region_scope_tree,
799                                                    &self.tables.borrow()))
800     }
801
802     /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
803     /// dereferenced, the lifetime of the pointer includes the deref expr.
804     fn constrain_adjustments(&mut self, expr: &hir::Expr) -> mc::McResult<mc::cmt_<'tcx>> {
805         debug!("constrain_adjustments(expr={:?})", expr);
806
807         let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
808
809         let tables = self.tables.borrow();
810         let adjustments = tables.expr_adjustments(&expr);
811         if adjustments.is_empty() {
812             return Ok(cmt);
813         }
814
815         debug!("constrain_adjustments: adjustments={:?}", adjustments);
816
817         // If necessary, constrain destructors in the unadjusted form of this
818         // expression.
819         self.check_safety_of_rvalue_destructor_if_necessary(&cmt, expr.span);
820
821         let expr_region = self.tcx.mk_region(ty::ReScope(
822             region::Scope::Node(expr.hir_id.local_id)));
823         for adjustment in adjustments {
824             debug!("constrain_adjustments: adjustment={:?}, cmt={:?}",
825                    adjustment, cmt);
826
827             if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
828                 debug!("constrain_adjustments: overloaded deref: {:?}", deref);
829
830                 // Treat overloaded autoderefs as if an AutoBorrow adjustment
831                 // was applied on the base type, as that is always the case.
832                 let input = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
833                     ty: cmt.ty,
834                     mutbl: deref.mutbl,
835                 });
836                 let output = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
837                     ty: adjustment.target,
838                     mutbl: deref.mutbl,
839                 });
840
841                 self.link_region(expr.span, deref.region,
842                                  ty::BorrowKind::from_mutbl(deref.mutbl), &cmt);
843
844                 // Specialized version of constrain_call.
845                 self.type_must_outlive(infer::CallRcvr(expr.span),
846                                        input, expr_region);
847                 self.type_must_outlive(infer::CallReturn(expr.span),
848                                        output, expr_region);
849             }
850
851             if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
852                 self.link_autoref(expr, &cmt, autoref);
853
854                 // Require that the resulting region encompasses
855                 // the current node.
856                 //
857                 // FIXME(#6268) remove to support nested method calls
858                 self.type_of_node_must_outlive(infer::AutoBorrow(expr.span),
859                                                expr.hir_id,
860                                                expr_region);
861             }
862
863             cmt = self.with_mc(|mc| mc.cat_expr_adjusted(expr, cmt, &adjustment))?;
864
865             if let Categorization::Deref(_, mc::BorrowedPtr(_, r_ptr)) = cmt.cat {
866                 self.mk_subregion_due_to_dereference(expr.span,
867                                                      expr_region, r_ptr);
868             }
869         }
870
871         Ok(cmt)
872     }
873
874     pub fn mk_subregion_due_to_dereference(&mut self,
875                                            deref_span: Span,
876                                            minimum_lifetime: ty::Region<'tcx>,
877                                            maximum_lifetime: ty::Region<'tcx>) {
878         self.sub_regions(infer::DerefPointer(deref_span),
879                          minimum_lifetime, maximum_lifetime)
880     }
881
882     fn check_safety_of_rvalue_destructor_if_necessary(&mut self,
883                                                      cmt: &mc::cmt_<'tcx>,
884                                                      span: Span) {
885         match cmt.cat {
886             Categorization::Rvalue(region) => {
887                 match *region {
888                     ty::ReScope(rvalue_scope) => {
889                         let typ = self.resolve_type(cmt.ty);
890                         let body_id = self.body_id;
891                         let _ = dropck::check_safety_of_destructor_if_necessary(
892                             self, typ, span, body_id, rvalue_scope);
893                     }
894                     ty::ReStatic => {}
895                     _ => {
896                         span_bug!(span,
897                                   "unexpected rvalue region in rvalue \
898                                    destructor safety checking: `{:?}`",
899                                   region);
900                     }
901                 }
902             }
903             _ => {}
904         }
905     }
906
907     /// Invoked on any index expression that occurs. Checks that if this is a slice
908     /// being indexed, the lifetime of the pointer includes the deref expr.
909     fn constrain_index(&mut self,
910                        index_expr: &hir::Expr,
911                        indexed_ty: Ty<'tcx>)
912     {
913         debug!("constrain_index(index_expr=?, indexed_ty={}",
914                self.ty_to_string(indexed_ty));
915
916         let r_index_expr = ty::ReScope(region::Scope::Node(index_expr.hir_id.local_id));
917         if let ty::Ref(r_ptr, r_ty, _) = indexed_ty.sty {
918             match r_ty.sty {
919                 ty::Slice(_) | ty::TyStr => {
920                     self.sub_regions(infer::IndexSlice(index_expr.span),
921                                      self.tcx.mk_region(r_index_expr), r_ptr);
922                 }
923                 _ => {}
924             }
925         }
926     }
927
928     /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
929     /// adjustments) are valid for at least `minimum_lifetime`
930     fn type_of_node_must_outlive(&mut self,
931         origin: infer::SubregionOrigin<'tcx>,
932         hir_id: hir::HirId,
933         minimum_lifetime: ty::Region<'tcx>)
934     {
935         // Try to resolve the type.  If we encounter an error, then typeck
936         // is going to fail anyway, so just stop here and let typeck
937         // report errors later on in the writeback phase.
938         let ty0 = self.resolve_node_type(hir_id);
939
940         let ty = self.tables
941                      .borrow()
942                      .adjustments()
943                      .get(hir_id)
944                      .and_then(|adj| adj.last())
945                      .map_or(ty0, |adj| adj.target);
946         let ty = self.resolve_type(ty);
947         debug!("constrain_regions_in_type_of_node(\
948                 ty={}, ty0={}, id={:?}, minimum_lifetime={:?})",
949                 ty,  ty0,
950                 hir_id, minimum_lifetime);
951         self.type_must_outlive(origin, ty, minimum_lifetime);
952     }
953
954     /// Adds constraints to inference such that `T: 'a` holds (or
955     /// reports an error if it cannot).
956     ///
957     /// # Parameters
958     ///
959     /// - `origin`, the reason we need this constraint
960     /// - `ty`, the type `T`
961     /// - `region`, the region `'a`
962     pub fn type_must_outlive(&self,
963                              origin: infer::SubregionOrigin<'tcx>,
964                              ty: Ty<'tcx>,
965                              region: ty::Region<'tcx>)
966     {
967         self.infcx.type_must_outlive(self.outlives_environment.region_bound_pairs(),
968                                      self.implicit_region_bound,
969                                      self.param_env,
970                                      origin,
971                                      ty,
972                                      region);
973     }
974
975     /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
976     /// resulting pointer is linked to the lifetime of its guarantor (if any).
977     fn link_addr_of(&mut self, expr: &hir::Expr,
978                     mutability: hir::Mutability, base: &hir::Expr) {
979         debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
980
981         let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
982
983         debug!("link_addr_of: cmt={:?}", cmt);
984
985         self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt);
986     }
987
988     /// Computes the guarantors for any ref bindings in a `let` and
989     /// then ensures that the lifetime of the resulting pointer is
990     /// linked to the lifetime of the initialization expression.
991     fn link_local(&self, local: &hir::Local) {
992         debug!("regionck::for_local()");
993         let init_expr = match local.init {
994             None => { return; }
995             Some(ref expr) => &**expr,
996         };
997         let discr_cmt = Rc::new(ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr))));
998         self.link_pattern(discr_cmt, &local.pat);
999     }
1000
1001     /// Computes the guarantors for any ref bindings in a match and
1002     /// then ensures that the lifetime of the resulting pointer is
1003     /// linked to the lifetime of its guarantor (if any).
1004     fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) {
1005         debug!("regionck::for_match()");
1006         let discr_cmt = Rc::new(ignore_err!(self.with_mc(|mc| mc.cat_expr(discr))));
1007         debug!("discr_cmt={:?}", discr_cmt);
1008         for arm in arms {
1009             for root_pat in &arm.pats {
1010                 self.link_pattern(discr_cmt.clone(), &root_pat);
1011             }
1012         }
1013     }
1014
1015     /// Computes the guarantors for any ref bindings in a match and
1016     /// then ensures that the lifetime of the resulting pointer is
1017     /// linked to the lifetime of its guarantor (if any).
1018     fn link_fn_args(&self, body_scope: region::Scope, args: &[hir::Arg]) {
1019         debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1020         for arg in args {
1021             let arg_ty = self.node_ty(arg.hir_id);
1022             let re_scope = self.tcx.mk_region(ty::ReScope(body_scope));
1023             let arg_cmt = self.with_mc(|mc| {
1024                 Rc::new(mc.cat_rvalue(arg.hir_id, arg.pat.span, re_scope, arg_ty))
1025             });
1026             debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1027                    arg_ty,
1028                    arg_cmt,
1029                    arg);
1030             self.link_pattern(arg_cmt, &arg.pat);
1031         }
1032     }
1033
1034     /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1035     /// in the discriminant, if needed.
1036     fn link_pattern(&self, discr_cmt: mc::cmt<'tcx>, root_pat: &hir::Pat) {
1037         debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1038                discr_cmt,
1039                root_pat);
1040         ignore_err!(self.with_mc(|mc| {
1041             mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, sub_pat| {
1042                 match sub_pat.node {
1043                     // `ref x` pattern
1044                     PatKind::Binding(..) => {
1045                         if let Some(&bm) = mc.tables.pat_binding_modes().get(sub_pat.hir_id) {
1046                             if let ty::BindByReference(mutbl) = bm {
1047                                 self.link_region_from_node_type(sub_pat.span, sub_pat.hir_id,
1048                                                                 mutbl, &sub_cmt);
1049                             }
1050                         } else {
1051                             self.tcx.sess.delay_span_bug(sub_pat.span, "missing binding mode");
1052                         }
1053                     }
1054                     _ => {}
1055                 }
1056             })
1057         }));
1058     }
1059
1060     /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1061     /// autoref'd.
1062     fn link_autoref(&self,
1063                     expr: &hir::Expr,
1064                     expr_cmt: &mc::cmt_<'tcx>,
1065                     autoref: &adjustment::AutoBorrow<'tcx>)
1066     {
1067         debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
1068
1069         match *autoref {
1070             adjustment::AutoBorrow::Ref(r, m) => {
1071                 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt);
1072             }
1073
1074             adjustment::AutoBorrow::RawPtr(m) => {
1075                 let r = self.tcx.mk_region(ty::ReScope(region::Scope::Node(expr.hir_id.local_id)));
1076                 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1077             }
1078         }
1079     }
1080
1081     /// Like `link_region()`, except that the region is extracted from the type of `id`,
1082     /// which must be some reference (`&T`, `&str`, etc).
1083     fn link_region_from_node_type(&self,
1084                                   span: Span,
1085                                   id: hir::HirId,
1086                                   mutbl: hir::Mutability,
1087                                   cmt_borrowed: &mc::cmt_<'tcx>) {
1088         debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1089                id, mutbl, cmt_borrowed);
1090
1091         let rptr_ty = self.resolve_node_type(id);
1092         if let ty::Ref(r, _, _) = rptr_ty.sty {
1093             debug!("rptr_ty={}",  rptr_ty);
1094             self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed);
1095         }
1096     }
1097
1098     /// Informs the inference engine that `borrow_cmt` is being borrowed with
1099     /// kind `borrow_kind` and lifetime `borrow_region`.
1100     /// In order to ensure borrowck is satisfied, this may create constraints
1101     /// between regions, as explained in `link_reborrowed_region()`.
1102     fn link_region(&self,
1103                    span: Span,
1104                    borrow_region: ty::Region<'tcx>,
1105                    borrow_kind: ty::BorrowKind,
1106                    borrow_cmt: &mc::cmt_<'tcx>) {
1107         let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1108         self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
1109
1110         let mut borrow_kind = borrow_kind;
1111         let mut borrow_cmt_cat = borrow_cmt.cat.clone();
1112
1113         loop {
1114             debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1115                    borrow_region,
1116                    borrow_kind,
1117                    borrow_cmt);
1118             match borrow_cmt_cat {
1119                 Categorization::Deref(ref_cmt, mc::BorrowedPtr(ref_kind, ref_region)) => {
1120                     match self.link_reborrowed_region(span,
1121                                                       borrow_region, borrow_kind,
1122                                                       ref_cmt, ref_region, ref_kind,
1123                                                       borrow_cmt.note) {
1124                         Some((c, k)) => {
1125                             borrow_cmt_cat = c.cat.clone();
1126                             borrow_kind = k;
1127                         }
1128                         None => {
1129                             return;
1130                         }
1131                     }
1132                 }
1133
1134                 Categorization::Downcast(cmt_base, _) |
1135                 Categorization::Deref(cmt_base, mc::Unique) |
1136                 Categorization::Interior(cmt_base, _) => {
1137                     // Borrowing interior or owned data requires the base
1138                     // to be valid and borrowable in the same fashion.
1139                     borrow_cmt_cat = cmt_base.cat.clone();
1140                     borrow_kind = borrow_kind;
1141                 }
1142
1143                 Categorization::Deref(_, mc::UnsafePtr(..)) |
1144                 Categorization::StaticItem |
1145                 Categorization::Upvar(..) |
1146                 Categorization::Local(..) |
1147                 Categorization::Rvalue(..) => {
1148                     // These are all "base cases" with independent lifetimes
1149                     // that are not subject to inference
1150                     return;
1151                 }
1152             }
1153         }
1154     }
1155
1156     /// This is the most complicated case: the path being borrowed is
1157     /// itself the referent of a borrowed pointer. Let me give an
1158     /// example fragment of code to make clear(er) the situation:
1159     ///
1160     ///    let r: &'a mut T = ...;  // the original reference "r" has lifetime 'a
1161     ///    ...
1162     ///    &'z *r                   // the reborrow has lifetime 'z
1163     ///
1164     /// Now, in this case, our primary job is to add the inference
1165     /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1166     /// parameters in (roughly) terms of the example:
1167     ///
1168     /// ```plain,ignore (pseudo-Rust)
1169     ///     A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1170     ///     borrow_region   ^~                 ref_region    ^~
1171     ///     borrow_kind        ^~               ref_kind        ^~
1172     ///     ref_cmt                 ^
1173     /// ```
1174     ///
1175     /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1176     ///
1177     /// Unfortunately, there are some complications beyond the simple
1178     /// scenario I just painted:
1179     ///
1180     /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1181     ///    case, we have two jobs. First, we are inferring whether this reference
1182     ///    should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1183     ///    adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1184     ///    then `r` must be an `&mut` reference). Second, whenever we link
1185     ///    two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1186     ///    case we adjust the cause to indicate that the reference being
1187     ///    "reborrowed" is itself an upvar. This provides a nicer error message
1188     ///    should something go wrong.
1189     ///
1190     /// 2. There may in fact be more levels of reborrowing. In the
1191     ///    example, I said the borrow was like `&'z *r`, but it might
1192     ///    in fact be a borrow like `&'z **q` where `q` has type `&'a
1193     ///    &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1194     ///    and `'z <= 'b`. This is explained more below.
1195     ///
1196     /// The return value of this function indicates whether we need to
1197     /// recurse and process `ref_cmt` (see case 2 above).
1198     fn link_reborrowed_region(&self,
1199                               span: Span,
1200                               borrow_region: ty::Region<'tcx>,
1201                               borrow_kind: ty::BorrowKind,
1202                               ref_cmt: mc::cmt<'tcx>,
1203                               ref_region: ty::Region<'tcx>,
1204                               mut ref_kind: ty::BorrowKind,
1205                               note: mc::Note)
1206                               -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1207     {
1208         // Possible upvar ID we may need later to create an entry in the
1209         // maybe link map.
1210
1211         // Detect by-ref upvar `x`:
1212         let cause = match note {
1213             mc::NoteUpvarRef(ref upvar_id) => {
1214                 match self.tables.borrow().upvar_capture_map.get(upvar_id) {
1215                     Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1216                         // The mutability of the upvar may have been modified
1217                         // by the above adjustment, so update our local variable.
1218                         ref_kind = upvar_borrow.kind;
1219
1220                         infer::ReborrowUpvar(span, *upvar_id)
1221                     }
1222                     _ => {
1223                         span_bug!( span, "Illegal upvar id: {:?}", upvar_id);
1224                     }
1225                 }
1226             }
1227             mc::NoteClosureEnv(ref upvar_id) => {
1228                 // We don't have any mutability changes to propagate, but
1229                 // we do want to note that an upvar reborrow caused this
1230                 // link
1231                 infer::ReborrowUpvar(span, *upvar_id)
1232             }
1233             _ => {
1234                 infer::Reborrow(span)
1235             }
1236         };
1237
1238         debug!("link_reborrowed_region: {:?} <= {:?}",
1239                borrow_region,
1240                ref_region);
1241         self.sub_regions(cause, borrow_region, ref_region);
1242
1243         // If we end up needing to recurse and establish a region link
1244         // with `ref_cmt`, calculate what borrow kind we will end up
1245         // needing. This will be used below.
1246         //
1247         // One interesting twist is that we can weaken the borrow kind
1248         // when we recurse: to reborrow an `&mut` referent as mutable,
1249         // borrowck requires a unique path to the `&mut` reference but not
1250         // necessarily a *mutable* path.
1251         let new_borrow_kind = match borrow_kind {
1252             ty::ImmBorrow =>
1253                 ty::ImmBorrow,
1254             ty::MutBorrow | ty::UniqueImmBorrow =>
1255                 ty::UniqueImmBorrow
1256         };
1257
1258         // Decide whether we need to recurse and link any regions within
1259         // the `ref_cmt`. This is concerned for the case where the value
1260         // being reborrowed is in fact a borrowed pointer found within
1261         // another borrowed pointer. For example:
1262         //
1263         //    let p: &'b &'a mut T = ...;
1264         //    ...
1265         //    &'z **p
1266         //
1267         // What makes this case particularly tricky is that, if the data
1268         // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1269         // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1270         // (otherwise the user might mutate through the `&mut T` reference
1271         // after `'b` expires and invalidate the borrow we are looking at
1272         // now).
1273         //
1274         // So let's re-examine our parameters in light of this more
1275         // complicated (possible) scenario:
1276         //
1277         //     A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1278         //     borrow_region   ^~                 ref_region             ^~
1279         //     borrow_kind        ^~               ref_kind                 ^~
1280         //     ref_cmt                 ^~~
1281         //
1282         // (Note that since we have not examined `ref_cmt.cat`, we don't
1283         // know whether this scenario has occurred; but I wanted to show
1284         // how all the types get adjusted.)
1285         match ref_kind {
1286             ty::ImmBorrow => {
1287                 // The reference being reborrowed is a shareable ref of
1288                 // type `&'a T`. In this case, it doesn't matter where we
1289                 // *found* the `&T` pointer, the memory it references will
1290                 // be valid and immutable for `'a`. So we can stop here.
1291                 //
1292                 // (Note that the `borrow_kind` must also be ImmBorrow or
1293                 // else the user is borrowed imm memory as mut memory,
1294                 // which means they'll get an error downstream in borrowck
1295                 // anyhow.)
1296                 return None;
1297             }
1298
1299             ty::MutBorrow | ty::UniqueImmBorrow => {
1300                 // The reference being reborrowed is either an `&mut T` or
1301                 // `&uniq T`. This is the case where recursion is needed.
1302                 return Some((ref_cmt, new_borrow_kind));
1303             }
1304         }
1305     }
1306
1307     /// Checks that the values provided for type/region arguments in a given
1308     /// expression are well-formed and in-scope.
1309     fn substs_wf_in_scope(&mut self,
1310                           origin: infer::ParameterOrigin,
1311                           substs: &Substs<'tcx>,
1312                           expr_span: Span,
1313                           expr_region: ty::Region<'tcx>) {
1314         debug!("substs_wf_in_scope(substs={:?}, \
1315                 expr_region={:?}, \
1316                 origin={:?}, \
1317                 expr_span={:?})",
1318                substs, expr_region, origin, expr_span);
1319
1320         let origin = infer::ParameterInScope(origin, expr_span);
1321
1322         for region in substs.regions() {
1323             self.sub_regions(origin.clone(), expr_region, region);
1324         }
1325
1326         for ty in substs.types() {
1327             let ty = self.resolve_type(ty);
1328             self.type_must_outlive(origin.clone(), ty, expr_region);
1329         }
1330     }
1331 }