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