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