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