]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/regionck.rs
Rollup merge of #59923 - czipperz:fix-convert-doc-links, r=steveklabnik
[rust.git] / src / librustc_typeck / check / regionck.rs
1 //! The region check is a final pass that runs over the AST after we have
2 //! inferred the type constraints but before we have actually finalized
3 //! the types. Its purpose is to embed a variety of region constraints.
4 //! Inserting these constraints as a separate pass is good because (1) it
5 //! localizes the code that has to do with region inference and (2) often
6 //! we cannot know what constraints are needed until the basic types have
7 //! been inferred.
8 //!
9 //! ### Interaction with the borrow checker
10 //!
11 //! In general, the job of the borrowck module (which runs later) is to
12 //! check that all soundness criteria are met, given a particular set of
13 //! regions. The job of *this* module is to anticipate the needs of the
14 //! borrow checker and infer regions that will satisfy its requirements.
15 //! It is generally true that the inference doesn't need to be sound,
16 //! meaning that if there is a bug and we inferred bad regions, the borrow
17 //! checker should catch it. This is not entirely true though; for
18 //! example, the borrow checker doesn't check subtyping, and it doesn't
19 //! check that region pointers are always live when they are used. It
20 //! might be worthwhile to fix this so that borrowck serves as a kind of
21 //! verification step -- that would add confidence in the overall
22 //! correctness of the compiler, at the cost of duplicating some type
23 //! checks and effort.
24 //!
25 //! ### Inferring the duration of borrows, automatic and otherwise
26 //!
27 //! Whenever we introduce a borrowed pointer, for example as the result of
28 //! a borrow expression `let x = &data`, the lifetime of the pointer `x`
29 //! is always specified as a region inference variable. `regionck` has the
30 //! job of adding constraints such that this inference variable is as
31 //! narrow as possible while still accommodating all uses (that is, every
32 //! dereference of the resulting pointer must be within the lifetime).
33 //!
34 //! #### Reborrows
35 //!
36 //! Generally speaking, `regionck` does NOT try to ensure that the data
37 //! `data` will outlive the pointer `x`. That is the job of borrowck. The
38 //! one exception is when "re-borrowing" the contents of another borrowed
39 //! pointer. For example, imagine you have a borrowed pointer `b` with
40 //! lifetime `L1` and you have an expression `&*b`. The result of this
41 //! expression will be another borrowed pointer with lifetime `L2` (which is
42 //! an inference variable). The borrow checker is going to enforce the
43 //! constraint that `L2 < L1`, because otherwise you are re-borrowing data
44 //! for a lifetime larger than the original loan. However, without the
45 //! routines in this module, the region inferencer would not know of this
46 //! dependency and thus it might infer the lifetime of `L2` to be greater
47 //! than `L1` (issue #3148).
48 //!
49 //! There are a number of troublesome scenarios in the tests
50 //! `region-dependent-*.rs`, but here is one example:
51 //!
52 //!     struct Foo { i: i32 }
53 //!     struct Bar { foo: Foo  }
54 //!     fn get_i<'a>(x: &'a Bar) -> &'a i32 {
55 //!        let foo = &x.foo; // Lifetime L1
56 //!        &foo.i            // Lifetime L2
57 //!     }
58 //!
59 //! Note that this comes up either with `&` expressions, `ref`
60 //! bindings, and `autorefs`, which are the three ways to introduce
61 //! a borrow.
62 //!
63 //! The key point here is that when you are borrowing a value that
64 //! is "guaranteed" by a borrowed pointer, you must link the
65 //! lifetime of that borrowed pointer (`L1`, here) to the lifetime of
66 //! the borrow itself (`L2`). What do I mean by "guaranteed" by a
67 //! borrowed pointer? I mean any data that is reached by first
68 //! dereferencing a borrowed pointer and then either traversing
69 //! interior offsets or boxes. We say that the guarantor
70 //! of such data is the region of the borrowed pointer that was
71 //! traversed. This is essentially the same as the ownership
72 //! relation, except that a borrowed pointer never owns its
73 //! contents.
74
75 use crate::check::dropck;
76 use crate::check::FnCtxt;
77 use crate::middle::mem_categorization as mc;
78 use crate::middle::mem_categorization::Categorization;
79 use crate::middle::region;
80 use rustc::hir::def_id::DefId;
81 use rustc::infer::outlives::env::OutlivesEnvironment;
82 use rustc::infer::{self, RegionObligation, SuppressRegionErrors};
83 use rustc::ty::adjustment;
84 use rustc::ty::subst::{SubstsRef, UnpackedKind};
85 use rustc::ty::{self, Ty};
86
87 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
88 use rustc::hir::{self, PatKind};
89 use std::mem;
90 use std::ops::Deref;
91 use std::rc::Rc;
92 use syntax_pos::Span;
93
94 // a variation on try that just returns unit
95 macro_rules! ignore_err {
96     ($e:expr) => {
97         match $e {
98             Ok(e) => e,
99             Err(_) => {
100                 debug!("ignoring mem-categorization error!");
101                 return ();
102             }
103         }
104     };
105 }
106
107 ///////////////////////////////////////////////////////////////////////////
108 // PUBLIC ENTRY POINTS
109
110 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
111     pub fn regionck_expr(&self, body: &'gcx hir::Body) {
112         let subject = self.tcx.hir().body_owner_def_id(body.id());
113         let id = body.value.hir_id;
114         let mut rcx = RegionCtxt::new(
115             self,
116             RepeatingScope(id),
117             id,
118             Subject(subject),
119             self.param_env,
120         );
121
122         // There are no add'l implied bounds when checking a
123         // standalone expr (e.g., the `E` in a type like `[u32; E]`).
124         rcx.outlives_environment.save_implied_bounds(id);
125
126         if self.err_count_since_creation() == 0 {
127             // regionck assumes typeck succeeded
128             rcx.visit_body(body);
129             rcx.visit_region_obligations(id);
130         }
131         rcx.resolve_regions_and_report_errors(SuppressRegionErrors::when_nll_is_enabled(self.tcx));
132
133         assert!(self.tables.borrow().free_region_map.is_empty());
134         self.tables.borrow_mut().free_region_map = rcx.outlives_environment.into_free_region_map();
135     }
136
137     /// Region checking during the WF phase for items. `wf_tys` are the
138     /// types from which we should derive implied bounds, if any.
139     pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: &[Ty<'tcx>]) {
140         debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys);
141         let subject = self.tcx.hir().local_def_id_from_hir_id(item_id);
142         let mut rcx = RegionCtxt::new(
143             self,
144             RepeatingScope(item_id),
145             item_id,
146             Subject(subject),
147             self.param_env,
148         );
149         rcx.outlives_environment
150             .add_implied_bounds(self, wf_tys, item_id, span);
151         rcx.outlives_environment.save_implied_bounds(item_id);
152         rcx.visit_region_obligations(item_id);
153         rcx.resolve_regions_and_report_errors(SuppressRegionErrors::default());
154     }
155
156     /// Region check a function body. Not invoked on closures, but
157     /// only on the "root" fn item (in which closures may be
158     /// embedded). Walks the function body and adds various add'l
159     /// constraints that are needed for region inference. This is
160     /// separated both to isolate "pure" region constraints from the
161     /// rest of type check and because sometimes we need type
162     /// inference to have completed before we can determine which
163     /// constraints to add.
164     pub fn regionck_fn(&self, fn_id: hir::HirId, body: &'gcx hir::Body) {
165         debug!("regionck_fn(id={})", fn_id);
166         let subject = self.tcx.hir().body_owner_def_id(body.id());
167         let hir_id = body.value.hir_id;
168         let mut rcx = RegionCtxt::new(
169             self,
170             RepeatingScope(hir_id),
171             hir_id,
172             Subject(subject),
173             self.param_env,
174         );
175
176         if self.err_count_since_creation() == 0 {
177             // regionck assumes typeck succeeded
178             rcx.visit_fn_body(fn_id, body, self.tcx.hir().span_by_hir_id(fn_id));
179         }
180
181         rcx.resolve_regions_and_report_errors(SuppressRegionErrors::when_nll_is_enabled(self.tcx));
182
183         // In this mode, we also copy the free-region-map into the
184         // tables of the enclosing fcx. In the other regionck modes
185         // (e.g., `regionck_item`), we don't have an enclosing tables.
186         assert!(self.tables.borrow().free_region_map.is_empty());
187         self.tables.borrow_mut().free_region_map = rcx.outlives_environment.into_free_region_map();
188     }
189 }
190
191 ///////////////////////////////////////////////////////////////////////////
192 // INTERNALS
193
194 pub struct RegionCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
195     pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
196
197     pub region_scope_tree: &'gcx region::ScopeTree,
198
199     outlives_environment: OutlivesEnvironment<'tcx>,
200
201     // id of innermost fn body id
202     body_id: hir::HirId,
203
204     // call_site scope of innermost fn
205     call_site_scope: Option<region::Scope>,
206
207     // id of innermost fn or loop
208     repeating_scope: hir::HirId,
209
210     // id of AST node being analyzed (the subject of the analysis).
211     subject_def_id: DefId,
212 }
213
214 impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> {
215     type Target = FnCtxt<'a, 'gcx, 'tcx>;
216     fn deref(&self) -> &Self::Target {
217         &self.fcx
218     }
219 }
220
221 pub struct RepeatingScope(hir::HirId);
222 pub struct Subject(DefId);
223
224 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
225     pub fn new(
226         fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
227         RepeatingScope(initial_repeating_scope): RepeatingScope,
228         initial_body_id: hir::HirId,
229         Subject(subject): Subject,
230         param_env: ty::ParamEnv<'tcx>,
231     ) -> RegionCtxt<'a, 'gcx, 'tcx> {
232         let region_scope_tree = fcx.tcx.region_scope_tree(subject);
233         let outlives_environment = OutlivesEnvironment::new(param_env);
234         RegionCtxt {
235             fcx,
236             region_scope_tree,
237             repeating_scope: initial_repeating_scope,
238             body_id: initial_body_id,
239             call_site_scope: None,
240             subject_def_id: subject,
241             outlives_environment,
242         }
243     }
244
245     fn set_repeating_scope(&mut self, scope: hir::HirId) -> hir::HirId {
246         mem::replace(&mut self.repeating_scope, scope)
247     }
248
249     /// Try to resolve the type for the given node, returning `t_err` if an error results. Note that
250     /// we never care about the details of the error, the same error will be detected and reported
251     /// in the writeback phase.
252     ///
253     /// Note one important point: we do not attempt to resolve *region variables* here. This is
254     /// because regionck is essentially adding constraints to those region variables and so may yet
255     /// influence how they are resolved.
256     ///
257     /// Consider this silly example:
258     ///
259     /// ```
260     /// fn borrow(x: &i32) -> &i32 {x}
261     /// fn foo(x: @i32) -> i32 {  // block: B
262     ///     let b = borrow(x);    // region: <R0>
263     ///     *b
264     /// }
265     /// ```
266     ///
267     /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
268     /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
269     /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
270     /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
271     /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
272     pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
273         self.resolve_type_vars_if_possible(&unresolved_ty)
274     }
275
276     /// Try to resolve the type for the given node.
277     fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> {
278         let t = self.node_ty(id);
279         self.resolve_type(t)
280     }
281
282     /// Try to resolve the type for the given node.
283     pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> {
284         let ty = self.tables.borrow().expr_ty_adjusted(expr);
285         self.resolve_type(ty)
286     }
287
288     /// This is the "main" function when region-checking a function item or a closure
289     /// within a function item. It begins by updating various fields (e.g., `call_site_scope`
290     /// and `outlives_environment`) to be appropriate to the function and then adds constraints
291     /// derived from the function body.
292     ///
293     /// Note that it does **not** restore the state of the fields that
294     /// it updates! This is intentional, since -- for the main
295     /// function -- we wish to be able to read the final
296     /// `outlives_environment` and other fields from the caller. For
297     /// closures, however, we save and restore any "scoped state"
298     /// before we invoke this function. (See `visit_fn` in the
299     /// `intravisit::Visitor` impl below.)
300     fn visit_fn_body(
301         &mut self,
302         id: hir::HirId, // the id of the fn itself
303         body: &'gcx hir::Body,
304         span: Span,
305     ) {
306         // When we enter a function, we can derive
307         debug!("visit_fn_body(id={:?})", id);
308
309         let body_id = body.id();
310         self.body_id = body_id.hir_id;
311
312         let call_site = region::Scope {
313             id: body.value.hir_id.local_id,
314             data: region::ScopeData::CallSite,
315         };
316         self.call_site_scope = Some(call_site);
317
318         let fn_sig = {
319             match self.tables.borrow().liberated_fn_sigs().get(id) {
320                 Some(f) => f.clone(),
321                 None => {
322                     bug!("No fn-sig entry for id={:?}", id);
323                 }
324             }
325         };
326
327         // Collect the types from which we create inferred bounds.
328         // For the return type, if diverging, substitute `bool` just
329         // because it will have no effect.
330         //
331         // FIXME(#27579) return types should not be implied bounds
332         let fn_sig_tys: Vec<_> = fn_sig
333             .inputs()
334             .iter()
335             .cloned()
336             .chain(Some(fn_sig.output()))
337             .collect();
338
339         self.outlives_environment.add_implied_bounds(
340             self.fcx,
341             &fn_sig_tys[..],
342             body_id.hir_id,
343             span,
344         );
345         self.outlives_environment
346             .save_implied_bounds(body_id.hir_id);
347         self.link_fn_args(
348             region::Scope {
349                 id: body.value.hir_id.local_id,
350                 data: region::ScopeData::Node,
351             },
352             &body.arguments,
353         );
354         self.visit_body(body);
355         self.visit_region_obligations(body_id.hir_id);
356
357         let call_site_scope = self.call_site_scope.unwrap();
358         debug!(
359             "visit_fn_body body.id {:?} call_site_scope: {:?}",
360             body.id(),
361             call_site_scope
362         );
363         let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
364
365         self.type_of_node_must_outlive(infer::CallReturn(span), body_id.hir_id, call_site_region);
366
367         self.constrain_opaque_types(
368             &self.fcx.opaque_types.borrow(),
369             self.outlives_environment.free_region_map(),
370         );
371     }
372
373     fn visit_region_obligations(&mut self, hir_id: hir::HirId) {
374         debug!("visit_region_obligations: hir_id={:?}", hir_id);
375
376         // region checking can introduce new pending obligations
377         // which, when processed, might generate new region
378         // obligations. So make sure we process those.
379         self.select_all_obligations_or_error();
380     }
381
382     fn resolve_regions_and_report_errors(&self, suppress: SuppressRegionErrors) {
383         self.infcx.process_registered_region_obligations(
384             self.outlives_environment.region_bound_pairs_map(),
385             self.implicit_region_bound,
386             self.param_env,
387         );
388
389         self.fcx.resolve_regions_and_report_errors(
390             self.subject_def_id,
391             &self.region_scope_tree,
392             &self.outlives_environment,
393             suppress,
394         );
395     }
396
397     fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) {
398         debug!("regionck::visit_pat(pat={:?})", pat);
399         pat.each_binding(|_, hir_id, span, _| {
400             // If we have a variable that contains region'd data, that
401             // data will be accessible from anywhere that the variable is
402             // accessed. We must be wary of loops like this:
403             //
404             //     // from src/test/compile-fail/borrowck-lend-flow.rs
405             //     let mut v = box 3, w = box 4;
406             //     let mut x = &mut w;
407             //     loop {
408             //         **x += 1;   // (2)
409             //         borrow(v);  //~ ERROR cannot borrow
410             //         x = &mut v; // (1)
411             //     }
412             //
413             // Typically, we try to determine the region of a borrow from
414             // those points where it is dereferenced. In this case, one
415             // might imagine that the lifetime of `x` need only be the
416             // body of the loop. But of course this is incorrect because
417             // the pointer that is created at point (1) is consumed at
418             // point (2), meaning that it must be live across the loop
419             // iteration. The easiest way to guarantee this is to require
420             // that the lifetime of any regions that appear in a
421             // variable's type enclose at least the variable's scope.
422             let var_scope = self.region_scope_tree.var_scope(hir_id.local_id);
423             let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
424
425             let origin = infer::BindingTypeIsNotValidAtDecl(span);
426             self.type_of_node_must_outlive(origin, hir_id, var_region);
427
428             let typ = self.resolve_node_type(hir_id);
429             let body_id = self.body_id;
430             let _ = dropck::check_safety_of_destructor_if_necessary(
431                 self, typ, span, body_id, var_scope,
432             );
433         })
434     }
435 }
436
437 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for RegionCtxt<'a, 'gcx, 'tcx> {
438     // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
439     // However, right now we run into an issue whereby some free
440     // regions are not properly related if they appear within the
441     // types of arguments that must be inferred. This could be
442     // addressed by deferring the construction of the region
443     // hierarchy, and in particular the relationships between free
444     // regions, until regionck, as described in #3238.
445
446     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
447         NestedVisitorMap::None
448     }
449
450     fn visit_fn(
451         &mut self,
452         fk: intravisit::FnKind<'gcx>,
453         _: &'gcx hir::FnDecl,
454         body_id: hir::BodyId,
455         span: Span,
456         hir_id: hir::HirId,
457     ) {
458         assert!(
459             match fk {
460                 intravisit::FnKind::Closure(..) => true,
461                 _ => false,
462             },
463             "visit_fn invoked for something other than a closure"
464         );
465
466         // Save state of current function before invoking
467         // `visit_fn_body`.  We will restore afterwards.
468         let old_body_id = self.body_id;
469         let old_call_site_scope = self.call_site_scope;
470         let env_snapshot = self.outlives_environment.push_snapshot_pre_closure();
471
472         let body = self.tcx.hir().body(body_id);
473         self.visit_fn_body(hir_id, body, span);
474
475         // Restore state from previous function.
476         self.outlives_environment
477             .pop_snapshot_post_closure(env_snapshot);
478         self.call_site_scope = old_call_site_scope;
479         self.body_id = old_body_id;
480     }
481
482     //visit_pat: visit_pat, // (..) see above
483
484     fn visit_arm(&mut self, arm: &'gcx hir::Arm) {
485         // see above
486         for p in &arm.pats {
487             self.constrain_bindings_in_pat(p);
488         }
489         intravisit::walk_arm(self, arm);
490     }
491
492     fn visit_local(&mut self, l: &'gcx hir::Local) {
493         // see above
494         self.constrain_bindings_in_pat(&l.pat);
495         self.link_local(l);
496         intravisit::walk_local(self, l);
497     }
498
499     fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
500         debug!(
501             "regionck::visit_expr(e={:?}, repeating_scope={:?})",
502             expr, self.repeating_scope
503         );
504
505         // No matter what, the type of each expression must outlive the
506         // scope of that expression. This also guarantees basic WF.
507         let expr_ty = self.resolve_node_type(expr.hir_id);
508         // the region corresponding to this expression
509         let expr_region = self.tcx.mk_region(ty::ReScope(region::Scope {
510             id: expr.hir_id.local_id,
511             data: region::ScopeData::Node,
512         }));
513         self.type_must_outlive(
514             infer::ExprTypeIsNotInScope(expr_ty, expr.span),
515             expr_ty,
516             expr_region,
517         );
518
519         let is_method_call = self.tables.borrow().is_method_call(expr);
520
521         // If we are calling a method (either explicitly or via an
522         // overloaded operator), check that all of the types provided as
523         // arguments for its type parameters are well-formed, and all the regions
524         // provided as arguments outlive the call.
525         if is_method_call {
526             let origin = match expr.node {
527                 hir::ExprKind::MethodCall(..) => infer::ParameterOrigin::MethodCall,
528                 hir::ExprKind::Unary(op, _) if op == hir::UnDeref => {
529                     infer::ParameterOrigin::OverloadedDeref
530                 }
531                 _ => infer::ParameterOrigin::OverloadedOperator,
532             };
533
534             let substs = self.tables.borrow().node_substs(expr.hir_id);
535             self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
536             // Arguments (sub-expressions) are checked via `constrain_call`, below.
537         }
538
539         // Check any autoderefs or autorefs that appear.
540         let cmt_result = self.constrain_adjustments(expr);
541
542         // If necessary, constrain destructors in this expression. This will be
543         // the adjusted form if there is an adjustment.
544         match cmt_result {
545             Ok(head_cmt) => {
546                 self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span);
547             }
548             Err(..) => {
549                 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
550             }
551         }
552
553         debug!(
554             "regionck::visit_expr(e={:?}, repeating_scope={:?}) - visiting subexprs",
555             expr, self.repeating_scope
556         );
557         match expr.node {
558             hir::ExprKind::Path(_) => {
559                 let substs = self.tables.borrow().node_substs(expr.hir_id);
560                 let origin = infer::ParameterOrigin::Path;
561                 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
562             }
563
564             hir::ExprKind::Call(ref callee, ref args) => {
565                 if is_method_call {
566                     self.constrain_call(expr, Some(&callee), args.iter().map(|e| &*e));
567                 } else {
568                     self.constrain_callee(&callee);
569                     self.constrain_call(expr, None, args.iter().map(|e| &*e));
570                 }
571
572                 intravisit::walk_expr(self, expr);
573             }
574
575             hir::ExprKind::MethodCall(.., ref args) => {
576                 self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &*e));
577
578                 intravisit::walk_expr(self, expr);
579             }
580
581             hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
582                 if is_method_call {
583                     self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
584                 }
585
586                 intravisit::walk_expr(self, expr);
587             }
588
589             hir::ExprKind::Index(ref lhs, ref rhs) if is_method_call => {
590                 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
591
592                 intravisit::walk_expr(self, expr);
593             }
594
595             hir::ExprKind::Binary(_, ref lhs, ref rhs) if is_method_call => {
596                 // As `ExprKind::MethodCall`, but the call is via an overloaded op.
597                 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
598
599                 intravisit::walk_expr(self, expr);
600             }
601
602             hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
603                 // If you do `x OP y`, then the types of `x` and `y` must
604                 // outlive the operation you are performing.
605                 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
606                 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
607                 for &ty in &[lhs_ty, rhs_ty] {
608                     self.type_must_outlive(infer::Operand(expr.span), ty, expr_region);
609                 }
610                 intravisit::walk_expr(self, expr);
611             }
612
613             hir::ExprKind::Unary(hir::UnDeref, ref base) => {
614                 // For *a, the lifetime of a must enclose the deref
615                 if is_method_call {
616                     self.constrain_call(expr, Some(base), None::<hir::Expr>.iter());
617                 }
618                 // For overloaded derefs, base_ty is the input to `Deref::deref`,
619                 // but it's a reference type uing the same region as the output.
620                 let base_ty = self.resolve_expr_type_adjusted(base);
621                 if let ty::Ref(r_ptr, _, _) = base_ty.sty {
622                     self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
623                 }
624
625                 intravisit::walk_expr(self, expr);
626             }
627
628             hir::ExprKind::Unary(_, ref lhs) if is_method_call => {
629                 // As above.
630                 self.constrain_call(expr, Some(&lhs), None::<hir::Expr>.iter());
631
632                 intravisit::walk_expr(self, expr);
633             }
634
635             hir::ExprKind::Index(ref vec_expr, _) => {
636                 // For a[b], the lifetime of a must enclose the deref
637                 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
638                 self.constrain_index(expr, vec_type);
639
640                 intravisit::walk_expr(self, expr);
641             }
642
643             hir::ExprKind::Cast(ref source, _) => {
644                 // Determine if we are casting `source` to a trait
645                 // instance.  If so, we have to be sure that the type of
646                 // the source obeys the trait's region bound.
647                 self.constrain_cast(expr, &source);
648                 intravisit::walk_expr(self, expr);
649             }
650
651             hir::ExprKind::AddrOf(m, ref base) => {
652                 self.link_addr_of(expr, m, &base);
653
654                 // Require that when you write a `&expr` expression, the
655                 // resulting pointer has a lifetime that encompasses the
656                 // `&expr` expression itself. Note that we constraining
657                 // the type of the node expr.id here *before applying
658                 // adjustments*.
659                 //
660                 // FIXME(https://github.com/rust-lang/rfcs/issues/811)
661                 // nested method calls requires that this rule change
662                 let ty0 = self.resolve_node_type(expr.hir_id);
663                 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
664                 intravisit::walk_expr(self, expr);
665             }
666
667             hir::ExprKind::Match(ref discr, ref arms, _) => {
668                 self.link_match(&discr, &arms[..]);
669
670                 intravisit::walk_expr(self, expr);
671             }
672
673             hir::ExprKind::Closure(.., body_id, _, _) => {
674                 self.check_expr_fn_block(expr, body_id);
675             }
676
677             hir::ExprKind::Loop(ref body, _, _) => {
678                 let repeating_scope = self.set_repeating_scope(body.hir_id);
679                 intravisit::walk_expr(self, expr);
680                 self.set_repeating_scope(repeating_scope);
681             }
682
683             hir::ExprKind::While(ref cond, ref body, _) => {
684                 let repeating_scope = self.set_repeating_scope(cond.hir_id);
685                 self.visit_expr(&cond);
686
687                 self.set_repeating_scope(body.hir_id);
688                 self.visit_block(&body);
689
690                 self.set_repeating_scope(repeating_scope);
691             }
692
693             hir::ExprKind::Ret(Some(ref ret_expr)) => {
694                 let call_site_scope = self.call_site_scope;
695                 debug!(
696                     "visit_expr ExprKind::Ret ret_expr.hir_id {} call_site_scope: {:?}",
697                     ret_expr.hir_id, call_site_scope
698                 );
699                 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
700                 self.type_of_node_must_outlive(
701                     infer::CallReturn(ret_expr.span),
702                     ret_expr.hir_id,
703                     call_site_region,
704                 );
705                 intravisit::walk_expr(self, expr);
706             }
707
708             _ => {
709                 intravisit::walk_expr(self, expr);
710             }
711         }
712     }
713 }
714
715 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
716     fn constrain_cast(&mut self, cast_expr: &hir::Expr, source_expr: &hir::Expr) {
717         debug!(
718             "constrain_cast(cast_expr={:?}, source_expr={:?})",
719             cast_expr, source_expr
720         );
721
722         let source_ty = self.resolve_node_type(source_expr.hir_id);
723         let target_ty = self.resolve_node_type(cast_expr.hir_id);
724
725         self.walk_cast(cast_expr, source_ty, target_ty);
726     }
727
728     fn walk_cast(&mut self, cast_expr: &hir::Expr, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) {
729         debug!("walk_cast(from_ty={:?}, to_ty={:?})", from_ty, to_ty);
730         match (&from_ty.sty, &to_ty.sty) {
731             /*From:*/
732             (&ty::Ref(from_r, from_ty, _), /*To:  */ &ty::Ref(to_r, to_ty, _)) => {
733                 // Target cannot outlive source, naturally.
734                 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
735                 self.walk_cast(cast_expr, from_ty, to_ty);
736             }
737
738             /*From:*/
739             (_, /*To:  */ &ty::Dynamic(.., r)) => {
740                 // When T is existentially quantified as a trait
741                 // `Foo+'to`, it must outlive the region bound `'to`.
742                 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
743             }
744
745             /*From:*/
746             (&ty::Adt(from_def, _), /*To:  */ &ty::Adt(to_def, _))
747                 if from_def.is_box() && to_def.is_box() =>
748             {
749                 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
750             }
751
752             _ => {}
753         }
754     }
755
756     fn check_expr_fn_block(&mut self, expr: &'gcx hir::Expr, body_id: hir::BodyId) {
757         let repeating_scope = self.set_repeating_scope(body_id.hir_id);
758         intravisit::walk_expr(self, expr);
759         self.set_repeating_scope(repeating_scope);
760     }
761
762     fn constrain_callee(&mut self, callee_expr: &hir::Expr) {
763         let callee_ty = self.resolve_node_type(callee_expr.hir_id);
764         match callee_ty.sty {
765             ty::FnDef(..) | ty::FnPtr(_) => {}
766             _ => {
767                 // this should not happen, but it does if the program is
768                 // erroneous
769                 //
770                 // bug!(
771                 //     callee_expr.span,
772                 //     "Calling non-function: {}",
773                 //     callee_ty);
774             }
775         }
776     }
777
778     fn constrain_call<'b, I: Iterator<Item = &'b hir::Expr>>(
779         &mut self,
780         call_expr: &hir::Expr,
781         receiver: Option<&hir::Expr>,
782         arg_exprs: I,
783     ) {
784         //! Invoked on every call site (i.e., normal calls, method calls,
785         //! and overloaded operators). Constrains the regions which appear
786         //! in the type of the function. Also constrains the regions that
787         //! appear in the arguments appropriately.
788
789         debug!(
790             "constrain_call(call_expr={:?}, receiver={:?})",
791             call_expr, receiver
792         );
793
794         // `callee_region` is the scope representing the time in which the
795         // call occurs.
796         //
797         // FIXME(#6268) to support nested method calls, should be callee_id
798         let callee_scope = region::Scope {
799             id: call_expr.hir_id.local_id,
800             data: region::ScopeData::Node,
801         };
802         let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
803
804         debug!("callee_region={:?}", callee_region);
805
806         for arg_expr in arg_exprs {
807             debug!("Argument: {:?}", arg_expr);
808
809             // ensure that any regions appearing in the argument type are
810             // valid for at least the lifetime of the function:
811             self.type_of_node_must_outlive(
812                 infer::CallArg(arg_expr.span),
813                 arg_expr.hir_id,
814                 callee_region,
815             );
816         }
817
818         // as loop above, but for receiver
819         if let Some(r) = receiver {
820             debug!("receiver: {:?}", r);
821             self.type_of_node_must_outlive(infer::CallRcvr(r.span), r.hir_id, callee_region);
822         }
823     }
824
825     /// Creates a temporary `MemCategorizationContext` and pass it to the closure.
826     fn with_mc<F, R>(&self, f: F) -> R
827     where
828         F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'gcx, 'tcx>) -> R,
829     {
830         f(mc::MemCategorizationContext::with_infer(
831             &self.infcx,
832             &self.region_scope_tree,
833             &self.tables.borrow(),
834         ))
835     }
836
837     /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
838     /// dereferenced, the lifetime of the pointer includes the deref expr.
839     fn constrain_adjustments(&mut self, expr: &hir::Expr) -> mc::McResult<mc::cmt_<'tcx>> {
840         debug!("constrain_adjustments(expr={:?})", expr);
841
842         let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
843
844         let tables = self.tables.borrow();
845         let adjustments = tables.expr_adjustments(&expr);
846         if adjustments.is_empty() {
847             return Ok(cmt);
848         }
849
850         debug!("constrain_adjustments: adjustments={:?}", adjustments);
851
852         // If necessary, constrain destructors in the unadjusted form of this
853         // expression.
854         self.check_safety_of_rvalue_destructor_if_necessary(&cmt, expr.span);
855
856         let expr_region = self.tcx.mk_region(ty::ReScope(region::Scope {
857             id: expr.hir_id.local_id,
858             data: region::ScopeData::Node,
859         }));
860         for adjustment in adjustments {
861             debug!(
862                 "constrain_adjustments: adjustment={:?}, cmt={:?}",
863                 adjustment, cmt
864             );
865
866             if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
867                 debug!("constrain_adjustments: overloaded deref: {:?}", deref);
868
869                 // Treat overloaded autoderefs as if an AutoBorrow adjustment
870                 // was applied on the base type, as that is always the case.
871                 let input = self.tcx.mk_ref(
872                     deref.region,
873                     ty::TypeAndMut {
874                         ty: cmt.ty,
875                         mutbl: deref.mutbl,
876                     },
877                 );
878                 let output = self.tcx.mk_ref(
879                     deref.region,
880                     ty::TypeAndMut {
881                         ty: adjustment.target,
882                         mutbl: deref.mutbl,
883                     },
884                 );
885
886                 self.link_region(
887                     expr.span,
888                     deref.region,
889                     ty::BorrowKind::from_mutbl(deref.mutbl),
890                     &cmt,
891                 );
892
893                 // Specialized version of constrain_call.
894                 self.type_must_outlive(infer::CallRcvr(expr.span), input, expr_region);
895                 self.type_must_outlive(infer::CallReturn(expr.span), output, expr_region);
896             }
897
898             if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
899                 self.link_autoref(expr, &cmt, autoref);
900
901                 // Require that the resulting region encompasses
902                 // the current node.
903                 //
904                 // FIXME(#6268) remove to support nested method calls
905                 self.type_of_node_must_outlive(
906                     infer::AutoBorrow(expr.span),
907                     expr.hir_id,
908                     expr_region,
909                 );
910             }
911
912             cmt = self.with_mc(|mc| mc.cat_expr_adjusted(expr, cmt, &adjustment))?;
913
914             if let Categorization::Deref(_, mc::BorrowedPtr(_, r_ptr)) = cmt.cat {
915                 self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
916             }
917         }
918
919         Ok(cmt)
920     }
921
922     pub fn mk_subregion_due_to_dereference(
923         &mut self,
924         deref_span: Span,
925         minimum_lifetime: ty::Region<'tcx>,
926         maximum_lifetime: ty::Region<'tcx>,
927     ) {
928         self.sub_regions(
929             infer::DerefPointer(deref_span),
930             minimum_lifetime,
931             maximum_lifetime,
932         )
933     }
934
935     fn check_safety_of_rvalue_destructor_if_necessary(&mut self, cmt: &mc::cmt_<'tcx>, span: Span) {
936         if let Categorization::Rvalue(region) = cmt.cat {
937             match *region {
938                 ty::ReScope(rvalue_scope) => {
939                     let typ = self.resolve_type(cmt.ty);
940                     let body_id = self.body_id;
941                     let _ = dropck::check_safety_of_destructor_if_necessary(
942                         self,
943                         typ,
944                         span,
945                         body_id,
946                         rvalue_scope,
947                     );
948                 }
949                 ty::ReStatic => {}
950                 _ => {
951                     span_bug!(
952                         span,
953                         "unexpected rvalue region in rvalue \
954                          destructor safety checking: `{:?}`",
955                         region
956                     );
957                 }
958             }
959         }
960     }
961
962     /// Invoked on any index expression that occurs. Checks that if this is a slice
963     /// being indexed, the lifetime of the pointer includes the deref expr.
964     fn constrain_index(&mut self, index_expr: &hir::Expr, indexed_ty: Ty<'tcx>) {
965         debug!(
966             "constrain_index(index_expr=?, indexed_ty={}",
967             self.ty_to_string(indexed_ty)
968         );
969
970         let r_index_expr = ty::ReScope(region::Scope {
971             id: index_expr.hir_id.local_id,
972             data: region::ScopeData::Node,
973         });
974         if let ty::Ref(r_ptr, r_ty, _) = indexed_ty.sty {
975             match r_ty.sty {
976                 ty::Slice(_) | ty::Str => {
977                     self.sub_regions(
978                         infer::IndexSlice(index_expr.span),
979                         self.tcx.mk_region(r_index_expr),
980                         r_ptr,
981                     );
982                 }
983                 _ => {}
984             }
985         }
986     }
987
988     /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
989     /// adjustments) are valid for at least `minimum_lifetime`
990     fn type_of_node_must_outlive(
991         &mut self,
992         origin: infer::SubregionOrigin<'tcx>,
993         hir_id: hir::HirId,
994         minimum_lifetime: ty::Region<'tcx>,
995     ) {
996         // Try to resolve the type.  If we encounter an error, then typeck
997         // is going to fail anyway, so just stop here and let typeck
998         // report errors later on in the writeback phase.
999         let ty0 = self.resolve_node_type(hir_id);
1000
1001         let ty = self.tables
1002             .borrow()
1003             .adjustments()
1004             .get(hir_id)
1005             .and_then(|adj| adj.last())
1006             .map_or(ty0, |adj| adj.target);
1007         let ty = self.resolve_type(ty);
1008         debug!(
1009             "constrain_regions_in_type_of_node(\
1010              ty={}, ty0={}, id={:?}, minimum_lifetime={:?})",
1011             ty, ty0, hir_id, minimum_lifetime
1012         );
1013         self.type_must_outlive(origin, ty, minimum_lifetime);
1014     }
1015
1016     /// Adds constraints to inference such that `T: 'a` holds (or
1017     /// reports an error if it cannot).
1018     ///
1019     /// # Parameters
1020     ///
1021     /// - `origin`, the reason we need this constraint
1022     /// - `ty`, the type `T`
1023     /// - `region`, the region `'a`
1024     pub fn type_must_outlive(
1025         &self,
1026         origin: infer::SubregionOrigin<'tcx>,
1027         ty: Ty<'tcx>,
1028         region: ty::Region<'tcx>,
1029     ) {
1030         self.infcx.register_region_obligation(
1031             self.body_id,
1032             RegionObligation {
1033                 sub_region: region,
1034                 sup_type: ty,
1035                 origin,
1036             },
1037         );
1038     }
1039
1040     /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1041     /// resulting pointer is linked to the lifetime of its guarantor (if any).
1042     fn link_addr_of(&mut self, expr: &hir::Expr, mutability: hir::Mutability, base: &hir::Expr) {
1043         debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
1044
1045         let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
1046
1047         debug!("link_addr_of: cmt={:?}", cmt);
1048
1049         self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt);
1050     }
1051
1052     /// Computes the guarantors for any ref bindings in a `let` and
1053     /// then ensures that the lifetime of the resulting pointer is
1054     /// linked to the lifetime of the initialization expression.
1055     fn link_local(&self, local: &hir::Local) {
1056         debug!("regionck::for_local()");
1057         let init_expr = match local.init {
1058             None => {
1059                 return;
1060             }
1061             Some(ref expr) => &**expr,
1062         };
1063         let discr_cmt = Rc::new(ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr))));
1064         self.link_pattern(discr_cmt, &local.pat);
1065     }
1066
1067     /// Computes the guarantors for any ref bindings in a match and
1068     /// then ensures that the lifetime of the resulting pointer is
1069     /// linked to the lifetime of its guarantor (if any).
1070     fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) {
1071         debug!("regionck::for_match()");
1072         let discr_cmt = Rc::new(ignore_err!(self.with_mc(|mc| mc.cat_expr(discr))));
1073         debug!("discr_cmt={:?}", discr_cmt);
1074         for arm in arms {
1075             for root_pat in &arm.pats {
1076                 self.link_pattern(discr_cmt.clone(), &root_pat);
1077             }
1078         }
1079     }
1080
1081     /// Computes the guarantors for any ref bindings in a match and
1082     /// then ensures that the lifetime of the resulting pointer is
1083     /// linked to the lifetime of its guarantor (if any).
1084     fn link_fn_args(&self, body_scope: region::Scope, args: &[hir::Arg]) {
1085         debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1086         for arg in args {
1087             let arg_ty = self.node_ty(arg.hir_id);
1088             let re_scope = self.tcx.mk_region(ty::ReScope(body_scope));
1089             let arg_cmt = self.with_mc(|mc| {
1090                 Rc::new(mc.cat_rvalue(arg.hir_id, arg.pat.span, re_scope, arg_ty))
1091             });
1092             debug!("arg_ty={:?} arg_cmt={:?} arg={:?}", arg_ty, arg_cmt, arg);
1093             self.link_pattern(arg_cmt, &arg.pat);
1094         }
1095     }
1096
1097     /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1098     /// in the discriminant, if needed.
1099     fn link_pattern(&self, discr_cmt: mc::cmt<'tcx>, root_pat: &hir::Pat) {
1100         debug!(
1101             "link_pattern(discr_cmt={:?}, root_pat={:?})",
1102             discr_cmt, root_pat
1103         );
1104         ignore_err!(self.with_mc(|mc| {
1105             mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, sub_pat| {
1106                 // `ref x` pattern
1107                 if let PatKind::Binding(..) = sub_pat.node {
1108                     if let Some(&bm) = mc.tables.pat_binding_modes().get(sub_pat.hir_id) {
1109                         if let ty::BindByReference(mutbl) = bm {
1110                             self.link_region_from_node_type(
1111                                 sub_pat.span,
1112                                 sub_pat.hir_id,
1113                                 mutbl,
1114                                 &sub_cmt,
1115                             );
1116                         }
1117                     } else {
1118                         self.tcx
1119                             .sess
1120                             .delay_span_bug(sub_pat.span, "missing binding mode");
1121                     }
1122                 }
1123             })
1124         }));
1125     }
1126
1127     /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1128     /// autoref'd.
1129     fn link_autoref(
1130         &self,
1131         expr: &hir::Expr,
1132         expr_cmt: &mc::cmt_<'tcx>,
1133         autoref: &adjustment::AutoBorrow<'tcx>,
1134     ) {
1135         debug!(
1136             "link_autoref(autoref={:?}, expr_cmt={:?})",
1137             autoref, expr_cmt
1138         );
1139
1140         match *autoref {
1141             adjustment::AutoBorrow::Ref(r, m) => {
1142                 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt);
1143             }
1144
1145             adjustment::AutoBorrow::RawPtr(m) => {
1146                 let r = self.tcx.mk_region(ty::ReScope(region::Scope {
1147                     id: expr.hir_id.local_id,
1148                     data: region::ScopeData::Node,
1149                 }));
1150                 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1151             }
1152         }
1153     }
1154
1155     /// Like `link_region()`, except that the region is extracted from the type of `id`,
1156     /// which must be some reference (`&T`, `&str`, etc).
1157     fn link_region_from_node_type(
1158         &self,
1159         span: Span,
1160         id: hir::HirId,
1161         mutbl: hir::Mutability,
1162         cmt_borrowed: &mc::cmt_<'tcx>,
1163     ) {
1164         debug!(
1165             "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1166             id, mutbl, cmt_borrowed
1167         );
1168
1169         let rptr_ty = self.resolve_node_type(id);
1170         if let ty::Ref(r, _, _) = rptr_ty.sty {
1171             debug!("rptr_ty={}", rptr_ty);
1172             self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed);
1173         }
1174     }
1175
1176     /// Informs the inference engine that `borrow_cmt` is being borrowed with
1177     /// kind `borrow_kind` and lifetime `borrow_region`.
1178     /// In order to ensure borrowck is satisfied, this may create constraints
1179     /// between regions, as explained in `link_reborrowed_region()`.
1180     fn link_region(
1181         &self,
1182         span: Span,
1183         borrow_region: ty::Region<'tcx>,
1184         borrow_kind: ty::BorrowKind,
1185         borrow_cmt: &mc::cmt_<'tcx>,
1186     ) {
1187         let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1188         self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
1189
1190         let mut borrow_kind = borrow_kind;
1191         let mut borrow_cmt_cat = borrow_cmt.cat.clone();
1192
1193         loop {
1194             debug!(
1195                 "link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1196                 borrow_region, borrow_kind, borrow_cmt
1197             );
1198             match borrow_cmt_cat {
1199                 Categorization::Deref(ref_cmt, mc::BorrowedPtr(ref_kind, ref_region)) => {
1200                     match self.link_reborrowed_region(
1201                         span,
1202                         borrow_region,
1203                         borrow_kind,
1204                         ref_cmt,
1205                         ref_region,
1206                         ref_kind,
1207                         borrow_cmt.note,
1208                     ) {
1209                         Some((c, k)) => {
1210                             borrow_cmt_cat = c.cat.clone();
1211                             borrow_kind = k;
1212                         }
1213                         None => {
1214                             return;
1215                         }
1216                     }
1217                 }
1218
1219                 Categorization::Downcast(cmt_base, _)
1220                 | Categorization::Deref(cmt_base, mc::Unique)
1221                 | Categorization::Interior(cmt_base, _) => {
1222                     // Borrowing interior or owned data requires the base
1223                     // to be valid and borrowable in the same fashion.
1224                     borrow_cmt_cat = cmt_base.cat.clone();
1225                     borrow_kind = borrow_kind;
1226                 }
1227
1228                 Categorization::Deref(_, mc::UnsafePtr(..))
1229                 | Categorization::StaticItem
1230                 | Categorization::Upvar(..)
1231                 | Categorization::Local(..)
1232                 | Categorization::ThreadLocal(..)
1233                 | Categorization::Rvalue(..) => {
1234                     // These are all "base cases" with independent lifetimes
1235                     // that are not subject to inference
1236                     return;
1237                 }
1238             }
1239         }
1240     }
1241
1242     /// This is the most complicated case: the path being borrowed is
1243     /// itself the referent of a borrowed pointer. Let me give an
1244     /// example fragment of code to make clear(er) the situation:
1245     ///
1246     ///    let r: &'a mut T = ...;  // the original reference "r" has lifetime 'a
1247     ///    ...
1248     ///    &'z *r                   // the reborrow has lifetime 'z
1249     ///
1250     /// Now, in this case, our primary job is to add the inference
1251     /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1252     /// parameters in (roughly) terms of the example:
1253     ///
1254     /// ```plain,ignore (pseudo-Rust)
1255     ///     A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1256     ///     borrow_region   ^~                 ref_region    ^~
1257     ///     borrow_kind        ^~               ref_kind        ^~
1258     ///     ref_cmt                 ^
1259     /// ```
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(
1285         &self,
1286         span: Span,
1287         borrow_region: ty::Region<'tcx>,
1288         borrow_kind: ty::BorrowKind,
1289         ref_cmt: mc::cmt<'tcx>,
1290         ref_region: ty::Region<'tcx>,
1291         mut ref_kind: ty::BorrowKind,
1292         note: mc::Note,
1293     ) -> Option<(mc::cmt<'tcx>, ty::BorrowKind)> {
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                 match self.tables.borrow().upvar_capture_map.get(upvar_id) {
1301                     Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1302                         // The mutability of the upvar may have been modified
1303                         // by the above adjustment, so update our local variable.
1304                         ref_kind = upvar_borrow.kind;
1305
1306                         infer::ReborrowUpvar(span, *upvar_id)
1307                     }
1308                     _ => {
1309                         span_bug!(span, "Illegal upvar id: {:?}", upvar_id);
1310                     }
1311                 }
1312             }
1313             mc::NoteClosureEnv(ref upvar_id) => {
1314                 // We don't have any mutability changes to propagate, but
1315                 // we do want to note that an upvar reborrow caused this
1316                 // link
1317                 infer::ReborrowUpvar(span, *upvar_id)
1318             }
1319             _ => infer::Reborrow(span),
1320         };
1321
1322         debug!(
1323             "link_reborrowed_region: {:?} <= {:?}",
1324             borrow_region, ref_region
1325         );
1326         self.sub_regions(cause, borrow_region, ref_region);
1327
1328         // If we end up needing to recurse and establish a region link
1329         // with `ref_cmt`, calculate what borrow kind we will end up
1330         // needing. This will be used below.
1331         //
1332         // One interesting twist is that we can weaken the borrow kind
1333         // when we recurse: to reborrow an `&mut` referent as mutable,
1334         // borrowck requires a unique path to the `&mut` reference but not
1335         // necessarily a *mutable* path.
1336         let new_borrow_kind = match borrow_kind {
1337             ty::ImmBorrow => ty::ImmBorrow,
1338             ty::MutBorrow | ty::UniqueImmBorrow => ty::UniqueImmBorrow,
1339         };
1340
1341         // Decide whether we need to recurse and link any regions within
1342         // the `ref_cmt`. This is concerned for the case where the value
1343         // being reborrowed is in fact a borrowed pointer found within
1344         // another borrowed pointer. For example:
1345         //
1346         //    let p: &'b &'a mut T = ...;
1347         //    ...
1348         //    &'z **p
1349         //
1350         // What makes this case particularly tricky is that, if the data
1351         // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1352         // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1353         // (otherwise the user might mutate through the `&mut T` reference
1354         // after `'b` expires and invalidate the borrow we are looking at
1355         // now).
1356         //
1357         // So let's re-examine our parameters in light of this more
1358         // complicated (possible) scenario:
1359         //
1360         //     A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1361         //     borrow_region   ^~                 ref_region             ^~
1362         //     borrow_kind        ^~               ref_kind                 ^~
1363         //     ref_cmt                 ^~~
1364         //
1365         // (Note that since we have not examined `ref_cmt.cat`, we don't
1366         // know whether this scenario has occurred; but I wanted to show
1367         // how all the types get adjusted.)
1368         match ref_kind {
1369             ty::ImmBorrow => {
1370                 // The reference being reborrowed is a shareable ref of
1371                 // type `&'a T`. In this case, it doesn't matter where we
1372                 // *found* the `&T` pointer, the memory it references will
1373                 // be valid and immutable for `'a`. So we can stop here.
1374                 //
1375                 // (Note that the `borrow_kind` must also be ImmBorrow or
1376                 // else the user is borrowed imm memory as mut memory,
1377                 // which means they'll get an error downstream in borrowck
1378                 // anyhow.)
1379                 return None;
1380             }
1381
1382             ty::MutBorrow | ty::UniqueImmBorrow => {
1383                 // The reference being reborrowed is either an `&mut T` or
1384                 // `&uniq T`. This is the case where recursion is needed.
1385                 return Some((ref_cmt, new_borrow_kind));
1386             }
1387         }
1388     }
1389
1390     /// Checks that the values provided for type/region arguments in a given
1391     /// expression are well-formed and in-scope.
1392     fn substs_wf_in_scope(
1393         &mut self,
1394         origin: infer::ParameterOrigin,
1395         substs: SubstsRef<'tcx>,
1396         expr_span: Span,
1397         expr_region: ty::Region<'tcx>,
1398     ) {
1399         debug!(
1400             "substs_wf_in_scope(substs={:?}, \
1401              expr_region={:?}, \
1402              origin={:?}, \
1403              expr_span={:?})",
1404             substs, expr_region, origin, expr_span
1405         );
1406
1407         let origin = infer::ParameterInScope(origin, expr_span);
1408
1409         for kind in substs {
1410             match kind.unpack() {
1411                 UnpackedKind::Lifetime(lt) => {
1412                     self.sub_regions(origin.clone(), expr_region, lt);
1413                 }
1414                 UnpackedKind::Type(ty) => {
1415                     let ty = self.resolve_type(ty);
1416                     self.type_must_outlive(origin.clone(), ty, expr_region);
1417                 }
1418                 UnpackedKind::Const(_) => {
1419                     // Const parameters don't impose constraints.
1420                 }
1421             }
1422         }
1423     }
1424 }