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 rustc::ty::adjustment;
80 use rustc::ty::subst::{GenericArgKind, SubstsRef};
81 use rustc::ty::{self, Ty};
83 use rustc_hir::def_id::DefId;
84 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
85 use rustc_hir::PatKind;
86 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
87 use rustc_infer::infer::{self, RegionObligation, RegionckMode};
89 use rustc_trait_selection::infer::OutlivesEnvironmentExt;
90 use rustc_trait_selection::opaque_types::InferCtxtExt;
94 // a variation on try that just returns unit
95 macro_rules! ignore_err {
100 debug!("ignoring mem-categorization error!");
107 ///////////////////////////////////////////////////////////////////////////
108 // PUBLIC ENTRY POINTS
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;
115 RegionCtxt::new(self, RepeatingScope(id), id, Subject(subject), self.param_env);
117 // There are no add'l implied bounds when checking a
118 // standalone expr (e.g., the `E` in a type like `[u32; E]`).
119 rcx.outlives_environment.save_implied_bounds(id);
121 if !self.errors_reported_since_creation() {
122 // regionck assumes typeck succeeded
123 rcx.visit_body(body);
124 rcx.visit_region_obligations(id);
126 rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx));
129 /// Region checking during the WF phase for items. `wf_tys` are the
130 /// types from which we should derive implied bounds, if any.
131 pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: &[Ty<'tcx>]) {
132 debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys);
133 let subject = self.tcx.hir().local_def_id(item_id);
134 let mut rcx = RegionCtxt::new(
136 RepeatingScope(item_id),
141 rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span);
142 rcx.outlives_environment.save_implied_bounds(item_id);
143 rcx.visit_region_obligations(item_id);
144 rcx.resolve_regions_and_report_errors(RegionckMode::default());
147 /// Region check a function body. Not invoked on closures, but
148 /// only on the "root" fn item (in which closures may be
149 /// embedded). Walks the function body and adds various add'l
150 /// constraints that are needed for region inference. This is
151 /// separated both to isolate "pure" region constraints from the
152 /// rest of type check and because sometimes we need type
153 /// inference to have completed before we can determine which
154 /// constraints to add.
155 pub fn regionck_fn(&self, fn_id: hir::HirId, body: &'tcx hir::Body<'tcx>) {
156 debug!("regionck_fn(id={})", fn_id);
157 let subject = self.tcx.hir().body_owner_def_id(body.id());
158 let hir_id = body.value.hir_id;
160 RegionCtxt::new(self, RepeatingScope(hir_id), hir_id, Subject(subject), self.param_env);
162 if !self.errors_reported_since_creation() {
163 // regionck assumes typeck succeeded
164 rcx.visit_fn_body(fn_id, body, self.tcx.hir().span(fn_id));
167 rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx));
171 ///////////////////////////////////////////////////////////////////////////
174 pub struct RegionCtxt<'a, 'tcx> {
175 pub fcx: &'a FnCtxt<'a, 'tcx>,
177 pub region_scope_tree: &'tcx region::ScopeTree,
179 outlives_environment: OutlivesEnvironment<'tcx>,
181 // id of innermost fn body id
185 // call_site scope of innermost fn
186 call_site_scope: Option<region::Scope>,
188 // id of innermost fn or loop
189 repeating_scope: hir::HirId,
191 // id of AST node being analyzed (the subject of the analysis).
192 subject_def_id: DefId,
195 impl<'a, 'tcx> Deref for RegionCtxt<'a, 'tcx> {
196 type Target = FnCtxt<'a, 'tcx>;
197 fn deref(&self) -> &Self::Target {
202 pub struct RepeatingScope(hir::HirId);
203 pub struct Subject(DefId);
205 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
207 fcx: &'a FnCtxt<'a, 'tcx>,
208 RepeatingScope(initial_repeating_scope): RepeatingScope,
209 initial_body_id: hir::HirId,
210 Subject(subject): Subject,
211 param_env: ty::ParamEnv<'tcx>,
212 ) -> RegionCtxt<'a, 'tcx> {
213 let region_scope_tree = fcx.tcx.region_scope_tree(subject);
214 let outlives_environment = OutlivesEnvironment::new(param_env);
218 repeating_scope: initial_repeating_scope,
219 body_id: initial_body_id,
221 call_site_scope: None,
222 subject_def_id: subject,
223 outlives_environment,
227 fn set_repeating_scope(&mut self, scope: hir::HirId) -> hir::HirId {
228 mem::replace(&mut self.repeating_scope, scope)
231 /// Try to resolve the type for the given node, returning `t_err` if an error results. Note that
232 /// we never care about the details of the error, the same error will be detected and reported
233 /// in the writeback phase.
235 /// Note one important point: we do not attempt to resolve *region variables* here. This is
236 /// because regionck is essentially adding constraints to those region variables and so may yet
237 /// influence how they are resolved.
239 /// Consider this silly example:
242 /// fn borrow(x: &i32) -> &i32 {x}
243 /// fn foo(x: @i32) -> i32 { // block: B
244 /// let b = borrow(x); // region: <R0>
249 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
250 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
251 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
252 /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
253 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
254 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
255 self.resolve_vars_if_possible(&unresolved_ty)
258 /// Try to resolve the type for the given node.
259 fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> {
260 let t = self.node_ty(id);
264 /// Try to resolve the type for the given node.
265 pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
266 let ty = self.tables.borrow().expr_ty_adjusted(expr);
267 self.resolve_type(ty)
270 /// This is the "main" function when region-checking a function item or a closure
271 /// within a function item. It begins by updating various fields (e.g., `call_site_scope`
272 /// and `outlives_environment`) to be appropriate to the function and then adds constraints
273 /// derived from the function body.
275 /// Note that it does **not** restore the state of the fields that
276 /// it updates! This is intentional, since -- for the main
277 /// function -- we wish to be able to read the final
278 /// `outlives_environment` and other fields from the caller. For
279 /// closures, however, we save and restore any "scoped state"
280 /// before we invoke this function. (See `visit_fn` in the
281 /// `intravisit::Visitor` impl below.)
284 id: hir::HirId, // the id of the fn itself
285 body: &'tcx hir::Body<'tcx>,
288 // When we enter a function, we can derive
289 debug!("visit_fn_body(id={:?})", id);
291 let body_id = body.id();
292 self.body_id = body_id.hir_id;
293 self.body_owner = self.tcx.hir().body_owner_def_id(body_id);
296 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
297 self.call_site_scope = Some(call_site);
300 match self.tables.borrow().liberated_fn_sigs().get(id) {
303 bug!("No fn-sig entry for id={:?}", id);
308 // Collect the types from which we create inferred bounds.
309 // For the return type, if diverging, substitute `bool` just
310 // because it will have no effect.
312 // FIXME(#27579) return types should not be implied bounds
313 let fn_sig_tys: Vec<_> =
314 fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
316 self.outlives_environment.add_implied_bounds(
322 self.outlives_environment.save_implied_bounds(body_id.hir_id);
323 self.link_fn_params(&body.params);
324 self.visit_body(body);
325 self.visit_region_obligations(body_id.hir_id);
327 let call_site_scope = self.call_site_scope.unwrap();
328 debug!("visit_fn_body body.id {:?} call_site_scope: {:?}", body.id(), call_site_scope);
329 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
331 self.type_of_node_must_outlive(infer::CallReturn(span), body_id.hir_id, call_site_region);
333 self.constrain_opaque_types(
334 &self.fcx.opaque_types.borrow(),
335 self.outlives_environment.free_region_map(),
339 fn visit_region_obligations(&mut self, hir_id: hir::HirId) {
340 debug!("visit_region_obligations: hir_id={:?}", hir_id);
342 // region checking can introduce new pending obligations
343 // which, when processed, might generate new region
344 // obligations. So make sure we process those.
345 self.select_all_obligations_or_error();
348 fn resolve_regions_and_report_errors(&self, mode: RegionckMode) {
349 self.infcx.process_registered_region_obligations(
350 self.outlives_environment.region_bound_pairs_map(),
351 self.implicit_region_bound,
355 self.fcx.resolve_regions_and_report_errors(
357 &self.region_scope_tree,
358 &self.outlives_environment,
363 fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>) {
364 debug!("regionck::visit_pat(pat={:?})", pat);
365 pat.each_binding(|_, hir_id, span, _| {
366 // If we have a variable that contains region'd data, that
367 // data will be accessible from anywhere that the variable is
368 // accessed. We must be wary of loops like this:
370 // // from src/test/compile-fail/borrowck-lend-flow.rs
371 // let mut v = box 3, w = box 4;
372 // let mut x = &mut w;
375 // borrow(v); //~ ERROR cannot borrow
376 // x = &mut v; // (1)
379 // Typically, we try to determine the region of a borrow from
380 // those points where it is dereferenced. In this case, one
381 // might imagine that the lifetime of `x` need only be the
382 // body of the loop. But of course this is incorrect because
383 // the pointer that is created at point (1) is consumed at
384 // point (2), meaning that it must be live across the loop
385 // iteration. The easiest way to guarantee this is to require
386 // that the lifetime of any regions that appear in a
387 // variable's type enclose at least the variable's scope.
388 let var_scope = self.region_scope_tree.var_scope(hir_id.local_id);
389 let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
391 let origin = infer::BindingTypeIsNotValidAtDecl(span);
392 self.type_of_node_must_outlive(origin, hir_id, var_region);
394 let typ = self.resolve_node_type(hir_id);
395 let body_id = self.body_id;
396 let _ = dropck::check_drop_obligations(self, typ, span, body_id);
401 impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> {
402 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
403 // However, right now we run into an issue whereby some free
404 // regions are not properly related if they appear within the
405 // types of arguments that must be inferred. This could be
406 // addressed by deferring the construction of the region
407 // hierarchy, and in particular the relationships between free
408 // regions, until regionck, as described in #3238.
410 type Map = intravisit::ErasedMap<'tcx>;
412 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
413 NestedVisitorMap::None
418 fk: intravisit::FnKind<'tcx>,
419 _: &'tcx hir::FnDecl<'tcx>,
420 body_id: hir::BodyId,
426 intravisit::FnKind::Closure(..) => true,
429 "visit_fn invoked for something other than a closure"
432 // Save state of current function before invoking
433 // `visit_fn_body`. We will restore afterwards.
434 let old_body_id = self.body_id;
435 let old_body_owner = self.body_owner;
436 let old_call_site_scope = self.call_site_scope;
437 let env_snapshot = self.outlives_environment.push_snapshot_pre_closure();
439 let body = self.tcx.hir().body(body_id);
440 self.visit_fn_body(hir_id, body, span);
442 // Restore state from previous function.
443 self.outlives_environment.pop_snapshot_post_closure(env_snapshot);
444 self.call_site_scope = old_call_site_scope;
445 self.body_id = old_body_id;
446 self.body_owner = old_body_owner;
449 //visit_pat: visit_pat, // (..) see above
451 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
453 self.constrain_bindings_in_pat(&arm.pat);
454 intravisit::walk_arm(self, arm);
457 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
459 self.constrain_bindings_in_pat(&l.pat);
461 intravisit::walk_local(self, l);
464 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
465 debug!("regionck::visit_expr(e={:?}, repeating_scope={:?})", expr, self.repeating_scope);
467 // No matter what, the type of each expression must outlive the
468 // scope of that expression. This also guarantees basic WF.
469 let expr_ty = self.resolve_node_type(expr.hir_id);
470 // the region corresponding to this expression
471 let expr_region = self.tcx.mk_region(ty::ReScope(region::Scope {
472 id: expr.hir_id.local_id,
473 data: region::ScopeData::Node,
475 self.type_must_outlive(
476 infer::ExprTypeIsNotInScope(expr_ty, expr.span),
481 let is_method_call = self.tables.borrow().is_method_call(expr);
483 // If we are calling a method (either explicitly or via an
484 // overloaded operator), check that all of the types provided as
485 // arguments for its type parameters are well-formed, and all the regions
486 // provided as arguments outlive the call.
488 let origin = match expr.kind {
489 hir::ExprKind::MethodCall(..) => infer::ParameterOrigin::MethodCall,
490 hir::ExprKind::Unary(op, _) if op == hir::UnOp::UnDeref => {
491 infer::ParameterOrigin::OverloadedDeref
493 _ => infer::ParameterOrigin::OverloadedOperator,
496 let substs = self.tables.borrow().node_substs(expr.hir_id);
497 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
498 // Arguments (sub-expressions) are checked via `constrain_call`, below.
501 // Check any autoderefs or autorefs that appear.
502 let cmt_result = self.constrain_adjustments(expr);
504 // If necessary, constrain destructors in this expression. This will be
505 // the adjusted form if there is an adjustment.
508 self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span);
511 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
516 "regionck::visit_expr(e={:?}, repeating_scope={:?}) - visiting subexprs",
517 expr, self.repeating_scope
520 hir::ExprKind::Path(_) => {
521 let substs = self.tables.borrow().node_substs(expr.hir_id);
522 let origin = infer::ParameterOrigin::Path;
523 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
526 hir::ExprKind::Call(ref callee, ref args) => {
528 self.constrain_call(expr, Some(&callee), args.iter().map(|e| &*e));
530 self.constrain_callee(&callee);
531 self.constrain_call(expr, None, args.iter().map(|e| &*e));
534 intravisit::walk_expr(self, expr);
537 hir::ExprKind::MethodCall(.., ref args) => {
538 self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &*e));
540 intravisit::walk_expr(self, expr);
543 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
545 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
548 intravisit::walk_expr(self, expr);
551 hir::ExprKind::Index(ref lhs, ref rhs) if is_method_call => {
552 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
554 intravisit::walk_expr(self, expr);
557 hir::ExprKind::Binary(_, ref lhs, ref rhs) if is_method_call => {
558 // As `ExprKind::MethodCall`, but the call is via an overloaded op.
559 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
561 intravisit::walk_expr(self, expr);
564 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
565 // If you do `x OP y`, then the types of `x` and `y` must
566 // outlive the operation you are performing.
567 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
568 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
569 for &ty in &[lhs_ty, rhs_ty] {
570 self.type_must_outlive(infer::Operand(expr.span), ty, expr_region);
572 intravisit::walk_expr(self, expr);
575 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
576 // For *a, the lifetime of a must enclose the deref
578 self.constrain_call(expr, Some(base), None::<hir::Expr<'_>>.iter());
580 // For overloaded derefs, base_ty is the input to `Deref::deref`,
581 // but it's a reference type uing the same region as the output.
582 let base_ty = self.resolve_expr_type_adjusted(base);
583 if let ty::Ref(r_ptr, _, _) = base_ty.kind {
584 self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
587 intravisit::walk_expr(self, expr);
590 hir::ExprKind::Unary(_, ref lhs) if is_method_call => {
592 self.constrain_call(expr, Some(&lhs), None::<hir::Expr<'_>>.iter());
594 intravisit::walk_expr(self, expr);
597 hir::ExprKind::Index(ref vec_expr, _) => {
598 // For a[b], the lifetime of a must enclose the deref
599 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
600 self.constrain_index(expr, vec_type);
602 intravisit::walk_expr(self, expr);
605 hir::ExprKind::Cast(ref source, _) => {
606 // Determine if we are casting `source` to a trait
607 // instance. If so, we have to be sure that the type of
608 // the source obeys the trait's region bound.
609 self.constrain_cast(expr, &source);
610 intravisit::walk_expr(self, expr);
613 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref base) => {
614 self.link_addr_of(expr, m, &base);
616 // Require that when you write a `&expr` expression, the
617 // resulting pointer has a lifetime that encompasses the
618 // `&expr` expression itself. Note that we constraining
619 // the type of the node expr.id here *before applying
622 // FIXME(https://github.com/rust-lang/rfcs/issues/811)
623 // nested method calls requires that this rule change
624 let ty0 = self.resolve_node_type(expr.hir_id);
625 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
626 intravisit::walk_expr(self, expr);
629 hir::ExprKind::Match(ref discr, ref arms, _) => {
630 self.link_match(&discr, &arms[..]);
632 intravisit::walk_expr(self, expr);
635 hir::ExprKind::Closure(.., body_id, _, _) => {
636 self.check_expr_fn_block(expr, body_id);
639 hir::ExprKind::Loop(ref body, _, _) => {
640 let repeating_scope = self.set_repeating_scope(body.hir_id);
641 intravisit::walk_expr(self, expr);
642 self.set_repeating_scope(repeating_scope);
645 hir::ExprKind::Ret(Some(ref ret_expr)) => {
646 let call_site_scope = self.call_site_scope;
648 "visit_expr ExprKind::Ret ret_expr.hir_id {} call_site_scope: {:?}",
649 ret_expr.hir_id, call_site_scope
651 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
652 self.type_of_node_must_outlive(
653 infer::CallReturn(ret_expr.span),
657 intravisit::walk_expr(self, expr);
661 intravisit::walk_expr(self, expr);
667 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
668 fn constrain_cast(&mut self, cast_expr: &hir::Expr<'_>, source_expr: &hir::Expr<'_>) {
669 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})", cast_expr, source_expr);
671 let source_ty = self.resolve_node_type(source_expr.hir_id);
672 let target_ty = self.resolve_node_type(cast_expr.hir_id);
674 self.walk_cast(cast_expr, source_ty, target_ty);
677 fn walk_cast(&mut self, cast_expr: &hir::Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) {
678 debug!("walk_cast(from_ty={:?}, to_ty={:?})", from_ty, to_ty);
679 match (&from_ty.kind, &to_ty.kind) {
681 (&ty::Ref(from_r, from_ty, _), /*To: */ &ty::Ref(to_r, to_ty, _)) => {
682 // Target cannot outlive source, naturally.
683 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
684 self.walk_cast(cast_expr, from_ty, to_ty);
688 (_, /*To: */ &ty::Dynamic(.., r)) => {
689 // When T is existentially quantified as a trait
690 // `Foo+'to`, it must outlive the region bound `'to`.
691 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
695 (&ty::Adt(from_def, _), /*To: */ &ty::Adt(to_def, _))
696 if from_def.is_box() && to_def.is_box() =>
698 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
705 fn check_expr_fn_block(&mut self, expr: &'tcx hir::Expr<'tcx>, body_id: hir::BodyId) {
706 let repeating_scope = self.set_repeating_scope(body_id.hir_id);
707 intravisit::walk_expr(self, expr);
708 self.set_repeating_scope(repeating_scope);
711 fn constrain_callee(&mut self, callee_expr: &hir::Expr<'_>) {
712 let callee_ty = self.resolve_node_type(callee_expr.hir_id);
713 match callee_ty.kind {
714 ty::FnDef(..) | ty::FnPtr(_) => {}
716 // this should not happen, but it does if the program is
721 // "Calling non-function: {}",
727 fn constrain_call<'b, I: Iterator<Item = &'b hir::Expr<'b>>>(
729 call_expr: &hir::Expr<'_>,
730 receiver: Option<&hir::Expr<'_>>,
733 //! Invoked on every call site (i.e., normal calls, method calls,
734 //! and overloaded operators). Constrains the regions which appear
735 //! in the type of the function. Also constrains the regions that
736 //! appear in the arguments appropriately.
738 debug!("constrain_call(call_expr={:?}, receiver={:?})", call_expr, receiver);
740 // `callee_region` is the scope representing the time in which the
743 // FIXME(#6268) to support nested method calls, should be callee_id
745 region::Scope { id: call_expr.hir_id.local_id, data: region::ScopeData::Node };
746 let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
748 debug!("callee_region={:?}", callee_region);
750 for arg_expr in arg_exprs {
751 debug!("argument: {:?}", arg_expr);
753 // ensure that any regions appearing in the argument type are
754 // valid for at least the lifetime of the function:
755 self.type_of_node_must_outlive(
756 infer::CallArg(arg_expr.span),
762 // as loop above, but for receiver
763 if let Some(r) = receiver {
764 debug!("receiver: {:?}", r);
765 self.type_of_node_must_outlive(infer::CallRcvr(r.span), r.hir_id, callee_region);
769 /// Creates a temporary `MemCategorizationContext` and pass it to the closure.
770 fn with_mc<F, R>(&self, f: F) -> R
772 F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R,
774 f(mc::MemCategorizationContext::new(
776 self.outlives_environment.param_env,
778 &self.tables.borrow(),
782 /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
783 /// dereferenced, the lifetime of the pointer includes the deref expr.
784 fn constrain_adjustments(&mut self, expr: &hir::Expr<'_>) -> mc::McResult<mc::Place<'tcx>> {
785 debug!("constrain_adjustments(expr={:?})", expr);
787 let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
789 let tables = self.tables.borrow();
790 let adjustments = tables.expr_adjustments(&expr);
791 if adjustments.is_empty() {
795 debug!("constrain_adjustments: adjustments={:?}", adjustments);
797 // If necessary, constrain destructors in the unadjusted form of this
799 self.check_safety_of_rvalue_destructor_if_necessary(&cmt, expr.span);
801 let expr_region = self.tcx.mk_region(ty::ReScope(region::Scope {
802 id: expr.hir_id.local_id,
803 data: region::ScopeData::Node,
805 for adjustment in adjustments {
806 debug!("constrain_adjustments: adjustment={:?}, cmt={:?}", adjustment, cmt);
808 if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
809 debug!("constrain_adjustments: overloaded deref: {:?}", deref);
811 // Treat overloaded autoderefs as if an AutoBorrow adjustment
812 // was applied on the base type, as that is always the case.
815 .mk_ref(deref.region, ty::TypeAndMut { ty: cmt.ty, mutbl: deref.mutbl });
816 let output = self.tcx.mk_ref(
818 ty::TypeAndMut { ty: adjustment.target, mutbl: deref.mutbl },
824 ty::BorrowKind::from_mutbl(deref.mutbl),
828 // Specialized version of constrain_call.
829 self.type_must_outlive(infer::CallRcvr(expr.span), input, expr_region);
830 self.type_must_outlive(infer::CallReturn(expr.span), output, expr_region);
833 if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
834 self.link_autoref(expr, &cmt, autoref);
836 // Require that the resulting region encompasses
839 // FIXME(#6268) remove to support nested method calls
840 self.type_of_node_must_outlive(
841 infer::AutoBorrow(expr.span),
847 cmt = self.with_mc(|mc| mc.cat_expr_adjusted(expr, cmt, &adjustment))?;
853 pub fn mk_subregion_due_to_dereference(
856 minimum_lifetime: ty::Region<'tcx>,
857 maximum_lifetime: ty::Region<'tcx>,
859 self.sub_regions(infer::DerefPointer(deref_span), minimum_lifetime, maximum_lifetime)
862 fn check_safety_of_rvalue_destructor_if_necessary(
864 place: &mc::Place<'tcx>,
867 if let mc::PlaceBase::Rvalue = place.base {
868 if place.projections.is_empty() {
869 let typ = self.resolve_type(place.ty);
870 let body_id = self.body_id;
871 let _ = dropck::check_drop_obligations(self, typ, span, body_id);
876 /// Invoked on any index expression that occurs. Checks that if this is a slice
877 /// being indexed, the lifetime of the pointer includes the deref expr.
878 fn constrain_index(&mut self, index_expr: &hir::Expr<'_>, indexed_ty: Ty<'tcx>) {
879 debug!("constrain_index(index_expr=?, indexed_ty={}", self.ty_to_string(indexed_ty));
881 let r_index_expr = ty::ReScope(region::Scope {
882 id: index_expr.hir_id.local_id,
883 data: region::ScopeData::Node,
885 if let ty::Ref(r_ptr, r_ty, _) = indexed_ty.kind {
887 ty::Slice(_) | ty::Str => {
889 infer::IndexSlice(index_expr.span),
890 self.tcx.mk_region(r_index_expr),
899 /// Guarantees that any lifetimes that appear in the type of the node `id` (after applying
900 /// adjustments) are valid for at least `minimum_lifetime`.
901 fn type_of_node_must_outlive(
903 origin: infer::SubregionOrigin<'tcx>,
905 minimum_lifetime: ty::Region<'tcx>,
907 // Try to resolve the type. If we encounter an error, then typeck
908 // is going to fail anyway, so just stop here and let typeck
909 // report errors later on in the writeback phase.
910 let ty0 = self.resolve_node_type(hir_id);
917 .and_then(|adj| adj.last())
918 .map_or(ty0, |adj| adj.target);
919 let ty = self.resolve_type(ty);
921 "constrain_regions_in_type_of_node(\
922 ty={}, ty0={}, id={:?}, minimum_lifetime={:?})",
923 ty, ty0, hir_id, minimum_lifetime
925 self.type_must_outlive(origin, ty, minimum_lifetime);
928 /// Adds constraints to inference such that `T: 'a` holds (or
929 /// reports an error if it cannot).
933 /// - `origin`, the reason we need this constraint
934 /// - `ty`, the type `T`
935 /// - `region`, the region `'a`
936 pub fn type_must_outlive(
938 origin: infer::SubregionOrigin<'tcx>,
940 region: ty::Region<'tcx>,
942 self.infcx.register_region_obligation(
944 RegionObligation { sub_region: region, sup_type: ty, origin },
948 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
949 /// resulting pointer is linked to the lifetime of its guarantor (if any).
952 expr: &hir::Expr<'_>,
953 mutability: hir::Mutability,
954 base: &hir::Expr<'_>,
956 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
958 let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
960 debug!("link_addr_of: cmt={:?}", cmt);
962 self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt);
965 /// Computes the guarantors for any ref bindings in a `let` and
966 /// then ensures that the lifetime of the resulting pointer is
967 /// linked to the lifetime of the initialization expression.
968 fn link_local(&self, local: &hir::Local<'_>) {
969 debug!("regionck::for_local()");
970 let init_expr = match local.init {
974 Some(ref expr) => &**expr,
976 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
977 self.link_pattern(discr_cmt, &local.pat);
980 /// Computes the guarantors for any ref bindings in a match and
981 /// then ensures that the lifetime of the resulting pointer is
982 /// linked to the lifetime of its guarantor (if any).
983 fn link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>]) {
984 debug!("regionck::for_match()");
985 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
986 debug!("discr_cmt={:?}", discr_cmt);
988 self.link_pattern(discr_cmt.clone(), &arm.pat);
992 /// Computes the guarantors for any ref bindings in a match and
993 /// then ensures that the lifetime of the resulting pointer is
994 /// linked to the lifetime of its guarantor (if any).
995 fn link_fn_params(&self, params: &[hir::Param<'_>]) {
996 for param in params {
997 let param_ty = self.node_ty(param.hir_id);
999 self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty));
1000 debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param);
1001 self.link_pattern(param_cmt, ¶m.pat);
1005 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1006 /// in the discriminant, if needed.
1007 fn link_pattern(&self, discr_cmt: mc::Place<'tcx>, root_pat: &hir::Pat<'_>) {
1008 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat);
1009 ignore_err!(self.with_mc(|mc| {
1010 mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id }| {
1012 if let PatKind::Binding(..) = kind {
1013 if let Some(ty::BindByReference(mutbl)) =
1014 mc.tables.extract_binding_mode(self.tcx.sess, *hir_id, *span)
1016 self.link_region_from_node_type(*span, *hir_id, mutbl, &sub_cmt);
1023 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1027 expr: &hir::Expr<'_>,
1028 expr_cmt: &mc::Place<'tcx>,
1029 autoref: &adjustment::AutoBorrow<'tcx>,
1031 debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
1034 adjustment::AutoBorrow::Ref(r, m) => {
1035 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt);
1038 adjustment::AutoBorrow::RawPtr(m) => {
1039 let r = self.tcx.mk_region(ty::ReScope(region::Scope {
1040 id: expr.hir_id.local_id,
1041 data: region::ScopeData::Node,
1043 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1048 /// Like `link_region()`, except that the region is extracted from the type of `id`,
1049 /// which must be some reference (`&T`, `&str`, etc).
1050 fn link_region_from_node_type(
1054 mutbl: hir::Mutability,
1055 cmt_borrowed: &mc::Place<'tcx>,
1058 "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1059 id, mutbl, cmt_borrowed
1062 let rptr_ty = self.resolve_node_type(id);
1063 if let ty::Ref(r, _, _) = rptr_ty.kind {
1064 debug!("rptr_ty={}", rptr_ty);
1065 self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed);
1069 /// Informs the inference engine that `borrow_cmt` is being borrowed with
1070 /// kind `borrow_kind` and lifetime `borrow_region`.
1071 /// In order to ensure borrowck is satisfied, this may create constraints
1072 /// between regions, as explained in `link_reborrowed_region()`.
1076 borrow_region: ty::Region<'tcx>,
1077 borrow_kind: ty::BorrowKind,
1078 borrow_place: &mc::Place<'tcx>,
1080 let origin = infer::DataBorrowed(borrow_place.ty, span);
1081 self.type_must_outlive(origin, borrow_place.ty, borrow_region);
1083 for pointer_ty in borrow_place.deref_tys() {
1085 "link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})",
1086 borrow_region, borrow_kind, borrow_place
1088 match pointer_ty.kind {
1089 ty::RawPtr(_) => return,
1090 ty::Ref(ref_region, _, ref_mutability) => {
1091 if self.link_reborrowed_region(span, borrow_region, ref_region, ref_mutability)
1096 _ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty),
1099 if let mc::PlaceBase::Upvar(upvar_id) = borrow_place.base {
1100 self.link_upvar_region(span, borrow_region, upvar_id);
1104 /// This is the most complicated case: the path being borrowed is
1105 /// itself the referent of a borrowed pointer. Let me give an
1106 /// example fragment of code to make clear(er) the situation:
1108 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1110 /// &'z *r // the reborrow has lifetime 'z
1112 /// Now, in this case, our primary job is to add the inference
1113 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1114 /// parameters in (roughly) terms of the example:
1116 /// ```plain,ignore (pseudo-Rust)
1117 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1118 /// borrow_region ^~ ref_region ^~
1119 /// borrow_kind ^~ ref_kind ^~
1123 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1125 /// There is a complication beyond the simple scenario I just painted: there
1126 /// may in fact be more levels of reborrowing. In the example, I said the
1127 /// borrow was like `&'z *r`, but it might in fact be a borrow like
1128 /// `&'z **q` where `q` has type `&'a &'b mut T`. In that case, we want to
1129 /// ensure that `'z <= 'a` and `'z <= 'b`.
1131 /// The return value of this function indicates whether we *don't* need to
1132 /// the recurse to the next reference up.
1134 /// This is explained more below.
1135 fn link_reborrowed_region(
1138 borrow_region: ty::Region<'tcx>,
1139 ref_region: ty::Region<'tcx>,
1140 ref_mutability: hir::Mutability,
1142 debug!("link_reborrowed_region: {:?} <= {:?}", borrow_region, ref_region);
1143 self.sub_regions(infer::Reborrow(span), borrow_region, ref_region);
1145 // Decide whether we need to recurse and link any regions within
1146 // the `ref_cmt`. This is concerned for the case where the value
1147 // being reborrowed is in fact a borrowed pointer found within
1148 // another borrowed pointer. For example:
1150 // let p: &'b &'a mut T = ...;
1154 // What makes this case particularly tricky is that, if the data
1155 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1156 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1157 // (otherwise the user might mutate through the `&mut T` reference
1158 // after `'b` expires and invalidate the borrow we are looking at
1161 // So let's re-examine our parameters in light of this more
1162 // complicated (possible) scenario:
1164 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1165 // borrow_region ^~ ref_region ^~
1166 // borrow_kind ^~ ref_kind ^~
1169 // (Note that since we have not examined `ref_cmt.cat`, we don't
1170 // know whether this scenario has occurred; but I wanted to show
1171 // how all the types get adjusted.)
1172 match ref_mutability {
1173 hir::Mutability::Not => {
1174 // The reference being reborrowed is a shareable ref of
1175 // type `&'a T`. In this case, it doesn't matter where we
1176 // *found* the `&T` pointer, the memory it references will
1177 // be valid and immutable for `'a`. So we can stop here.
1181 hir::Mutability::Mut => {
1182 // The reference being reborrowed is either an `&mut T`. This is
1183 // the case where recursion is needed.
1189 /// An upvar may be behind up to 2 references:
1191 /// * One can come from the reference to a "by-reference" upvar.
1192 /// * Another one can come from the reference to the closure itself if it's
1193 /// a `FnMut` or `Fn` closure.
1195 /// This function links the lifetimes of those references to the lifetime
1196 /// of the borrow that's provided. See [link_reborrowed_region] for some
1197 /// more explanation of this in the general case.
1199 /// We also supply a *cause*, and in this case we set the cause to
1200 /// indicate that the reference being "reborrowed" is itself an upvar. This
1201 /// provides a nicer error message should something go wrong.
1202 fn link_upvar_region(
1205 borrow_region: ty::Region<'tcx>,
1206 upvar_id: ty::UpvarId,
1208 debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id);
1209 // A by-reference upvar can't be borrowed for longer than the
1210 // upvar is borrowed from the environment.
1211 match self.tables.borrow().upvar_capture(upvar_id) {
1212 ty::UpvarCapture::ByRef(upvar_borrow) => {
1214 infer::ReborrowUpvar(span, upvar_id),
1216 upvar_borrow.region,
1218 if let ty::ImmBorrow = upvar_borrow.kind {
1219 debug!("link_upvar_region: capture by shared ref");
1223 ty::UpvarCapture::ByValue => {}
1225 let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(upvar_id.closure_expr_id);
1226 let ty = self.resolve_node_type(fn_hir_id);
1227 debug!("link_upvar_region: ty={:?}", ty);
1229 // A closure capture can't be borrowed for longer than the
1230 // reference to the closure.
1231 if let ty::Closure(closure_def_id, substs) = ty.kind {
1232 match self.infcx.closure_kind(closure_def_id, substs) {
1233 Some(ty::ClosureKind::Fn) | Some(ty::ClosureKind::FnMut) => {
1234 // Region of environment pointer
1235 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
1236 scope: upvar_id.closure_expr_id.to_def_id(),
1237 bound_region: ty::BrEnv,
1240 infer::ReborrowUpvar(span, upvar_id),
1245 Some(ty::ClosureKind::FnOnce) => {}
1247 span_bug!(span, "Have not inferred closure kind before regionck");
1253 /// Checks that the values provided for type/region arguments in a given
1254 /// expression are well-formed and in-scope.
1255 fn substs_wf_in_scope(
1257 origin: infer::ParameterOrigin,
1258 substs: SubstsRef<'tcx>,
1260 expr_region: ty::Region<'tcx>,
1263 "substs_wf_in_scope(substs={:?}, \
1267 substs, expr_region, origin, expr_span
1270 let origin = infer::ParameterInScope(origin, expr_span);
1272 for kind in substs {
1273 match kind.unpack() {
1274 GenericArgKind::Lifetime(lt) => {
1275 self.sub_regions(origin.clone(), expr_region, lt);
1277 GenericArgKind::Type(ty) => {
1278 let ty = self.resolve_type(ty);
1279 self.type_must_outlive(origin.clone(), ty, expr_region);
1281 GenericArgKind::Const(_) => {
1282 // Const parameters don't impose constraints.