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