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