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