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 crate::outlives::outlives_bounds::InferCtxtExt as _;
80 use rustc_data_structures::stable_set::FxHashSet;
81 use rustc_hir as hir;
82 use rustc_hir::def_id::LocalDefId;
83 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
84 use rustc_hir::PatKind;
85 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
86 use rustc_infer::infer::{self, InferCtxt, RegionObligation, RegionckMode};
87 use rustc_middle::hir::place::{PlaceBase, PlaceWithHirId};
88 use rustc_middle::ty::adjustment;
89 use rustc_middle::ty::{self, Ty};
90 use rustc_span::Span;
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 pub(crate) trait OutlivesEnvironmentExt<'tcx> {
add_implied_bounds( &mut self, infcx: &InferCtxt<'a, 'tcx>, fn_sig_tys: FxHashSet<Ty<'tcx>>, body_id: hir::HirId, span: Span, )107     fn add_implied_bounds(
108         &mut self,
109         infcx: &InferCtxt<'a, 'tcx>,
110         fn_sig_tys: FxHashSet<Ty<'tcx>>,
111         body_id: hir::HirId,
112         span: Span,
113     );
114 }
115 
116 impl<'tcx> OutlivesEnvironmentExt<'tcx> for OutlivesEnvironment<'tcx> {
117     /// This method adds "implied bounds" into the outlives environment.
118     /// Implied bounds are outlives relationships that we can deduce
119     /// on the basis that certain types must be well-formed -- these are
120     /// either the types that appear in the function signature or else
121     /// the input types to an impl. For example, if you have a function
122     /// like
123     ///
124     /// ```
125     /// fn foo<'a, 'b, T>(x: &'a &'b [T]) { }
126     /// ```
127     ///
128     /// we can assume in the caller's body that `'b: 'a` and that `T:
129     /// 'b` (and hence, transitively, that `T: 'a`). This method would
130     /// add those assumptions into the outlives-environment.
131     ///
132     /// Tests: `src/test/ui/regions/regions-free-region-ordering-*.rs`
add_implied_bounds( &mut self, infcx: &InferCtxt<'a, 'tcx>, fn_sig_tys: FxHashSet<Ty<'tcx>>, body_id: hir::HirId, span: Span, )133     fn add_implied_bounds(
134         &mut self,
135         infcx: &InferCtxt<'a, 'tcx>,
136         fn_sig_tys: FxHashSet<Ty<'tcx>>,
137         body_id: hir::HirId,
138         span: Span,
139     ) {
140         debug!("add_implied_bounds()");
141 
142         for ty in fn_sig_tys {
143             let ty = infcx.resolve_vars_if_possible(ty);
144             debug!("add_implied_bounds: ty = {}", ty);
145             let implied_bounds = infcx.implied_outlives_bounds(self.param_env, body_id, ty, span);
146             self.add_outlives_bounds(Some(infcx), implied_bounds)
147         }
148     }
149 }
150 
151 ///////////////////////////////////////////////////////////////////////////
152 // PUBLIC ENTRY POINTS
153 
154 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
regionck_expr(&self, body: &'tcx hir::Body<'tcx>)155     pub fn regionck_expr(&self, body: &'tcx hir::Body<'tcx>) {
156         let subject = self.tcx.hir().body_owner_def_id(body.id());
157         let id = body.value.hir_id;
158         let mut rcx = RegionCtxt::new(self, id, Subject(subject), self.param_env);
159 
160         // There are no add'l implied bounds when checking a
161         // standalone expr (e.g., the `E` in a type like `[u32; E]`).
162         rcx.outlives_environment.save_implied_bounds(id);
163 
164         if !self.errors_reported_since_creation() {
165             // regionck assumes typeck succeeded
166             rcx.visit_body(body);
167             rcx.visit_region_obligations(id);
168         }
169         rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx));
170     }
171 
172     /// Region checking during the WF phase for items. `wf_tys` are the
173     /// types from which we should derive implied bounds, if any.
regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: FxHashSet<Ty<'tcx>>)174     pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: FxHashSet<Ty<'tcx>>) {
175         debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys);
176         let subject = self.tcx.hir().local_def_id(item_id);
177         let mut rcx = RegionCtxt::new(self, item_id, Subject(subject), self.param_env);
178         rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span);
179         rcx.outlives_environment.save_implied_bounds(item_id);
180         rcx.visit_region_obligations(item_id);
181         rcx.resolve_regions_and_report_errors(RegionckMode::default());
182     }
183 
184     /// Region check a function body. Not invoked on closures, but
185     /// only on the "root" fn item (in which closures may be
186     /// embedded). Walks the function body and adds various add'l
187     /// constraints that are needed for region inference. This is
188     /// separated both to isolate "pure" region constraints from the
189     /// rest of type check and because sometimes we need type
190     /// inference to have completed before we can determine which
191     /// constraints to add.
regionck_fn( &self, fn_id: hir::HirId, body: &'tcx hir::Body<'tcx>, span: Span, wf_tys: FxHashSet<Ty<'tcx>>, )192     pub(crate) fn regionck_fn(
193         &self,
194         fn_id: hir::HirId,
195         body: &'tcx hir::Body<'tcx>,
196         span: Span,
197         wf_tys: FxHashSet<Ty<'tcx>>,
198     ) {
199         debug!("regionck_fn(id={})", fn_id);
200         let subject = self.tcx.hir().body_owner_def_id(body.id());
201         let hir_id = body.value.hir_id;
202         let mut rcx = RegionCtxt::new(self, hir_id, Subject(subject), self.param_env);
203         // We need to add the implied bounds from the function signature
204         rcx.outlives_environment.add_implied_bounds(self, wf_tys, fn_id, span);
205         rcx.outlives_environment.save_implied_bounds(fn_id);
206 
207         if !self.errors_reported_since_creation() {
208             // regionck assumes typeck succeeded
209             rcx.visit_fn_body(fn_id, body, self.tcx.hir().span(fn_id));
210         }
211 
212         rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx));
213     }
214 }
215 
216 ///////////////////////////////////////////////////////////////////////////
217 // INTERNALS
218 
219 pub struct RegionCtxt<'a, 'tcx> {
220     pub fcx: &'a FnCtxt<'a, 'tcx>,
221 
222     pub region_scope_tree: &'tcx region::ScopeTree,
223 
224     outlives_environment: OutlivesEnvironment<'tcx>,
225 
226     // id of innermost fn body id
227     body_id: hir::HirId,
228     body_owner: LocalDefId,
229 
230     // id of AST node being analyzed (the subject of the analysis).
231     subject_def_id: LocalDefId,
232 }
233 
234 impl<'a, 'tcx> Deref for RegionCtxt<'a, 'tcx> {
235     type Target = FnCtxt<'a, 'tcx>;
deref(&self) -> &Self::Target236     fn deref(&self) -> &Self::Target {
237         self.fcx
238     }
239 }
240 
241 pub struct Subject(LocalDefId);
242 
243 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
new( fcx: &'a FnCtxt<'a, 'tcx>, initial_body_id: hir::HirId, Subject(subject): Subject, param_env: ty::ParamEnv<'tcx>, ) -> RegionCtxt<'a, 'tcx>244     pub fn new(
245         fcx: &'a FnCtxt<'a, 'tcx>,
246         initial_body_id: hir::HirId,
247         Subject(subject): Subject,
248         param_env: ty::ParamEnv<'tcx>,
249     ) -> RegionCtxt<'a, 'tcx> {
250         let region_scope_tree = fcx.tcx.region_scope_tree(subject);
251         let outlives_environment = OutlivesEnvironment::new(param_env);
252         RegionCtxt {
253             fcx,
254             region_scope_tree,
255             body_id: initial_body_id,
256             body_owner: subject,
257             subject_def_id: subject,
258             outlives_environment,
259         }
260     }
261 
262     /// Try to resolve the type for the given node, returning `t_err` if an error results. Note that
263     /// we never care about the details of the error, the same error will be detected and reported
264     /// in the writeback phase.
265     ///
266     /// Note one important point: we do not attempt to resolve *region variables* here. This is
267     /// because regionck is essentially adding constraints to those region variables and so may yet
268     /// influence how they are resolved.
269     ///
270     /// Consider this silly example:
271     ///
272     /// ```
273     /// fn borrow(x: &i32) -> &i32 {x}
274     /// fn foo(x: @i32) -> i32 {  // block: B
275     ///     let b = borrow(x);    // region: <R0>
276     ///     *b
277     /// }
278     /// ```
279     ///
280     /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
281     /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
282     /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
283     /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
284     /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx>285     pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
286         self.resolve_vars_if_possible(unresolved_ty)
287     }
288 
289     /// Try to resolve the type for the given node.
resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx>290     fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> {
291         let t = self.node_ty(id);
292         self.resolve_type(t)
293     }
294 
295     /// This is the "main" function when region-checking a function item or a
296     /// closure within a function item. It begins by updating various fields
297     /// (e.g., `outlives_environment`) to be appropriate to the function and
298     /// then adds constraints derived from the function body.
299     ///
300     /// Note that it does **not** restore the state of the fields that
301     /// it updates! This is intentional, since -- for the main
302     /// function -- we wish to be able to read the final
303     /// `outlives_environment` and other fields from the caller. For
304     /// closures, however, we save and restore any "scoped state"
305     /// before we invoke this function. (See `visit_fn` in the
306     /// `intravisit::Visitor` impl below.)
visit_fn_body( &mut self, id: hir::HirId, body: &'tcx hir::Body<'tcx>, span: Span, )307     fn visit_fn_body(
308         &mut self,
309         id: hir::HirId, // the id of the fn itself
310         body: &'tcx hir::Body<'tcx>,
311         span: Span,
312     ) {
313         // When we enter a function, we can derive
314         debug!("visit_fn_body(id={:?})", id);
315 
316         let body_id = body.id();
317         self.body_id = body_id.hir_id;
318         self.body_owner = self.tcx.hir().body_owner_def_id(body_id);
319 
320         let fn_sig = {
321             match self.typeck_results.borrow().liberated_fn_sigs().get(id) {
322                 Some(f) => *f,
323                 None => {
324                     bug!("No fn-sig entry for id={:?}", id);
325                 }
326             }
327         };
328 
329         // Collect the types from which we create inferred bounds.
330         // For the return type, if diverging, substitute `bool` just
331         // because it will have no effect.
332         //
333         // FIXME(#27579) return types should not be implied bounds
334         let fn_sig_tys: FxHashSet<_> =
335             fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
336 
337         self.outlives_environment.add_implied_bounds(self.fcx, fn_sig_tys, body_id.hir_id, span);
338         self.outlives_environment.save_implied_bounds(body_id.hir_id);
339         self.link_fn_params(body.params);
340         self.visit_body(body);
341         self.visit_region_obligations(body_id.hir_id);
342     }
343 
visit_inline_const(&mut self, id: hir::HirId, body: &'tcx hir::Body<'tcx>)344     fn visit_inline_const(&mut self, id: hir::HirId, body: &'tcx hir::Body<'tcx>) {
345         debug!("visit_inline_const(id={:?})", id);
346 
347         // Save state of current function. We will restore afterwards.
348         let old_body_id = self.body_id;
349         let old_body_owner = self.body_owner;
350         let env_snapshot = self.outlives_environment.push_snapshot_pre_typeck_child();
351 
352         let body_id = body.id();
353         self.body_id = body_id.hir_id;
354         self.body_owner = self.tcx.hir().body_owner_def_id(body_id);
355 
356         self.outlives_environment.save_implied_bounds(body_id.hir_id);
357 
358         self.visit_body(body);
359         self.visit_region_obligations(body_id.hir_id);
360 
361         // Restore state from previous function.
362         self.outlives_environment.pop_snapshot_post_typeck_child(env_snapshot);
363         self.body_id = old_body_id;
364         self.body_owner = old_body_owner;
365     }
366 
visit_region_obligations(&mut self, hir_id: hir::HirId)367     fn visit_region_obligations(&mut self, hir_id: hir::HirId) {
368         debug!("visit_region_obligations: hir_id={:?}", hir_id);
369 
370         // region checking can introduce new pending obligations
371         // which, when processed, might generate new region
372         // obligations. So make sure we process those.
373         self.select_all_obligations_or_error();
374     }
375 
resolve_regions_and_report_errors(&self, mode: RegionckMode)376     fn resolve_regions_and_report_errors(&self, mode: RegionckMode) {
377         self.infcx.process_registered_region_obligations(
378             self.outlives_environment.region_bound_pairs_map(),
379             Some(self.tcx.lifetimes.re_root_empty),
380             self.param_env,
381         );
382 
383         self.fcx.resolve_regions_and_report_errors(
384             self.subject_def_id.to_def_id(),
385             &self.outlives_environment,
386             mode,
387         );
388     }
389 
constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>)390     fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>) {
391         debug!("regionck::visit_pat(pat={:?})", pat);
392         pat.each_binding(|_, hir_id, span, _| {
393             let typ = self.resolve_node_type(hir_id);
394             let body_id = self.body_id;
395             dropck::check_drop_obligations(self, typ, span, body_id);
396         })
397     }
398 }
399 
400 impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> {
401     // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
402     // However, right now we run into an issue whereby some free
403     // regions are not properly related if they appear within the
404     // types of arguments that must be inferred. This could be
405     // addressed by deferring the construction of the region
406     // hierarchy, and in particular the relationships between free
407     // regions, until regionck, as described in #3238.
408 
409     type Map = intravisit::ErasedMap<'tcx>;
410 
nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map>411     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
412         NestedVisitorMap::None
413     }
414 
visit_fn( &mut self, fk: intravisit::FnKind<'tcx>, _: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, span: Span, hir_id: hir::HirId, )415     fn visit_fn(
416         &mut self,
417         fk: intravisit::FnKind<'tcx>,
418         _: &'tcx hir::FnDecl<'tcx>,
419         body_id: hir::BodyId,
420         span: Span,
421         hir_id: hir::HirId,
422     ) {
423         assert!(
424             matches!(fk, intravisit::FnKind::Closure),
425             "visit_fn invoked for something other than a closure"
426         );
427 
428         // Save state of current function before invoking
429         // `visit_fn_body`.  We will restore afterwards.
430         let old_body_id = self.body_id;
431         let old_body_owner = self.body_owner;
432         let env_snapshot = self.outlives_environment.push_snapshot_pre_typeck_child();
433 
434         let body = self.tcx.hir().body(body_id);
435         self.visit_fn_body(hir_id, body, span);
436 
437         // Restore state from previous function.
438         self.outlives_environment.pop_snapshot_post_typeck_child(env_snapshot);
439         self.body_id = old_body_id;
440         self.body_owner = old_body_owner;
441     }
442 
443     //visit_pat: visit_pat, // (..) see above
444 
visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>)445     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
446         // see above
447         self.constrain_bindings_in_pat(arm.pat);
448         intravisit::walk_arm(self, arm);
449     }
450 
visit_local(&mut self, l: &'tcx hir::Local<'tcx>)451     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
452         // see above
453         self.constrain_bindings_in_pat(l.pat);
454         self.link_local(l);
455         intravisit::walk_local(self, l);
456     }
457 
visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>)458     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
459         // Check any autoderefs or autorefs that appear.
460         let cmt_result = self.constrain_adjustments(expr);
461 
462         // If necessary, constrain destructors in this expression. This will be
463         // the adjusted form if there is an adjustment.
464         match cmt_result {
465             Ok(head_cmt) => {
466                 self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span);
467             }
468             Err(..) => {
469                 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
470             }
471         }
472 
473         match expr.kind {
474             hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref base) => {
475                 self.link_addr_of(expr, m, base);
476 
477                 intravisit::walk_expr(self, expr);
478             }
479 
480             hir::ExprKind::Match(ref discr, arms, _) => {
481                 self.link_match(discr, arms);
482 
483                 intravisit::walk_expr(self, expr);
484             }
485 
486             hir::ExprKind::ConstBlock(anon_const) => {
487                 let body = self.tcx.hir().body(anon_const.body);
488                 self.visit_inline_const(anon_const.hir_id, body);
489             }
490 
491             _ => intravisit::walk_expr(self, expr),
492         }
493     }
494 }
495 
496 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
497     /// Creates a temporary `MemCategorizationContext` and pass it to the closure.
with_mc<F, R>(&self, f: F) -> R where F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R,498     fn with_mc<F, R>(&self, f: F) -> R
499     where
500         F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R,
501     {
502         f(mc::MemCategorizationContext::new(
503             &self.infcx,
504             self.outlives_environment.param_env,
505             self.body_owner,
506             &self.typeck_results.borrow(),
507         ))
508     }
509 
510     /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
511     /// dereferenced, the lifetime of the pointer includes the deref expr.
constrain_adjustments( &mut self, expr: &hir::Expr<'_>, ) -> mc::McResult<PlaceWithHirId<'tcx>>512     fn constrain_adjustments(
513         &mut self,
514         expr: &hir::Expr<'_>,
515     ) -> mc::McResult<PlaceWithHirId<'tcx>> {
516         debug!("constrain_adjustments(expr={:?})", expr);
517 
518         let mut place = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
519 
520         let typeck_results = self.typeck_results.borrow();
521         let adjustments = typeck_results.expr_adjustments(expr);
522         if adjustments.is_empty() {
523             return Ok(place);
524         }
525 
526         debug!("constrain_adjustments: adjustments={:?}", adjustments);
527 
528         // If necessary, constrain destructors in the unadjusted form of this
529         // expression.
530         self.check_safety_of_rvalue_destructor_if_necessary(&place, expr.span);
531 
532         for adjustment in adjustments {
533             debug!("constrain_adjustments: adjustment={:?}, place={:?}", adjustment, place);
534 
535             if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
536                 self.link_region(
537                     expr.span,
538                     deref.region,
539                     ty::BorrowKind::from_mutbl(deref.mutbl),
540                     &place,
541                 );
542             }
543 
544             if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
545                 self.link_autoref(expr, &place, autoref);
546             }
547 
548             place = self.with_mc(|mc| mc.cat_expr_adjusted(expr, place, adjustment))?;
549         }
550 
551         Ok(place)
552     }
553 
check_safety_of_rvalue_destructor_if_necessary( &mut self, place_with_id: &PlaceWithHirId<'tcx>, span: Span, )554     fn check_safety_of_rvalue_destructor_if_necessary(
555         &mut self,
556         place_with_id: &PlaceWithHirId<'tcx>,
557         span: Span,
558     ) {
559         if let PlaceBase::Rvalue = place_with_id.place.base {
560             if place_with_id.place.projections.is_empty() {
561                 let typ = self.resolve_type(place_with_id.place.ty());
562                 let body_id = self.body_id;
563                 dropck::check_drop_obligations(self, typ, span, body_id);
564             }
565         }
566     }
567     /// Adds constraints to inference such that `T: 'a` holds (or
568     /// reports an error if it cannot).
569     ///
570     /// # Parameters
571     ///
572     /// - `origin`, the reason we need this constraint
573     /// - `ty`, the type `T`
574     /// - `region`, the region `'a`
type_must_outlive( &self, origin: infer::SubregionOrigin<'tcx>, ty: Ty<'tcx>, region: ty::Region<'tcx>, )575     pub fn type_must_outlive(
576         &self,
577         origin: infer::SubregionOrigin<'tcx>,
578         ty: Ty<'tcx>,
579         region: ty::Region<'tcx>,
580     ) {
581         self.infcx.register_region_obligation(
582             self.body_id,
583             RegionObligation { sub_region: region, sup_type: ty, origin },
584         );
585     }
586 
587     /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
588     /// resulting pointer is linked to the lifetime of its guarantor (if any).
link_addr_of( &mut self, expr: &hir::Expr<'_>, mutability: hir::Mutability, base: &hir::Expr<'_>, )589     fn link_addr_of(
590         &mut self,
591         expr: &hir::Expr<'_>,
592         mutability: hir::Mutability,
593         base: &hir::Expr<'_>,
594     ) {
595         debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
596 
597         let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
598 
599         debug!("link_addr_of: cmt={:?}", cmt);
600 
601         self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt);
602     }
603 
604     /// Computes the guarantors for any ref bindings in a `let` and
605     /// then ensures that the lifetime of the resulting pointer is
606     /// linked to the lifetime of the initialization expression.
link_local(&self, local: &hir::Local<'_>)607     fn link_local(&self, local: &hir::Local<'_>) {
608         debug!("regionck::for_local()");
609         let init_expr = match local.init {
610             None => {
611                 return;
612             }
613             Some(expr) => &*expr,
614         };
615         let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
616         self.link_pattern(discr_cmt, local.pat);
617     }
618 
619     /// Computes the guarantors for any ref bindings in a match and
620     /// then ensures that the lifetime of the resulting pointer is
621     /// linked to the lifetime of its guarantor (if any).
link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>])622     fn link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>]) {
623         debug!("regionck::for_match()");
624         let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
625         debug!("discr_cmt={:?}", discr_cmt);
626         for arm in arms {
627             self.link_pattern(discr_cmt.clone(), arm.pat);
628         }
629     }
630 
631     /// Computes the guarantors for any ref bindings in a match and
632     /// then ensures that the lifetime of the resulting pointer is
633     /// linked to the lifetime of its guarantor (if any).
link_fn_params(&self, params: &[hir::Param<'_>])634     fn link_fn_params(&self, params: &[hir::Param<'_>]) {
635         for param in params {
636             let param_ty = self.node_ty(param.hir_id);
637             let param_cmt =
638                 self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty));
639             debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param);
640             self.link_pattern(param_cmt, param.pat);
641         }
642     }
643 
644     /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
645     /// in the discriminant, if needed.
link_pattern(&self, discr_cmt: PlaceWithHirId<'tcx>, root_pat: &hir::Pat<'_>)646     fn link_pattern(&self, discr_cmt: PlaceWithHirId<'tcx>, root_pat: &hir::Pat<'_>) {
647         debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat);
648         ignore_err!(self.with_mc(|mc| {
649             mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id, .. }| {
650                 // `ref x` pattern
651                 if let PatKind::Binding(..) = kind {
652                     if let Some(ty::BindByReference(mutbl)) =
653                         mc.typeck_results.extract_binding_mode(self.tcx.sess, *hir_id, *span)
654                     {
655                         self.link_region_from_node_type(*span, *hir_id, mutbl, sub_cmt);
656                     }
657                 }
658             })
659         }));
660     }
661 
662     /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
663     /// autoref'd.
link_autoref( &self, expr: &hir::Expr<'_>, expr_cmt: &PlaceWithHirId<'tcx>, autoref: &adjustment::AutoBorrow<'tcx>, )664     fn link_autoref(
665         &self,
666         expr: &hir::Expr<'_>,
667         expr_cmt: &PlaceWithHirId<'tcx>,
668         autoref: &adjustment::AutoBorrow<'tcx>,
669     ) {
670         debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
671 
672         match *autoref {
673             adjustment::AutoBorrow::Ref(r, m) => {
674                 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt);
675             }
676 
677             adjustment::AutoBorrow::RawPtr(_) => {}
678         }
679     }
680 
681     /// Like `link_region()`, except that the region is extracted from the type of `id`,
682     /// which must be some reference (`&T`, `&str`, etc).
link_region_from_node_type( &self, span: Span, id: hir::HirId, mutbl: hir::Mutability, cmt_borrowed: &PlaceWithHirId<'tcx>, )683     fn link_region_from_node_type(
684         &self,
685         span: Span,
686         id: hir::HirId,
687         mutbl: hir::Mutability,
688         cmt_borrowed: &PlaceWithHirId<'tcx>,
689     ) {
690         debug!(
691             "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
692             id, mutbl, cmt_borrowed
693         );
694 
695         let rptr_ty = self.resolve_node_type(id);
696         if let ty::Ref(r, _, _) = rptr_ty.kind() {
697             debug!("rptr_ty={}", rptr_ty);
698             self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed);
699         }
700     }
701 
702     /// Informs the inference engine that `borrow_cmt` is being borrowed with
703     /// kind `borrow_kind` and lifetime `borrow_region`.
704     /// In order to ensure borrowck is satisfied, this may create constraints
705     /// between regions, as explained in `link_reborrowed_region()`.
link_region( &self, span: Span, borrow_region: ty::Region<'tcx>, borrow_kind: ty::BorrowKind, borrow_place: &PlaceWithHirId<'tcx>, )706     fn link_region(
707         &self,
708         span: Span,
709         borrow_region: ty::Region<'tcx>,
710         borrow_kind: ty::BorrowKind,
711         borrow_place: &PlaceWithHirId<'tcx>,
712     ) {
713         let origin = infer::DataBorrowed(borrow_place.place.ty(), span);
714         self.type_must_outlive(origin, borrow_place.place.ty(), borrow_region);
715 
716         for pointer_ty in borrow_place.place.deref_tys() {
717             debug!(
718                 "link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})",
719                 borrow_region, borrow_kind, borrow_place
720             );
721             match *pointer_ty.kind() {
722                 ty::RawPtr(_) => return,
723                 ty::Ref(ref_region, _, ref_mutability) => {
724                     if self.link_reborrowed_region(span, borrow_region, ref_region, ref_mutability)
725                     {
726                         return;
727                     }
728                 }
729                 _ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty),
730             }
731         }
732         if let PlaceBase::Upvar(upvar_id) = borrow_place.place.base {
733             self.link_upvar_region(span, borrow_region, upvar_id);
734         }
735     }
736 
737     /// This is the most complicated case: the path being borrowed is
738     /// itself the referent of a borrowed pointer. Let me give an
739     /// example fragment of code to make clear(er) the situation:
740     ///
741     /// ```ignore (incomplete Rust code)
742     /// let r: &'a mut T = ...;  // the original reference "r" has lifetime 'a
743     /// ...
744     /// &'z *r                   // the reborrow has lifetime 'z
745     /// ```
746     ///
747     /// Now, in this case, our primary job is to add the inference
748     /// constraint that `'z <= 'a`. Given this setup, let's clarify the
749     /// parameters in (roughly) terms of the example:
750     ///
751     /// ```plain,ignore (pseudo-Rust)
752     /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
753     /// borrow_region   ^~                 ref_region    ^~
754     /// borrow_kind        ^~               ref_kind        ^~
755     /// ref_cmt                 ^
756     /// ```
757     ///
758     /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
759     ///
760     /// There is a complication beyond the simple scenario I just painted: there
761     /// may in fact be more levels of reborrowing. In the example, I said the
762     /// borrow was like `&'z *r`, but it might in fact be a borrow like
763     /// `&'z **q` where `q` has type `&'a &'b mut T`. In that case, we want to
764     /// ensure that `'z <= 'a` and `'z <= 'b`.
765     ///
766     /// The return value of this function indicates whether we *don't* need to
767     /// the recurse to the next reference up.
768     ///
769     /// This is explained more below.
link_reborrowed_region( &self, span: Span, borrow_region: ty::Region<'tcx>, ref_region: ty::Region<'tcx>, ref_mutability: hir::Mutability, ) -> bool770     fn link_reborrowed_region(
771         &self,
772         span: Span,
773         borrow_region: ty::Region<'tcx>,
774         ref_region: ty::Region<'tcx>,
775         ref_mutability: hir::Mutability,
776     ) -> bool {
777         debug!("link_reborrowed_region: {:?} <= {:?}", borrow_region, ref_region);
778         self.sub_regions(infer::Reborrow(span), borrow_region, ref_region);
779 
780         // Decide whether we need to recurse and link any regions within
781         // the `ref_cmt`. This is concerned for the case where the value
782         // being reborrowed is in fact a borrowed pointer found within
783         // another borrowed pointer. For example:
784         //
785         //    let p: &'b &'a mut T = ...;
786         //    ...
787         //    &'z **p
788         //
789         // What makes this case particularly tricky is that, if the data
790         // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
791         // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
792         // (otherwise the user might mutate through the `&mut T` reference
793         // after `'b` expires and invalidate the borrow we are looking at
794         // now).
795         //
796         // So let's re-examine our parameters in light of this more
797         // complicated (possible) scenario:
798         //
799         //     A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
800         //     borrow_region   ^~                 ref_region             ^~
801         //     borrow_kind        ^~               ref_kind                 ^~
802         //     ref_cmt                 ^~~
803         //
804         // (Note that since we have not examined `ref_cmt.cat`, we don't
805         // know whether this scenario has occurred; but I wanted to show
806         // how all the types get adjusted.)
807         match ref_mutability {
808             hir::Mutability::Not => {
809                 // The reference being reborrowed is a shareable ref of
810                 // type `&'a T`. In this case, it doesn't matter where we
811                 // *found* the `&T` pointer, the memory it references will
812                 // be valid and immutable for `'a`. So we can stop here.
813                 true
814             }
815 
816             hir::Mutability::Mut => {
817                 // The reference being reborrowed is either an `&mut T`. This is
818                 // the case where recursion is needed.
819                 false
820             }
821         }
822     }
823 
824     /// An upvar may be behind up to 2 references:
825     ///
826     /// * One can come from the reference to a "by-reference" upvar.
827     /// * Another one can come from the reference to the closure itself if it's
828     ///   a `FnMut` or `Fn` closure.
829     ///
830     /// This function links the lifetimes of those references to the lifetime
831     /// of the borrow that's provided. See [RegionCtxt::link_reborrowed_region] for some
832     /// more explanation of this in the general case.
833     ///
834     /// We also supply a *cause*, and in this case we set the cause to
835     /// indicate that the reference being "reborrowed" is itself an upvar. This
836     /// provides a nicer error message should something go wrong.
link_upvar_region( &self, span: Span, borrow_region: ty::Region<'tcx>, upvar_id: ty::UpvarId, )837     fn link_upvar_region(
838         &self,
839         span: Span,
840         borrow_region: ty::Region<'tcx>,
841         upvar_id: ty::UpvarId,
842     ) {
843         debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id);
844         // A by-reference upvar can't be borrowed for longer than the
845         // upvar is borrowed from the environment.
846         let closure_local_def_id = upvar_id.closure_expr_id;
847         let mut all_captures_are_imm_borrow = true;
848         for captured_place in self
849             .typeck_results
850             .borrow()
851             .closure_min_captures
852             .get(&closure_local_def_id.to_def_id())
853             .and_then(|root_var_min_cap| root_var_min_cap.get(&upvar_id.var_path.hir_id))
854             .into_iter()
855             .flatten()
856         {
857             match captured_place.info.capture_kind {
858                 ty::UpvarCapture::ByRef(upvar_borrow) => {
859                     self.sub_regions(
860                         infer::ReborrowUpvar(span, upvar_id),
861                         borrow_region,
862                         upvar_borrow.region,
863                     );
864                     if let ty::ImmBorrow = upvar_borrow.kind {
865                         debug!("link_upvar_region: capture by shared ref");
866                     } else {
867                         all_captures_are_imm_borrow = false;
868                     }
869                 }
870                 ty::UpvarCapture::ByValue(_) => {
871                     all_captures_are_imm_borrow = false;
872                 }
873             }
874         }
875         if all_captures_are_imm_borrow {
876             return;
877         }
878         let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_local_def_id);
879         let ty = self.resolve_node_type(fn_hir_id);
880         debug!("link_upvar_region: ty={:?}", ty);
881 
882         // A closure capture can't be borrowed for longer than the
883         // reference to the closure.
884         if let ty::Closure(_, substs) = ty.kind() {
885             match self.infcx.closure_kind(substs) {
886                 Some(ty::ClosureKind::Fn | ty::ClosureKind::FnMut) => {
887                     // Region of environment pointer
888                     let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
889                         scope: upvar_id.closure_expr_id.to_def_id(),
890                         bound_region: ty::BrEnv,
891                     }));
892                     self.sub_regions(
893                         infer::ReborrowUpvar(span, upvar_id),
894                         borrow_region,
895                         env_region,
896                     );
897                 }
898                 Some(ty::ClosureKind::FnOnce) => {}
899                 None => {
900                     span_bug!(span, "Have not inferred closure kind before regionck");
901                 }
902             }
903         }
904     }
905 }
906