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