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
9 //! ### Interaction with the borrow checker
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.
25 //! ### Inferring the duration of borrows, automatic and otherwise
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).
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).
49 //! There are a number of troublesome scenarios in the tests
50 //! `region-dependent-*.rs`, but here is one example:
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
59 //! Note that this comes up either with `&` expressions, `ref`
60 //! bindings, and `autorefs`, which are the three ways to introduce
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
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;
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};
91 use rustc_trait_selection::opaque_types::InferCtxtExt as _;
94 // a variation on try that just returns unit
95 macro_rules! ignore_err {
100 debug!("ignoring mem-categorization error!");
107 trait OutlivesEnvironmentExt<'tcx> {
108 fn add_implied_bounds(
110 infcx: &InferCtxt<'a, 'tcx>,
111 fn_sig_tys: FxHashSet<Ty<'tcx>>,
117 impl<'tcx> OutlivesEnvironmentExt<'tcx> for OutlivesEnvironment<'tcx> {
118 /// This method adds "implied bounds" into the outlives environment.
119 /// Implied bounds are outlives relationships that we can deduce
120 /// on the basis that certain types must be well-formed -- these are
121 /// either the types that appear in the function signature or else
122 /// the input types to an impl. For example, if you have a function
126 /// fn foo<'a, 'b, T>(x: &'a &'b [T]) { }
129 /// we can assume in the caller's body that `'b: 'a` and that `T:
130 /// 'b` (and hence, transitively, that `T: 'a`). This method would
131 /// add those assumptions into the outlives-environment.
133 /// Tests: `src/test/ui/regions/regions-free-region-ordering-*.rs`
134 fn add_implied_bounds(
136 infcx: &InferCtxt<'a, 'tcx>,
137 fn_sig_tys: FxHashSet<Ty<'tcx>>,
141 debug!("add_implied_bounds()");
143 for ty in fn_sig_tys {
144 let ty = infcx.resolve_vars_if_possible(ty);
145 debug!("add_implied_bounds: ty = {}", ty);
146 let implied_bounds = infcx.implied_outlives_bounds(self.param_env, body_id, ty, span);
147 self.add_outlives_bounds(Some(infcx), implied_bounds)
152 ///////////////////////////////////////////////////////////////////////////
153 // PUBLIC ENTRY POINTS
155 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
156 pub fn regionck_expr(&self, body: &'tcx hir::Body<'tcx>) {
157 let subject = self.tcx.hir().body_owner_def_id(body.id());
158 let id = body.value.hir_id;
159 let mut rcx = RegionCtxt::new(self, id, Subject(subject), self.param_env);
161 // There are no add'l implied bounds when checking a
162 // standalone expr (e.g., the `E` in a type like `[u32; E]`).
163 rcx.outlives_environment.save_implied_bounds(id);
165 if !self.errors_reported_since_creation() {
166 // regionck assumes typeck succeeded
167 rcx.visit_body(body);
168 rcx.visit_region_obligations(id);
170 rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx));
173 /// Region checking during the WF phase for items. `wf_tys` are the
174 /// types from which we should derive implied bounds, if any.
175 pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: FxHashSet<Ty<'tcx>>) {
176 debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys);
177 let subject = self.tcx.hir().local_def_id(item_id);
178 let mut rcx = RegionCtxt::new(self, item_id, Subject(subject), self.param_env);
179 rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span);
180 rcx.outlives_environment.save_implied_bounds(item_id);
181 rcx.visit_region_obligations(item_id);
182 rcx.resolve_regions_and_report_errors(RegionckMode::default());
185 /// Region check a function body. Not invoked on closures, but
186 /// only on the "root" fn item (in which closures may be
187 /// embedded). Walks the function body and adds various add'l
188 /// constraints that are needed for region inference. This is
189 /// separated both to isolate "pure" region constraints from the
190 /// rest of type check and because sometimes we need type
191 /// inference to have completed before we can determine which
192 /// constraints to add.
193 pub(crate) fn regionck_fn(
196 body: &'tcx hir::Body<'tcx>,
198 wf_tys: FxHashSet<Ty<'tcx>>,
200 debug!("regionck_fn(id={})", fn_id);
201 let subject = self.tcx.hir().body_owner_def_id(body.id());
202 let hir_id = body.value.hir_id;
203 let mut rcx = RegionCtxt::new(self, hir_id, Subject(subject), self.param_env);
204 // We need to add the implied bounds from the function signature
205 rcx.outlives_environment.add_implied_bounds(self, wf_tys, fn_id, span);
206 rcx.outlives_environment.save_implied_bounds(fn_id);
208 if !self.errors_reported_since_creation() {
209 // regionck assumes typeck succeeded
210 rcx.visit_fn_body(fn_id, body, self.tcx.hir().span(fn_id));
213 rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx));
217 ///////////////////////////////////////////////////////////////////////////
220 pub struct RegionCtxt<'a, 'tcx> {
221 pub fcx: &'a FnCtxt<'a, 'tcx>,
223 pub region_scope_tree: &'tcx region::ScopeTree,
225 outlives_environment: OutlivesEnvironment<'tcx>,
227 // id of innermost fn body id
229 body_owner: LocalDefId,
231 // id of AST node being analyzed (the subject of the analysis).
232 subject_def_id: LocalDefId,
235 impl<'a, 'tcx> Deref for RegionCtxt<'a, 'tcx> {
236 type Target = FnCtxt<'a, 'tcx>;
237 fn deref(&self) -> &Self::Target {
242 pub struct Subject(LocalDefId);
244 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
246 fcx: &'a FnCtxt<'a, 'tcx>,
247 initial_body_id: hir::HirId,
248 Subject(subject): Subject,
249 param_env: ty::ParamEnv<'tcx>,
250 ) -> RegionCtxt<'a, 'tcx> {
251 let region_scope_tree = fcx.tcx.region_scope_tree(subject);
252 let outlives_environment = OutlivesEnvironment::new(param_env);
256 body_id: initial_body_id,
258 subject_def_id: subject,
259 outlives_environment,
263 /// Try to resolve the type for the given node, returning `t_err` if an error results. Note that
264 /// we never care about the details of the error, the same error will be detected and reported
265 /// in the writeback phase.
267 /// Note one important point: we do not attempt to resolve *region variables* here. This is
268 /// because regionck is essentially adding constraints to those region variables and so may yet
269 /// influence how they are resolved.
271 /// Consider this silly example:
274 /// fn borrow(x: &i32) -> &i32 {x}
275 /// fn foo(x: @i32) -> i32 { // block: B
276 /// let b = borrow(x); // region: <R0>
281 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
282 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
283 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
284 /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
285 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
286 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
287 self.resolve_vars_if_possible(unresolved_ty)
290 /// Try to resolve the type for the given node.
291 fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> {
292 let t = self.node_ty(id);
296 /// This is the "main" function when region-checking a function item or a
297 /// closure within a function item. It begins by updating various fields
298 /// (e.g., `outlives_environment`) to be appropriate to the function and
299 /// then adds constraints derived from the function body.
301 /// Note that it does **not** restore the state of the fields that
302 /// it updates! This is intentional, since -- for the main
303 /// function -- we wish to be able to read the final
304 /// `outlives_environment` and other fields from the caller. For
305 /// closures, however, we save and restore any "scoped state"
306 /// before we invoke this function. (See `visit_fn` in the
307 /// `intravisit::Visitor` impl below.)
310 id: hir::HirId, // the id of the fn itself
311 body: &'tcx hir::Body<'tcx>,
314 // When we enter a function, we can derive
315 debug!("visit_fn_body(id={:?})", id);
317 let body_id = body.id();
318 self.body_id = body_id.hir_id;
319 self.body_owner = self.tcx.hir().body_owner_def_id(body_id);
322 match self.typeck_results.borrow().liberated_fn_sigs().get(id) {
325 bug!("No fn-sig entry for id={:?}", id);
330 // Collect the types from which we create inferred bounds.
331 // For the return type, if diverging, substitute `bool` just
332 // because it will have no effect.
334 // FIXME(#27579) return types should not be implied bounds
335 let fn_sig_tys: FxHashSet<_> =
336 fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
338 self.outlives_environment.add_implied_bounds(self.fcx, fn_sig_tys, body_id.hir_id, span);
339 self.outlives_environment.save_implied_bounds(body_id.hir_id);
340 self.link_fn_params(body.params);
341 self.visit_body(body);
342 self.visit_region_obligations(body_id.hir_id);
344 self.constrain_opaque_types();
347 fn visit_region_obligations(&mut self, hir_id: hir::HirId) {
348 debug!("visit_region_obligations: hir_id={:?}", hir_id);
350 // region checking can introduce new pending obligations
351 // which, when processed, might generate new region
352 // obligations. So make sure we process those.
353 self.select_all_obligations_or_error();
356 fn resolve_regions_and_report_errors(&self, mode: RegionckMode) {
357 self.infcx.process_registered_region_obligations(
358 self.outlives_environment.region_bound_pairs_map(),
359 Some(self.tcx.lifetimes.re_root_empty),
363 self.fcx.resolve_regions_and_report_errors(
364 self.subject_def_id.to_def_id(),
365 &self.outlives_environment,
370 fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>) {
371 debug!("regionck::visit_pat(pat={:?})", pat);
372 pat.each_binding(|_, hir_id, span, _| {
373 let typ = self.resolve_node_type(hir_id);
374 let body_id = self.body_id;
375 dropck::check_drop_obligations(self, typ, span, body_id);
380 impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> {
381 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
382 // However, right now we run into an issue whereby some free
383 // regions are not properly related if they appear within the
384 // types of arguments that must be inferred. This could be
385 // addressed by deferring the construction of the region
386 // hierarchy, and in particular the relationships between free
387 // regions, until regionck, as described in #3238.
389 type Map = intravisit::ErasedMap<'tcx>;
391 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
392 NestedVisitorMap::None
397 fk: intravisit::FnKind<'tcx>,
398 _: &'tcx hir::FnDecl<'tcx>,
399 body_id: hir::BodyId,
404 matches!(fk, intravisit::FnKind::Closure),
405 "visit_fn invoked for something other than a closure"
408 // Save state of current function before invoking
409 // `visit_fn_body`. We will restore afterwards.
410 let old_body_id = self.body_id;
411 let old_body_owner = self.body_owner;
412 let env_snapshot = self.outlives_environment.push_snapshot_pre_closure();
414 let body = self.tcx.hir().body(body_id);
415 self.visit_fn_body(hir_id, body, span);
417 // Restore state from previous function.
418 self.outlives_environment.pop_snapshot_post_closure(env_snapshot);
419 self.body_id = old_body_id;
420 self.body_owner = old_body_owner;
423 //visit_pat: visit_pat, // (..) see above
425 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
427 self.constrain_bindings_in_pat(arm.pat);
428 intravisit::walk_arm(self, arm);
431 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
433 self.constrain_bindings_in_pat(l.pat);
435 intravisit::walk_local(self, l);
438 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
439 // Check any autoderefs or autorefs that appear.
440 let cmt_result = self.constrain_adjustments(expr);
442 // If necessary, constrain destructors in this expression. This will be
443 // the adjusted form if there is an adjustment.
446 self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span);
449 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
454 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref base) => {
455 self.link_addr_of(expr, m, base);
457 intravisit::walk_expr(self, expr);
460 hir::ExprKind::Match(ref discr, arms, _) => {
461 self.link_match(discr, arms);
463 intravisit::walk_expr(self, expr);
466 _ => intravisit::walk_expr(self, expr),
471 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
472 /// Creates a temporary `MemCategorizationContext` and pass it to the closure.
473 fn with_mc<F, R>(&self, f: F) -> R
475 F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R,
477 f(mc::MemCategorizationContext::new(
479 self.outlives_environment.param_env,
481 &self.typeck_results.borrow(),
485 /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
486 /// dereferenced, the lifetime of the pointer includes the deref expr.
487 fn constrain_adjustments(
489 expr: &hir::Expr<'_>,
490 ) -> mc::McResult<PlaceWithHirId<'tcx>> {
491 debug!("constrain_adjustments(expr={:?})", expr);
493 let mut place = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
495 let typeck_results = self.typeck_results.borrow();
496 let adjustments = typeck_results.expr_adjustments(expr);
497 if adjustments.is_empty() {
501 debug!("constrain_adjustments: adjustments={:?}", adjustments);
503 // If necessary, constrain destructors in the unadjusted form of this
505 self.check_safety_of_rvalue_destructor_if_necessary(&place, expr.span);
507 for adjustment in adjustments {
508 debug!("constrain_adjustments: adjustment={:?}, place={:?}", adjustment, place);
510 if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
514 ty::BorrowKind::from_mutbl(deref.mutbl),
519 if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
520 self.link_autoref(expr, &place, autoref);
523 place = self.with_mc(|mc| mc.cat_expr_adjusted(expr, place, adjustment))?;
529 fn check_safety_of_rvalue_destructor_if_necessary(
531 place_with_id: &PlaceWithHirId<'tcx>,
534 if let PlaceBase::Rvalue = place_with_id.place.base {
535 if place_with_id.place.projections.is_empty() {
536 let typ = self.resolve_type(place_with_id.place.ty());
537 let body_id = self.body_id;
538 dropck::check_drop_obligations(self, typ, span, body_id);
542 /// Adds constraints to inference such that `T: 'a` holds (or
543 /// reports an error if it cannot).
547 /// - `origin`, the reason we need this constraint
548 /// - `ty`, the type `T`
549 /// - `region`, the region `'a`
550 pub fn type_must_outlive(
552 origin: infer::SubregionOrigin<'tcx>,
554 region: ty::Region<'tcx>,
556 self.infcx.register_region_obligation(
558 RegionObligation { sub_region: region, sup_type: ty, origin },
562 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
563 /// resulting pointer is linked to the lifetime of its guarantor (if any).
566 expr: &hir::Expr<'_>,
567 mutability: hir::Mutability,
568 base: &hir::Expr<'_>,
570 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
572 let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
574 debug!("link_addr_of: cmt={:?}", cmt);
576 self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt);
579 /// Computes the guarantors for any ref bindings in a `let` and
580 /// then ensures that the lifetime of the resulting pointer is
581 /// linked to the lifetime of the initialization expression.
582 fn link_local(&self, local: &hir::Local<'_>) {
583 debug!("regionck::for_local()");
584 let init_expr = match local.init {
588 Some(expr) => &*expr,
590 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
591 self.link_pattern(discr_cmt, local.pat);
594 /// Computes the guarantors for any ref bindings in a match and
595 /// then ensures that the lifetime of the resulting pointer is
596 /// linked to the lifetime of its guarantor (if any).
597 fn link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>]) {
598 debug!("regionck::for_match()");
599 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
600 debug!("discr_cmt={:?}", discr_cmt);
602 self.link_pattern(discr_cmt.clone(), arm.pat);
606 /// Computes the guarantors for any ref bindings in a match and
607 /// then ensures that the lifetime of the resulting pointer is
608 /// linked to the lifetime of its guarantor (if any).
609 fn link_fn_params(&self, params: &[hir::Param<'_>]) {
610 for param in params {
611 let param_ty = self.node_ty(param.hir_id);
613 self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty));
614 debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param);
615 self.link_pattern(param_cmt, param.pat);
619 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
620 /// in the discriminant, if needed.
621 fn link_pattern(&self, discr_cmt: PlaceWithHirId<'tcx>, root_pat: &hir::Pat<'_>) {
622 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat);
623 ignore_err!(self.with_mc(|mc| {
624 mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id, .. }| {
626 if let PatKind::Binding(..) = kind {
627 if let Some(ty::BindByReference(mutbl)) =
628 mc.typeck_results.extract_binding_mode(self.tcx.sess, *hir_id, *span)
630 self.link_region_from_node_type(*span, *hir_id, mutbl, sub_cmt);
637 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
641 expr: &hir::Expr<'_>,
642 expr_cmt: &PlaceWithHirId<'tcx>,
643 autoref: &adjustment::AutoBorrow<'tcx>,
645 debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
648 adjustment::AutoBorrow::Ref(r, m) => {
649 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt);
652 adjustment::AutoBorrow::RawPtr(_) => {}
656 /// Like `link_region()`, except that the region is extracted from the type of `id`,
657 /// which must be some reference (`&T`, `&str`, etc).
658 fn link_region_from_node_type(
662 mutbl: hir::Mutability,
663 cmt_borrowed: &PlaceWithHirId<'tcx>,
666 "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
667 id, mutbl, cmt_borrowed
670 let rptr_ty = self.resolve_node_type(id);
671 if let ty::Ref(r, _, _) = rptr_ty.kind() {
672 debug!("rptr_ty={}", rptr_ty);
673 self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed);
677 /// Informs the inference engine that `borrow_cmt` is being borrowed with
678 /// kind `borrow_kind` and lifetime `borrow_region`.
679 /// In order to ensure borrowck is satisfied, this may create constraints
680 /// between regions, as explained in `link_reborrowed_region()`.
684 borrow_region: ty::Region<'tcx>,
685 borrow_kind: ty::BorrowKind,
686 borrow_place: &PlaceWithHirId<'tcx>,
688 let origin = infer::DataBorrowed(borrow_place.place.ty(), span);
689 self.type_must_outlive(origin, borrow_place.place.ty(), borrow_region);
691 for pointer_ty in borrow_place.place.deref_tys() {
693 "link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})",
694 borrow_region, borrow_kind, borrow_place
696 match *pointer_ty.kind() {
697 ty::RawPtr(_) => return,
698 ty::Ref(ref_region, _, ref_mutability) => {
699 if self.link_reborrowed_region(span, borrow_region, ref_region, ref_mutability)
704 _ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty),
707 if let PlaceBase::Upvar(upvar_id) = borrow_place.place.base {
708 self.link_upvar_region(span, borrow_region, upvar_id);
712 /// This is the most complicated case: the path being borrowed is
713 /// itself the referent of a borrowed pointer. Let me give an
714 /// example fragment of code to make clear(er) the situation:
716 /// ```ignore (incomplete Rust code)
717 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
719 /// &'z *r // the reborrow has lifetime 'z
722 /// Now, in this case, our primary job is to add the inference
723 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
724 /// parameters in (roughly) terms of the example:
726 /// ```plain,ignore (pseudo-Rust)
727 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
728 /// borrow_region ^~ ref_region ^~
729 /// borrow_kind ^~ ref_kind ^~
733 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
735 /// There is a complication beyond the simple scenario I just painted: there
736 /// may in fact be more levels of reborrowing. In the example, I said the
737 /// borrow was like `&'z *r`, but it might in fact be a borrow like
738 /// `&'z **q` where `q` has type `&'a &'b mut T`. In that case, we want to
739 /// ensure that `'z <= 'a` and `'z <= 'b`.
741 /// The return value of this function indicates whether we *don't* need to
742 /// the recurse to the next reference up.
744 /// This is explained more below.
745 fn link_reborrowed_region(
748 borrow_region: ty::Region<'tcx>,
749 ref_region: ty::Region<'tcx>,
750 ref_mutability: hir::Mutability,
752 debug!("link_reborrowed_region: {:?} <= {:?}", borrow_region, ref_region);
753 self.sub_regions(infer::Reborrow(span), borrow_region, ref_region);
755 // Decide whether we need to recurse and link any regions within
756 // the `ref_cmt`. This is concerned for the case where the value
757 // being reborrowed is in fact a borrowed pointer found within
758 // another borrowed pointer. For example:
760 // let p: &'b &'a mut T = ...;
764 // What makes this case particularly tricky is that, if the data
765 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
766 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
767 // (otherwise the user might mutate through the `&mut T` reference
768 // after `'b` expires and invalidate the borrow we are looking at
771 // So let's re-examine our parameters in light of this more
772 // complicated (possible) scenario:
774 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
775 // borrow_region ^~ ref_region ^~
776 // borrow_kind ^~ ref_kind ^~
779 // (Note that since we have not examined `ref_cmt.cat`, we don't
780 // know whether this scenario has occurred; but I wanted to show
781 // how all the types get adjusted.)
782 match ref_mutability {
783 hir::Mutability::Not => {
784 // The reference being reborrowed is a shareable ref of
785 // type `&'a T`. In this case, it doesn't matter where we
786 // *found* the `&T` pointer, the memory it references will
787 // be valid and immutable for `'a`. So we can stop here.
791 hir::Mutability::Mut => {
792 // The reference being reborrowed is either an `&mut T`. This is
793 // the case where recursion is needed.
799 /// An upvar may be behind up to 2 references:
801 /// * One can come from the reference to a "by-reference" upvar.
802 /// * Another one can come from the reference to the closure itself if it's
803 /// a `FnMut` or `Fn` closure.
805 /// This function links the lifetimes of those references to the lifetime
806 /// of the borrow that's provided. See [RegionCtxt::link_reborrowed_region] for some
807 /// more explanation of this in the general case.
809 /// We also supply a *cause*, and in this case we set the cause to
810 /// indicate that the reference being "reborrowed" is itself an upvar. This
811 /// provides a nicer error message should something go wrong.
812 fn link_upvar_region(
815 borrow_region: ty::Region<'tcx>,
816 upvar_id: ty::UpvarId,
818 debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id);
819 // A by-reference upvar can't be borrowed for longer than the
820 // upvar is borrowed from the environment.
821 let closure_local_def_id = upvar_id.closure_expr_id;
822 let mut all_captures_are_imm_borrow = true;
823 for captured_place in self
826 .closure_min_captures
827 .get(&closure_local_def_id.to_def_id())
828 .and_then(|root_var_min_cap| root_var_min_cap.get(&upvar_id.var_path.hir_id))
832 match captured_place.info.capture_kind {
833 ty::UpvarCapture::ByRef(upvar_borrow) => {
835 infer::ReborrowUpvar(span, upvar_id),
839 if let ty::ImmBorrow = upvar_borrow.kind {
840 debug!("link_upvar_region: capture by shared ref");
842 all_captures_are_imm_borrow = false;
845 ty::UpvarCapture::ByValue(_) => {
846 all_captures_are_imm_borrow = false;
850 if all_captures_are_imm_borrow {
853 let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_local_def_id);
854 let ty = self.resolve_node_type(fn_hir_id);
855 debug!("link_upvar_region: ty={:?}", ty);
857 // A closure capture can't be borrowed for longer than the
858 // reference to the closure.
859 if let ty::Closure(_, substs) = ty.kind() {
860 match self.infcx.closure_kind(substs) {
861 Some(ty::ClosureKind::Fn | ty::ClosureKind::FnMut) => {
862 // Region of environment pointer
863 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
864 scope: upvar_id.closure_expr_id.to_def_id(),
865 bound_region: ty::BrEnv,
868 infer::ReborrowUpvar(span, upvar_id),
873 Some(ty::ClosureKind::FnOnce) => {}
875 span_bug!(span, "Have not inferred closure kind before regionck");