]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/regionck.rs
rustc: do not depend on infcx.tables in MemCategorizationContext.
[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 =
390                 ty::wf::implied_bounds(self, self.fcx.param_env, body_id, ty, span);
391
392             // Record any relations between free regions that we observe into the free-region-map.
393             self.free_region_map.relate_free_regions_from_implied_bounds(&implied_bounds);
394
395             // But also record other relationships, such as `T:'x`,
396             // that don't go into the free-region-map but which we use
397             // here.
398             for implication in implied_bounds {
399                 debug!("implication: {:?}", implication);
400                 match implication {
401                     ImpliedBound::RegionSubRegion(r_a @ &ty::ReEarlyBound(_),
402                                                   &ty::ReVar(vid_b)) |
403                     ImpliedBound::RegionSubRegion(r_a @ &ty::ReFree(_),
404                                                   &ty::ReVar(vid_b)) => {
405                         self.add_given(r_a, vid_b);
406                     }
407                     ImpliedBound::RegionSubParam(r_a, param_b) => {
408                         self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
409                     }
410                     ImpliedBound::RegionSubProjection(r_a, projection_b) => {
411                         self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
412                     }
413                     ImpliedBound::RegionSubRegion(..) => {
414                         // In principle, we could record (and take
415                         // advantage of) every relationship here, but
416                         // we are also free not to -- it simply means
417                         // strictly less that we can successfully type
418                         // check. (It may also be that we should
419                         // revise our inference system to be more
420                         // general and to make use of *every*
421                         // relationship that arises here, but
422                         // presently we do not.)
423                     }
424                 }
425             }
426         }
427
428         debug!("<< relate_free_regions");
429     }
430
431     fn resolve_regions_and_report_errors(&self) {
432         self.fcx.resolve_regions_and_report_errors(self.subject_def_id,
433                                                    &self.region_maps,
434                                                    &self.free_region_map);
435     }
436
437     fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) {
438         debug!("regionck::visit_pat(pat={:?})", pat);
439         pat.each_binding(|_, id, span, _| {
440             // If we have a variable that contains region'd data, that
441             // data will be accessible from anywhere that the variable is
442             // accessed. We must be wary of loops like this:
443             //
444             //     // from src/test/compile-fail/borrowck-lend-flow.rs
445             //     let mut v = box 3, w = box 4;
446             //     let mut x = &mut w;
447             //     loop {
448             //         **x += 1;   // (2)
449             //         borrow(v);  //~ ERROR cannot borrow
450             //         x = &mut v; // (1)
451             //     }
452             //
453             // Typically, we try to determine the region of a borrow from
454             // those points where it is dereferenced. In this case, one
455             // might imagine that the lifetime of `x` need only be the
456             // body of the loop. But of course this is incorrect because
457             // the pointer that is created at point (1) is consumed at
458             // point (2), meaning that it must be live across the loop
459             // iteration. The easiest way to guarantee this is to require
460             // that the lifetime of any regions that appear in a
461             // variable's type enclose at least the variable's scope.
462
463             let var_scope = self.region_maps.var_scope(id);
464             let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
465
466             let origin = infer::BindingTypeIsNotValidAtDecl(span);
467             self.type_of_node_must_outlive(origin, id, var_region);
468
469             let typ = self.resolve_node_type(id);
470             let _ = dropck::check_safety_of_destructor_if_necessary(
471                 self, typ, span, var_scope);
472         })
473     }
474 }
475
476 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for RegionCtxt<'a, 'gcx, 'tcx> {
477     // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
478     // However, right now we run into an issue whereby some free
479     // regions are not properly related if they appear within the
480     // types of arguments that must be inferred. This could be
481     // addressed by deferring the construction of the region
482     // hierarchy, and in particular the relationships between free
483     // regions, until regionck, as described in #3238.
484
485     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
486         NestedVisitorMap::None
487     }
488
489     fn visit_fn(&mut self, _fk: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
490                 b: hir::BodyId, span: Span, id: ast::NodeId) {
491         let body = self.tcx.hir.body(b);
492         self.visit_fn_body(id, body, span)
493     }
494
495     //visit_pat: visit_pat, // (..) see above
496
497     fn visit_arm(&mut self, arm: &'gcx hir::Arm) {
498         // see above
499         for p in &arm.pats {
500             self.constrain_bindings_in_pat(p);
501         }
502         intravisit::walk_arm(self, arm);
503     }
504
505     fn visit_local(&mut self, l: &'gcx hir::Local) {
506         // see above
507         self.constrain_bindings_in_pat(&l.pat);
508         self.link_local(l);
509         intravisit::walk_local(self, l);
510     }
511
512     fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
513         debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
514                expr, self.repeating_scope);
515
516         // No matter what, the type of each expression must outlive the
517         // scope of that expression. This also guarantees basic WF.
518         let expr_ty = self.resolve_node_type(expr.id);
519         // the region corresponding to this expression
520         let expr_region = self.tcx.node_scope_region(expr.id);
521         self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span),
522                                expr_ty, expr_region);
523
524         let is_method_call = self.tables.borrow().is_method_call(expr);
525
526         // If we are calling a method (either explicitly or via an
527         // overloaded operator), check that all of the types provided as
528         // arguments for its type parameters are well-formed, and all the regions
529         // provided as arguments outlive the call.
530         if is_method_call {
531             let origin = match expr.node {
532                 hir::ExprMethodCall(..) =>
533                     infer::ParameterOrigin::MethodCall,
534                 hir::ExprUnary(op, _) if op == hir::UnDeref =>
535                     infer::ParameterOrigin::OverloadedDeref,
536                 _ =>
537                     infer::ParameterOrigin::OverloadedOperator
538             };
539
540             let substs = self.tables.borrow().node_substs(expr.id);
541             self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
542             // Arguments (sub-expressions) are checked via `constrain_call`, below.
543         }
544
545         // Check any autoderefs or autorefs that appear.
546         let cmt_result = self.constrain_adjustments(expr);
547
548         // If necessary, constrain destructors in this expression. This will be
549         // the adjusted form if there is an adjustment.
550         match cmt_result {
551             Ok(head_cmt) => {
552                 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, expr.span);
553             }
554             Err(..) => {
555                 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
556             }
557         }
558
559         debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
560                expr, self.repeating_scope);
561         match expr.node {
562             hir::ExprPath(_) => {
563                 let substs = self.tables.borrow().node_substs(expr.id);
564                 let origin = infer::ParameterOrigin::Path;
565                 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
566             }
567
568             hir::ExprCall(ref callee, ref args) => {
569                 if is_method_call {
570                     self.constrain_call(expr, Some(&callee), args.iter().map(|e| &*e));
571                 } else {
572                     self.constrain_callee(callee.id, expr, &callee);
573                     self.constrain_call(expr, None, args.iter().map(|e| &*e));
574                 }
575
576                 intravisit::walk_expr(self, expr);
577             }
578
579             hir::ExprMethodCall(.., ref args) => {
580                 self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &*e));
581
582                 intravisit::walk_expr(self, expr);
583             }
584
585             hir::ExprAssignOp(_, ref lhs, ref rhs) => {
586                 if is_method_call {
587                     self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
588                 }
589
590                 intravisit::walk_expr(self, expr);
591             }
592
593             hir::ExprIndex(ref lhs, ref rhs) if is_method_call => {
594                 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
595
596                 intravisit::walk_expr(self, expr);
597             },
598
599             hir::ExprBinary(_, ref lhs, ref rhs) if is_method_call => {
600                 // As `ExprMethodCall`, but the call is via an overloaded op.
601                 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
602
603                 intravisit::walk_expr(self, expr);
604             }
605
606             hir::ExprBinary(_, ref lhs, ref rhs) => {
607                 // If you do `x OP y`, then the types of `x` and `y` must
608                 // outlive the operation you are performing.
609                 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
610                 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
611                 for &ty in &[lhs_ty, rhs_ty] {
612                     self.type_must_outlive(infer::Operand(expr.span),
613                                            ty, expr_region);
614                 }
615                 intravisit::walk_expr(self, expr);
616             }
617
618             hir::ExprUnary(hir::UnDeref, ref base) => {
619                 // For *a, the lifetime of a must enclose the deref
620                 if is_method_call {
621                     self.constrain_call(expr, Some(base), None::<hir::Expr>.iter());
622                 }
623                 // For overloaded derefs, base_ty is the input to `Deref::deref`,
624                 // but it's a reference type uing the same region as the output.
625                 let base_ty = self.resolve_expr_type_adjusted(base);
626                 if let ty::TyRef(r_ptr, _) = base_ty.sty {
627                     self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
628                 }
629
630                 intravisit::walk_expr(self, expr);
631             }
632
633             hir::ExprUnary(_, ref lhs) if is_method_call => {
634                 // As above.
635                 self.constrain_call(expr, Some(&lhs), None::<hir::Expr>.iter());
636
637                 intravisit::walk_expr(self, expr);
638             }
639
640             hir::ExprIndex(ref vec_expr, _) => {
641                 // For a[b], the lifetime of a must enclose the deref
642                 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
643                 self.constrain_index(expr, vec_type);
644
645                 intravisit::walk_expr(self, expr);
646             }
647
648             hir::ExprCast(ref source, _) => {
649                 // Determine if we are casting `source` to a trait
650                 // instance.  If so, we have to be sure that the type of
651                 // the source obeys the trait's region bound.
652                 self.constrain_cast(expr, &source);
653                 intravisit::walk_expr(self, expr);
654             }
655
656             hir::ExprAddrOf(m, ref base) => {
657                 self.link_addr_of(expr, m, &base);
658
659                 // Require that when you write a `&expr` expression, the
660                 // resulting pointer has a lifetime that encompasses the
661                 // `&expr` expression itself. Note that we constraining
662                 // the type of the node expr.id here *before applying
663                 // adjustments*.
664                 //
665                 // FIXME(#6268) nested method calls requires that this rule change
666                 let ty0 = self.resolve_node_type(expr.id);
667                 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
668                 intravisit::walk_expr(self, expr);
669             }
670
671             hir::ExprMatch(ref discr, ref arms, _) => {
672                 self.link_match(&discr, &arms[..]);
673
674                 intravisit::walk_expr(self, expr);
675             }
676
677             hir::ExprClosure(.., body_id, _) => {
678                 self.check_expr_fn_block(expr, body_id);
679             }
680
681             hir::ExprLoop(ref body, _, _) => {
682                 let repeating_scope = self.set_repeating_scope(body.id);
683                 intravisit::walk_expr(self, expr);
684                 self.set_repeating_scope(repeating_scope);
685             }
686
687             hir::ExprWhile(ref cond, ref body, _) => {
688                 let repeating_scope = self.set_repeating_scope(cond.id);
689                 self.visit_expr(&cond);
690
691                 self.set_repeating_scope(body.id);
692                 self.visit_block(&body);
693
694                 self.set_repeating_scope(repeating_scope);
695             }
696
697             hir::ExprRet(Some(ref ret_expr)) => {
698                 let call_site_scope = self.call_site_scope;
699                 debug!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}",
700                        ret_expr.id, call_site_scope);
701                 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
702                 self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span),
703                                                ret_expr.id,
704                                                call_site_region);
705                 intravisit::walk_expr(self, expr);
706             }
707
708             _ => {
709                 intravisit::walk_expr(self, expr);
710             }
711         }
712     }
713 }
714
715 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
716     fn constrain_cast(&mut self,
717                       cast_expr: &hir::Expr,
718                       source_expr: &hir::Expr)
719     {
720         debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
721                cast_expr,
722                source_expr);
723
724         let source_ty = self.resolve_node_type(source_expr.id);
725         let target_ty = self.resolve_node_type(cast_expr.id);
726
727         self.walk_cast(cast_expr, source_ty, target_ty);
728     }
729
730     fn walk_cast(&mut self,
731                  cast_expr: &hir::Expr,
732                  from_ty: Ty<'tcx>,
733                  to_ty: Ty<'tcx>) {
734         debug!("walk_cast(from_ty={:?}, to_ty={:?})",
735                from_ty,
736                to_ty);
737         match (&from_ty.sty, &to_ty.sty) {
738             /*From:*/ (&ty::TyRef(from_r, ref from_mt),
739             /*To:  */  &ty::TyRef(to_r, ref to_mt)) => {
740                 // Target cannot outlive source, naturally.
741                 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
742                 self.walk_cast(cast_expr, from_mt.ty, to_mt.ty);
743             }
744
745             /*From:*/ (_,
746             /*To:  */  &ty::TyDynamic(.., r)) => {
747                 // When T is existentially quantified as a trait
748                 // `Foo+'to`, it must outlive the region bound `'to`.
749                 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
750             }
751
752             /*From:*/ (&ty::TyAdt(from_def, _),
753             /*To:  */  &ty::TyAdt(to_def, _)) if from_def.is_box() && to_def.is_box() => {
754                 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
755             }
756
757             _ => { }
758         }
759     }
760
761     fn check_expr_fn_block(&mut self,
762                            expr: &'gcx hir::Expr,
763                            body_id: hir::BodyId) {
764         let repeating_scope = self.set_repeating_scope(body_id.node_id);
765         intravisit::walk_expr(self, expr);
766         self.set_repeating_scope(repeating_scope);
767     }
768
769     fn constrain_callee(&mut self,
770                         callee_id: ast::NodeId,
771                         _call_expr: &hir::Expr,
772                         _callee_expr: &hir::Expr) {
773         let callee_ty = self.resolve_node_type(callee_id);
774         match callee_ty.sty {
775             ty::TyFnDef(..) | ty::TyFnPtr(_) => { }
776             _ => {
777                 // this should not happen, but it does if the program is
778                 // erroneous
779                 //
780                 // bug!(
781                 //     callee_expr.span,
782                 //     "Calling non-function: {}",
783                 //     callee_ty);
784             }
785         }
786     }
787
788     fn constrain_call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
789                                                            call_expr: &hir::Expr,
790                                                            receiver: Option<&hir::Expr>,
791                                                            arg_exprs: I) {
792         //! Invoked on every call site (i.e., normal calls, method calls,
793         //! and overloaded operators). Constrains the regions which appear
794         //! in the type of the function. Also constrains the regions that
795         //! appear in the arguments appropriately.
796
797         debug!("constrain_call(call_expr={:?}, receiver={:?})",
798                 call_expr,
799                 receiver);
800
801         // `callee_region` is the scope representing the time in which the
802         // call occurs.
803         //
804         // FIXME(#6268) to support nested method calls, should be callee_id
805         let callee_scope = CodeExtent::Misc(call_expr.id);
806         let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
807
808         debug!("callee_region={:?}", callee_region);
809
810         for arg_expr in arg_exprs {
811             debug!("Argument: {:?}", arg_expr);
812
813             // ensure that any regions appearing in the argument type are
814             // valid for at least the lifetime of the function:
815             self.type_of_node_must_outlive(infer::CallArg(arg_expr.span),
816                                            arg_expr.id, callee_region);
817         }
818
819         // as loop above, but for receiver
820         if let Some(r) = receiver {
821             debug!("receiver: {:?}", r);
822             self.type_of_node_must_outlive(infer::CallRcvr(r.span),
823                                            r.id, callee_region);
824         }
825     }
826
827     /// Create a temporary `MemCategorizationContext` and pass it to the closure.
828     fn with_mc<F, R>(&self, f: F) -> R
829         where F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'gcx, 'tcx>) -> R
830     {
831         f(mc::MemCategorizationContext::new(&self.infcx,
832                                             &self.region_maps,
833                                             &self.tables.borrow()))
834     }
835
836     /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
837     /// dereferenced, the lifetime of the pointer includes the deref expr.
838     fn constrain_adjustments(&mut self, expr: &hir::Expr) -> mc::McResult<mc::cmt<'tcx>> {
839         debug!("constrain_adjustments(expr={:?})", expr);
840
841         let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
842
843         let tables = self.tables.borrow();
844         let adjustments = tables.expr_adjustments(&expr);
845         if adjustments.is_empty() {
846             return Ok(cmt);
847         }
848
849         debug!("constrain_adjustments: adjustments={:?}", adjustments);
850
851         // If necessary, constrain destructors in the unadjusted form of this
852         // expression.
853         self.check_safety_of_rvalue_destructor_if_necessary(cmt.clone(), expr.span);
854
855         let expr_region = self.tcx.node_scope_region(expr.id);
856         for adjustment in adjustments {
857             debug!("constrain_adjustments: adjustment={:?}, cmt={:?}",
858                    adjustment, cmt);
859
860             if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
861                 debug!("constrain_adjustments: overloaded deref: {:?}", deref);
862
863                 // Treat overloaded autoderefs as if an AutoBorrow adjustment
864                 // was applied on the base type, as that is always the case.
865                 let input = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
866                     ty: cmt.ty,
867                     mutbl: deref.mutbl,
868                 });
869                 let output = self.tcx.mk_ref(deref.region, ty::TypeAndMut {
870                     ty: adjustment.target,
871                     mutbl: deref.mutbl,
872                 });
873
874                 self.link_region(expr.span, deref.region,
875                                  ty::BorrowKind::from_mutbl(deref.mutbl), cmt.clone());
876
877                 // Specialized version of constrain_call.
878                 self.type_must_outlive(infer::CallRcvr(expr.span),
879                                        input, expr_region);
880                 self.type_must_outlive(infer::CallReturn(expr.span),
881                                        output, expr_region);
882             }
883
884             if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
885                 self.link_autoref(expr, cmt.clone(), autoref);
886
887                 // Require that the resulting region encompasses
888                 // the current node.
889                 //
890                 // FIXME(#6268) remove to support nested method calls
891                 self.type_of_node_must_outlive(infer::AutoBorrow(expr.span),
892                                                expr.id, expr_region);
893             }
894
895             cmt = self.with_mc(|mc| mc.cat_expr_adjusted(expr, cmt, &adjustment))?;
896
897             if let Categorization::Deref(_, mc::BorrowedPtr(_, r_ptr)) = cmt.cat {
898                 self.mk_subregion_due_to_dereference(expr.span,
899                                                      expr_region, r_ptr);
900             }
901         }
902
903         Ok(cmt)
904     }
905
906     pub fn mk_subregion_due_to_dereference(&mut self,
907                                            deref_span: Span,
908                                            minimum_lifetime: ty::Region<'tcx>,
909                                            maximum_lifetime: ty::Region<'tcx>) {
910         self.sub_regions(infer::DerefPointer(deref_span),
911                          minimum_lifetime, maximum_lifetime)
912     }
913
914     fn check_safety_of_rvalue_destructor_if_necessary(&mut self,
915                                                      cmt: mc::cmt<'tcx>,
916                                                      span: Span) {
917         match cmt.cat {
918             Categorization::Rvalue(region) => {
919                 match *region {
920                     ty::ReScope(rvalue_scope) => {
921                         let typ = self.resolve_type(cmt.ty);
922                         let _ = dropck::check_safety_of_destructor_if_necessary(
923                             self, typ, span, rvalue_scope);
924                     }
925                     ty::ReStatic => {}
926                     _ => {
927                         span_bug!(span,
928                                   "unexpected rvalue region in rvalue \
929                                    destructor safety checking: `{:?}`",
930                                   region);
931                     }
932                 }
933             }
934             _ => {}
935         }
936     }
937
938     /// Invoked on any index expression that occurs. Checks that if this is a slice
939     /// being indexed, the lifetime of the pointer includes the deref expr.
940     fn constrain_index(&mut self,
941                        index_expr: &hir::Expr,
942                        indexed_ty: Ty<'tcx>)
943     {
944         debug!("constrain_index(index_expr=?, indexed_ty={}",
945                self.ty_to_string(indexed_ty));
946
947         let r_index_expr = ty::ReScope(CodeExtent::Misc(index_expr.id));
948         if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
949             match mt.ty.sty {
950                 ty::TySlice(_) | ty::TyStr => {
951                     self.sub_regions(infer::IndexSlice(index_expr.span),
952                                      self.tcx.mk_region(r_index_expr), r_ptr);
953                 }
954                 _ => {}
955             }
956         }
957     }
958
959     /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
960     /// adjustments) are valid for at least `minimum_lifetime`
961     fn type_of_node_must_outlive(&mut self,
962         origin: infer::SubregionOrigin<'tcx>,
963         id: ast::NodeId,
964         minimum_lifetime: ty::Region<'tcx>)
965     {
966         // Try to resolve the type.  If we encounter an error, then typeck
967         // is going to fail anyway, so just stop here and let typeck
968         // report errors later on in the writeback phase.
969         let ty0 = self.resolve_node_type(id);
970         let ty = self.tables.borrow().adjustments.get(&id)
971             .and_then(|adj| adj.last())
972             .map_or(ty0, |adj| adj.target);
973         let ty = self.resolve_type(ty);
974         debug!("constrain_regions_in_type_of_node(\
975                 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
976                 ty,  ty0,
977                id, minimum_lifetime);
978         self.type_must_outlive(origin, ty, minimum_lifetime);
979     }
980
981     /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
982     /// resulting pointer is linked to the lifetime of its guarantor (if any).
983     fn link_addr_of(&mut self, expr: &hir::Expr,
984                     mutability: hir::Mutability, base: &hir::Expr) {
985         debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
986
987         let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
988
989         debug!("link_addr_of: cmt={:?}", cmt);
990
991         self.link_region_from_node_type(expr.span, expr.id, mutability, cmt);
992     }
993
994     /// Computes the guarantors for any ref bindings in a `let` and
995     /// then ensures that the lifetime of the resulting pointer is
996     /// linked to the lifetime of the initialization expression.
997     fn link_local(&self, local: &hir::Local) {
998         debug!("regionck::for_local()");
999         let init_expr = match local.init {
1000             None => { return; }
1001             Some(ref expr) => &**expr,
1002         };
1003         let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
1004         self.link_pattern(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 discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
1013         debug!("discr_cmt={:?}", discr_cmt);
1014         for arm in arms {
1015             for root_pat in &arm.pats {
1016                 self.link_pattern(discr_cmt.clone(), &root_pat);
1017             }
1018         }
1019     }
1020
1021     /// Computes the guarantors for any ref bindings in a match and
1022     /// then ensures that the lifetime of the resulting pointer is
1023     /// linked to the lifetime of its guarantor (if any).
1024     fn link_fn_args(&self, body_scope: CodeExtent, args: &[hir::Arg]) {
1025         debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1026         for arg in args {
1027             let arg_ty = self.node_ty(arg.id);
1028             let re_scope = self.tcx.mk_region(ty::ReScope(body_scope));
1029             let arg_cmt = self.with_mc(|mc| {
1030                 mc.cat_rvalue(arg.id, arg.pat.span, re_scope, arg_ty)
1031             });
1032             debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1033                    arg_ty,
1034                    arg_cmt,
1035                    arg);
1036             self.link_pattern(arg_cmt, &arg.pat);
1037         }
1038     }
1039
1040     /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1041     /// in the discriminant, if needed.
1042     fn link_pattern(&self, discr_cmt: mc::cmt<'tcx>, root_pat: &hir::Pat) {
1043         debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1044                discr_cmt,
1045                root_pat);
1046         let _ = self.with_mc(|mc| {
1047             mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, sub_pat| {
1048                 match sub_pat.node {
1049                     // `ref x` pattern
1050                     PatKind::Binding(hir::BindByRef(mutbl), ..) => {
1051                         self.link_region_from_node_type(sub_pat.span, sub_pat.id,
1052                                                         mutbl, sub_cmt);
1053                     }
1054                     _ => {}
1055                 }
1056             })
1057         });
1058     }
1059
1060     /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1061     /// autoref'd.
1062     fn link_autoref(&self,
1063                     expr: &hir::Expr,
1064                     expr_cmt: mc::cmt<'tcx>,
1065                     autoref: &adjustment::AutoBorrow<'tcx>)
1066     {
1067         debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
1068
1069         match *autoref {
1070             adjustment::AutoBorrow::Ref(r, m) => {
1071                 self.link_region(expr.span, r,
1072                                  ty::BorrowKind::from_mutbl(m), expr_cmt);
1073             }
1074
1075             adjustment::AutoBorrow::RawPtr(m) => {
1076                 let r = self.tcx.node_scope_region(expr.id);
1077                 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1078             }
1079         }
1080     }
1081
1082     /// Like `link_region()`, except that the region is extracted from the type of `id`,
1083     /// which must be some reference (`&T`, `&str`, etc).
1084     fn link_region_from_node_type(&self,
1085                                   span: Span,
1086                                   id: ast::NodeId,
1087                                   mutbl: hir::Mutability,
1088                                   cmt_borrowed: mc::cmt<'tcx>) {
1089         debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1090                id, mutbl, cmt_borrowed);
1091
1092         let rptr_ty = self.resolve_node_type(id);
1093         if let ty::TyRef(r, _) = rptr_ty.sty {
1094             debug!("rptr_ty={}",  rptr_ty);
1095             self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl),
1096                              cmt_borrowed);
1097         }
1098     }
1099
1100     /// Informs the inference engine that `borrow_cmt` is being borrowed with
1101     /// kind `borrow_kind` and lifetime `borrow_region`.
1102     /// In order to ensure borrowck is satisfied, this may create constraints
1103     /// between regions, as explained in `link_reborrowed_region()`.
1104     fn link_region(&self,
1105                    span: Span,
1106                    borrow_region: ty::Region<'tcx>,
1107                    borrow_kind: ty::BorrowKind,
1108                    borrow_cmt: mc::cmt<'tcx>) {
1109         let mut borrow_cmt = borrow_cmt;
1110         let mut borrow_kind = borrow_kind;
1111
1112         let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1113         self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
1114
1115         loop {
1116             debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1117                    borrow_region,
1118                    borrow_kind,
1119                    borrow_cmt);
1120             match borrow_cmt.cat.clone() {
1121                 Categorization::Deref(ref_cmt, mc::Implicit(ref_kind, ref_region)) |
1122                 Categorization::Deref(ref_cmt, mc::BorrowedPtr(ref_kind, ref_region)) => {
1123                     match self.link_reborrowed_region(span,
1124                                                       borrow_region, borrow_kind,
1125                                                       ref_cmt, ref_region, ref_kind,
1126                                                       borrow_cmt.note) {
1127                         Some((c, k)) => {
1128                             borrow_cmt = c;
1129                             borrow_kind = k;
1130                         }
1131                         None => {
1132                             return;
1133                         }
1134                     }
1135                 }
1136
1137                 Categorization::Downcast(cmt_base, _) |
1138                 Categorization::Deref(cmt_base, mc::Unique) |
1139                 Categorization::Interior(cmt_base, _) => {
1140                     // Borrowing interior or owned data requires the base
1141                     // to be valid and borrowable in the same fashion.
1142                     borrow_cmt = cmt_base;
1143                     borrow_kind = borrow_kind;
1144                 }
1145
1146                 Categorization::Deref(_, mc::UnsafePtr(..)) |
1147                 Categorization::StaticItem |
1148                 Categorization::Upvar(..) |
1149                 Categorization::Local(..) |
1150                 Categorization::Rvalue(..) => {
1151                     // These are all "base cases" with independent lifetimes
1152                     // that are not subject to inference
1153                     return;
1154                 }
1155             }
1156         }
1157     }
1158
1159     /// This is the most complicated case: the path being borrowed is
1160     /// itself the referent of a borrowed pointer. Let me give an
1161     /// example fragment of code to make clear(er) the situation:
1162     ///
1163     ///    let r: &'a mut T = ...;  // the original reference "r" has lifetime 'a
1164     ///    ...
1165     ///    &'z *r                   // the reborrow has lifetime 'z
1166     ///
1167     /// Now, in this case, our primary job is to add the inference
1168     /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1169     /// parameters in (roughly) terms of the example:
1170     ///
1171     ///     A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1172     ///     borrow_region   ^~                 ref_region    ^~
1173     ///     borrow_kind        ^~               ref_kind        ^~
1174     ///     ref_cmt                 ^
1175     ///
1176     /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1177     ///
1178     /// Unfortunately, there are some complications beyond the simple
1179     /// scenario I just painted:
1180     ///
1181     /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1182     ///    case, we have two jobs. First, we are inferring whether this reference
1183     ///    should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1184     ///    adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1185     ///    then `r` must be an `&mut` reference). Second, whenever we link
1186     ///    two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1187     ///    case we adjust the cause to indicate that the reference being
1188     ///    "reborrowed" is itself an upvar. This provides a nicer error message
1189     ///    should something go wrong.
1190     ///
1191     /// 2. There may in fact be more levels of reborrowing. In the
1192     ///    example, I said the borrow was like `&'z *r`, but it might
1193     ///    in fact be a borrow like `&'z **q` where `q` has type `&'a
1194     ///    &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1195     ///    and `'z <= 'b`. This is explained more below.
1196     ///
1197     /// The return value of this function indicates whether we need to
1198     /// recurse and process `ref_cmt` (see case 2 above).
1199     fn link_reborrowed_region(&self,
1200                               span: Span,
1201                               borrow_region: ty::Region<'tcx>,
1202                               borrow_kind: ty::BorrowKind,
1203                               ref_cmt: mc::cmt<'tcx>,
1204                               ref_region: ty::Region<'tcx>,
1205                               mut ref_kind: ty::BorrowKind,
1206                               note: mc::Note)
1207                               -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1208     {
1209         // Possible upvar ID we may need later to create an entry in the
1210         // maybe link map.
1211
1212         // Detect by-ref upvar `x`:
1213         let cause = match note {
1214             mc::NoteUpvarRef(ref upvar_id) => {
1215                 match self.tables.borrow().upvar_capture_map.get(upvar_id) {
1216                     Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1217                         // The mutability of the upvar may have been modified
1218                         // by the above adjustment, so update our local variable.
1219                         ref_kind = upvar_borrow.kind;
1220
1221                         infer::ReborrowUpvar(span, *upvar_id)
1222                     }
1223                     _ => {
1224                         span_bug!( span, "Illegal upvar id: {:?}", upvar_id);
1225                     }
1226                 }
1227             }
1228             mc::NoteClosureEnv(ref upvar_id) => {
1229                 // We don't have any mutability changes to propagate, but
1230                 // we do want to note that an upvar reborrow caused this
1231                 // link
1232                 infer::ReborrowUpvar(span, *upvar_id)
1233             }
1234             _ => {
1235                 infer::Reborrow(span)
1236             }
1237         };
1238
1239         debug!("link_reborrowed_region: {:?} <= {:?}",
1240                borrow_region,
1241                ref_region);
1242         self.sub_regions(cause, borrow_region, ref_region);
1243
1244         // If we end up needing to recurse and establish a region link
1245         // with `ref_cmt`, calculate what borrow kind we will end up
1246         // needing. This will be used below.
1247         //
1248         // One interesting twist is that we can weaken the borrow kind
1249         // when we recurse: to reborrow an `&mut` referent as mutable,
1250         // borrowck requires a unique path to the `&mut` reference but not
1251         // necessarily a *mutable* path.
1252         let new_borrow_kind = match borrow_kind {
1253             ty::ImmBorrow =>
1254                 ty::ImmBorrow,
1255             ty::MutBorrow | ty::UniqueImmBorrow =>
1256                 ty::UniqueImmBorrow
1257         };
1258
1259         // Decide whether we need to recurse and link any regions within
1260         // the `ref_cmt`. This is concerned for the case where the value
1261         // being reborrowed is in fact a borrowed pointer found within
1262         // another borrowed pointer. For example:
1263         //
1264         //    let p: &'b &'a mut T = ...;
1265         //    ...
1266         //    &'z **p
1267         //
1268         // What makes this case particularly tricky is that, if the data
1269         // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1270         // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1271         // (otherwise the user might mutate through the `&mut T` reference
1272         // after `'b` expires and invalidate the borrow we are looking at
1273         // now).
1274         //
1275         // So let's re-examine our parameters in light of this more
1276         // complicated (possible) scenario:
1277         //
1278         //     A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1279         //     borrow_region   ^~                 ref_region             ^~
1280         //     borrow_kind        ^~               ref_kind                 ^~
1281         //     ref_cmt                 ^~~
1282         //
1283         // (Note that since we have not examined `ref_cmt.cat`, we don't
1284         // know whether this scenario has occurred; but I wanted to show
1285         // how all the types get adjusted.)
1286         match ref_kind {
1287             ty::ImmBorrow => {
1288                 // The reference being reborrowed is a sharable ref of
1289                 // type `&'a T`. In this case, it doesn't matter where we
1290                 // *found* the `&T` pointer, the memory it references will
1291                 // be valid and immutable for `'a`. So we can stop here.
1292                 //
1293                 // (Note that the `borrow_kind` must also be ImmBorrow or
1294                 // else the user is borrowed imm memory as mut memory,
1295                 // which means they'll get an error downstream in borrowck
1296                 // anyhow.)
1297                 return None;
1298             }
1299
1300             ty::MutBorrow | ty::UniqueImmBorrow => {
1301                 // The reference being reborrowed is either an `&mut T` or
1302                 // `&uniq T`. This is the case where recursion is needed.
1303                 return Some((ref_cmt, new_borrow_kind));
1304             }
1305         }
1306     }
1307
1308     /// Checks that the values provided for type/region arguments in a given
1309     /// expression are well-formed and in-scope.
1310     fn substs_wf_in_scope(&mut self,
1311                           origin: infer::ParameterOrigin,
1312                           substs: &Substs<'tcx>,
1313                           expr_span: Span,
1314                           expr_region: ty::Region<'tcx>) {
1315         debug!("substs_wf_in_scope(substs={:?}, \
1316                 expr_region={:?}, \
1317                 origin={:?}, \
1318                 expr_span={:?})",
1319                substs, expr_region, origin, expr_span);
1320
1321         let origin = infer::ParameterInScope(origin, expr_span);
1322
1323         for region in substs.regions() {
1324             self.sub_regions(origin.clone(), expr_region, region);
1325         }
1326
1327         for ty in substs.types() {
1328             let ty = self.resolve_type(ty);
1329             self.type_must_outlive(origin.clone(), ty, expr_region);
1330         }
1331     }
1332
1333     /// Ensures that type is well-formed in `region`, which implies (among
1334     /// other things) that all borrowed data reachable via `ty` outlives
1335     /// `region`.
1336     pub fn type_must_outlive(&self,
1337                              origin: infer::SubregionOrigin<'tcx>,
1338                              ty: Ty<'tcx>,
1339                              region: ty::Region<'tcx>)
1340     {
1341         let ty = self.resolve_type(ty);
1342
1343         debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1344                ty,
1345                region,
1346                origin);
1347
1348         assert!(!ty.has_escaping_regions());
1349
1350         let components = self.tcx.outlives_components(ty);
1351         self.components_must_outlive(origin, components, region);
1352     }
1353
1354     fn components_must_outlive(&self,
1355                                origin: infer::SubregionOrigin<'tcx>,
1356                                components: Vec<ty::outlives::Component<'tcx>>,
1357                                region: ty::Region<'tcx>)
1358     {
1359         for component in components {
1360             let origin = origin.clone();
1361             match component {
1362                 ty::outlives::Component::Region(region1) => {
1363                     self.sub_regions(origin, region, region1);
1364                 }
1365                 ty::outlives::Component::Param(param_ty) => {
1366                     self.param_ty_must_outlive(origin, region, param_ty);
1367                 }
1368                 ty::outlives::Component::Projection(projection_ty) => {
1369                     self.projection_must_outlive(origin, region, projection_ty);
1370                 }
1371                 ty::outlives::Component::EscapingProjection(subcomponents) => {
1372                     self.components_must_outlive(origin, subcomponents, region);
1373                 }
1374                 ty::outlives::Component::UnresolvedInferenceVariable(v) => {
1375                     // ignore this, we presume it will yield an error
1376                     // later, since if a type variable is not resolved by
1377                     // this point it never will be
1378                     self.tcx.sess.delay_span_bug(
1379                         origin.span(),
1380                         &format!("unresolved inference variable in outlives: {:?}", v));
1381                 }
1382             }
1383         }
1384     }
1385
1386     fn param_ty_must_outlive(&self,
1387                              origin: infer::SubregionOrigin<'tcx>,
1388                              region: ty::Region<'tcx>,
1389                              param_ty: ty::ParamTy) {
1390         debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1391                region, param_ty, origin);
1392
1393         let verify_bound = self.param_bound(param_ty);
1394         let generic = GenericKind::Param(param_ty);
1395         self.verify_generic_bound(origin, generic, region, verify_bound);
1396     }
1397
1398     fn projection_must_outlive(&self,
1399                                origin: infer::SubregionOrigin<'tcx>,
1400                                region: ty::Region<'tcx>,
1401                                projection_ty: ty::ProjectionTy<'tcx>)
1402     {
1403         debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1404                region, projection_ty, origin);
1405
1406         // This case is thorny for inference. The fundamental problem is
1407         // that there are many cases where we have choice, and inference
1408         // doesn't like choice (the current region inference in
1409         // particular). :) First off, we have to choose between using the
1410         // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1411         // OutlivesProjectionComponent rules, any one of which is
1412         // sufficient.  If there are no inference variables involved, it's
1413         // not hard to pick the right rule, but if there are, we're in a
1414         // bit of a catch 22: if we picked which rule we were going to
1415         // use, we could add constraints to the region inference graph
1416         // that make it apply, but if we don't add those constraints, the
1417         // rule might not apply (but another rule might). For now, we err
1418         // on the side of adding too few edges into the graph.
1419
1420         // Compute the bounds we can derive from the environment or trait
1421         // definition.  We know that the projection outlives all the
1422         // regions in this list.
1423         let env_bounds = self.projection_declared_bounds(origin.span(), projection_ty);
1424
1425         debug!("projection_must_outlive: env_bounds={:?}",
1426                env_bounds);
1427
1428         // If we know that the projection outlives 'static, then we're
1429         // done here.
1430         if env_bounds.contains(&&ty::ReStatic) {
1431             debug!("projection_must_outlive: 'static as declared bound");
1432             return;
1433         }
1434
1435         // If declared bounds list is empty, the only applicable rule is
1436         // OutlivesProjectionComponent. If there are inference variables,
1437         // then, we can break down the outlives into more primitive
1438         // components without adding unnecessary edges.
1439         //
1440         // If there are *no* inference variables, however, we COULD do
1441         // this, but we choose not to, because the error messages are less
1442         // good. For example, a requirement like `T::Item: 'r` would be
1443         // translated to a requirement that `T: 'r`; when this is reported
1444         // to the user, it will thus say "T: 'r must hold so that T::Item:
1445         // 'r holds". But that makes it sound like the only way to fix
1446         // the problem is to add `T: 'r`, which isn't true. So, if there are no
1447         // inference variables, we use a verify constraint instead of adding
1448         // edges, which winds up enforcing the same condition.
1449         let needs_infer = projection_ty.trait_ref.needs_infer();
1450         if env_bounds.is_empty() && needs_infer {
1451             debug!("projection_must_outlive: no declared bounds");
1452
1453             for component_ty in projection_ty.trait_ref.substs.types() {
1454                 self.type_must_outlive(origin.clone(), component_ty, region);
1455             }
1456
1457             for r in projection_ty.trait_ref.substs.regions() {
1458                 self.sub_regions(origin.clone(), region, r);
1459             }
1460
1461             return;
1462         }
1463
1464         // If we find that there is a unique declared bound `'b`, and this bound
1465         // appears in the trait reference, then the best action is to require that `'b:'r`,
1466         // so do that. This is best no matter what rule we use:
1467         //
1468         // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1469         // the requirement that `'b:'r`
1470         // - OutlivesProjectionComponent: this would require `'b:'r` in addition to
1471         // other conditions
1472         if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1473             let unique_bound = env_bounds[0];
1474             debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
1475             if projection_ty.trait_ref.substs.regions().any(|r| env_bounds.contains(&r)) {
1476                 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1477                 self.sub_regions(origin.clone(), region, unique_bound);
1478                 return;
1479             }
1480         }
1481
1482         // Fallback to verifying after the fact that there exists a
1483         // declared bound, or that all the components appearing in the
1484         // projection outlive; in some cases, this may add insufficient
1485         // edges into the inference graph, leading to inference failures
1486         // even though a satisfactory solution exists.
1487         let verify_bound = self.projection_bound(origin.span(), env_bounds, projection_ty);
1488         let generic = GenericKind::Projection(projection_ty);
1489         self.verify_generic_bound(origin, generic.clone(), region, verify_bound);
1490     }
1491
1492     fn type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1493         match ty.sty {
1494             ty::TyParam(p) => {
1495                 self.param_bound(p)
1496             }
1497             ty::TyProjection(data) => {
1498                 let declared_bounds = self.projection_declared_bounds(span, data);
1499                 self.projection_bound(span, declared_bounds, data)
1500             }
1501             _ => {
1502                 self.recursive_type_bound(span, ty)
1503             }
1504         }
1505     }
1506
1507     fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound<'tcx> {
1508         debug!("param_bound(param_ty={:?})",
1509                param_ty);
1510
1511         let mut param_bounds = self.declared_generic_bounds_from_env(GenericKind::Param(param_ty));
1512
1513         // Add in the default bound of fn body that applies to all in
1514         // scope type parameters:
1515         param_bounds.extend(self.implicit_region_bound);
1516
1517         VerifyBound::AnyRegion(param_bounds)
1518     }
1519
1520     fn projection_declared_bounds(&self,
1521                                   span: Span,
1522                                   projection_ty: ty::ProjectionTy<'tcx>)
1523                                   -> Vec<ty::Region<'tcx>>
1524     {
1525         // First assemble bounds from where clauses and traits.
1526
1527         let mut declared_bounds =
1528             self.declared_generic_bounds_from_env(GenericKind::Projection(projection_ty));
1529
1530         declared_bounds.extend_from_slice(
1531             &self.declared_projection_bounds_from_trait(span, projection_ty));
1532
1533         declared_bounds
1534     }
1535
1536     fn projection_bound(&self,
1537                         span: Span,
1538                         declared_bounds: Vec<ty::Region<'tcx>>,
1539                         projection_ty: ty::ProjectionTy<'tcx>)
1540                         -> VerifyBound<'tcx> {
1541         debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1542                declared_bounds, projection_ty);
1543
1544         // see the extensive comment in projection_must_outlive
1545         let item_name = projection_ty.item_name(self.tcx);
1546         let ty = self.tcx.mk_projection(projection_ty.trait_ref, item_name);
1547         let recursive_bound = self.recursive_type_bound(span, ty);
1548
1549         VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1550     }
1551
1552     fn recursive_type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1553         let mut bounds = vec![];
1554
1555         for subty in ty.walk_shallow() {
1556             bounds.push(self.type_bound(span, subty));
1557         }
1558
1559         let mut regions = ty.regions();
1560         regions.retain(|r| !r.is_late_bound()); // ignore late-bound regions
1561         bounds.push(VerifyBound::AllRegions(regions));
1562
1563         // remove bounds that must hold, since they are not interesting
1564         bounds.retain(|b| !b.must_hold());
1565
1566         if bounds.len() == 1 {
1567             bounds.pop().unwrap()
1568         } else {
1569             VerifyBound::AllBounds(bounds)
1570         }
1571     }
1572
1573     fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>)
1574                                         -> Vec<ty::Region<'tcx>>
1575     {
1576         let param_env = &self.param_env;
1577
1578         // To start, collect bounds from user:
1579         let mut param_bounds = self.tcx.required_region_bounds(generic.to_ty(self.tcx),
1580                                                                param_env.caller_bounds.to_vec());
1581
1582         // Next, collect regions we scraped from the well-formedness
1583         // constraints in the fn signature. To do that, we walk the list
1584         // of known relations from the fn ctxt.
1585         //
1586         // This is crucial because otherwise code like this fails:
1587         //
1588         //     fn foo<'a, A>(x: &'a A) { x.bar() }
1589         //
1590         // The problem is that the type of `x` is `&'a A`. To be
1591         // well-formed, then, A must be lower-generic by `'a`, but we
1592         // don't know that this holds from first principles.
1593         for &(r, p) in &self.region_bound_pairs {
1594             debug!("generic={:?} p={:?}",
1595                    generic,
1596                    p);
1597             if generic == p {
1598                 param_bounds.push(r);
1599             }
1600         }
1601
1602         param_bounds
1603     }
1604
1605     fn declared_projection_bounds_from_trait(&self,
1606                                              span: Span,
1607                                              projection_ty: ty::ProjectionTy<'tcx>)
1608                                              -> Vec<ty::Region<'tcx>>
1609     {
1610         debug!("projection_bounds(projection_ty={:?})",
1611                projection_ty);
1612         let item_name = projection_ty.item_name(self.tcx);
1613         let ty = self.tcx.mk_projection(projection_ty.trait_ref.clone(),
1614                                         item_name);
1615
1616         // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1617         // in looking for a trait definition like:
1618         //
1619         // ```
1620         // trait SomeTrait<'a> {
1621         //     type SomeType : 'a;
1622         // }
1623         // ```
1624         //
1625         // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1626         let trait_predicates = self.tcx.predicates_of(projection_ty.trait_ref.def_id);
1627         assert_eq!(trait_predicates.parent, None);
1628         let predicates = trait_predicates.predicates.as_slice().to_vec();
1629         traits::elaborate_predicates(self.tcx, predicates)
1630             .filter_map(|predicate| {
1631                 // we're only interesting in `T : 'a` style predicates:
1632                 let outlives = match predicate {
1633                     ty::Predicate::TypeOutlives(data) => data,
1634                     _ => { return None; }
1635                 };
1636
1637                 debug!("projection_bounds: outlives={:?} (1)",
1638                        outlives);
1639
1640                 // apply the substitutions (and normalize any projected types)
1641                 let outlives = self.instantiate_type_scheme(span,
1642                                                             projection_ty.trait_ref.substs,
1643                                                             &outlives);
1644
1645                 debug!("projection_bounds: outlives={:?} (2)",
1646                        outlives);
1647
1648                 let region_result = self.commit_if_ok(|_| {
1649                     let (outlives, _) =
1650                         self.replace_late_bound_regions_with_fresh_var(
1651                             span,
1652                             infer::AssocTypeProjection(projection_ty.item_name(self.tcx)),
1653                             &outlives);
1654
1655                     debug!("projection_bounds: outlives={:?} (3)",
1656                            outlives);
1657
1658                     // check whether this predicate applies to our current projection
1659                     let cause = self.fcx.misc(span);
1660                     match self.at(&cause, self.fcx.param_env).eq(outlives.0, ty) {
1661                         Ok(ok) => {
1662                             self.register_infer_ok_obligations(ok);
1663                             Ok(outlives.1)
1664                         }
1665                         Err(_) => { Err(()) }
1666                     }
1667                 });
1668
1669                 debug!("projection_bounds: region_result={:?}",
1670                        region_result);
1671
1672                 region_result.ok()
1673             })
1674             .collect()
1675     }
1676 }