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