]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/regionck.rs
rustc: remove temporary lifetime extension by borrow hint
[rust.git] / src / librustc_typeck / check / regionck.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The region check is a final pass that runs over the AST after we have
12 //! inferred the type constraints but before we have actually finalized
13 //! the types.  Its purpose is to embed a variety of region constraints.
14 //! Inserting these constraints as a separate pass is good because (1) it
15 //! localizes the code that has to do with region inference and (2) often
16 //! we cannot know what constraints are needed until the basic types have
17 //! been inferred.
18 //!
19 //! ### Interaction with the borrow checker
20 //!
21 //! In general, the job of the borrowck module (which runs later) is to
22 //! check that all soundness criteria are met, given a particular set of
23 //! regions. The job of *this* module is to anticipate the needs of the
24 //! borrow checker and infer regions that will satisfy its requirements.
25 //! It is generally true that the inference doesn't need to be sound,
26 //! meaning that if there is a bug and we inferred bad regions, the borrow
27 //! checker should catch it. This is not entirely true though; for
28 //! example, the borrow checker doesn't check subtyping, and it doesn't
29 //! check that region pointers are always live when they are used. It
30 //! might be worthwhile to fix this so that borrowck serves as a kind of
31 //! verification step -- that would add confidence in the overall
32 //! correctness of the compiler, at the cost of duplicating some type
33 //! checks and effort.
34 //!
35 //! ### Inferring the duration of borrows, automatic and otherwise
36 //!
37 //! Whenever we introduce a borrowed pointer, for example as the result of
38 //! a borrow expression `let x = &data`, the lifetime of the pointer `x`
39 //! is always specified as a region inference variable. `regionck` has the
40 //! job of adding constraints such that this inference variable is as
41 //! narrow as possible while still accommodating all uses (that is, every
42 //! dereference of the resulting pointer must be within the lifetime).
43 //!
44 //! #### Reborrows
45 //!
46 //! Generally speaking, `regionck` does NOT try to ensure that the data
47 //! `data` will outlive the pointer `x`. That is the job of borrowck.  The
48 //! one exception is when "re-borrowing" the contents of another borrowed
49 //! pointer. For example, imagine you have a borrowed pointer `b` with
50 //! lifetime L1 and you have an expression `&*b`. The result of this
51 //! expression will be another borrowed pointer with lifetime L2 (which is
52 //! an inference variable). The borrow checker is going to enforce the
53 //! constraint that L2 < L1, because otherwise you are re-borrowing data
54 //! for a lifetime larger than the original loan.  However, without the
55 //! routines in this module, the region inferencer would not know of this
56 //! dependency and thus it might infer the lifetime of L2 to be greater
57 //! than L1 (issue #3148).
58 //!
59 //! There are a number of troublesome scenarios in the tests
60 //! `region-dependent-*.rs`, but here is one example:
61 //!
62 //!     struct Foo { i: i32 }
63 //!     struct Bar { foo: Foo  }
64 //!     fn get_i<'a>(x: &'a Bar) -> &'a i32 {
65 //!        let foo = &x.foo; // Lifetime L1
66 //!        &foo.i            // Lifetime L2
67 //!     }
68 //!
69 //! Note that this comes up either with `&` expressions, `ref`
70 //! bindings, and `autorefs`, which are the three ways to introduce
71 //! a borrow.
72 //!
73 //! The key point here is that when you are borrowing a value that
74 //! is "guaranteed" by a borrowed pointer, you must link the
75 //! lifetime of that borrowed pointer (L1, here) to the lifetime of
76 //! the borrow itself (L2).  What do I mean by "guaranteed" by a
77 //! borrowed pointer? I mean any data that is reached by first
78 //! dereferencing a borrowed pointer and then either traversing
79 //! interior offsets or boxes.  We say that the guarantor
80 //! of such data is the region of the borrowed pointer that was
81 //! traversed.  This is essentially the same as the ownership
82 //! relation, except that a borrowed pointer never owns its
83 //! contents.
84
85 use check::dropck;
86 use check::FnCtxt;
87 use middle::free_region::FreeRegionMap;
88 use middle::mem_categorization as mc;
89 use middle::mem_categorization::Categorization;
90 use middle::region::{CodeExtent, RegionMaps};
91 use rustc::hir::def_id::DefId;
92 use rustc::ty::subst::Substs;
93 use rustc::traits;
94 use rustc::ty::{self, Ty, TypeFoldable};
95 use rustc::infer::{self, GenericKind, SubregionOrigin, VerifyBound};
96 use rustc::ty::adjustment;
97 use rustc::ty::wf::ImpliedBound;
98
99 use std::mem;
100 use std::ops::Deref;
101 use std::rc::Rc;
102 use syntax::ast;
103 use syntax_pos::Span;
104 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
105 use rustc::hir::{self, PatKind};
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 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
116     pub fn regionck_expr(&self, body: &'gcx hir::Body) {
117         let subject = self.tcx.hir.body_owner_def_id(body.id());
118         let id = body.value.id;
119         let mut rcx = RegionCtxt::new(self, RepeatingScope(id), id, Subject(subject));
120         if self.err_count_since_creation() == 0 {
121             // regionck assumes typeck succeeded
122             rcx.visit_body(body);
123             rcx.visit_region_obligations(id);
124         }
125         rcx.resolve_regions_and_report_errors();
126
127         assert!(self.tables.borrow().free_region_map.is_empty());
128         self.tables.borrow_mut().free_region_map = rcx.free_region_map;
129     }
130
131     /// Region checking during the WF phase for items. `wf_tys` are the
132     /// types from which we should derive implied bounds, if any.
133     pub fn regionck_item(&self,
134                          item_id: ast::NodeId,
135                          span: Span,
136                          wf_tys: &[Ty<'tcx>]) {
137         debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys);
138         let subject = self.tcx.hir.local_def_id(item_id);
139         let mut rcx = RegionCtxt::new(self, RepeatingScope(item_id), item_id, Subject(subject));
140         rcx.free_region_map.relate_free_regions_from_predicates(
141             &self.param_env.caller_bounds);
142         rcx.relate_free_regions(wf_tys, item_id, span);
143         rcx.visit_region_obligations(item_id);
144         rcx.resolve_regions_and_report_errors();
145     }
146
147     pub fn regionck_fn(&self,
148                        fn_id: ast::NodeId,
149                        body: &'gcx hir::Body) {
150         debug!("regionck_fn(id={})", fn_id);
151         let subject = self.tcx.hir.body_owner_def_id(body.id());
152         let node_id = body.value.id;
153         let mut rcx = RegionCtxt::new(self, RepeatingScope(node_id), node_id, Subject(subject));
154
155         if self.err_count_since_creation() == 0 {
156             // regionck assumes typeck succeeded
157             rcx.visit_fn_body(fn_id, body, self.tcx.hir.span(fn_id));
158         }
159
160         rcx.free_region_map.relate_free_regions_from_predicates(
161             &self.param_env.caller_bounds);
162
163         rcx.resolve_regions_and_report_errors();
164
165         // In this mode, we also copy the free-region-map into the
166         // tables of the enclosing fcx. In the other regionck modes
167         // (e.g., `regionck_item`), we don't have an enclosing tables.
168         assert!(self.tables.borrow().free_region_map.is_empty());
169         self.tables.borrow_mut().free_region_map = rcx.free_region_map;
170     }
171 }
172
173 ///////////////////////////////////////////////////////////////////////////
174 // INTERNALS
175
176 pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
177     pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
178
179     region_bound_pairs: Vec<(ty::Region<'tcx>, GenericKind<'tcx>)>,
180
181     pub region_maps: Rc<RegionMaps>,
182
183     free_region_map: FreeRegionMap<'tcx>,
184
185     // id of innermost fn body id
186     body_id: ast::NodeId,
187
188     // call_site scope of innermost fn
189     call_site_scope: Option<CodeExtent>,
190
191     // id of innermost fn or loop
192     repeating_scope: ast::NodeId,
193
194     // id of AST node being analyzed (the subject of the analysis).
195     subject_def_id: DefId,
196
197 }
198
199 impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> {
200     type Target = FnCtxt<'a, 'gcx, 'tcx>;
201     fn deref(&self) -> &Self::Target {
202         &self.fcx
203     }
204 }
205
206 pub struct RepeatingScope(ast::NodeId);
207 pub struct Subject(DefId);
208
209 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
210     pub fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
211                RepeatingScope(initial_repeating_scope): RepeatingScope,
212                initial_body_id: ast::NodeId,
213                Subject(subject): Subject) -> RegionCtxt<'a, 'gcx, 'tcx> {
214         let region_maps = fcx.tcx.region_maps(subject);
215         RegionCtxt {
216             fcx: fcx,
217             region_maps: region_maps,
218             repeating_scope: initial_repeating_scope,
219             body_id: initial_body_id,
220             call_site_scope: None,
221             subject_def_id: subject,
222             region_bound_pairs: Vec::new(),
223             free_region_map: FreeRegionMap::new(),
224         }
225     }
226
227     fn set_call_site_scope(&mut self, call_site_scope: Option<CodeExtent>)
228                            -> Option<CodeExtent> {
229         mem::replace(&mut self.call_site_scope, call_site_scope)
230     }
231
232     fn set_body_id(&mut self, body_id: ast::NodeId) -> ast::NodeId {
233         mem::replace(&mut self.body_id, body_id)
234     }
235
236     fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
237         mem::replace(&mut self.repeating_scope, scope)
238     }
239
240     /// Try to resolve the type for the given node, returning t_err if an error results.  Note that
241     /// we never care about the details of the error, the same error will be detected and reported
242     /// in the writeback phase.
243     ///
244     /// Note one important point: we do not attempt to resolve *region variables* here.  This is
245     /// because regionck is essentially adding constraints to those region variables and so may yet
246     /// influence how they are resolved.
247     ///
248     /// Consider this silly example:
249     ///
250     /// ```
251     /// fn borrow(x: &i32) -> &i32 {x}
252     /// fn foo(x: @i32) -> i32 {  // block: B
253     ///     let b = borrow(x);    // region: <R0>
254     ///     *b
255     /// }
256     /// ```
257     ///
258     /// Here, the region of `b` will be `<R0>`.  `<R0>` is constrained to be some subregion of the
259     /// block B and some superregion of the call.  If we forced it now, we'd choose the smaller
260     /// region (the call).  But that would make the *b illegal.  Since we don't resolve, the type
261     /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
262     /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
263     pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
264         self.resolve_type_vars_if_possible(&unresolved_ty)
265     }
266
267     /// Try to resolve the type for the given node.
268     fn resolve_node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
269         let t = self.node_ty(id);
270         self.resolve_type(t)
271     }
272
273     /// Try to resolve the type for the given node.
274     pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> {
275         let ty = self.tables.borrow().expr_ty_adjusted(expr);
276         self.resolve_type(ty)
277     }
278
279     fn visit_fn_body(&mut self,
280                      id: ast::NodeId, // the id of the fn itself
281                      body: &'gcx hir::Body,
282                      span: Span)
283     {
284         // When we enter a function, we can derive
285         debug!("visit_fn_body(id={})", id);
286
287         let body_id = body.id();
288
289         let call_site = CodeExtent::CallSiteScope(body_id);
290         let old_call_site_scope = self.set_call_site_scope(Some(call_site));
291
292         let fn_sig = {
293             let fn_sig_map = &self.tables.borrow().liberated_fn_sigs;
294             match fn_sig_map.get(&id) {
295                 Some(f) => f.clone(),
296                 None => {
297                     bug!("No fn-sig entry for id={}", id);
298                 }
299             }
300         };
301
302         let old_region_bounds_pairs_len = self.region_bound_pairs.len();
303
304         // Collect the types from which we create inferred bounds.
305         // For the return type, if diverging, substitute `bool` just
306         // because it will have no effect.
307         //
308         // FIXME(#27579) return types should not be implied bounds
309         let fn_sig_tys: Vec<_> =
310             fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
311
312         let old_body_id = self.set_body_id(body_id.node_id);
313         self.relate_free_regions(&fn_sig_tys[..], body_id.node_id, span);
314         self.link_fn_args(CodeExtent::Misc(body_id.node_id), &body.arguments);
315         self.visit_body(body);
316         self.visit_region_obligations(body_id.node_id);
317
318         let call_site_scope = self.call_site_scope.unwrap();
319         debug!("visit_fn_body body.id {:?} call_site_scope: {:?}",
320                body.id(), call_site_scope);
321         let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
322         self.type_of_node_must_outlive(infer::CallReturn(span),
323                                        body_id.node_id,
324                                        call_site_region);
325
326         self.region_bound_pairs.truncate(old_region_bounds_pairs_len);
327
328         self.set_body_id(old_body_id);
329         self.set_call_site_scope(old_call_site_scope);
330     }
331
332     fn visit_region_obligations(&mut self, node_id: ast::NodeId)
333     {
334         debug!("visit_region_obligations: node_id={}", node_id);
335
336         // region checking can introduce new pending obligations
337         // which, when processed, might generate new region
338         // obligations. So make sure we process those.
339         self.select_all_obligations_or_error();
340
341         // Make a copy of the region obligations vec because we'll need
342         // to be able to borrow the fulfillment-cx below when projecting.
343         let region_obligations =
344             self.fulfillment_cx
345                 .borrow()
346                 .region_obligations(node_id)
347                 .to_vec();
348
349         for r_o in &region_obligations {
350             debug!("visit_region_obligations: r_o={:?} cause={:?}",
351                    r_o, r_o.cause);
352             let sup_type = self.resolve_type(r_o.sup_type);
353             let origin = self.code_to_origin(&r_o.cause, sup_type);
354             self.type_must_outlive(origin, sup_type, r_o.sub_region);
355         }
356
357         // Processing the region obligations should not cause the list to grow further:
358         assert_eq!(region_obligations.len(),
359                    self.fulfillment_cx.borrow().region_obligations(node_id).len());
360     }
361
362     fn code_to_origin(&self,
363                       cause: &traits::ObligationCause<'tcx>,
364                       sup_type: Ty<'tcx>)
365                       -> SubregionOrigin<'tcx> {
366         SubregionOrigin::from_obligation_cause(cause,
367                                                || infer::RelateParamBound(cause.span, sup_type))
368     }
369
370     /// This method populates the region map's `free_region_map`. It walks over the transformed
371     /// argument and return types for each function just before we check the body of that function,
372     /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
373     /// [usize]`.  We do not allow references to outlive the things they point at, so we can assume
374     /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
375     /// the caller side, the caller is responsible for checking that the type of every expression
376     /// (including the actual values for the arguments, as well as the return type of the fn call)
377     /// is well-formed.
378     ///
379     /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
380     fn relate_free_regions(&mut self,
381                            fn_sig_tys: &[Ty<'tcx>],
382                            body_id: ast::NodeId,
383                            span: Span) {
384         debug!("relate_free_regions >>");
385
386         for &ty in fn_sig_tys {
387             let ty = self.resolve_type(ty);
388             debug!("relate_free_regions(t={:?})", ty);
389             let implied_bounds = ty::wf::implied_bounds(self, body_id, ty, span);
390
391             // Record any relations between free regions that we observe into the free-region-map.
392             self.free_region_map.relate_free_regions_from_implied_bounds(&implied_bounds);
393
394             // But also record other relationships, such as `T:'x`,
395             // that don't go into the free-region-map but which we use
396             // here.
397             for implication in implied_bounds {
398                 debug!("implication: {:?}", implication);
399                 match implication {
400                     ImpliedBound::RegionSubRegion(r_a @ &ty::ReEarlyBound(_),
401                                                   &ty::ReVar(vid_b)) |
402                     ImpliedBound::RegionSubRegion(r_a @ &ty::ReFree(_),
403                                                   &ty::ReVar(vid_b)) => {
404                         self.add_given(r_a, vid_b);
405                     }
406                     ImpliedBound::RegionSubParam(r_a, param_b) => {
407                         self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
408                     }
409                     ImpliedBound::RegionSubProjection(r_a, projection_b) => {
410                         self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
411                     }
412                     ImpliedBound::RegionSubRegion(..) => {
413                         // In principle, we could record (and take
414                         // advantage of) every relationship here, but
415                         // we are also free not to -- it simply means
416                         // strictly less that we can successfully type
417                         // check. (It may also be that we should
418                         // revise our inference system to be more
419                         // general and to make use of *every*
420                         // relationship that arises here, but
421                         // presently we do not.)
422                     }
423                 }
424             }
425         }
426
427         debug!("<< relate_free_regions");
428     }
429
430     fn resolve_regions_and_report_errors(&self) {
431         self.fcx.resolve_regions_and_report_errors(self.subject_def_id,
432                                                    &self.region_maps,
433                                                    &self.free_region_map);
434     }
435
436     fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) {
437         debug!("regionck::visit_pat(pat={:?})", pat);
438         pat.each_binding(|_, id, span, _| {
439             // If we have a variable that contains region'd data, that
440             // data will be accessible from anywhere that the variable is
441             // accessed. We must be wary of loops like this:
442             //
443             //     // from src/test/compile-fail/borrowck-lend-flow.rs
444             //     let mut v = box 3, w = box 4;
445             //     let mut x = &mut w;
446             //     loop {
447             //         **x += 1;   // (2)
448             //         borrow(v);  //~ ERROR cannot borrow
449             //         x = &mut v; // (1)
450             //     }
451             //
452             // Typically, we try to determine the region of a borrow from
453             // those points where it is dereferenced. In this case, one
454             // might imagine that the lifetime of `x` need only be the
455             // body of the loop. But of course this is incorrect because
456             // the pointer that is created at point (1) is consumed at
457             // point (2), meaning that it must be live across the loop
458             // iteration. The easiest way to guarantee this is to require
459             // that the lifetime of any regions that appear in a
460             // variable's type enclose at least the variable's scope.
461
462             let var_scope = self.region_maps.var_scope(id);
463             let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
464
465             let origin = infer::BindingTypeIsNotValidAtDecl(span);
466             self.type_of_node_must_outlive(origin, id, var_region);
467
468             let typ = self.resolve_node_type(id);
469             let _ = dropck::check_safety_of_destructor_if_necessary(
470                 self, typ, span, var_scope);
471         })
472     }
473 }
474
475 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for RegionCtxt<'a, 'gcx, 'tcx> {
476     // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
477     // However, right now we run into an issue whereby some free
478     // regions are not properly related if they appear within the
479     // types of arguments that must be inferred. This could be
480     // addressed by deferring the construction of the region
481     // hierarchy, and in particular the relationships between free
482     // regions, until regionck, as described in #3238.
483
484     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
485         NestedVisitorMap::None
486     }
487
488     fn visit_fn(&mut self, _fk: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
489                 b: hir::BodyId, span: Span, id: ast::NodeId) {
490         let body = self.tcx.hir.body(b);
491         self.visit_fn_body(id, body, span)
492     }
493
494     //visit_pat: visit_pat, // (..) see above
495
496     fn visit_arm(&mut self, arm: &'gcx hir::Arm) {
497         // see above
498         for p in &arm.pats {
499             self.constrain_bindings_in_pat(p);
500         }
501         intravisit::walk_arm(self, arm);
502     }
503
504     fn visit_local(&mut self, l: &'gcx hir::Local) {
505         // see above
506         self.constrain_bindings_in_pat(&l.pat);
507         self.link_local(l);
508         intravisit::walk_local(self, l);
509     }
510
511     fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
512         debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
513                expr, self.repeating_scope);
514
515         // No matter what, the type of each expression must outlive the
516         // scope of that expression. This also guarantees basic WF.
517         let expr_ty = self.resolve_node_type(expr.id);
518         // the region corresponding to this expression
519         let expr_region = self.tcx.node_scope_region(expr.id);
520         self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span),
521                                expr_ty, expr_region);
522
523         let is_method_call = self.tables.borrow().is_method_call(expr);
524
525         // If we are calling a method (either explicitly or via an
526         // overloaded operator), check that all of the types provided as
527         // arguments for its type parameters are well-formed, and all the regions
528         // provided as arguments outlive the call.
529         if is_method_call {
530             let origin = match expr.node {
531                 hir::ExprMethodCall(..) =>
532                     infer::ParameterOrigin::MethodCall,
533                 hir::ExprUnary(op, _) if op == hir::UnDeref =>
534                     infer::ParameterOrigin::OverloadedDeref,
535                 _ =>
536                     infer::ParameterOrigin::OverloadedOperator
537             };
538
539             let substs = self.tables.borrow().node_substs(expr.id);
540             self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
541             // Arguments (sub-expressions) are checked via `constrain_call`, below.
542         }
543
544         // Check any autoderefs or autorefs that appear.
545         let cmt_result = self.constrain_adjustments(expr);
546
547         // If necessary, constrain destructors in this expression. This will be
548         // the adjusted form if there is an adjustment.
549         match cmt_result {
550             Ok(head_cmt) => {
551                 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, expr.span);
552             }
553             Err(..) => {
554                 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
555             }
556         }
557
558         debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
559                expr, self.repeating_scope);
560         match expr.node {
561             hir::ExprPath(_) => {
562                 let substs = self.tables.borrow().node_substs(expr.id);
563                 let origin = infer::ParameterOrigin::Path;
564                 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
565             }
566
567             hir::ExprCall(ref callee, ref args) => {
568                 if is_method_call {
569                     self.constrain_call(expr, Some(&callee), args.iter().map(|e| &*e));
570                 } else {
571                     self.constrain_callee(callee.id, expr, &callee);
572                     self.constrain_call(expr, None, args.iter().map(|e| &*e));
573                 }
574
575                 intravisit::walk_expr(self, expr);
576             }
577
578             hir::ExprMethodCall(.., ref args) => {
579                 self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &*e));
580
581                 intravisit::walk_expr(self, expr);
582             }
583
584             hir::ExprAssignOp(_, ref lhs, ref rhs) => {
585                 if is_method_call {
586                     self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
587                 }
588
589                 intravisit::walk_expr(self, expr);
590             }
591
592             hir::ExprIndex(ref lhs, ref rhs) if is_method_call => {
593                 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
594
595                 intravisit::walk_expr(self, expr);
596             },
597
598             hir::ExprBinary(_, ref lhs, ref rhs) if is_method_call => {
599                 // As `ExprMethodCall`, but the call is via an overloaded op.
600                 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
601
602                 intravisit::walk_expr(self, expr);
603             }
604
605             hir::ExprBinary(_, ref lhs, ref rhs) => {
606                 // If you do `x OP y`, then the types of `x` and `y` must
607                 // outlive the operation you are performing.
608                 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
609                 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
610                 for &ty in &[lhs_ty, rhs_ty] {
611                     self.type_must_outlive(infer::Operand(expr.span),
612                                            ty, expr_region);
613                 }
614                 intravisit::walk_expr(self, expr);
615             }
616
617             hir::ExprUnary(hir::UnDeref, ref base) => {
618                 // For *a, the lifetime of a must enclose the deref
619                 if is_method_call {
620                     self.constrain_call(expr, Some(base), None::<hir::Expr>.iter());
621                 }
622                 // For overloaded derefs, base_ty is the input to `Deref::deref`,
623                 // but it's a reference type uing the same region as the output.
624                 let base_ty = self.resolve_expr_type_adjusted(base);
625                 if let ty::TyRef(r_ptr, _) = base_ty.sty {
626                     self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
627                 }
628
629                 intravisit::walk_expr(self, expr);
630             }
631
632             hir::ExprUnary(_, ref lhs) if is_method_call => {
633                 // As above.
634                 self.constrain_call(expr, Some(&lhs), None::<hir::Expr>.iter());
635
636                 intravisit::walk_expr(self, expr);
637             }
638
639             hir::ExprIndex(ref vec_expr, _) => {
640                 // For a[b], the lifetime of a must enclose the deref
641                 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
642                 self.constrain_index(expr, vec_type);
643
644                 intravisit::walk_expr(self, expr);
645             }
646
647             hir::ExprCast(ref source, _) => {
648                 // Determine if we are casting `source` to a trait
649                 // instance.  If so, we have to be sure that the type of
650                 // the source obeys the trait's region bound.
651                 self.constrain_cast(expr, &source);
652                 intravisit::walk_expr(self, expr);
653             }
654
655             hir::ExprAddrOf(m, ref base) => {
656                 self.link_addr_of(expr, m, &base);
657
658                 // Require that when you write a `&expr` expression, the
659                 // resulting pointer has a lifetime that encompasses the
660                 // `&expr` expression itself. Note that we constraining
661                 // the type of the node expr.id here *before applying
662                 // adjustments*.
663                 //
664                 // FIXME(#6268) nested method calls requires that this rule change
665                 let ty0 = self.resolve_node_type(expr.id);
666                 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
667                 intravisit::walk_expr(self, expr);
668             }
669
670             hir::ExprMatch(ref discr, ref arms, _) => {
671                 self.link_match(&discr, &arms[..]);
672
673                 intravisit::walk_expr(self, expr);
674             }
675
676             hir::ExprClosure(.., body_id, _) => {
677                 self.check_expr_fn_block(expr, body_id);
678             }
679
680             hir::ExprLoop(ref body, _, _) => {
681                 let repeating_scope = self.set_repeating_scope(body.id);
682                 intravisit::walk_expr(self, expr);
683                 self.set_repeating_scope(repeating_scope);
684             }
685
686             hir::ExprWhile(ref cond, ref body, _) => {
687                 let repeating_scope = self.set_repeating_scope(cond.id);
688                 self.visit_expr(&cond);
689
690                 self.set_repeating_scope(body.id);
691                 self.visit_block(&body);
692
693                 self.set_repeating_scope(repeating_scope);
694             }
695
696             hir::ExprRet(Some(ref ret_expr)) => {
697                 let call_site_scope = self.call_site_scope;
698                 debug!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}",
699                        ret_expr.id, call_site_scope);
700                 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
701                 self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span),
702                                                ret_expr.id,
703                                                call_site_region);
704                 intravisit::walk_expr(self, expr);
705             }
706
707             _ => {
708                 intravisit::walk_expr(self, expr);
709             }
710         }
711     }
712 }
713
714 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
715     fn constrain_cast(&mut self,
716                       cast_expr: &hir::Expr,
717                       source_expr: &hir::Expr)
718     {
719         debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
720                cast_expr,
721                source_expr);
722
723         let source_ty = self.resolve_node_type(source_expr.id);
724         let target_ty = self.resolve_node_type(cast_expr.id);
725
726         self.walk_cast(cast_expr, source_ty, target_ty);
727     }
728
729     fn walk_cast(&mut self,
730                  cast_expr: &hir::Expr,
731                  from_ty: Ty<'tcx>,
732                  to_ty: Ty<'tcx>) {
733         debug!("walk_cast(from_ty={:?}, to_ty={:?})",
734                from_ty,
735                to_ty);
736         match (&from_ty.sty, &to_ty.sty) {
737             /*From:*/ (&ty::TyRef(from_r, ref from_mt),
738             /*To:  */  &ty::TyRef(to_r, ref to_mt)) => {
739                 // Target cannot outlive source, naturally.
740                 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
741                 self.walk_cast(cast_expr, from_mt.ty, to_mt.ty);
742             }
743
744             /*From:*/ (_,
745             /*To:  */  &ty::TyDynamic(.., r)) => {
746                 // When T is existentially quantified as a trait
747                 // `Foo+'to`, it must outlive the region bound `'to`.
748                 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
749             }
750
751             /*From:*/ (&ty::TyAdt(from_def, _),
752             /*To:  */  &ty::TyAdt(to_def, _)) if from_def.is_box() && to_def.is_box() => {
753                 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
754             }
755
756             _ => { }
757         }
758     }
759
760     fn check_expr_fn_block(&mut self,
761                            expr: &'gcx hir::Expr,
762                            body_id: hir::BodyId) {
763         let repeating_scope = self.set_repeating_scope(body_id.node_id);
764         intravisit::walk_expr(self, expr);
765         self.set_repeating_scope(repeating_scope);
766     }
767
768     fn constrain_callee(&mut self,
769                         callee_id: ast::NodeId,
770                         _call_expr: &hir::Expr,
771                         _callee_expr: &hir::Expr) {
772         let callee_ty = self.resolve_node_type(callee_id);
773         match callee_ty.sty {
774             ty::TyFnDef(..) | ty::TyFnPtr(_) => { }
775             _ => {
776                 // this should not happen, but it does if the program is
777                 // erroneous
778                 //
779                 // bug!(
780                 //     callee_expr.span,
781                 //     "Calling non-function: {}",
782                 //     callee_ty);
783             }
784         }
785     }
786
787     fn constrain_call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
788                                                            call_expr: &hir::Expr,
789                                                            receiver: Option<&hir::Expr>,
790                                                            arg_exprs: I) {
791         //! Invoked on every call site (i.e., normal calls, method calls,
792         //! and overloaded operators). Constrains the regions which appear
793         //! in the type of the function. Also constrains the regions that
794         //! appear in the arguments appropriately.
795
796         debug!("constrain_call(call_expr={:?}, receiver={:?})",
797                 call_expr,
798                 receiver);
799
800         // `callee_region` is the scope representing the time in which the
801         // call occurs.
802         //
803         // FIXME(#6268) to support nested method calls, should be callee_id
804         let callee_scope = CodeExtent::Misc(call_expr.id);
805         let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
806
807         debug!("callee_region={:?}", callee_region);
808
809         for arg_expr in arg_exprs {
810             debug!("Argument: {:?}", arg_expr);
811
812             // ensure that any regions appearing in the argument type are
813             // valid for at least the lifetime of the function:
814             self.type_of_node_must_outlive(infer::CallArg(arg_expr.span),
815                                            arg_expr.id, callee_region);
816         }
817
818         // as loop above, but for receiver
819         if let Some(r) = receiver {
820             debug!("receiver: {:?}", r);
821             self.type_of_node_must_outlive(infer::CallRcvr(r.span),
822                                            r.id, callee_region);
823         }
824     }
825
826     /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
827     /// dereferenced, the lifetime of the pointer includes the deref expr.
828     fn constrain_adjustments(&mut self, expr: &hir::Expr) -> mc::McResult<mc::cmt<'tcx>> {
829         debug!("constrain_adjustments(expr={:?})", expr);
830
831         let mut cmt = {
832             let mc = mc::MemCategorizationContext::new(self, &self.region_maps);
833             mc.cat_expr_unadjusted(expr)?
834         };
835
836         //NOTE(@jroesch): mixed RefCell borrow causes crash
837         let adjustments = self.tables.borrow().expr_adjustments(&expr).to_vec();
838         if adjustments.is_empty() {
839             return Ok(cmt);
840         }
841
842         debug!("constrain_adjustments: adjustments={:?}", adjustments);
843
844         // If necessary, constrain destructors in the unadjusted form of this
845         // expression.
846         self.check_safety_of_rvalue_destructor_if_necessary(cmt.clone(), expr.span);
847
848         let expr_region = self.tcx.node_scope_region(expr.id);
849         for adjustment in adjustments {
850             debug!("constrain_adjustments: adjustment={:?}, cmt={:?}",
851                    adjustment, cmt);
852
853             if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
854                 debug!("constrain_adjustments: overloaded deref: {:?}", deref);
855
856                 // Treat overloaded autoderefs as if an AutoBorrow adjustment
857                 // was applied on the base type, as that is always the case.
858                 let input = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
859                     ty: cmt.ty,
860                     mutbl: deref.mutbl,
861                 });
862                 let output = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
863                     ty: adjustment.target,
864                     mutbl: deref.mutbl,
865                 });
866
867                 self.link_region(expr.span, deref.region,
868                                  ty::BorrowKind::from_mutbl(deref.mutbl), cmt.clone());
869
870                 // Specialized version of constrain_call.
871                 self.type_must_outlive(infer::CallRcvr(expr.span),
872                                        input, expr_region);
873                 self.type_must_outlive(infer::CallReturn(expr.span),
874                                        output, expr_region);
875             }
876
877             if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
878                 self.link_autoref(expr, cmt.clone(), autoref);
879
880                 // Require that the resulting region encompasses
881                 // the current node.
882                 //
883                 // FIXME(#6268) remove to support nested method calls
884                 self.type_of_node_must_outlive(infer::AutoBorrow(expr.span),
885                                                expr.id, expr_region);
886             }
887
888             {
889                 let mc = mc::MemCategorizationContext::new(self, &self.region_maps);
890                 cmt = mc.cat_expr_adjusted(expr, cmt, &adjustment)?;
891             }
892
893             if let Categorization::Deref(_, mc::BorrowedPtr(_, r_ptr)) = cmt.cat {
894                 self.mk_subregion_due_to_dereference(expr.span,
895                                                      expr_region, r_ptr);
896             }
897         }
898
899         Ok(cmt)
900     }
901
902     pub fn mk_subregion_due_to_dereference(&mut self,
903                                            deref_span: Span,
904                                            minimum_lifetime: ty::Region<'tcx>,
905                                            maximum_lifetime: ty::Region<'tcx>) {
906         self.sub_regions(infer::DerefPointer(deref_span),
907                          minimum_lifetime, maximum_lifetime)
908     }
909
910     fn check_safety_of_rvalue_destructor_if_necessary(&mut self,
911                                                      cmt: mc::cmt<'tcx>,
912                                                      span: Span) {
913         match cmt.cat {
914             Categorization::Rvalue(region) => {
915                 match *region {
916                     ty::ReScope(rvalue_scope) => {
917                         let typ = self.resolve_type(cmt.ty);
918                         let _ = dropck::check_safety_of_destructor_if_necessary(
919                             self, typ, span, rvalue_scope);
920                     }
921                     ty::ReStatic => {}
922                     _ => {
923                         span_bug!(span,
924                                   "unexpected rvalue region in rvalue \
925                                    destructor safety checking: `{:?}`",
926                                   region);
927                     }
928                 }
929             }
930             _ => {}
931         }
932     }
933
934     /// Invoked on any index expression that occurs. Checks that if this is a slice
935     /// being indexed, the lifetime of the pointer includes the deref expr.
936     fn constrain_index(&mut self,
937                        index_expr: &hir::Expr,
938                        indexed_ty: Ty<'tcx>)
939     {
940         debug!("constrain_index(index_expr=?, indexed_ty={}",
941                self.ty_to_string(indexed_ty));
942
943         let r_index_expr = ty::ReScope(CodeExtent::Misc(index_expr.id));
944         if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
945             match mt.ty.sty {
946                 ty::TySlice(_) | ty::TyStr => {
947                     self.sub_regions(infer::IndexSlice(index_expr.span),
948                                      self.tcx.mk_region(r_index_expr), r_ptr);
949                 }
950                 _ => {}
951             }
952         }
953     }
954
955     /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
956     /// adjustments) are valid for at least `minimum_lifetime`
957     fn type_of_node_must_outlive(&mut self,
958         origin: infer::SubregionOrigin<'tcx>,
959         id: ast::NodeId,
960         minimum_lifetime: ty::Region<'tcx>)
961     {
962         // Try to resolve the type.  If we encounter an error, then typeck
963         // is going to fail anyway, so just stop here and let typeck
964         // report errors later on in the writeback phase.
965         let ty0 = self.resolve_node_type(id);
966         let ty = self.tables.borrow().adjustments.get(&id)
967             .and_then(|adj| adj.last())
968             .map_or(ty0, |adj| adj.target);
969         let ty = self.resolve_type(ty);
970         debug!("constrain_regions_in_type_of_node(\
971                 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
972                 ty,  ty0,
973                id, minimum_lifetime);
974         self.type_must_outlive(origin, ty, minimum_lifetime);
975     }
976
977     /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
978     /// resulting pointer is linked to the lifetime of its guarantor (if any).
979     fn link_addr_of(&mut self, expr: &hir::Expr,
980                     mutability: hir::Mutability, base: &hir::Expr) {
981         debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
982
983         let cmt = {
984             let mc = mc::MemCategorizationContext::new(self, &self.region_maps);
985             ignore_err!(mc.cat_expr(base))
986         };
987
988         debug!("link_addr_of: cmt={:?}", cmt);
989
990         self.link_region_from_node_type(expr.span, expr.id, mutability, cmt);
991     }
992
993     /// Computes the guarantors for any ref bindings in a `let` and
994     /// then ensures that the lifetime of the resulting pointer is
995     /// linked to the lifetime of the initialization expression.
996     fn link_local(&self, local: &hir::Local) {
997         debug!("regionck::for_local()");
998         let init_expr = match local.init {
999             None => { return; }
1000             Some(ref expr) => &**expr,
1001         };
1002         let mc = &mc::MemCategorizationContext::new(self, &self.region_maps);
1003         let discr_cmt = ignore_err!(mc.cat_expr(init_expr));
1004         self.link_pattern(mc, discr_cmt, &local.pat);
1005     }
1006
1007     /// Computes the guarantors for any ref bindings in a match and
1008     /// then ensures that the lifetime of the resulting pointer is
1009     /// linked to the lifetime of its guarantor (if any).
1010     fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) {
1011         debug!("regionck::for_match()");
1012         let mc = &mc::MemCategorizationContext::new(self, &self.region_maps);
1013         let discr_cmt = ignore_err!(mc.cat_expr(discr));
1014         debug!("discr_cmt={:?}", discr_cmt);
1015         for arm in arms {
1016             for root_pat in &arm.pats {
1017                 self.link_pattern(mc, discr_cmt.clone(), &root_pat);
1018             }
1019         }
1020     }
1021
1022     /// Computes the guarantors for any ref bindings in a match and
1023     /// then ensures that the lifetime of the resulting pointer is
1024     /// linked to the lifetime of its guarantor (if any).
1025     fn link_fn_args(&self, body_scope: CodeExtent, args: &[hir::Arg]) {
1026         debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1027         let mc = &mc::MemCategorizationContext::new(self, &self.region_maps);
1028         for arg in args {
1029             let arg_ty = self.node_ty(arg.id);
1030             let re_scope = self.tcx.mk_region(ty::ReScope(body_scope));
1031             let arg_cmt = mc.cat_rvalue(
1032                 arg.id, arg.pat.span, re_scope, arg_ty);
1033             debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1034                    arg_ty,
1035                    arg_cmt,
1036                    arg);
1037             self.link_pattern(mc, arg_cmt, &arg.pat);
1038         }
1039     }
1040
1041     /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1042     /// in the discriminant, if needed.
1043     fn link_pattern<'t>(&self,
1044                         mc: &mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
1045                         discr_cmt: mc::cmt<'tcx>,
1046                         root_pat: &hir::Pat) {
1047         debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1048                discr_cmt,
1049                root_pat);
1050         let _ = mc.cat_pattern(discr_cmt, root_pat, |_, sub_cmt, sub_pat| {
1051                 match sub_pat.node {
1052                     // `ref x` pattern
1053                     PatKind::Binding(hir::BindByRef(mutbl), ..) => {
1054                         self.link_region_from_node_type(sub_pat.span, sub_pat.id,
1055                                                         mutbl, sub_cmt);
1056                     }
1057                     _ => {}
1058                 }
1059             });
1060     }
1061
1062     /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1063     /// autoref'd.
1064     fn link_autoref(&self,
1065                     expr: &hir::Expr,
1066                     expr_cmt: mc::cmt<'tcx>,
1067                     autoref: &adjustment::AutoBorrow<'tcx>)
1068     {
1069         debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
1070
1071         match *autoref {
1072             adjustment::AutoBorrow::Ref(r, m) => {
1073                 self.link_region(expr.span, r,
1074                                  ty::BorrowKind::from_mutbl(m), expr_cmt);
1075             }
1076
1077             adjustment::AutoBorrow::RawPtr(m) => {
1078                 let r = self.tcx.node_scope_region(expr.id);
1079                 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1080             }
1081         }
1082     }
1083
1084     /// Like `link_region()`, except that the region is extracted from the type of `id`,
1085     /// which must be some reference (`&T`, `&str`, etc).
1086     fn link_region_from_node_type(&self,
1087                                   span: Span,
1088                                   id: ast::NodeId,
1089                                   mutbl: hir::Mutability,
1090                                   cmt_borrowed: mc::cmt<'tcx>) {
1091         debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1092                id, mutbl, cmt_borrowed);
1093
1094         let rptr_ty = self.resolve_node_type(id);
1095         if let ty::TyRef(r, _) = rptr_ty.sty {
1096             debug!("rptr_ty={}",  rptr_ty);
1097             self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl),
1098                              cmt_borrowed);
1099         }
1100     }
1101
1102     /// Informs the inference engine that `borrow_cmt` is being borrowed with
1103     /// kind `borrow_kind` and lifetime `borrow_region`.
1104     /// In order to ensure borrowck is satisfied, this may create constraints
1105     /// between regions, as explained in `link_reborrowed_region()`.
1106     fn link_region(&self,
1107                    span: Span,
1108                    borrow_region: ty::Region<'tcx>,
1109                    borrow_kind: ty::BorrowKind,
1110                    borrow_cmt: mc::cmt<'tcx>) {
1111         let mut borrow_cmt = borrow_cmt;
1112         let mut borrow_kind = borrow_kind;
1113
1114         let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1115         self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
1116
1117         loop {
1118             debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1119                    borrow_region,
1120                    borrow_kind,
1121                    borrow_cmt);
1122             match borrow_cmt.cat.clone() {
1123                 Categorization::Deref(ref_cmt, mc::Implicit(ref_kind, ref_region)) |
1124                 Categorization::Deref(ref_cmt, mc::BorrowedPtr(ref_kind, ref_region)) => {
1125                     match self.link_reborrowed_region(span,
1126                                                       borrow_region, borrow_kind,
1127                                                       ref_cmt, ref_region, ref_kind,
1128                                                       borrow_cmt.note) {
1129                         Some((c, k)) => {
1130                             borrow_cmt = c;
1131                             borrow_kind = k;
1132                         }
1133                         None => {
1134                             return;
1135                         }
1136                     }
1137                 }
1138
1139                 Categorization::Downcast(cmt_base, _) |
1140                 Categorization::Deref(cmt_base, mc::Unique) |
1141                 Categorization::Interior(cmt_base, _) => {
1142                     // Borrowing interior or owned data requires the base
1143                     // to be valid and borrowable in the same fashion.
1144                     borrow_cmt = cmt_base;
1145                     borrow_kind = borrow_kind;
1146                 }
1147
1148                 Categorization::Deref(_, mc::UnsafePtr(..)) |
1149                 Categorization::StaticItem |
1150                 Categorization::Upvar(..) |
1151                 Categorization::Local(..) |
1152                 Categorization::Rvalue(..) => {
1153                     // These are all "base cases" with independent lifetimes
1154                     // that are not subject to inference
1155                     return;
1156                 }
1157             }
1158         }
1159     }
1160
1161     /// This is the most complicated case: the path being borrowed is
1162     /// itself the referent of a borrowed pointer. Let me give an
1163     /// example fragment of code to make clear(er) the situation:
1164     ///
1165     ///    let r: &'a mut T = ...;  // the original reference "r" has lifetime 'a
1166     ///    ...
1167     ///    &'z *r                   // the reborrow has lifetime 'z
1168     ///
1169     /// Now, in this case, our primary job is to add the inference
1170     /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1171     /// parameters in (roughly) terms of the example:
1172     ///
1173     ///     A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1174     ///     borrow_region   ^~                 ref_region    ^~
1175     ///     borrow_kind        ^~               ref_kind        ^~
1176     ///     ref_cmt                 ^
1177     ///
1178     /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1179     ///
1180     /// Unfortunately, there are some complications beyond the simple
1181     /// scenario I just painted:
1182     ///
1183     /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1184     ///    case, we have two jobs. First, we are inferring whether this reference
1185     ///    should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1186     ///    adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1187     ///    then `r` must be an `&mut` reference). Second, whenever we link
1188     ///    two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1189     ///    case we adjust the cause to indicate that the reference being
1190     ///    "reborrowed" is itself an upvar. This provides a nicer error message
1191     ///    should something go wrong.
1192     ///
1193     /// 2. There may in fact be more levels of reborrowing. In the
1194     ///    example, I said the borrow was like `&'z *r`, but it might
1195     ///    in fact be a borrow like `&'z **q` where `q` has type `&'a
1196     ///    &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1197     ///    and `'z <= 'b`. This is explained more below.
1198     ///
1199     /// The return value of this function indicates whether we need to
1200     /// recurse and process `ref_cmt` (see case 2 above).
1201     fn link_reborrowed_region(&self,
1202                               span: Span,
1203                               borrow_region: ty::Region<'tcx>,
1204                               borrow_kind: ty::BorrowKind,
1205                               ref_cmt: mc::cmt<'tcx>,
1206                               ref_region: ty::Region<'tcx>,
1207                               mut ref_kind: ty::BorrowKind,
1208                               note: mc::Note)
1209                               -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1210     {
1211         // Possible upvar ID we may need later to create an entry in the
1212         // maybe link map.
1213
1214         // Detect by-ref upvar `x`:
1215         let cause = match note {
1216             mc::NoteUpvarRef(ref upvar_id) => {
1217                 let upvar_capture_map = &self.tables.borrow_mut().upvar_capture_map;
1218                 match upvar_capture_map.get(upvar_id) {
1219                     Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1220                         // The mutability of the upvar may have been modified
1221                         // by the above adjustment, so update our local variable.
1222                         ref_kind = upvar_borrow.kind;
1223
1224                         infer::ReborrowUpvar(span, *upvar_id)
1225                     }
1226                     _ => {
1227                         span_bug!( span, "Illegal upvar id: {:?}", upvar_id);
1228                     }
1229                 }
1230             }
1231             mc::NoteClosureEnv(ref upvar_id) => {
1232                 // We don't have any mutability changes to propagate, but
1233                 // we do want to note that an upvar reborrow caused this
1234                 // link
1235                 infer::ReborrowUpvar(span, *upvar_id)
1236             }
1237             _ => {
1238                 infer::Reborrow(span)
1239             }
1240         };
1241
1242         debug!("link_reborrowed_region: {:?} <= {:?}",
1243                borrow_region,
1244                ref_region);
1245         self.sub_regions(cause, borrow_region, ref_region);
1246
1247         // If we end up needing to recurse and establish a region link
1248         // with `ref_cmt`, calculate what borrow kind we will end up
1249         // needing. This will be used below.
1250         //
1251         // One interesting twist is that we can weaken the borrow kind
1252         // when we recurse: to reborrow an `&mut` referent as mutable,
1253         // borrowck requires a unique path to the `&mut` reference but not
1254         // necessarily a *mutable* path.
1255         let new_borrow_kind = match borrow_kind {
1256             ty::ImmBorrow =>
1257                 ty::ImmBorrow,
1258             ty::MutBorrow | ty::UniqueImmBorrow =>
1259                 ty::UniqueImmBorrow
1260         };
1261
1262         // Decide whether we need to recurse and link any regions within
1263         // the `ref_cmt`. This is concerned for the case where the value
1264         // being reborrowed is in fact a borrowed pointer found within
1265         // another borrowed pointer. For example:
1266         //
1267         //    let p: &'b &'a mut T = ...;
1268         //    ...
1269         //    &'z **p
1270         //
1271         // What makes this case particularly tricky is that, if the data
1272         // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1273         // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1274         // (otherwise the user might mutate through the `&mut T` reference
1275         // after `'b` expires and invalidate the borrow we are looking at
1276         // now).
1277         //
1278         // So let's re-examine our parameters in light of this more
1279         // complicated (possible) scenario:
1280         //
1281         //     A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1282         //     borrow_region   ^~                 ref_region             ^~
1283         //     borrow_kind        ^~               ref_kind                 ^~
1284         //     ref_cmt                 ^~~
1285         //
1286         // (Note that since we have not examined `ref_cmt.cat`, we don't
1287         // know whether this scenario has occurred; but I wanted to show
1288         // how all the types get adjusted.)
1289         match ref_kind {
1290             ty::ImmBorrow => {
1291                 // The reference being reborrowed is a sharable ref of
1292                 // type `&'a T`. In this case, it doesn't matter where we
1293                 // *found* the `&T` pointer, the memory it references will
1294                 // be valid and immutable for `'a`. So we can stop here.
1295                 //
1296                 // (Note that the `borrow_kind` must also be ImmBorrow or
1297                 // else the user is borrowed imm memory as mut memory,
1298                 // which means they'll get an error downstream in borrowck
1299                 // anyhow.)
1300                 return None;
1301             }
1302
1303             ty::MutBorrow | ty::UniqueImmBorrow => {
1304                 // The reference being reborrowed is either an `&mut T` or
1305                 // `&uniq T`. This is the case where recursion is needed.
1306                 return Some((ref_cmt, new_borrow_kind));
1307             }
1308         }
1309     }
1310
1311     /// Checks that the values provided for type/region arguments in a given
1312     /// expression are well-formed and in-scope.
1313     fn substs_wf_in_scope(&mut self,
1314                           origin: infer::ParameterOrigin,
1315                           substs: &Substs<'tcx>,
1316                           expr_span: Span,
1317                           expr_region: ty::Region<'tcx>) {
1318         debug!("substs_wf_in_scope(substs={:?}, \
1319                 expr_region={:?}, \
1320                 origin={:?}, \
1321                 expr_span={:?})",
1322                substs, expr_region, origin, expr_span);
1323
1324         let origin = infer::ParameterInScope(origin, expr_span);
1325
1326         for region in substs.regions() {
1327             self.sub_regions(origin.clone(), expr_region, region);
1328         }
1329
1330         for ty in substs.types() {
1331             let ty = self.resolve_type(ty);
1332             self.type_must_outlive(origin.clone(), ty, expr_region);
1333         }
1334     }
1335
1336     /// Ensures that type is well-formed in `region`, which implies (among
1337     /// other things) that all borrowed data reachable via `ty` outlives
1338     /// `region`.
1339     pub fn type_must_outlive(&self,
1340                              origin: infer::SubregionOrigin<'tcx>,
1341                              ty: Ty<'tcx>,
1342                              region: ty::Region<'tcx>)
1343     {
1344         let ty = self.resolve_type(ty);
1345
1346         debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1347                ty,
1348                region,
1349                origin);
1350
1351         assert!(!ty.has_escaping_regions());
1352
1353         let components = self.tcx.outlives_components(ty);
1354         self.components_must_outlive(origin, components, region);
1355     }
1356
1357     fn components_must_outlive(&self,
1358                                origin: infer::SubregionOrigin<'tcx>,
1359                                components: Vec<ty::outlives::Component<'tcx>>,
1360                                region: ty::Region<'tcx>)
1361     {
1362         for component in components {
1363             let origin = origin.clone();
1364             match component {
1365                 ty::outlives::Component::Region(region1) => {
1366                     self.sub_regions(origin, region, region1);
1367                 }
1368                 ty::outlives::Component::Param(param_ty) => {
1369                     self.param_ty_must_outlive(origin, region, param_ty);
1370                 }
1371                 ty::outlives::Component::Projection(projection_ty) => {
1372                     self.projection_must_outlive(origin, region, projection_ty);
1373                 }
1374                 ty::outlives::Component::EscapingProjection(subcomponents) => {
1375                     self.components_must_outlive(origin, subcomponents, region);
1376                 }
1377                 ty::outlives::Component::UnresolvedInferenceVariable(v) => {
1378                     // ignore this, we presume it will yield an error
1379                     // later, since if a type variable is not resolved by
1380                     // this point it never will be
1381                     self.tcx.sess.delay_span_bug(
1382                         origin.span(),
1383                         &format!("unresolved inference variable in outlives: {:?}", v));
1384                 }
1385             }
1386         }
1387     }
1388
1389     fn param_ty_must_outlive(&self,
1390                              origin: infer::SubregionOrigin<'tcx>,
1391                              region: ty::Region<'tcx>,
1392                              param_ty: ty::ParamTy) {
1393         debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1394                region, param_ty, origin);
1395
1396         let verify_bound = self.param_bound(param_ty);
1397         let generic = GenericKind::Param(param_ty);
1398         self.verify_generic_bound(origin, generic, region, verify_bound);
1399     }
1400
1401     fn projection_must_outlive(&self,
1402                                origin: infer::SubregionOrigin<'tcx>,
1403                                region: ty::Region<'tcx>,
1404                                projection_ty: ty::ProjectionTy<'tcx>)
1405     {
1406         debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1407                region, projection_ty, origin);
1408
1409         // This case is thorny for inference. The fundamental problem is
1410         // that there are many cases where we have choice, and inference
1411         // doesn't like choice (the current region inference in
1412         // particular). :) First off, we have to choose between using the
1413         // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1414         // OutlivesProjectionComponent rules, any one of which is
1415         // sufficient.  If there are no inference variables involved, it's
1416         // not hard to pick the right rule, but if there are, we're in a
1417         // bit of a catch 22: if we picked which rule we were going to
1418         // use, we could add constraints to the region inference graph
1419         // that make it apply, but if we don't add those constraints, the
1420         // rule might not apply (but another rule might). For now, we err
1421         // on the side of adding too few edges into the graph.
1422
1423         // Compute the bounds we can derive from the environment or trait
1424         // definition.  We know that the projection outlives all the
1425         // regions in this list.
1426         let env_bounds = self.projection_declared_bounds(origin.span(), projection_ty);
1427
1428         debug!("projection_must_outlive: env_bounds={:?}",
1429                env_bounds);
1430
1431         // If we know that the projection outlives 'static, then we're
1432         // done here.
1433         if env_bounds.contains(&&ty::ReStatic) {
1434             debug!("projection_must_outlive: 'static as declared bound");
1435             return;
1436         }
1437
1438         // If declared bounds list is empty, the only applicable rule is
1439         // OutlivesProjectionComponent. If there are inference variables,
1440         // then, we can break down the outlives into more primitive
1441         // components without adding unnecessary edges.
1442         //
1443         // If there are *no* inference variables, however, we COULD do
1444         // this, but we choose not to, because the error messages are less
1445         // good. For example, a requirement like `T::Item: 'r` would be
1446         // translated to a requirement that `T: 'r`; when this is reported
1447         // to the user, it will thus say "T: 'r must hold so that T::Item:
1448         // 'r holds". But that makes it sound like the only way to fix
1449         // the problem is to add `T: 'r`, which isn't true. So, if there are no
1450         // inference variables, we use a verify constraint instead of adding
1451         // edges, which winds up enforcing the same condition.
1452         let needs_infer = projection_ty.trait_ref.needs_infer();
1453         if env_bounds.is_empty() && needs_infer {
1454             debug!("projection_must_outlive: no declared bounds");
1455
1456             for component_ty in projection_ty.trait_ref.substs.types() {
1457                 self.type_must_outlive(origin.clone(), component_ty, region);
1458             }
1459
1460             for r in projection_ty.trait_ref.substs.regions() {
1461                 self.sub_regions(origin.clone(), region, r);
1462             }
1463
1464             return;
1465         }
1466
1467         // If we find that there is a unique declared bound `'b`, and this bound
1468         // appears in the trait reference, then the best action is to require that `'b:'r`,
1469         // so do that. This is best no matter what rule we use:
1470         //
1471         // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1472         // the requirement that `'b:'r`
1473         // - OutlivesProjectionComponent: this would require `'b:'r` in addition to
1474         // other conditions
1475         if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1476             let unique_bound = env_bounds[0];
1477             debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
1478             if projection_ty.trait_ref.substs.regions().any(|r| env_bounds.contains(&r)) {
1479                 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1480                 self.sub_regions(origin.clone(), region, unique_bound);
1481                 return;
1482             }
1483         }
1484
1485         // Fallback to verifying after the fact that there exists a
1486         // declared bound, or that all the components appearing in the
1487         // projection outlive; in some cases, this may add insufficient
1488         // edges into the inference graph, leading to inference failures
1489         // even though a satisfactory solution exists.
1490         let verify_bound = self.projection_bound(origin.span(), env_bounds, projection_ty);
1491         let generic = GenericKind::Projection(projection_ty);
1492         self.verify_generic_bound(origin, generic.clone(), region, verify_bound);
1493     }
1494
1495     fn type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1496         match ty.sty {
1497             ty::TyParam(p) => {
1498                 self.param_bound(p)
1499             }
1500             ty::TyProjection(data) => {
1501                 let declared_bounds = self.projection_declared_bounds(span, data);
1502                 self.projection_bound(span, declared_bounds, data)
1503             }
1504             _ => {
1505                 self.recursive_type_bound(span, ty)
1506             }
1507         }
1508     }
1509
1510     fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound<'tcx> {
1511         debug!("param_bound(param_ty={:?})",
1512                param_ty);
1513
1514         let mut param_bounds = self.declared_generic_bounds_from_env(GenericKind::Param(param_ty));
1515
1516         // Add in the default bound of fn body that applies to all in
1517         // scope type parameters:
1518         param_bounds.extend(self.implicit_region_bound);
1519
1520         VerifyBound::AnyRegion(param_bounds)
1521     }
1522
1523     fn projection_declared_bounds(&self,
1524                                   span: Span,
1525                                   projection_ty: ty::ProjectionTy<'tcx>)
1526                                   -> Vec<ty::Region<'tcx>>
1527     {
1528         // First assemble bounds from where clauses and traits.
1529
1530         let mut declared_bounds =
1531             self.declared_generic_bounds_from_env(GenericKind::Projection(projection_ty));
1532
1533         declared_bounds.extend_from_slice(
1534             &self.declared_projection_bounds_from_trait(span, projection_ty));
1535
1536         declared_bounds
1537     }
1538
1539     fn projection_bound(&self,
1540                         span: Span,
1541                         declared_bounds: Vec<ty::Region<'tcx>>,
1542                         projection_ty: ty::ProjectionTy<'tcx>)
1543                         -> VerifyBound<'tcx> {
1544         debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1545                declared_bounds, projection_ty);
1546
1547         // see the extensive comment in projection_must_outlive
1548         let item_name = projection_ty.item_name(self.tcx);
1549         let ty = self.tcx.mk_projection(projection_ty.trait_ref, item_name);
1550         let recursive_bound = self.recursive_type_bound(span, ty);
1551
1552         VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1553     }
1554
1555     fn recursive_type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1556         let mut bounds = vec![];
1557
1558         for subty in ty.walk_shallow() {
1559             bounds.push(self.type_bound(span, subty));
1560         }
1561
1562         let mut regions = ty.regions();
1563         regions.retain(|r| !r.is_late_bound()); // ignore late-bound regions
1564         bounds.push(VerifyBound::AllRegions(regions));
1565
1566         // remove bounds that must hold, since they are not interesting
1567         bounds.retain(|b| !b.must_hold());
1568
1569         if bounds.len() == 1 {
1570             bounds.pop().unwrap()
1571         } else {
1572             VerifyBound::AllBounds(bounds)
1573         }
1574     }
1575
1576     fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>)
1577                                         -> Vec<ty::Region<'tcx>>
1578     {
1579         let param_env = &self.param_env;
1580
1581         // To start, collect bounds from user:
1582         let mut param_bounds = self.tcx.required_region_bounds(generic.to_ty(self.tcx),
1583                                                                param_env.caller_bounds.to_vec());
1584
1585         // Next, collect regions we scraped from the well-formedness
1586         // constraints in the fn signature. To do that, we walk the list
1587         // of known relations from the fn ctxt.
1588         //
1589         // This is crucial because otherwise code like this fails:
1590         //
1591         //     fn foo<'a, A>(x: &'a A) { x.bar() }
1592         //
1593         // The problem is that the type of `x` is `&'a A`. To be
1594         // well-formed, then, A must be lower-generic by `'a`, but we
1595         // don't know that this holds from first principles.
1596         for &(r, p) in &self.region_bound_pairs {
1597             debug!("generic={:?} p={:?}",
1598                    generic,
1599                    p);
1600             if generic == p {
1601                 param_bounds.push(r);
1602             }
1603         }
1604
1605         param_bounds
1606     }
1607
1608     fn declared_projection_bounds_from_trait(&self,
1609                                              span: Span,
1610                                              projection_ty: ty::ProjectionTy<'tcx>)
1611                                              -> Vec<ty::Region<'tcx>>
1612     {
1613         debug!("projection_bounds(projection_ty={:?})",
1614                projection_ty);
1615         let item_name = projection_ty.item_name(self.tcx);
1616         let ty = self.tcx.mk_projection(projection_ty.trait_ref.clone(),
1617                                         item_name);
1618
1619         // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1620         // in looking for a trait definition like:
1621         //
1622         // ```
1623         // trait SomeTrait<'a> {
1624         //     type SomeType : 'a;
1625         // }
1626         // ```
1627         //
1628         // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1629         let trait_predicates = self.tcx.predicates_of(projection_ty.trait_ref.def_id);
1630         assert_eq!(trait_predicates.parent, None);
1631         let predicates = trait_predicates.predicates.as_slice().to_vec();
1632         traits::elaborate_predicates(self.tcx, predicates)
1633             .filter_map(|predicate| {
1634                 // we're only interesting in `T : 'a` style predicates:
1635                 let outlives = match predicate {
1636                     ty::Predicate::TypeOutlives(data) => data,
1637                     _ => { return None; }
1638                 };
1639
1640                 debug!("projection_bounds: outlives={:?} (1)",
1641                        outlives);
1642
1643                 // apply the substitutions (and normalize any projected types)
1644                 let outlives = self.instantiate_type_scheme(span,
1645                                                             projection_ty.trait_ref.substs,
1646                                                             &outlives);
1647
1648                 debug!("projection_bounds: outlives={:?} (2)",
1649                        outlives);
1650
1651                 let region_result = self.commit_if_ok(|_| {
1652                     let (outlives, _) =
1653                         self.replace_late_bound_regions_with_fresh_var(
1654                             span,
1655                             infer::AssocTypeProjection(projection_ty.item_name(self.tcx)),
1656                             &outlives);
1657
1658                     debug!("projection_bounds: outlives={:?} (3)",
1659                            outlives);
1660
1661                     // check whether this predicate applies to our current projection
1662                     let cause = self.fcx.misc(span);
1663                     match self.eq_types(false, &cause, ty, outlives.0) {
1664                         Ok(ok) => {
1665                             self.register_infer_ok_obligations(ok);
1666                             Ok(outlives.1)
1667                         }
1668                         Err(_) => { Err(()) }
1669                     }
1670                 });
1671
1672                 debug!("projection_bounds: region_result={:?}",
1673                        region_result);
1674
1675                 region_result.ok()
1676             })
1677             .collect()
1678     }
1679 }