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