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