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