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