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