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