]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/regionck.rs
Merge pull request #20510 from tshepang/patch-6
[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: int }
63 //!     struct Bar { foo: Foo  }
64 //!     fn get_i(x: &'a Bar) -> &'a int {
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 owned pointers.  We say that the guarantor
80 //! of such data it 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 astconv::AstConv;
86 use check::FnCtxt;
87 use check::regionmanip;
88 use check::vtable;
89 use middle::def;
90 use middle::mem_categorization as mc;
91 use middle::region::CodeExtent;
92 use middle::traits;
93 use middle::ty::{ReScope};
94 use middle::ty::{self, Ty, MethodCall};
95 use middle::infer;
96 use middle::pat_util;
97 use util::ppaux::{ty_to_string, Repr};
98
99 use syntax::{ast, ast_util};
100 use syntax::codemap::Span;
101 use syntax::visit;
102 use syntax::visit::Visitor;
103
104 use self::RepeatingScope::Repeating;
105 use self::SubjectNode::Subject;
106
107 // a variation on try that just returns unit
108 macro_rules! ignore_err {
109     ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () })
110 }
111
112 ///////////////////////////////////////////////////////////////////////////
113 // PUBLIC ENTRY POINTS
114
115 pub fn regionck_expr(fcx: &FnCtxt, e: &ast::Expr) {
116     let mut rcx = Rcx::new(fcx, Repeating(e.id), Subject(e.id));
117     if fcx.err_count_since_creation() == 0 {
118         // regionck assumes typeck succeeded
119         rcx.visit_expr(e);
120         rcx.visit_region_obligations(e.id);
121     }
122     rcx.resolve_regions_and_report_errors();
123 }
124
125 pub fn regionck_item(fcx: &FnCtxt, item: &ast::Item) {
126     let mut rcx = Rcx::new(fcx, Repeating(item.id), Subject(item.id));
127     rcx.visit_region_obligations(item.id);
128     rcx.resolve_regions_and_report_errors();
129 }
130
131 pub fn regionck_fn(fcx: &FnCtxt, id: ast::NodeId, decl: &ast::FnDecl, blk: &ast::Block) {
132     let mut rcx = Rcx::new(fcx, Repeating(blk.id), Subject(id));
133     if fcx.err_count_since_creation() == 0 {
134         // regionck assumes typeck succeeded
135         rcx.visit_fn_body(id, decl, blk);
136     }
137
138     // Region checking a fn can introduce new trait obligations,
139     // particularly around closure bounds.
140     vtable::select_all_fcx_obligations_or_error(fcx);
141
142     rcx.resolve_regions_and_report_errors();
143 }
144
145 /// Checks that the types in `component_tys` are well-formed. This will add constraints into the
146 /// region graph. Does *not* run `resolve_regions_and_report_errors` and so forth.
147 pub fn regionck_ensure_component_tys_wf<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
148                                                   span: Span,
149                                                   component_tys: &[Ty<'tcx>]) {
150     let mut rcx = Rcx::new(fcx, Repeating(0), SubjectNode::None);
151     for &component_ty in component_tys.iter() {
152         // Check that each type outlives the empty region. Since the
153         // empty region is a subregion of all others, this can't fail
154         // unless the type does not meet the well-formedness
155         // requirements.
156         type_must_outlive(&mut rcx, infer::RelateRegionParamBound(span),
157                           component_ty, ty::ReEmpty);
158     }
159 }
160
161 ///////////////////////////////////////////////////////////////////////////
162 // INTERNALS
163
164 pub struct Rcx<'a, 'tcx: 'a> {
165     fcx: &'a FnCtxt<'a, 'tcx>,
166
167     region_param_pairs: Vec<(ty::Region, ty::ParamTy)>,
168
169     // id of innermost fn or loop
170     repeating_scope: ast::NodeId,
171
172     // id of AST node being analyzed (the subject of the analysis).
173     subject: SubjectNode,
174 }
175
176 /// Returns the validity region of `def` -- that is, how long is `def` valid?
177 fn region_of_def(fcx: &FnCtxt, def: def::Def) -> ty::Region {
178     let tcx = fcx.tcx();
179     match def {
180         def::DefLocal(node_id) => {
181             tcx.region_maps.var_region(node_id)
182         }
183         def::DefUpvar(node_id, _, body_id) => {
184             if body_id == ast::DUMMY_NODE_ID {
185                 tcx.region_maps.var_region(node_id)
186             } else {
187                 ReScope(CodeExtent::from_node_id(body_id))
188             }
189         }
190         _ => {
191             tcx.sess.bug(format!("unexpected def in region_of_def: {}",
192                                  def)[])
193         }
194     }
195 }
196
197 pub enum RepeatingScope { Repeating(ast::NodeId) }
198 pub enum SubjectNode { Subject(ast::NodeId), None }
199
200 impl<'a, 'tcx> Rcx<'a, 'tcx> {
201     pub fn new(fcx: &'a FnCtxt<'a, 'tcx>,
202                initial_repeating_scope: RepeatingScope,
203                subject: SubjectNode) -> Rcx<'a, 'tcx> {
204         let Repeating(initial_repeating_scope) = initial_repeating_scope;
205         Rcx { fcx: fcx,
206               repeating_scope: initial_repeating_scope,
207               subject: subject,
208               region_param_pairs: Vec::new() }
209     }
210
211     pub fn tcx(&self) -> &'a ty::ctxt<'tcx> {
212         self.fcx.ccx.tcx
213     }
214
215     pub fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
216         let old_scope = self.repeating_scope;
217         self.repeating_scope = scope;
218         old_scope
219     }
220
221     /// Try to resolve the type for the given node, returning t_err if an error results.  Note that
222     /// we never care about the details of the error, the same error will be detected and reported
223     /// in the writeback phase.
224     ///
225     /// Note one important point: we do not attempt to resolve *region variables* here.  This is
226     /// because regionck is essentially adding constraints to those region variables and so may yet
227     /// influence how they are resolved.
228     ///
229     /// Consider this silly example:
230     ///
231     /// ```
232     /// fn borrow(x: &int) -> &int {x}
233     /// fn foo(x: @int) -> int {  // block: B
234     ///     let b = borrow(x);    // region: <R0>
235     ///     *b
236     /// }
237     /// ```
238     ///
239     /// Here, the region of `b` will be `<R0>`.  `<R0>` is constrainted to be some subregion of the
240     /// block B and some superregion of the call.  If we forced it now, we'd choose the smaller
241     /// region (the call).  But that would make the *b illegal.  Since we don't resolve, the type
242     /// of b will be `&<R0>.int` and then `*b` will require that `<R0>` be bigger than the let and
243     /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
244     pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
245         self.fcx.infcx().resolve_type_vars_if_possible(&unresolved_ty)
246     }
247
248     /// Try to resolve the type for the given node.
249     fn resolve_node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
250         let t = self.fcx.node_ty(id);
251         self.resolve_type(t)
252     }
253
254     fn resolve_method_type(&self, method_call: MethodCall) -> Option<Ty<'tcx>> {
255         let method_ty = self.fcx.inh.method_map.borrow()
256                             .get(&method_call).map(|method| method.ty);
257         method_ty.map(|method_ty| self.resolve_type(method_ty))
258     }
259
260     /// Try to resolve the type for the given node.
261     pub fn resolve_expr_type_adjusted(&mut self, expr: &ast::Expr) -> Ty<'tcx> {
262         let ty_unadjusted = self.resolve_node_type(expr.id);
263         if ty::type_is_error(ty_unadjusted) {
264             ty_unadjusted
265         } else {
266             let tcx = self.fcx.tcx();
267             ty::adjust_ty(tcx, expr.span, expr.id, ty_unadjusted,
268                           self.fcx.inh.adjustments.borrow().get(&expr.id),
269                           |method_call| self.resolve_method_type(method_call))
270         }
271     }
272
273     fn visit_fn_body(&mut self,
274                      id: ast::NodeId,
275                      fn_decl: &ast::FnDecl,
276                      body: &ast::Block)
277     {
278         // When we enter a function, we can derive
279
280         let fn_sig_map = self.fcx.inh.fn_sig_map.borrow();
281         let fn_sig = match fn_sig_map.get(&id) {
282             Some(f) => f,
283             None => {
284                 self.tcx().sess.bug(
285                     format!("No fn-sig entry for id={}", id)[]);
286             }
287         };
288
289         let len = self.region_param_pairs.len();
290         self.relate_free_regions(fn_sig[], body.id);
291         link_fn_args(self, CodeExtent::from_node_id(body.id), fn_decl.inputs[]);
292         self.visit_block(body);
293         self.visit_region_obligations(body.id);
294         self.region_param_pairs.truncate(len);
295     }
296
297     fn visit_region_obligations(&mut self, node_id: ast::NodeId)
298     {
299         debug!("visit_region_obligations: node_id={}", node_id);
300         let fulfillment_cx = self.fcx.inh.fulfillment_cx.borrow();
301         for r_o in fulfillment_cx.region_obligations(node_id).iter() {
302             debug!("visit_region_obligations: r_o={}",
303                    r_o.repr(self.tcx()));
304             let sup_type = self.resolve_type(r_o.sup_type);
305             let origin = infer::RelateRegionParamBound(r_o.cause.span);
306             type_must_outlive(self, origin, sup_type, r_o.sub_region);
307         }
308     }
309
310     /// This method populates the region map's `free_region_map`. It walks over the transformed
311     /// argument and return types for each function just before we check the body of that function,
312     /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
313     /// [uint]`.  We do not allow references to outlive the things they point at, so we can assume
314     /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
315     /// the caller side, the caller is responsible for checking that the type of every expression
316     /// (including the actual values for the arguments, as well as the return type of the fn call)
317     /// is well-formed.
318     ///
319     /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
320     fn relate_free_regions(&mut self,
321                            fn_sig_tys: &[Ty<'tcx>],
322                            body_id: ast::NodeId) {
323         debug!("relate_free_regions >>");
324         let tcx = self.tcx();
325
326         for &ty in fn_sig_tys.iter() {
327             let ty = self.resolve_type(ty);
328             debug!("relate_free_regions(t={})", ty.repr(tcx));
329             let body_scope = CodeExtent::from_node_id(body_id);
330             let body_scope = ty::ReScope(body_scope);
331             let constraints =
332                 regionmanip::region_wf_constraints(
333                     tcx,
334                     ty,
335                     body_scope);
336             for constraint in constraints.iter() {
337                 debug!("constraint: {}", constraint.repr(tcx));
338                 match *constraint {
339                     regionmanip::RegionSubRegionConstraint(_,
340                                               ty::ReFree(free_a),
341                                               ty::ReFree(free_b)) => {
342                         tcx.region_maps.relate_free_regions(free_a, free_b);
343                     }
344                     regionmanip::RegionSubRegionConstraint(_,
345                                               ty::ReFree(free_a),
346                                               ty::ReInfer(ty::ReVar(vid_b))) => {
347                         self.fcx.inh.infcx.add_given(free_a, vid_b);
348                     }
349                     regionmanip::RegionSubRegionConstraint(..) => {
350                         // In principle, we could record (and take
351                         // advantage of) every relationship here, but
352                         // we are also free not to -- it simply means
353                         // strictly less that we can successfully type
354                         // check. (It may also be that we should
355                         // revise our inference system to be more
356                         // general and to make use of *every*
357                         // relationship that arises here, but
358                         // presently we do not.)
359                     }
360                     regionmanip::RegionSubParamConstraint(_, r_a, p_b) => {
361                         debug!("RegionSubParamConstraint: {} <= {}",
362                                r_a.repr(tcx), p_b.repr(tcx));
363
364                         self.region_param_pairs.push((r_a, p_b));
365                     }
366                 }
367             }
368         }
369
370         debug!("<< relate_free_regions");
371     }
372
373     fn resolve_regions_and_report_errors(&self) {
374         let subject_node_id = match self.subject {
375             Subject(s) => s,
376             SubjectNode::None => {
377                 self.tcx().sess.bug("cannot resolve_regions_and_report_errors \
378                                      without subject node");
379             }
380         };
381
382         self.fcx.infcx().resolve_regions_and_report_errors(subject_node_id);
383     }
384 }
385
386 impl<'a, 'tcx, 'v> Visitor<'v> for Rcx<'a, 'tcx> {
387     // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
388     // However, right now we run into an issue whereby some free
389     // regions are not properly related if they appear within the
390     // types of arguments that must be inferred. This could be
391     // addressed by deferring the construction of the region
392     // hierarchy, and in particular the relationships between free
393     // regions, until regionck, as described in #3238.
394
395     fn visit_fn(&mut self, _fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
396                 b: &'v ast::Block, _s: Span, id: ast::NodeId) {
397         self.visit_fn_body(id, fd, b)
398     }
399
400     fn visit_item(&mut self, i: &ast::Item) { visit_item(self, i); }
401
402     fn visit_expr(&mut self, ex: &ast::Expr) { visit_expr(self, ex); }
403
404     //visit_pat: visit_pat, // (..) see above
405
406     fn visit_arm(&mut self, a: &ast::Arm) { visit_arm(self, a); }
407
408     fn visit_local(&mut self, l: &ast::Local) { visit_local(self, l); }
409
410     fn visit_block(&mut self, b: &ast::Block) { visit_block(self, b); }
411 }
412
413 fn visit_item(_rcx: &mut Rcx, _item: &ast::Item) {
414     // Ignore items
415 }
416
417 fn visit_block(rcx: &mut Rcx, b: &ast::Block) {
418     visit::walk_block(rcx, b);
419 }
420
421 fn visit_arm(rcx: &mut Rcx, arm: &ast::Arm) {
422     // see above
423     for p in arm.pats.iter() {
424         constrain_bindings_in_pat(&**p, rcx);
425     }
426
427     visit::walk_arm(rcx, arm);
428 }
429
430 fn visit_local(rcx: &mut Rcx, l: &ast::Local) {
431     // see above
432     constrain_bindings_in_pat(&*l.pat, rcx);
433     link_local(rcx, l);
434     visit::walk_local(rcx, l);
435 }
436
437 fn constrain_bindings_in_pat(pat: &ast::Pat, rcx: &mut Rcx) {
438     let tcx = rcx.fcx.tcx();
439     debug!("regionck::visit_pat(pat={})", pat.repr(tcx));
440     pat_util::pat_bindings(&tcx.def_map, pat, |_, id, span, _| {
441         // If we have a variable that contains region'd data, that
442         // data will be accessible from anywhere that the variable is
443         // accessed. We must be wary of loops like this:
444         //
445         //     // from src/test/compile-fail/borrowck-lend-flow.rs
446         //     let mut v = box 3, w = box 4;
447         //     let mut x = &mut w;
448         //     loop {
449         //         **x += 1;   // (2)
450         //         borrow(v);  //~ ERROR cannot borrow
451         //         x = &mut v; // (1)
452         //     }
453         //
454         // Typically, we try to determine the region of a borrow from
455         // those points where it is dereferenced. In this case, one
456         // might imagine that the lifetime of `x` need only be the
457         // body of the loop. But of course this is incorrect because
458         // the pointer that is created at point (1) is consumed at
459         // point (2), meaning that it must be live across the loop
460         // iteration. The easiest way to guarantee this is to require
461         // that the lifetime of any regions that appear in a
462         // variable's type enclose at least the variable's scope.
463
464         let var_region = tcx.region_maps.var_region(id);
465         type_of_node_must_outlive(
466             rcx, infer::BindingTypeIsNotValidAtDecl(span),
467             id, var_region);
468     })
469 }
470
471 fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
472     debug!("regionck::visit_expr(e={}, repeating_scope={})",
473            expr.repr(rcx.fcx.tcx()), rcx.repeating_scope);
474
475     // No matter what, the type of each expression must outlive the
476     // scope of that expression. This also guarantees basic WF.
477     let expr_ty = rcx.resolve_node_type(expr.id);
478
479     type_must_outlive(rcx, infer::ExprTypeIsNotInScope(expr_ty, expr.span),
480                       expr_ty, ty::ReScope(CodeExtent::from_node_id(expr.id)));
481
482     let method_call = MethodCall::expr(expr.id);
483     let has_method_map = rcx.fcx.inh.method_map.borrow().contains_key(&method_call);
484
485     // Check any autoderefs or autorefs that appear.
486     for &adjustment in rcx.fcx.inh.adjustments.borrow().get(&expr.id).iter() {
487         debug!("adjustment={}", adjustment);
488         match *adjustment {
489             ty::AdjustDerefRef(ty::AutoDerefRef {autoderefs, autoref: ref opt_autoref}) => {
490                 let expr_ty = rcx.resolve_node_type(expr.id);
491                 constrain_autoderefs(rcx, expr, autoderefs, expr_ty);
492                 for autoref in opt_autoref.iter() {
493                     link_autoref(rcx, expr, autoderefs, autoref);
494
495                     // Require that the resulting region encompasses
496                     // the current node.
497                     //
498                     // FIXME(#6268) remove to support nested method calls
499                     type_of_node_must_outlive(
500                         rcx, infer::AutoBorrow(expr.span),
501                         expr.id, ty::ReScope(CodeExtent::from_node_id(expr.id)));
502                 }
503             }
504             /*
505             ty::AutoObject(_, ref bounds, _, _) => {
506                 // Determine if we are casting `expr` to a trait
507                 // instance. If so, we have to be sure that the type
508                 // of the source obeys the new region bound.
509                 let source_ty = rcx.resolve_node_type(expr.id);
510                 type_must_outlive(rcx, infer::RelateObjectBound(expr.span),
511                                   source_ty, bounds.region_bound);
512             }
513             */
514             _ => {}
515         }
516     }
517
518     match expr.node {
519         ast::ExprCall(ref callee, ref args) => {
520             if has_method_map {
521                 constrain_call(rcx, expr, Some(&**callee),
522                                args.iter().map(|e| &**e), false);
523             } else {
524                 constrain_callee(rcx, callee.id, expr, &**callee);
525                 constrain_call(rcx, expr, None,
526                                args.iter().map(|e| &**e), false);
527             }
528
529             visit::walk_expr(rcx, expr);
530         }
531
532         ast::ExprMethodCall(_, _, ref args) => {
533             constrain_call(rcx, expr, Some(&*args[0]),
534                            args.slice_from(1).iter().map(|e| &**e), false);
535
536             visit::walk_expr(rcx, expr);
537         }
538
539         ast::ExprAssignOp(_, ref lhs, ref rhs) => {
540             if has_method_map {
541                 constrain_call(rcx, expr, Some(&**lhs),
542                                Some(&**rhs).into_iter(), true);
543             }
544
545             visit::walk_expr(rcx, expr);
546         }
547
548         ast::ExprIndex(ref lhs, ref rhs) if has_method_map => {
549             constrain_call(rcx, expr, Some(&**lhs),
550                            Some(&**rhs).into_iter(), true);
551
552             visit::walk_expr(rcx, expr);
553         },
554
555         ast::ExprBinary(op, ref lhs, ref rhs) if has_method_map => {
556             let implicitly_ref_args = !ast_util::is_by_value_binop(op);
557
558             // As `expr_method_call`, but the call is via an
559             // overloaded op.  Note that we (sadly) currently use an
560             // implicit "by ref" sort of passing style here.  This
561             // should be converted to an adjustment!
562             constrain_call(rcx, expr, Some(&**lhs),
563                            Some(&**rhs).into_iter(), implicitly_ref_args);
564
565             visit::walk_expr(rcx, expr);
566         }
567
568         ast::ExprUnary(op, ref lhs) if has_method_map => {
569             let implicitly_ref_args = !ast_util::is_by_value_unop(op);
570
571             // As above.
572             constrain_call(rcx, expr, Some(&**lhs),
573                            None::<ast::Expr>.iter(), implicitly_ref_args);
574
575             visit::walk_expr(rcx, expr);
576         }
577
578         ast::ExprUnary(ast::UnDeref, ref base) => {
579             // For *a, the lifetime of a must enclose the deref
580             let method_call = MethodCall::expr(expr.id);
581             let base_ty = match rcx.fcx.inh.method_map.borrow().get(&method_call) {
582                 Some(method) => {
583                     constrain_call(rcx, expr, Some(&**base),
584                                    None::<ast::Expr>.iter(), true);
585                     ty::ty_fn_ret(method.ty).unwrap()
586                 }
587                 None => rcx.resolve_node_type(base.id)
588             };
589             if let ty::ty_rptr(r_ptr, _) = base_ty.sty {
590                 mk_subregion_due_to_dereference(
591                     rcx, expr.span, ty::ReScope(CodeExtent::from_node_id(expr.id)), *r_ptr);
592             }
593
594             visit::walk_expr(rcx, expr);
595         }
596
597         ast::ExprIndex(ref vec_expr, _) => {
598             // For a[b], the lifetime of a must enclose the deref
599             let vec_type = rcx.resolve_expr_type_adjusted(&**vec_expr);
600             constrain_index(rcx, expr, vec_type);
601
602             visit::walk_expr(rcx, expr);
603         }
604
605         ast::ExprCast(ref source, _) => {
606             // Determine if we are casting `source` to a trait
607             // instance.  If so, we have to be sure that the type of
608             // the source obeys the trait's region bound.
609             constrain_cast(rcx, expr, &**source);
610             visit::walk_expr(rcx, expr);
611         }
612
613         ast::ExprAddrOf(m, ref base) => {
614             link_addr_of(rcx, expr, m, &**base);
615
616             // Require that when you write a `&expr` expression, the
617             // resulting pointer has a lifetime that encompasses the
618             // `&expr` expression itself. Note that we constraining
619             // the type of the node expr.id here *before applying
620             // adjustments*.
621             //
622             // FIXME(#6268) nested method calls requires that this rule change
623             let ty0 = rcx.resolve_node_type(expr.id);
624             type_must_outlive(rcx, infer::AddrOf(expr.span),
625                               ty0, ty::ReScope(CodeExtent::from_node_id(expr.id)));
626             visit::walk_expr(rcx, expr);
627         }
628
629         ast::ExprMatch(ref discr, ref arms, _) => {
630             link_match(rcx, &**discr, arms[]);
631
632             visit::walk_expr(rcx, expr);
633         }
634
635         ast::ExprClosure(_, _, _, ref body) => {
636             check_expr_fn_block(rcx, expr, &**body);
637         }
638
639         ast::ExprLoop(ref body, _) => {
640             let repeating_scope = rcx.set_repeating_scope(body.id);
641             visit::walk_expr(rcx, expr);
642             rcx.set_repeating_scope(repeating_scope);
643         }
644
645         ast::ExprWhile(ref cond, ref body, _) => {
646             let repeating_scope = rcx.set_repeating_scope(cond.id);
647             rcx.visit_expr(&**cond);
648
649             rcx.set_repeating_scope(body.id);
650             rcx.visit_block(&**body);
651
652             rcx.set_repeating_scope(repeating_scope);
653         }
654
655         ast::ExprForLoop(ref pat, ref head, ref body, _) => {
656             constrain_bindings_in_pat(&**pat, rcx);
657
658             {
659                 let mc = mc::MemCategorizationContext::new(rcx.fcx);
660                 let pat_ty = rcx.resolve_node_type(pat.id);
661                 let pat_cmt = mc.cat_rvalue(pat.id,
662                                             pat.span,
663                                             ty::ReScope(CodeExtent::from_node_id(body.id)),
664                                             pat_ty);
665                 link_pattern(rcx, mc, pat_cmt, &**pat);
666             }
667
668             rcx.visit_expr(&**head);
669             type_of_node_must_outlive(rcx,
670                                       infer::AddrOf(expr.span),
671                                       head.id,
672                                       ty::ReScope(CodeExtent::from_node_id(expr.id)));
673
674             let repeating_scope = rcx.set_repeating_scope(body.id);
675             rcx.visit_block(&**body);
676             rcx.set_repeating_scope(repeating_scope);
677         }
678
679         _ => {
680             visit::walk_expr(rcx, expr);
681         }
682     }
683 }
684
685 fn constrain_cast(rcx: &mut Rcx,
686                   cast_expr: &ast::Expr,
687                   source_expr: &ast::Expr)
688 {
689     debug!("constrain_cast(cast_expr={}, source_expr={})",
690            cast_expr.repr(rcx.tcx()),
691            source_expr.repr(rcx.tcx()));
692
693     let source_ty = rcx.resolve_node_type(source_expr.id);
694     let target_ty = rcx.resolve_node_type(cast_expr.id);
695
696     walk_cast(rcx, cast_expr, source_ty, target_ty);
697
698     fn walk_cast<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
699                            cast_expr: &ast::Expr,
700                            from_ty: Ty<'tcx>,
701                            to_ty: Ty<'tcx>) {
702         debug!("walk_cast(from_ty={}, to_ty={})",
703                from_ty.repr(rcx.tcx()),
704                to_ty.repr(rcx.tcx()));
705         match (&from_ty.sty, &to_ty.sty) {
706             /*From:*/ (&ty::ty_rptr(from_r, ref from_mt),
707             /*To:  */  &ty::ty_rptr(to_r, ref to_mt)) => {
708                 // Target cannot outlive source, naturally.
709                 rcx.fcx.mk_subr(infer::Reborrow(cast_expr.span), *to_r, *from_r);
710                 walk_cast(rcx, cast_expr, from_mt.ty, to_mt.ty);
711             }
712
713             /*From:*/ (_,
714             /*To:  */  &ty::ty_trait(box ty::TyTrait { ref bounds, .. })) => {
715                 // When T is existentially quantified as a trait
716                 // `Foo+'to`, it must outlive the region bound `'to`.
717                 type_must_outlive(rcx, infer::RelateObjectBound(cast_expr.span),
718                                   from_ty, bounds.region_bound);
719             }
720
721             /*From:*/ (&ty::ty_uniq(from_referent_ty),
722             /*To:  */  &ty::ty_uniq(to_referent_ty)) => {
723                 walk_cast(rcx, cast_expr, from_referent_ty, to_referent_ty);
724             }
725
726             _ => { }
727         }
728     }
729 }
730
731 fn check_expr_fn_block(rcx: &mut Rcx,
732                        expr: &ast::Expr,
733                        body: &ast::Block) {
734     let tcx = rcx.fcx.tcx();
735     let function_type = rcx.resolve_node_type(expr.id);
736
737     match function_type.sty {
738         ty::ty_closure(box ty::ClosureTy{store: ty::RegionTraitStore(..),
739                                          ref bounds,
740                                          ..}) => {
741             // For closure, ensure that the variables outlive region
742             // bound, since they are captured by reference.
743             ty::with_freevars(tcx, expr.id, |freevars| {
744                 if freevars.is_empty() {
745                     // No free variables means that the environment
746                     // will be NULL at runtime and hence the closure
747                     // has static lifetime.
748                 } else {
749                     // Variables being referenced must outlive closure.
750                     constrain_free_variables_in_by_ref_closure(
751                         rcx, bounds.region_bound, expr, freevars);
752
753                     // Closure is stack allocated and hence cannot
754                     // outlive the appropriate temporary scope.
755                     let s = rcx.repeating_scope;
756                     rcx.fcx.mk_subr(infer::InfStackClosure(expr.span),
757                                     bounds.region_bound, ty::ReScope(CodeExtent::from_node_id(s)));
758                 }
759             });
760         }
761         ty::ty_unboxed_closure(_, region, _) => {
762             if tcx.capture_modes.borrow()[expr.id].clone() == ast::CaptureByRef {
763                 ty::with_freevars(tcx, expr.id, |freevars| {
764                     if !freevars.is_empty() {
765                         // Variables being referenced must be constrained and registered
766                         // in the upvar borrow map
767                         constrain_free_variables_in_by_ref_closure(
768                             rcx, *region, expr, freevars);
769                     }
770                 })
771             }
772         }
773         _ => { }
774     }
775
776     let repeating_scope = rcx.set_repeating_scope(body.id);
777     visit::walk_expr(rcx, expr);
778     rcx.set_repeating_scope(repeating_scope);
779
780     match function_type.sty {
781         ty::ty_closure(box ty::ClosureTy {ref bounds, ..}) => {
782             ty::with_freevars(tcx, expr.id, |freevars| {
783                 ensure_free_variable_types_outlive_closure_bound(rcx, bounds, expr, freevars);
784             })
785         }
786         ty::ty_unboxed_closure(_, region, _) => {
787             ty::with_freevars(tcx, expr.id, |freevars| {
788                 let bounds = ty::region_existential_bound(*region);
789                 ensure_free_variable_types_outlive_closure_bound(rcx, &bounds, expr, freevars);
790             })
791         }
792         _ => {}
793     }
794
795     /// Make sure that the type of all free variables referenced inside a closure/proc outlive the
796     /// closure/proc's lifetime bound. This is just a special case of the usual rules about closed
797     /// over values outliving the object's lifetime bound.
798     fn ensure_free_variable_types_outlive_closure_bound(
799         rcx: &mut Rcx,
800         bounds: &ty::ExistentialBounds,
801         expr: &ast::Expr,
802         freevars: &[ty::Freevar])
803     {
804         let tcx = rcx.fcx.ccx.tcx;
805
806         debug!("ensure_free_variable_types_outlive_closure_bound({}, {})",
807                bounds.region_bound.repr(tcx), expr.repr(tcx));
808
809         for freevar in freevars.iter() {
810             let var_node_id = {
811                 let def_id = freevar.def.def_id();
812                 assert!(def_id.krate == ast::LOCAL_CRATE);
813                 def_id.node
814             };
815
816             // Compute the type of the field in the environment that
817             // represents `var_node_id`.  For a by-value closure, this
818             // will be the same as the type of the variable.  For a
819             // by-reference closure, this will be `&T` where `T` is
820             // the type of the variable.
821             let raw_var_ty = rcx.resolve_node_type(var_node_id);
822             let upvar_id = ty::UpvarId { var_id: var_node_id,
823                                          closure_expr_id: expr.id };
824             let var_ty = match rcx.fcx.inh.upvar_borrow_map.borrow().get(&upvar_id) {
825                 Some(upvar_borrow) => {
826                     ty::mk_rptr(rcx.tcx(),
827                                 rcx.tcx().mk_region(upvar_borrow.region),
828                                 ty::mt { mutbl: upvar_borrow.kind.to_mutbl_lossy(),
829                                          ty: raw_var_ty })
830                 }
831                 None => raw_var_ty
832             };
833
834             // Check that the type meets the criteria of the existential bounds:
835             for builtin_bound in bounds.builtin_bounds.iter() {
836                 let code = traits::ClosureCapture(var_node_id, expr.span, builtin_bound);
837                 let cause = traits::ObligationCause::new(freevar.span, rcx.fcx.body_id, code);
838                 rcx.fcx.register_builtin_bound(var_ty, builtin_bound, cause);
839             }
840
841             type_must_outlive(
842                 rcx, infer::FreeVariable(expr.span, var_node_id),
843                 var_ty, bounds.region_bound);
844         }
845     }
846
847     /// Make sure that all free variables referenced inside the closure outlive the closure's
848     /// lifetime bound. Also, create an entry in the upvar_borrows map with a region.
849     fn constrain_free_variables_in_by_ref_closure(
850         rcx: &mut Rcx,
851         region_bound: ty::Region,
852         expr: &ast::Expr,
853         freevars: &[ty::Freevar])
854     {
855         let tcx = rcx.fcx.ccx.tcx;
856         debug!("constrain_free_variables({}, {})",
857                region_bound.repr(tcx), expr.repr(tcx));
858         for freevar in freevars.iter() {
859             debug!("freevar def is {}", freevar.def);
860
861             // Identify the variable being closed over and its node-id.
862             let def = freevar.def;
863             let var_node_id = {
864                 let def_id = def.def_id();
865                 assert!(def_id.krate == ast::LOCAL_CRATE);
866                 def_id.node
867             };
868             let upvar_id = ty::UpvarId { var_id: var_node_id,
869                                          closure_expr_id: expr.id };
870
871             let upvar_borrow = rcx.fcx.inh.upvar_borrow_map.borrow()[upvar_id];
872
873             rcx.fcx.mk_subr(infer::FreeVariable(freevar.span, var_node_id),
874                             region_bound, upvar_borrow.region);
875
876             // Guarantee that the closure does not outlive the variable itself.
877             let enclosing_region = region_of_def(rcx.fcx, def);
878             debug!("enclosing_region = {}", enclosing_region.repr(tcx));
879             rcx.fcx.mk_subr(infer::FreeVariable(freevar.span, var_node_id),
880                             region_bound, enclosing_region);
881         }
882     }
883 }
884
885 fn constrain_callee(rcx: &mut Rcx,
886                     callee_id: ast::NodeId,
887                     call_expr: &ast::Expr,
888                     callee_expr: &ast::Expr) {
889     let call_region = ty::ReScope(CodeExtent::from_node_id(call_expr.id));
890
891     let callee_ty = rcx.resolve_node_type(callee_id);
892     match callee_ty.sty {
893         ty::ty_bare_fn(..) => { }
894         ty::ty_closure(ref closure_ty) => {
895             let region = match closure_ty.store {
896                 ty::RegionTraitStore(r, _) => {
897                     // While we're here, link the closure's region with a unique
898                     // immutable borrow (gathered later in borrowck)
899                     let mc = mc::MemCategorizationContext::new(rcx.fcx);
900                     let expr_cmt = ignore_err!(mc.cat_expr(callee_expr));
901                     link_region(rcx, callee_expr.span, call_region,
902                                 ty::UniqueImmBorrow, expr_cmt);
903                     r
904                 }
905                 ty::UniqTraitStore => ty::ReStatic
906             };
907             rcx.fcx.mk_subr(infer::InvokeClosure(callee_expr.span),
908                             call_region, region);
909
910             let region = closure_ty.bounds.region_bound;
911             rcx.fcx.mk_subr(infer::InvokeClosure(callee_expr.span),
912                             call_region, region);
913         }
914         _ => {
915             // this should not happen, but it does if the program is
916             // erroneous
917             //
918             // tcx.sess.span_bug(
919             //     callee_expr.span,
920             //     format!("Calling non-function: {}", callee_ty.repr(tcx)));
921         }
922     }
923 }
924
925 fn constrain_call<'a, I: Iterator<Item=&'a ast::Expr>>(rcx: &mut Rcx,
926                                                        call_expr: &ast::Expr,
927                                                        receiver: Option<&ast::Expr>,
928                                                        mut arg_exprs: I,
929                                                        implicitly_ref_args: bool) {
930     //! Invoked on every call site (i.e., normal calls, method calls,
931     //! and overloaded operators). Constrains the regions which appear
932     //! in the type of the function. Also constrains the regions that
933     //! appear in the arguments appropriately.
934
935     let tcx = rcx.fcx.tcx();
936     debug!("constrain_call(call_expr={}, \
937             receiver={}, \
938             implicitly_ref_args={})",
939             call_expr.repr(tcx),
940             receiver.repr(tcx),
941             implicitly_ref_args);
942
943     // `callee_region` is the scope representing the time in which the
944     // call occurs.
945     //
946     // FIXME(#6268) to support nested method calls, should be callee_id
947     let callee_scope = CodeExtent::from_node_id(call_expr.id);
948     let callee_region = ty::ReScope(callee_scope);
949
950     debug!("callee_region={}", callee_region.repr(tcx));
951
952     for arg_expr in arg_exprs {
953         debug!("Argument: {}", arg_expr.repr(tcx));
954
955         // ensure that any regions appearing in the argument type are
956         // valid for at least the lifetime of the function:
957         type_of_node_must_outlive(
958             rcx, infer::CallArg(arg_expr.span),
959             arg_expr.id, callee_region);
960
961         // unfortunately, there are two means of taking implicit
962         // references, and we need to propagate constraints as a
963         // result. modes are going away and the "DerefArgs" code
964         // should be ported to use adjustments
965         if implicitly_ref_args {
966             link_by_ref(rcx, arg_expr, callee_scope);
967         }
968     }
969
970     // as loop above, but for receiver
971     for r in receiver.iter() {
972         debug!("receiver: {}", r.repr(tcx));
973         type_of_node_must_outlive(
974             rcx, infer::CallRcvr(r.span),
975             r.id, callee_region);
976         if implicitly_ref_args {
977             link_by_ref(rcx, &**r, callee_scope);
978         }
979     }
980 }
981
982 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
983 /// dereferenced, the lifetime of the pointer includes the deref expr.
984 fn constrain_autoderefs<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
985                                   deref_expr: &ast::Expr,
986                                   derefs: uint,
987                                   mut derefd_ty: Ty<'tcx>) {
988     let r_deref_expr = ty::ReScope(CodeExtent::from_node_id(deref_expr.id));
989     for i in range(0u, derefs) {
990         debug!("constrain_autoderefs(deref_expr=?, derefd_ty={}, derefs={}/{}",
991                rcx.fcx.infcx().ty_to_string(derefd_ty),
992                i, derefs);
993
994         let method_call = MethodCall::autoderef(deref_expr.id, i);
995         derefd_ty = match rcx.fcx.inh.method_map.borrow().get(&method_call) {
996             Some(method) => {
997                 // Treat overloaded autoderefs as if an AutoRef adjustment
998                 // was applied on the base type, as that is always the case.
999                 let fn_sig = ty::ty_fn_sig(method.ty);
1000                 let self_ty = fn_sig.0.inputs[0];
1001                 let (m, r) = match self_ty.sty {
1002                     ty::ty_rptr(r, ref m) => (m.mutbl, r),
1003                     _ => rcx.tcx().sess.span_bug(deref_expr.span,
1004                             format!("bad overloaded deref type {}",
1005                                     method.ty.repr(rcx.tcx()))[])
1006                 };
1007                 {
1008                     let mc = mc::MemCategorizationContext::new(rcx.fcx);
1009                     let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i));
1010                     link_region(rcx, deref_expr.span, *r,
1011                                 ty::BorrowKind::from_mutbl(m), self_cmt);
1012                 }
1013
1014                 // Specialized version of constrain_call.
1015                 type_must_outlive(rcx, infer::CallRcvr(deref_expr.span),
1016                                   self_ty, r_deref_expr);
1017                 match fn_sig.0.output {
1018                     ty::FnConverging(return_type) => {
1019                         type_must_outlive(rcx, infer::CallReturn(deref_expr.span),
1020                                           return_type, r_deref_expr);
1021                         return_type
1022                     }
1023                     ty::FnDiverging => unreachable!()
1024                 }
1025             }
1026             None => derefd_ty
1027         };
1028
1029         if let ty::ty_rptr(r_ptr, _) =  derefd_ty.sty {
1030             mk_subregion_due_to_dereference(rcx, deref_expr.span,
1031                                             r_deref_expr, *r_ptr);
1032         }
1033
1034         match ty::deref(derefd_ty, true) {
1035             Some(mt) => derefd_ty = mt.ty,
1036             /* if this type can't be dereferenced, then there's already an error
1037                in the session saying so. Just bail out for now */
1038             None => break
1039         }
1040     }
1041 }
1042
1043 pub fn mk_subregion_due_to_dereference(rcx: &mut Rcx,
1044                                        deref_span: Span,
1045                                        minimum_lifetime: ty::Region,
1046                                        maximum_lifetime: ty::Region) {
1047     rcx.fcx.mk_subr(infer::DerefPointer(deref_span),
1048                     minimum_lifetime, maximum_lifetime)
1049 }
1050
1051
1052 /// Invoked on any index expression that occurs. Checks that if this is a slice being indexed, the
1053 /// lifetime of the pointer includes the deref expr.
1054 fn constrain_index<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1055                              index_expr: &ast::Expr,
1056                              indexed_ty: Ty<'tcx>)
1057 {
1058     debug!("constrain_index(index_expr=?, indexed_ty={}",
1059            rcx.fcx.infcx().ty_to_string(indexed_ty));
1060
1061     let r_index_expr = ty::ReScope(CodeExtent::from_node_id(index_expr.id));
1062     if let ty::ty_rptr(r_ptr, mt) = indexed_ty.sty {
1063         match mt.ty.sty {
1064             ty::ty_vec(_, None) | ty::ty_str => {
1065                 rcx.fcx.mk_subr(infer::IndexSlice(index_expr.span),
1066                                 r_index_expr, *r_ptr);
1067             }
1068             _ => {}
1069         }
1070     }
1071 }
1072
1073 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1074 /// adjustments) are valid for at least `minimum_lifetime`
1075 fn type_of_node_must_outlive<'a, 'tcx>(
1076     rcx: &mut Rcx<'a, 'tcx>,
1077     origin: infer::SubregionOrigin<'tcx>,
1078     id: ast::NodeId,
1079     minimum_lifetime: ty::Region)
1080 {
1081     let tcx = rcx.fcx.tcx();
1082
1083     // Try to resolve the type.  If we encounter an error, then typeck
1084     // is going to fail anyway, so just stop here and let typeck
1085     // report errors later on in the writeback phase.
1086     let ty0 = rcx.resolve_node_type(id);
1087     let ty = ty::adjust_ty(tcx, origin.span(), id, ty0,
1088                            rcx.fcx.inh.adjustments.borrow().get(&id),
1089                            |method_call| rcx.resolve_method_type(method_call));
1090     debug!("constrain_regions_in_type_of_node(\
1091             ty={}, ty0={}, id={}, minimum_lifetime={})",
1092            ty_to_string(tcx, ty), ty_to_string(tcx, ty0),
1093            id, minimum_lifetime);
1094     type_must_outlive(rcx, origin, ty, minimum_lifetime);
1095 }
1096
1097 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1098 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1099 fn link_addr_of(rcx: &mut Rcx, expr: &ast::Expr,
1100                mutability: ast::Mutability, base: &ast::Expr) {
1101     debug!("link_addr_of(base=?)");
1102
1103     let cmt = {
1104         let mc = mc::MemCategorizationContext::new(rcx.fcx);
1105         ignore_err!(mc.cat_expr(base))
1106     };
1107     link_region_from_node_type(rcx, expr.span, expr.id, mutability, cmt);
1108 }
1109
1110 /// Computes the guarantors for any ref bindings in a `let` and
1111 /// then ensures that the lifetime of the resulting pointer is
1112 /// linked to the lifetime of the initialization expression.
1113 fn link_local(rcx: &Rcx, local: &ast::Local) {
1114     debug!("regionck::for_local()");
1115     let init_expr = match local.init {
1116         None => { return; }
1117         Some(ref expr) => &**expr,
1118     };
1119     let mc = mc::MemCategorizationContext::new(rcx.fcx);
1120     let discr_cmt = ignore_err!(mc.cat_expr(init_expr));
1121     link_pattern(rcx, mc, discr_cmt, &*local.pat);
1122 }
1123
1124 /// Computes the guarantors for any ref bindings in a match and
1125 /// then ensures that the lifetime of the resulting pointer is
1126 /// linked to the lifetime of its guarantor (if any).
1127 fn link_match(rcx: &Rcx, discr: &ast::Expr, arms: &[ast::Arm]) {
1128     debug!("regionck::for_match()");
1129     let mc = mc::MemCategorizationContext::new(rcx.fcx);
1130     let discr_cmt = ignore_err!(mc.cat_expr(discr));
1131     debug!("discr_cmt={}", discr_cmt.repr(rcx.tcx()));
1132     for arm in arms.iter() {
1133         for root_pat in arm.pats.iter() {
1134             link_pattern(rcx, mc, discr_cmt.clone(), &**root_pat);
1135         }
1136     }
1137 }
1138
1139 /// Computes the guarantors for any ref bindings in a match and
1140 /// then ensures that the lifetime of the resulting pointer is
1141 /// linked to the lifetime of its guarantor (if any).
1142 fn link_fn_args(rcx: &Rcx, body_scope: CodeExtent, args: &[ast::Arg]) {
1143     debug!("regionck::link_fn_args(body_scope={})", body_scope);
1144     let mc = mc::MemCategorizationContext::new(rcx.fcx);
1145     for arg in args.iter() {
1146         let arg_ty = rcx.fcx.node_ty(arg.id);
1147         let re_scope = ty::ReScope(body_scope);
1148         let arg_cmt = mc.cat_rvalue(arg.id, arg.ty.span, re_scope, arg_ty);
1149         debug!("arg_ty={} arg_cmt={}",
1150                arg_ty.repr(rcx.tcx()),
1151                arg_cmt.repr(rcx.tcx()));
1152         link_pattern(rcx, mc, arg_cmt, &*arg.pat);
1153     }
1154 }
1155
1156 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found in the discriminant, if
1157 /// needed.
1158 fn link_pattern<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1159                           mc: mc::MemCategorizationContext<FnCtxt<'a, 'tcx>>,
1160                           discr_cmt: mc::cmt<'tcx>,
1161                           root_pat: &ast::Pat) {
1162     debug!("link_pattern(discr_cmt={}, root_pat={})",
1163            discr_cmt.repr(rcx.tcx()),
1164            root_pat.repr(rcx.tcx()));
1165     let _ = mc.cat_pattern(discr_cmt, root_pat, |mc, sub_cmt, sub_pat| {
1166             match sub_pat.node {
1167                 // `ref x` pattern
1168                 ast::PatIdent(ast::BindByRef(mutbl), _, _) => {
1169                     link_region_from_node_type(
1170                         rcx, sub_pat.span, sub_pat.id,
1171                         mutbl, sub_cmt);
1172                 }
1173
1174                 // `[_, ..slice, _]` pattern
1175                 ast::PatVec(_, Some(ref slice_pat), _) => {
1176                     match mc.cat_slice_pattern(sub_cmt, &**slice_pat) {
1177                         Ok((slice_cmt, slice_mutbl, slice_r)) => {
1178                             link_region(rcx, sub_pat.span, slice_r,
1179                                         ty::BorrowKind::from_mutbl(slice_mutbl),
1180                                         slice_cmt);
1181                         }
1182                         Err(()) => {}
1183                     }
1184                 }
1185                 _ => {}
1186             }
1187         });
1188 }
1189
1190 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1191 /// autoref'd.
1192 fn link_autoref(rcx: &Rcx,
1193                 expr: &ast::Expr,
1194                 autoderefs: uint,
1195                 autoref: &ty::AutoRef) {
1196
1197     debug!("link_autoref(autoref={})", autoref);
1198     let mc = mc::MemCategorizationContext::new(rcx.fcx);
1199     let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs));
1200     debug!("expr_cmt={}", expr_cmt.repr(rcx.tcx()));
1201
1202     match *autoref {
1203         ty::AutoPtr(r, m, _) => {
1204             link_region(rcx, expr.span, r,
1205                 ty::BorrowKind::from_mutbl(m), expr_cmt);
1206         }
1207
1208         ty::AutoUnsafe(..) | ty::AutoUnsizeUniq(_) | ty::AutoUnsize(_) => {}
1209     }
1210 }
1211
1212 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1213 /// must outlive `callee_scope`.
1214 fn link_by_ref(rcx: &Rcx,
1215                expr: &ast::Expr,
1216                callee_scope: CodeExtent) {
1217     let tcx = rcx.tcx();
1218     debug!("link_by_ref(expr={}, callee_scope={})",
1219            expr.repr(tcx), callee_scope);
1220     let mc = mc::MemCategorizationContext::new(rcx.fcx);
1221     let expr_cmt = ignore_err!(mc.cat_expr(expr));
1222     let borrow_region = ty::ReScope(callee_scope);
1223     link_region(rcx, expr.span, borrow_region, ty::ImmBorrow, expr_cmt);
1224 }
1225
1226 /// Like `link_region()`, except that the region is extracted from the type of `id`, which must be
1227 /// some reference (`&T`, `&str`, etc).
1228 fn link_region_from_node_type<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1229                                         span: Span,
1230                                         id: ast::NodeId,
1231                                         mutbl: ast::Mutability,
1232                                         cmt_borrowed: mc::cmt<'tcx>) {
1233     let rptr_ty = rcx.resolve_node_type(id);
1234     if !ty::type_is_error(rptr_ty) {
1235         let tcx = rcx.fcx.ccx.tcx;
1236         debug!("rptr_ty={}", ty_to_string(tcx, rptr_ty));
1237         let r = ty::ty_region(tcx, span, rptr_ty);
1238         link_region(rcx, span, r, ty::BorrowKind::from_mutbl(mutbl),
1239                     cmt_borrowed);
1240     }
1241 }
1242
1243 /// Informs the inference engine that `borrow_cmt` is being borrowed with kind `borrow_kind` and
1244 /// lifetime `borrow_region`. In order to ensure borrowck is satisfied, this may create constraints
1245 /// between regions, as explained in `link_reborrowed_region()`.
1246 fn link_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1247                          span: Span,
1248                          borrow_region: ty::Region,
1249                          borrow_kind: ty::BorrowKind,
1250                          borrow_cmt: mc::cmt<'tcx>) {
1251     let mut borrow_cmt = borrow_cmt;
1252     let mut borrow_kind = borrow_kind;
1253
1254     loop {
1255         debug!("link_region(borrow_region={}, borrow_kind={}, borrow_cmt={})",
1256                borrow_region.repr(rcx.tcx()),
1257                borrow_kind.repr(rcx.tcx()),
1258                borrow_cmt.repr(rcx.tcx()));
1259         match borrow_cmt.cat.clone() {
1260             mc::cat_deref(ref_cmt, _,
1261                           mc::Implicit(ref_kind, ref_region)) |
1262             mc::cat_deref(ref_cmt, _,
1263                           mc::BorrowedPtr(ref_kind, ref_region)) => {
1264                 match link_reborrowed_region(rcx, span,
1265                                              borrow_region, borrow_kind,
1266                                              ref_cmt, ref_region, ref_kind,
1267                                              borrow_cmt.note) {
1268                     Some((c, k)) => {
1269                         borrow_cmt = c;
1270                         borrow_kind = k;
1271                     }
1272                     None => {
1273                         return;
1274                     }
1275                 }
1276             }
1277
1278             mc::cat_downcast(cmt_base, _) |
1279             mc::cat_deref(cmt_base, _, mc::Unique) |
1280             mc::cat_interior(cmt_base, _) => {
1281                 // Borrowing interior or owned data requires the base
1282                 // to be valid and borrowable in the same fashion.
1283                 borrow_cmt = cmt_base;
1284                 borrow_kind = borrow_kind;
1285             }
1286
1287             mc::cat_deref(_, _, mc::UnsafePtr(..)) |
1288             mc::cat_static_item |
1289             mc::cat_upvar(..) |
1290             mc::cat_local(..) |
1291             mc::cat_rvalue(..) => {
1292                 // These are all "base cases" with independent lifetimes
1293                 // that are not subject to inference
1294                 return;
1295             }
1296         }
1297     }
1298 }
1299
1300 /// This is the most complicated case: the path being borrowed is
1301 /// itself the referent of a borrowed pointer. Let me give an
1302 /// example fragment of code to make clear(er) the situation:
1303 ///
1304 ///    let r: &'a mut T = ...;  // the original reference "r" has lifetime 'a
1305 ///    ...
1306 ///    &'z *r                   // the reborrow has lifetime 'z
1307 ///
1308 /// Now, in this case, our primary job is to add the inference
1309 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1310 /// parameters in (roughly) terms of the example:
1311 ///
1312 ///     A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1313 ///     borrow_region   ^~                 ref_region    ^~
1314 ///     borrow_kind        ^~               ref_kind        ^~
1315 ///     ref_cmt                 ^
1316 ///
1317 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1318 ///
1319 /// Unfortunately, there are some complications beyond the simple
1320 /// scenario I just painted:
1321 ///
1322 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1323 ///    case, we have two jobs. First, we are inferring whether this reference
1324 ///    should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1325 ///    adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1326 ///    then `r` must be an `&mut` reference). Second, whenever we link
1327 ///    two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1328 ///    case we adjust the cause to indicate that the reference being
1329 ///    "reborrowed" is itself an upvar. This provides a nicer error message
1330 ///    should something go wrong.
1331 ///
1332 /// 2. There may in fact be more levels of reborrowing. In the
1333 ///    example, I said the borrow was like `&'z *r`, but it might
1334 ///    in fact be a borrow like `&'z **q` where `q` has type `&'a
1335 ///    &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1336 ///    and `'z <= 'b`. This is explained more below.
1337 ///
1338 /// The return value of this function indicates whether we need to
1339 /// recurse and process `ref_cmt` (see case 2 above).
1340 fn link_reborrowed_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1341                                     span: Span,
1342                                     borrow_region: ty::Region,
1343                                     borrow_kind: ty::BorrowKind,
1344                                     ref_cmt: mc::cmt<'tcx>,
1345                                     ref_region: ty::Region,
1346                                     mut ref_kind: ty::BorrowKind,
1347                                     note: mc::Note)
1348                                     -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1349 {
1350     // Possible upvar ID we may need later to create an entry in the
1351     // maybe link map.
1352
1353     // Detect by-ref upvar `x`:
1354     let cause = match note {
1355         mc::NoteUpvarRef(ref upvar_id) => {
1356             let mut upvar_borrow_map =
1357                 rcx.fcx.inh.upvar_borrow_map.borrow_mut();
1358             match upvar_borrow_map.get_mut(upvar_id) {
1359                 Some(upvar_borrow) => {
1360                     // The mutability of the upvar may have been modified
1361                     // by the above adjustment, so update our local variable.
1362                     ref_kind = upvar_borrow.kind;
1363
1364                     infer::ReborrowUpvar(span, *upvar_id)
1365                 }
1366                 None => {
1367                     rcx.tcx().sess.span_bug(
1368                         span,
1369                         format!("Illegal upvar id: {}",
1370                                 upvar_id.repr(
1371                                     rcx.tcx()))[]);
1372                 }
1373             }
1374         }
1375         mc::NoteClosureEnv(ref upvar_id) => {
1376             // We don't have any mutability changes to propagate, but
1377             // we do want to note that an upvar reborrow caused this
1378             // link
1379             infer::ReborrowUpvar(span, *upvar_id)
1380         }
1381         _ => {
1382             infer::Reborrow(span)
1383         }
1384     };
1385
1386     debug!("link_reborrowed_region: {} <= {}",
1387            borrow_region.repr(rcx.tcx()),
1388            ref_region.repr(rcx.tcx()));
1389     rcx.fcx.mk_subr(cause, borrow_region, ref_region);
1390
1391     // If we end up needing to recurse and establish a region link
1392     // with `ref_cmt`, calculate what borrow kind we will end up
1393     // needing. This will be used below.
1394     //
1395     // One interesting twist is that we can weaken the borrow kind
1396     // when we recurse: to reborrow an `&mut` referent as mutable,
1397     // borrowck requires a unique path to the `&mut` reference but not
1398     // necessarily a *mutable* path.
1399     let new_borrow_kind = match borrow_kind {
1400         ty::ImmBorrow =>
1401             ty::ImmBorrow,
1402         ty::MutBorrow | ty::UniqueImmBorrow =>
1403             ty::UniqueImmBorrow
1404     };
1405
1406     // Decide whether we need to recurse and link any regions within
1407     // the `ref_cmt`. This is concerned for the case where the value
1408     // being reborrowed is in fact a borrowed pointer found within
1409     // another borrowed pointer. For example:
1410     //
1411     //    let p: &'b &'a mut T = ...;
1412     //    ...
1413     //    &'z **p
1414     //
1415     // What makes this case particularly tricky is that, if the data
1416     // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1417     // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1418     // (otherwise the user might mutate through the `&mut T` reference
1419     // after `'b` expires and invalidate the borrow we are looking at
1420     // now).
1421     //
1422     // So let's re-examine our parameters in light of this more
1423     // complicated (possible) scenario:
1424     //
1425     //     A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1426     //     borrow_region   ^~                 ref_region             ^~
1427     //     borrow_kind        ^~               ref_kind                 ^~
1428     //     ref_cmt                 ^~~
1429     //
1430     // (Note that since we have not examined `ref_cmt.cat`, we don't
1431     // know whether this scenario has occurred; but I wanted to show
1432     // how all the types get adjusted.)
1433     match ref_kind {
1434         ty::ImmBorrow => {
1435             // The reference being reborrowed is a sharable ref of
1436             // type `&'a T`. In this case, it doesn't matter where we
1437             // *found* the `&T` pointer, the memory it references will
1438             // be valid and immutable for `'a`. So we can stop here.
1439             //
1440             // (Note that the `borrow_kind` must also be ImmBorrow or
1441             // else the user is borrowed imm memory as mut memory,
1442             // which means they'll get an error downstream in borrowck
1443             // anyhow.)
1444             return None;
1445         }
1446
1447         ty::MutBorrow | ty::UniqueImmBorrow => {
1448             // The reference being reborrowed is either an `&mut T` or
1449             // `&uniq T`. This is the case where recursion is needed.
1450             return Some((ref_cmt, new_borrow_kind));
1451         }
1452     }
1453 }
1454
1455 /// Ensures that all borrowed data reachable via `ty` outlives `region`.
1456 fn type_must_outlive<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1457                                origin: infer::SubregionOrigin<'tcx>,
1458                                ty: Ty<'tcx>,
1459                                region: ty::Region)
1460 {
1461     debug!("type_must_outlive(ty={}, region={})",
1462            ty.repr(rcx.tcx()),
1463            region.repr(rcx.tcx()));
1464
1465     let constraints =
1466         regionmanip::region_wf_constraints(
1467             rcx.tcx(),
1468             ty,
1469             region);
1470     for constraint in constraints.iter() {
1471         debug!("constraint: {}", constraint.repr(rcx.tcx()));
1472         match *constraint {
1473             regionmanip::RegionSubRegionConstraint(None, r_a, r_b) => {
1474                 rcx.fcx.mk_subr(origin.clone(), r_a, r_b);
1475             }
1476             regionmanip::RegionSubRegionConstraint(Some(ty), r_a, r_b) => {
1477                 let o1 = infer::ReferenceOutlivesReferent(ty, origin.span());
1478                 rcx.fcx.mk_subr(o1, r_a, r_b);
1479             }
1480             regionmanip::RegionSubParamConstraint(None, r_a, param_b) => {
1481                 param_must_outlive(rcx, origin.clone(), r_a, param_b);
1482             }
1483             regionmanip::RegionSubParamConstraint(Some(ty), r_a, param_b) => {
1484                 let o1 = infer::ReferenceOutlivesReferent(ty, origin.span());
1485                 param_must_outlive(rcx, o1, r_a, param_b);
1486             }
1487         }
1488     }
1489 }
1490
1491 fn param_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1492                                 origin: infer::SubregionOrigin<'tcx>,
1493                                 region: ty::Region,
1494                                 param_ty: ty::ParamTy) {
1495     let param_env = &rcx.fcx.inh.param_env;
1496
1497     debug!("param_must_outlive(region={}, param_ty={})",
1498            region.repr(rcx.tcx()),
1499            param_ty.repr(rcx.tcx()));
1500
1501     // To start, collect bounds from user:
1502     let mut param_bounds =
1503         ty::required_region_bounds(rcx.tcx(),
1504                                    param_ty.to_ty(rcx.tcx()),
1505                                    param_env.caller_bounds.predicates.as_slice().to_vec());
1506
1507     // Add in the default bound of fn body that applies to all in
1508     // scope type parameters:
1509     param_bounds.push(param_env.implicit_region_bound);
1510
1511     // Finally, collect regions we scraped from the well-formedness
1512     // constraints in the fn signature. To do that, we walk the list
1513     // of known relations from the fn ctxt.
1514     //
1515     // This is crucial because otherwise code like this fails:
1516     //
1517     //     fn foo<'a, A>(x: &'a A) { x.bar() }
1518     //
1519     // The problem is that the type of `x` is `&'a A`. To be
1520     // well-formed, then, A must be lower-bounded by `'a`, but we
1521     // don't know that this holds from first principles.
1522     for &(ref r, ref p) in rcx.region_param_pairs.iter() {
1523         debug!("param_ty={} p={}",
1524                param_ty.repr(rcx.tcx()),
1525                p.repr(rcx.tcx()));
1526         if param_ty == *p {
1527             param_bounds.push(*r);
1528         }
1529     }
1530
1531     // Inform region inference that this parameter type must be
1532     // properly bounded.
1533     infer::verify_param_bound(rcx.fcx.infcx(),
1534                               origin,
1535                               param_ty,
1536                               region,
1537                               param_bounds);
1538 }