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