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