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::hir::def_id::DefId;
80 use rustc::infer::outlives::env::OutlivesEnvironment;
81 use rustc::infer::{self, RegionObligation, SuppressRegionErrors};
82 use rustc::ty::adjustment;
83 use rustc::ty::subst::{GenericArgKind, SubstsRef};
84 use rustc::ty::{self, Ty};
86 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
87 use rustc::hir::{self, PatKind};
92 // a variation on try that just returns unit
93 macro_rules! ignore_err {
98 debug!("ignoring mem-categorization error!");
105 ///////////////////////////////////////////////////////////////////////////
106 // PUBLIC ENTRY POINTS
108 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
109 pub fn regionck_expr(&self, body: &'tcx hir::Body<'tcx>) {
110 let subject = self.tcx.hir().body_owner_def_id(body.id());
111 let id = body.value.hir_id;
113 RegionCtxt::new(self, RepeatingScope(id), id, Subject(subject), self.param_env);
115 // There are no add'l implied bounds when checking a
116 // standalone expr (e.g., the `E` in a type like `[u32; E]`).
117 rcx.outlives_environment.save_implied_bounds(id);
119 if !self.errors_reported_since_creation() {
120 // regionck assumes typeck succeeded
121 rcx.visit_body(body);
122 rcx.visit_region_obligations(id);
124 rcx.resolve_regions_and_report_errors(SuppressRegionErrors::when_nll_is_enabled(self.tcx));
126 assert!(self.tables.borrow().free_region_map.is_empty());
127 self.tables.borrow_mut().free_region_map = rcx.outlives_environment.into_free_region_map();
130 /// Region checking during the WF phase for items. `wf_tys` are the
131 /// types from which we should derive implied bounds, if any.
132 pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: &[Ty<'tcx>]) {
133 debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys);
134 let subject = self.tcx.hir().local_def_id(item_id);
135 let mut rcx = RegionCtxt::new(
137 RepeatingScope(item_id),
142 rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span);
143 rcx.outlives_environment.save_implied_bounds(item_id);
144 rcx.visit_region_obligations(item_id);
145 rcx.resolve_regions_and_report_errors(SuppressRegionErrors::default());
148 /// Region check a function body. Not invoked on closures, but
149 /// only on the "root" fn item (in which closures may be
150 /// embedded). Walks the function body and adds various add'l
151 /// constraints that are needed for region inference. This is
152 /// separated both to isolate "pure" region constraints from the
153 /// rest of type check and because sometimes we need type
154 /// inference to have completed before we can determine which
155 /// constraints to add.
156 pub fn regionck_fn(&self, fn_id: hir::HirId, body: &'tcx hir::Body<'tcx>) {
157 debug!("regionck_fn(id={})", fn_id);
158 let subject = self.tcx.hir().body_owner_def_id(body.id());
159 let hir_id = body.value.hir_id;
161 RegionCtxt::new(self, RepeatingScope(hir_id), hir_id, Subject(subject), self.param_env);
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));
168 rcx.resolve_regions_and_report_errors(SuppressRegionErrors::when_nll_is_enabled(self.tcx));
170 // In this mode, we also copy the free-region-map into the
171 // tables of the enclosing fcx. In the other regionck modes
172 // (e.g., `regionck_item`), we don't have an enclosing tables.
173 assert!(self.tables.borrow().free_region_map.is_empty());
174 self.tables.borrow_mut().free_region_map = rcx.outlives_environment.into_free_region_map();
178 ///////////////////////////////////////////////////////////////////////////
181 pub struct RegionCtxt<'a, 'tcx> {
182 pub fcx: &'a FnCtxt<'a, 'tcx>,
184 pub region_scope_tree: &'tcx region::ScopeTree,
186 outlives_environment: OutlivesEnvironment<'tcx>,
188 // id of innermost fn body id
192 // call_site scope of innermost fn
193 call_site_scope: Option<region::Scope>,
195 // id of innermost fn or loop
196 repeating_scope: hir::HirId,
198 // id of AST node being analyzed (the subject of the analysis).
199 subject_def_id: DefId,
202 impl<'a, 'tcx> Deref for RegionCtxt<'a, 'tcx> {
203 type Target = FnCtxt<'a, 'tcx>;
204 fn deref(&self) -> &Self::Target {
209 pub struct RepeatingScope(hir::HirId);
210 pub struct Subject(DefId);
212 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
214 fcx: &'a FnCtxt<'a, 'tcx>,
215 RepeatingScope(initial_repeating_scope): RepeatingScope,
216 initial_body_id: hir::HirId,
217 Subject(subject): Subject,
218 param_env: ty::ParamEnv<'tcx>,
219 ) -> RegionCtxt<'a, 'tcx> {
220 let region_scope_tree = fcx.tcx.region_scope_tree(subject);
221 let outlives_environment = OutlivesEnvironment::new(param_env);
225 repeating_scope: initial_repeating_scope,
226 body_id: initial_body_id,
228 call_site_scope: None,
229 subject_def_id: subject,
230 outlives_environment,
234 fn set_repeating_scope(&mut self, scope: hir::HirId) -> hir::HirId {
235 mem::replace(&mut self.repeating_scope, scope)
238 /// Try to resolve the type for the given node, returning `t_err` if an error results. Note that
239 /// we never care about the details of the error, the same error will be detected and reported
240 /// in the writeback phase.
242 /// Note one important point: we do not attempt to resolve *region variables* here. This is
243 /// because regionck is essentially adding constraints to those region variables and so may yet
244 /// influence how they are resolved.
246 /// Consider this silly example:
249 /// fn borrow(x: &i32) -> &i32 {x}
250 /// fn foo(x: @i32) -> i32 { // block: B
251 /// let b = borrow(x); // region: <R0>
256 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
257 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
258 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
259 /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
260 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
261 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
262 self.resolve_vars_if_possible(&unresolved_ty)
265 /// Try to resolve the type for the given node.
266 fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> {
267 let t = self.node_ty(id);
271 /// Try to resolve the type for the given node.
272 pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
273 let ty = self.tables.borrow().expr_ty_adjusted(expr);
274 self.resolve_type(ty)
277 /// This is the "main" function when region-checking a function item or a closure
278 /// within a function item. It begins by updating various fields (e.g., `call_site_scope`
279 /// and `outlives_environment`) to be appropriate to the function and then adds constraints
280 /// derived from the function body.
282 /// Note that it does **not** restore the state of the fields that
283 /// it updates! This is intentional, since -- for the main
284 /// function -- we wish to be able to read the final
285 /// `outlives_environment` and other fields from the caller. For
286 /// closures, however, we save and restore any "scoped state"
287 /// before we invoke this function. (See `visit_fn` in the
288 /// `intravisit::Visitor` impl below.)
291 id: hir::HirId, // the id of the fn itself
292 body: &'tcx hir::Body<'tcx>,
295 // When we enter a function, we can derive
296 debug!("visit_fn_body(id={:?})", id);
298 let body_id = body.id();
299 self.body_id = body_id.hir_id;
300 self.body_owner = self.tcx.hir().body_owner_def_id(body_id);
303 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
304 self.call_site_scope = Some(call_site);
307 match self.tables.borrow().liberated_fn_sigs().get(id) {
308 Some(f) => f.clone(),
310 bug!("No fn-sig entry for id={:?}", id);
315 // Collect the types from which we create inferred bounds.
316 // For the return type, if diverging, substitute `bool` just
317 // because it will have no effect.
319 // FIXME(#27579) return types should not be implied bounds
320 let fn_sig_tys: Vec<_> =
321 fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
323 self.outlives_environment.add_implied_bounds(
329 self.outlives_environment.save_implied_bounds(body_id.hir_id);
330 self.link_fn_params(&body.params);
331 self.visit_body(body);
332 self.visit_region_obligations(body_id.hir_id);
334 let call_site_scope = self.call_site_scope.unwrap();
335 debug!("visit_fn_body body.id {:?} call_site_scope: {:?}", body.id(), call_site_scope);
336 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
338 self.type_of_node_must_outlive(infer::CallReturn(span), body_id.hir_id, call_site_region);
340 self.constrain_opaque_types(
341 &self.fcx.opaque_types.borrow(),
342 self.outlives_environment.free_region_map(),
346 fn visit_region_obligations(&mut self, hir_id: hir::HirId) {
347 debug!("visit_region_obligations: hir_id={:?}", hir_id);
349 // region checking can introduce new pending obligations
350 // which, when processed, might generate new region
351 // obligations. So make sure we process those.
352 self.select_all_obligations_or_error();
355 fn resolve_regions_and_report_errors(&self, suppress: SuppressRegionErrors) {
356 self.infcx.process_registered_region_obligations(
357 self.outlives_environment.region_bound_pairs_map(),
358 self.implicit_region_bound,
362 self.fcx.resolve_regions_and_report_errors(
364 &self.region_scope_tree,
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 // If we have a variable that contains region'd data, that
374 // data will be accessible from anywhere that the variable is
375 // accessed. We must be wary of loops like this:
377 // // from src/test/compile-fail/borrowck-lend-flow.rs
378 // let mut v = box 3, w = box 4;
379 // let mut x = &mut w;
382 // borrow(v); //~ ERROR cannot borrow
383 // x = &mut v; // (1)
386 // Typically, we try to determine the region of a borrow from
387 // those points where it is dereferenced. In this case, one
388 // might imagine that the lifetime of `x` need only be the
389 // body of the loop. But of course this is incorrect because
390 // the pointer that is created at point (1) is consumed at
391 // point (2), meaning that it must be live across the loop
392 // iteration. The easiest way to guarantee this is to require
393 // that the lifetime of any regions that appear in a
394 // variable's type enclose at least the variable's scope.
395 let var_scope = self.region_scope_tree.var_scope(hir_id.local_id);
396 let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
398 let origin = infer::BindingTypeIsNotValidAtDecl(span);
399 self.type_of_node_must_outlive(origin, hir_id, var_region);
401 let typ = self.resolve_node_type(hir_id);
402 let body_id = self.body_id;
403 let _ = dropck::check_drop_obligations(self, typ, span, body_id);
408 impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> {
409 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
410 // However, right now we run into an issue whereby some free
411 // regions are not properly related if they appear within the
412 // types of arguments that must be inferred. This could be
413 // addressed by deferring the construction of the region
414 // hierarchy, and in particular the relationships between free
415 // regions, until regionck, as described in #3238.
417 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
418 NestedVisitorMap::None
423 fk: intravisit::FnKind<'tcx>,
424 _: &'tcx hir::FnDecl<'tcx>,
425 body_id: hir::BodyId,
431 intravisit::FnKind::Closure(..) => true,
434 "visit_fn invoked for something other than a closure"
437 // Save state of current function before invoking
438 // `visit_fn_body`. We will restore afterwards.
439 let old_body_id = self.body_id;
440 let old_body_owner = self.body_owner;
441 let old_call_site_scope = self.call_site_scope;
442 let env_snapshot = self.outlives_environment.push_snapshot_pre_closure();
444 let body = self.tcx.hir().body(body_id);
445 self.visit_fn_body(hir_id, body, span);
447 // Restore state from previous function.
448 self.outlives_environment.pop_snapshot_post_closure(env_snapshot);
449 self.call_site_scope = old_call_site_scope;
450 self.body_id = old_body_id;
451 self.body_owner = old_body_owner;
454 //visit_pat: visit_pat, // (..) see above
456 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
458 self.constrain_bindings_in_pat(&arm.pat);
459 intravisit::walk_arm(self, arm);
462 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
464 self.constrain_bindings_in_pat(&l.pat);
466 intravisit::walk_local(self, l);
469 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
470 debug!("regionck::visit_expr(e={:?}, repeating_scope={:?})", expr, self.repeating_scope);
472 // No matter what, the type of each expression must outlive the
473 // scope of that expression. This also guarantees basic WF.
474 let expr_ty = self.resolve_node_type(expr.hir_id);
475 // the region corresponding to this expression
476 let expr_region = self.tcx.mk_region(ty::ReScope(region::Scope {
477 id: expr.hir_id.local_id,
478 data: region::ScopeData::Node,
480 self.type_must_outlive(
481 infer::ExprTypeIsNotInScope(expr_ty, expr.span),
486 let is_method_call = self.tables.borrow().is_method_call(expr);
488 // If we are calling a method (either explicitly or via an
489 // overloaded operator), check that all of the types provided as
490 // arguments for its type parameters are well-formed, and all the regions
491 // provided as arguments outlive the call.
493 let origin = match expr.kind {
494 hir::ExprKind::MethodCall(..) => infer::ParameterOrigin::MethodCall,
495 hir::ExprKind::Unary(op, _) if op == hir::UnDeref => {
496 infer::ParameterOrigin::OverloadedDeref
498 _ => infer::ParameterOrigin::OverloadedOperator,
501 let substs = self.tables.borrow().node_substs(expr.hir_id);
502 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
503 // Arguments (sub-expressions) are checked via `constrain_call`, below.
506 // Check any autoderefs or autorefs that appear.
507 let cmt_result = self.constrain_adjustments(expr);
509 // If necessary, constrain destructors in this expression. This will be
510 // the adjusted form if there is an adjustment.
513 self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span);
516 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
521 "regionck::visit_expr(e={:?}, repeating_scope={:?}) - visiting subexprs",
522 expr, self.repeating_scope
525 hir::ExprKind::Path(_) => {
526 let substs = self.tables.borrow().node_substs(expr.hir_id);
527 let origin = infer::ParameterOrigin::Path;
528 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
531 hir::ExprKind::Call(ref callee, ref args) => {
533 self.constrain_call(expr, Some(&callee), args.iter().map(|e| &*e));
535 self.constrain_callee(&callee);
536 self.constrain_call(expr, None, args.iter().map(|e| &*e));
539 intravisit::walk_expr(self, expr);
542 hir::ExprKind::MethodCall(.., ref args) => {
543 self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &*e));
545 intravisit::walk_expr(self, expr);
548 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
550 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
553 intravisit::walk_expr(self, expr);
556 hir::ExprKind::Index(ref lhs, ref rhs) if is_method_call => {
557 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
559 intravisit::walk_expr(self, expr);
562 hir::ExprKind::Binary(_, ref lhs, ref rhs) if is_method_call => {
563 // As `ExprKind::MethodCall`, but the call is via an overloaded op.
564 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
566 intravisit::walk_expr(self, expr);
569 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
570 // If you do `x OP y`, then the types of `x` and `y` must
571 // outlive the operation you are performing.
572 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
573 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
574 for &ty in &[lhs_ty, rhs_ty] {
575 self.type_must_outlive(infer::Operand(expr.span), ty, expr_region);
577 intravisit::walk_expr(self, expr);
580 hir::ExprKind::Unary(hir::UnDeref, ref base) => {
581 // For *a, the lifetime of a must enclose the deref
583 self.constrain_call(expr, Some(base), None::<hir::Expr<'_>>.iter());
585 // For overloaded derefs, base_ty is the input to `Deref::deref`,
586 // but it's a reference type uing the same region as the output.
587 let base_ty = self.resolve_expr_type_adjusted(base);
588 if let ty::Ref(r_ptr, _, _) = base_ty.kind {
589 self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
592 intravisit::walk_expr(self, expr);
595 hir::ExprKind::Unary(_, ref lhs) if is_method_call => {
597 self.constrain_call(expr, Some(&lhs), None::<hir::Expr<'_>>.iter());
599 intravisit::walk_expr(self, expr);
602 hir::ExprKind::Index(ref vec_expr, _) => {
603 // For a[b], the lifetime of a must enclose the deref
604 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
605 self.constrain_index(expr, vec_type);
607 intravisit::walk_expr(self, expr);
610 hir::ExprKind::Cast(ref source, _) => {
611 // Determine if we are casting `source` to a trait
612 // instance. If so, we have to be sure that the type of
613 // the source obeys the trait's region bound.
614 self.constrain_cast(expr, &source);
615 intravisit::walk_expr(self, expr);
618 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref base) => {
619 self.link_addr_of(expr, m, &base);
621 // Require that when you write a `&expr` expression, the
622 // resulting pointer has a lifetime that encompasses the
623 // `&expr` expression itself. Note that we constraining
624 // the type of the node expr.id here *before applying
627 // FIXME(https://github.com/rust-lang/rfcs/issues/811)
628 // nested method calls requires that this rule change
629 let ty0 = self.resolve_node_type(expr.hir_id);
630 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
631 intravisit::walk_expr(self, expr);
634 hir::ExprKind::Match(ref discr, ref arms, _) => {
635 self.link_match(&discr, &arms[..]);
637 intravisit::walk_expr(self, expr);
640 hir::ExprKind::Closure(.., body_id, _, _) => {
641 self.check_expr_fn_block(expr, body_id);
644 hir::ExprKind::Loop(ref body, _, _) => {
645 let repeating_scope = self.set_repeating_scope(body.hir_id);
646 intravisit::walk_expr(self, expr);
647 self.set_repeating_scope(repeating_scope);
650 hir::ExprKind::Ret(Some(ref ret_expr)) => {
651 let call_site_scope = self.call_site_scope;
653 "visit_expr ExprKind::Ret ret_expr.hir_id {} call_site_scope: {:?}",
654 ret_expr.hir_id, call_site_scope
656 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
657 self.type_of_node_must_outlive(
658 infer::CallReturn(ret_expr.span),
662 intravisit::walk_expr(self, expr);
666 intravisit::walk_expr(self, expr);
672 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
673 fn constrain_cast(&mut self, cast_expr: &hir::Expr<'_>, source_expr: &hir::Expr<'_>) {
674 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})", cast_expr, source_expr);
676 let source_ty = self.resolve_node_type(source_expr.hir_id);
677 let target_ty = self.resolve_node_type(cast_expr.hir_id);
679 self.walk_cast(cast_expr, source_ty, target_ty);
682 fn walk_cast(&mut self, cast_expr: &hir::Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) {
683 debug!("walk_cast(from_ty={:?}, to_ty={:?})", from_ty, to_ty);
684 match (&from_ty.kind, &to_ty.kind) {
686 (&ty::Ref(from_r, from_ty, _), /*To: */ &ty::Ref(to_r, to_ty, _)) => {
687 // Target cannot outlive source, naturally.
688 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
689 self.walk_cast(cast_expr, from_ty, to_ty);
693 (_, /*To: */ &ty::Dynamic(.., r)) => {
694 // When T is existentially quantified as a trait
695 // `Foo+'to`, it must outlive the region bound `'to`.
696 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
700 (&ty::Adt(from_def, _), /*To: */ &ty::Adt(to_def, _))
701 if from_def.is_box() && to_def.is_box() =>
703 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
710 fn check_expr_fn_block(&mut self, expr: &'tcx hir::Expr<'tcx>, body_id: hir::BodyId) {
711 let repeating_scope = self.set_repeating_scope(body_id.hir_id);
712 intravisit::walk_expr(self, expr);
713 self.set_repeating_scope(repeating_scope);
716 fn constrain_callee(&mut self, callee_expr: &hir::Expr<'_>) {
717 let callee_ty = self.resolve_node_type(callee_expr.hir_id);
718 match callee_ty.kind {
719 ty::FnDef(..) | ty::FnPtr(_) => {}
721 // this should not happen, but it does if the program is
726 // "Calling non-function: {}",
732 fn constrain_call<'b, I: Iterator<Item = &'b hir::Expr<'b>>>(
734 call_expr: &hir::Expr<'_>,
735 receiver: Option<&hir::Expr<'_>>,
738 //! Invoked on every call site (i.e., normal calls, method calls,
739 //! and overloaded operators). Constrains the regions which appear
740 //! in the type of the function. Also constrains the regions that
741 //! appear in the arguments appropriately.
743 debug!("constrain_call(call_expr={:?}, receiver={:?})", call_expr, receiver);
745 // `callee_region` is the scope representing the time in which the
748 // FIXME(#6268) to support nested method calls, should be callee_id
750 region::Scope { id: call_expr.hir_id.local_id, data: region::ScopeData::Node };
751 let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
753 debug!("callee_region={:?}", callee_region);
755 for arg_expr in arg_exprs {
756 debug!("argument: {:?}", arg_expr);
758 // ensure that any regions appearing in the argument type are
759 // valid for at least the lifetime of the function:
760 self.type_of_node_must_outlive(
761 infer::CallArg(arg_expr.span),
767 // as loop above, but for receiver
768 if let Some(r) = receiver {
769 debug!("receiver: {:?}", r);
770 self.type_of_node_must_outlive(infer::CallRcvr(r.span), r.hir_id, callee_region);
774 /// Creates a temporary `MemCategorizationContext` and pass it to the closure.
775 fn with_mc<F, R>(&self, f: F) -> R
777 F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R,
779 f(mc::MemCategorizationContext::new(
781 self.outlives_environment.param_env,
783 &self.tables.borrow(),
787 /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
788 /// dereferenced, the lifetime of the pointer includes the deref expr.
789 fn constrain_adjustments(&mut self, expr: &hir::Expr<'_>) -> mc::McResult<mc::Place<'tcx>> {
790 debug!("constrain_adjustments(expr={:?})", expr);
792 let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
794 let tables = self.tables.borrow();
795 let adjustments = tables.expr_adjustments(&expr);
796 if adjustments.is_empty() {
800 debug!("constrain_adjustments: adjustments={:?}", adjustments);
802 // If necessary, constrain destructors in the unadjusted form of this
804 self.check_safety_of_rvalue_destructor_if_necessary(&cmt, expr.span);
806 let expr_region = self.tcx.mk_region(ty::ReScope(region::Scope {
807 id: expr.hir_id.local_id,
808 data: region::ScopeData::Node,
810 for adjustment in adjustments {
811 debug!("constrain_adjustments: adjustment={:?}, cmt={:?}", adjustment, cmt);
813 if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
814 debug!("constrain_adjustments: overloaded deref: {:?}", deref);
816 // Treat overloaded autoderefs as if an AutoBorrow adjustment
817 // was applied on the base type, as that is always the case.
820 .mk_ref(deref.region, ty::TypeAndMut { ty: cmt.ty, mutbl: deref.mutbl });
821 let output = self.tcx.mk_ref(
823 ty::TypeAndMut { ty: adjustment.target, mutbl: deref.mutbl },
829 ty::BorrowKind::from_mutbl(deref.mutbl),
833 // Specialized version of constrain_call.
834 self.type_must_outlive(infer::CallRcvr(expr.span), input, expr_region);
835 self.type_must_outlive(infer::CallReturn(expr.span), output, expr_region);
838 if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
839 self.link_autoref(expr, &cmt, autoref);
841 // Require that the resulting region encompasses
844 // FIXME(#6268) remove to support nested method calls
845 self.type_of_node_must_outlive(
846 infer::AutoBorrow(expr.span),
852 cmt = self.with_mc(|mc| mc.cat_expr_adjusted(expr, cmt, &adjustment))?;
858 pub fn mk_subregion_due_to_dereference(
861 minimum_lifetime: ty::Region<'tcx>,
862 maximum_lifetime: ty::Region<'tcx>,
864 self.sub_regions(infer::DerefPointer(deref_span), minimum_lifetime, maximum_lifetime)
867 fn check_safety_of_rvalue_destructor_if_necessary(
869 place: &mc::Place<'tcx>,
872 if let mc::PlaceBase::Rvalue = place.base {
873 if place.projections.is_empty() {
874 let typ = self.resolve_type(place.ty);
875 let body_id = self.body_id;
876 let _ = dropck::check_drop_obligations(self, typ, span, body_id);
881 /// Invoked on any index expression that occurs. Checks that if this is a slice
882 /// being indexed, the lifetime of the pointer includes the deref expr.
883 fn constrain_index(&mut self, index_expr: &hir::Expr<'_>, indexed_ty: Ty<'tcx>) {
884 debug!("constrain_index(index_expr=?, indexed_ty={}", self.ty_to_string(indexed_ty));
886 let r_index_expr = ty::ReScope(region::Scope {
887 id: index_expr.hir_id.local_id,
888 data: region::ScopeData::Node,
890 if let ty::Ref(r_ptr, r_ty, _) = indexed_ty.kind {
892 ty::Slice(_) | ty::Str => {
894 infer::IndexSlice(index_expr.span),
895 self.tcx.mk_region(r_index_expr),
904 /// Guarantees that any lifetimes that appear in the type of the node `id` (after applying
905 /// adjustments) are valid for at least `minimum_lifetime`.
906 fn type_of_node_must_outlive(
908 origin: infer::SubregionOrigin<'tcx>,
910 minimum_lifetime: ty::Region<'tcx>,
912 // Try to resolve the type. If we encounter an error, then typeck
913 // is going to fail anyway, so just stop here and let typeck
914 // report errors later on in the writeback phase.
915 let ty0 = self.resolve_node_type(hir_id);
922 .and_then(|adj| adj.last())
923 .map_or(ty0, |adj| adj.target);
924 let ty = self.resolve_type(ty);
926 "constrain_regions_in_type_of_node(\
927 ty={}, ty0={}, id={:?}, minimum_lifetime={:?})",
928 ty, ty0, hir_id, minimum_lifetime
930 self.type_must_outlive(origin, ty, minimum_lifetime);
933 /// Adds constraints to inference such that `T: 'a` holds (or
934 /// reports an error if it cannot).
938 /// - `origin`, the reason we need this constraint
939 /// - `ty`, the type `T`
940 /// - `region`, the region `'a`
941 pub fn type_must_outlive(
943 origin: infer::SubregionOrigin<'tcx>,
945 region: ty::Region<'tcx>,
947 self.infcx.register_region_obligation(
949 RegionObligation { sub_region: region, sup_type: ty, origin },
953 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
954 /// resulting pointer is linked to the lifetime of its guarantor (if any).
957 expr: &hir::Expr<'_>,
958 mutability: hir::Mutability,
959 base: &hir::Expr<'_>,
961 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
963 let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
965 debug!("link_addr_of: cmt={:?}", cmt);
967 self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt);
970 /// Computes the guarantors for any ref bindings in a `let` and
971 /// then ensures that the lifetime of the resulting pointer is
972 /// linked to the lifetime of the initialization expression.
973 fn link_local(&self, local: &hir::Local<'_>) {
974 debug!("regionck::for_local()");
975 let init_expr = match local.init {
979 Some(ref expr) => &**expr,
981 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
982 self.link_pattern(discr_cmt, &local.pat);
985 /// Computes the guarantors for any ref bindings in a match and
986 /// then ensures that the lifetime of the resulting pointer is
987 /// linked to the lifetime of its guarantor (if any).
988 fn link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>]) {
989 debug!("regionck::for_match()");
990 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
991 debug!("discr_cmt={:?}", discr_cmt);
993 self.link_pattern(discr_cmt.clone(), &arm.pat);
997 /// Computes the guarantors for any ref bindings in a match and
998 /// then ensures that the lifetime of the resulting pointer is
999 /// linked to the lifetime of its guarantor (if any).
1000 fn link_fn_params(&self, params: &[hir::Param<'_>]) {
1001 for param in params {
1002 let param_ty = self.node_ty(param.hir_id);
1004 self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty));
1005 debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param);
1006 self.link_pattern(param_cmt, ¶m.pat);
1010 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1011 /// in the discriminant, if needed.
1012 fn link_pattern(&self, discr_cmt: mc::Place<'tcx>, root_pat: &hir::Pat<'_>) {
1013 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat);
1014 ignore_err!(self.with_mc(|mc| {
1015 mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id }| {
1017 if let PatKind::Binding(..) = kind {
1018 if let Some(ty::BindByReference(mutbl)) =
1019 mc.tables.extract_binding_mode(self.tcx.sess, *hir_id, *span)
1021 self.link_region_from_node_type(*span, *hir_id, mutbl, &sub_cmt);
1028 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1032 expr: &hir::Expr<'_>,
1033 expr_cmt: &mc::Place<'tcx>,
1034 autoref: &adjustment::AutoBorrow<'tcx>,
1036 debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
1039 adjustment::AutoBorrow::Ref(r, m) => {
1040 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt);
1043 adjustment::AutoBorrow::RawPtr(m) => {
1044 let r = self.tcx.mk_region(ty::ReScope(region::Scope {
1045 id: expr.hir_id.local_id,
1046 data: region::ScopeData::Node,
1048 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1053 /// Like `link_region()`, except that the region is extracted from the type of `id`,
1054 /// which must be some reference (`&T`, `&str`, etc).
1055 fn link_region_from_node_type(
1059 mutbl: hir::Mutability,
1060 cmt_borrowed: &mc::Place<'tcx>,
1063 "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1064 id, mutbl, cmt_borrowed
1067 let rptr_ty = self.resolve_node_type(id);
1068 if let ty::Ref(r, _, _) = rptr_ty.kind {
1069 debug!("rptr_ty={}", rptr_ty);
1070 self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed);
1074 /// Informs the inference engine that `borrow_cmt` is being borrowed with
1075 /// kind `borrow_kind` and lifetime `borrow_region`.
1076 /// In order to ensure borrowck is satisfied, this may create constraints
1077 /// between regions, as explained in `link_reborrowed_region()`.
1081 borrow_region: ty::Region<'tcx>,
1082 borrow_kind: ty::BorrowKind,
1083 borrow_place: &mc::Place<'tcx>,
1085 let origin = infer::DataBorrowed(borrow_place.ty, span);
1086 self.type_must_outlive(origin, borrow_place.ty, borrow_region);
1088 for pointer_ty in borrow_place.deref_tys() {
1090 "link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})",
1091 borrow_region, borrow_kind, borrow_place
1093 match pointer_ty.kind {
1094 ty::RawPtr(_) => return,
1095 ty::Ref(ref_region, _, ref_mutability) => {
1096 if self.link_reborrowed_region(span, borrow_region, ref_region, ref_mutability)
1101 _ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty),
1104 if let mc::PlaceBase::Upvar(upvar_id) = borrow_place.base {
1105 self.link_upvar_region(span, borrow_region, upvar_id);
1109 /// This is the most complicated case: the path being borrowed is
1110 /// itself the referent of a borrowed pointer. Let me give an
1111 /// example fragment of code to make clear(er) the situation:
1113 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1115 /// &'z *r // the reborrow has lifetime 'z
1117 /// Now, in this case, our primary job is to add the inference
1118 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1119 /// parameters in (roughly) terms of the example:
1121 /// ```plain,ignore (pseudo-Rust)
1122 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1123 /// borrow_region ^~ ref_region ^~
1124 /// borrow_kind ^~ ref_kind ^~
1128 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1130 /// There is a complication beyond the simple scenario I just painted: there
1131 /// may in fact be more levels of reborrowing. In the example, I said the
1132 /// borrow was like `&'z *r`, but it might in fact be a borrow like
1133 /// `&'z **q` where `q` has type `&'a &'b mut T`. In that case, we want to
1134 /// ensure that `'z <= 'a` and `'z <= 'b`.
1136 /// The return value of this function indicates whether we *don't* need to
1137 /// the recurse to the next reference up.
1139 /// This is explained more below.
1140 fn link_reborrowed_region(
1143 borrow_region: ty::Region<'tcx>,
1144 ref_region: ty::Region<'tcx>,
1145 ref_mutability: hir::Mutability,
1147 debug!("link_reborrowed_region: {:?} <= {:?}", borrow_region, ref_region);
1148 self.sub_regions(infer::Reborrow(span), borrow_region, ref_region);
1150 // Decide whether we need to recurse and link any regions within
1151 // the `ref_cmt`. This is concerned for the case where the value
1152 // being reborrowed is in fact a borrowed pointer found within
1153 // another borrowed pointer. For example:
1155 // let p: &'b &'a mut T = ...;
1159 // What makes this case particularly tricky is that, if the data
1160 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1161 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1162 // (otherwise the user might mutate through the `&mut T` reference
1163 // after `'b` expires and invalidate the borrow we are looking at
1166 // So let's re-examine our parameters in light of this more
1167 // complicated (possible) scenario:
1169 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1170 // borrow_region ^~ ref_region ^~
1171 // borrow_kind ^~ ref_kind ^~
1174 // (Note that since we have not examined `ref_cmt.cat`, we don't
1175 // know whether this scenario has occurred; but I wanted to show
1176 // how all the types get adjusted.)
1177 match ref_mutability {
1178 hir::Mutability::Not => {
1179 // The reference being reborrowed is a shareable ref of
1180 // type `&'a T`. In this case, it doesn't matter where we
1181 // *found* the `&T` pointer, the memory it references will
1182 // be valid and immutable for `'a`. So we can stop here.
1186 hir::Mutability::Mut => {
1187 // The reference being reborrowed is either an `&mut T`. This is
1188 // the case where recursion is needed.
1194 /// An upvar may be behind up to 2 references:
1196 /// * One can come from the reference to a "by-reference" upvar.
1197 /// * Another one can come from the reference to the closure itself if it's
1198 /// a `FnMut` or `Fn` closure.
1200 /// This function links the lifetimes of those references to the lifetime
1201 /// of the borrow that's provided. See [link_reborrowed_region] for some
1202 /// more explanation of this in the general case.
1204 /// We also supply a *cause*, and in this case we set the cause to
1205 /// indicate that the reference being "reborrowed" is itself an upvar. This
1206 /// provides a nicer error message should something go wrong.
1207 fn link_upvar_region(
1210 borrow_region: ty::Region<'tcx>,
1211 upvar_id: ty::UpvarId,
1213 debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id);
1214 // A by-reference upvar can't be borrowed for longer than the
1215 // upvar is borrowed from the environment.
1216 match self.tables.borrow().upvar_capture(upvar_id) {
1217 ty::UpvarCapture::ByRef(upvar_borrow) => {
1219 infer::ReborrowUpvar(span, upvar_id),
1221 upvar_borrow.region,
1223 if let ty::ImmBorrow = upvar_borrow.kind {
1224 debug!("link_upvar_region: capture by shared ref");
1228 ty::UpvarCapture::ByValue => {}
1230 let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(upvar_id.closure_expr_id);
1231 let ty = self.resolve_node_type(fn_hir_id);
1232 debug!("link_upvar_region: ty={:?}", ty);
1234 // A closure capture can't be borrowed for longer than the
1235 // reference to the closure.
1236 if let ty::Closure(closure_def_id, substs) = ty.kind {
1237 match self.infcx.closure_kind(closure_def_id, substs) {
1238 Some(ty::ClosureKind::Fn) | Some(ty::ClosureKind::FnMut) => {
1239 // Region of environment pointer
1240 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
1241 scope: upvar_id.closure_expr_id.to_def_id(),
1242 bound_region: ty::BrEnv,
1245 infer::ReborrowUpvar(span, upvar_id),
1250 Some(ty::ClosureKind::FnOnce) => {}
1252 span_bug!(span, "Have not inferred closure kind before regionck");
1258 /// Checks that the values provided for type/region arguments in a given
1259 /// expression are well-formed and in-scope.
1260 fn substs_wf_in_scope(
1262 origin: infer::ParameterOrigin,
1263 substs: SubstsRef<'tcx>,
1265 expr_region: ty::Region<'tcx>,
1268 "substs_wf_in_scope(substs={:?}, \
1272 substs, expr_region, origin, expr_span
1275 let origin = infer::ParameterInScope(origin, expr_span);
1277 for kind in substs {
1278 match kind.unpack() {
1279 GenericArgKind::Lifetime(lt) => {
1280 self.sub_regions(origin.clone(), expr_region, lt);
1282 GenericArgKind::Type(ty) => {
1283 let ty = self.resolve_type(ty);
1284 self.type_must_outlive(origin.clone(), ty, expr_region);
1286 GenericArgKind::Const(_) => {
1287 // Const parameters don't impose constraints.