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