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::map::Map;
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::def_id::DefId;
87 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
88 use rustc_hir::PatKind;
93 // a variation on try that just returns unit
94 macro_rules! ignore_err {
99 debug!("ignoring mem-categorization error!");
106 ///////////////////////////////////////////////////////////////////////////
107 // PUBLIC ENTRY POINTS
109 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
110 pub fn regionck_expr(&self, body: &'tcx hir::Body<'tcx>) {
111 let subject = self.tcx.hir().body_owner_def_id(body.id());
112 let id = body.value.hir_id;
114 RegionCtxt::new(self, RepeatingScope(id), id, Subject(subject), self.param_env);
116 // There are no add'l implied bounds when checking a
117 // standalone expr (e.g., the `E` in a type like `[u32; E]`).
118 rcx.outlives_environment.save_implied_bounds(id);
120 if !self.errors_reported_since_creation() {
121 // regionck assumes typeck succeeded
122 rcx.visit_body(body);
123 rcx.visit_region_obligations(id);
125 rcx.resolve_regions_and_report_errors(SuppressRegionErrors::when_nll_is_enabled(self.tcx));
127 assert!(self.tables.borrow().free_region_map.is_empty());
128 self.tables.borrow_mut().free_region_map = rcx.outlives_environment.into_free_region_map();
131 /// Region checking during the WF phase for items. `wf_tys` are the
132 /// types from which we should derive implied bounds, if any.
133 pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: &[Ty<'tcx>]) {
134 debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys);
135 let subject = self.tcx.hir().local_def_id(item_id);
136 let mut rcx = RegionCtxt::new(
138 RepeatingScope(item_id),
143 rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span);
144 rcx.outlives_environment.save_implied_bounds(item_id);
145 rcx.visit_region_obligations(item_id);
146 rcx.resolve_regions_and_report_errors(SuppressRegionErrors::default());
149 /// Region check a function body. Not invoked on closures, but
150 /// only on the "root" fn item (in which closures may be
151 /// embedded). Walks the function body and adds various add'l
152 /// constraints that are needed for region inference. This is
153 /// separated both to isolate "pure" region constraints from the
154 /// rest of type check and because sometimes we need type
155 /// inference to have completed before we can determine which
156 /// constraints to add.
157 pub fn regionck_fn(&self, fn_id: hir::HirId, body: &'tcx hir::Body<'tcx>) {
158 debug!("regionck_fn(id={})", fn_id);
159 let subject = self.tcx.hir().body_owner_def_id(body.id());
160 let hir_id = body.value.hir_id;
162 RegionCtxt::new(self, RepeatingScope(hir_id), hir_id, Subject(subject), self.param_env);
164 if !self.errors_reported_since_creation() {
165 // regionck assumes typeck succeeded
166 rcx.visit_fn_body(fn_id, body, self.tcx.hir().span(fn_id));
169 rcx.resolve_regions_and_report_errors(SuppressRegionErrors::when_nll_is_enabled(self.tcx));
171 // In this mode, we also copy the free-region-map into the
172 // tables of the enclosing fcx. In the other regionck modes
173 // (e.g., `regionck_item`), we don't have an enclosing tables.
174 assert!(self.tables.borrow().free_region_map.is_empty());
175 self.tables.borrow_mut().free_region_map = rcx.outlives_environment.into_free_region_map();
179 ///////////////////////////////////////////////////////////////////////////
182 pub struct RegionCtxt<'a, 'tcx> {
183 pub fcx: &'a FnCtxt<'a, 'tcx>,
185 pub region_scope_tree: &'tcx region::ScopeTree,
187 outlives_environment: OutlivesEnvironment<'tcx>,
189 // id of innermost fn body id
193 // call_site scope of innermost fn
194 call_site_scope: Option<region::Scope>,
196 // id of innermost fn or loop
197 repeating_scope: hir::HirId,
199 // id of AST node being analyzed (the subject of the analysis).
200 subject_def_id: DefId,
203 impl<'a, 'tcx> Deref for RegionCtxt<'a, 'tcx> {
204 type Target = FnCtxt<'a, 'tcx>;
205 fn deref(&self) -> &Self::Target {
210 pub struct RepeatingScope(hir::HirId);
211 pub struct Subject(DefId);
213 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
215 fcx: &'a FnCtxt<'a, 'tcx>,
216 RepeatingScope(initial_repeating_scope): RepeatingScope,
217 initial_body_id: hir::HirId,
218 Subject(subject): Subject,
219 param_env: ty::ParamEnv<'tcx>,
220 ) -> RegionCtxt<'a, 'tcx> {
221 let region_scope_tree = fcx.tcx.region_scope_tree(subject);
222 let outlives_environment = OutlivesEnvironment::new(param_env);
226 repeating_scope: initial_repeating_scope,
227 body_id: initial_body_id,
229 call_site_scope: None,
230 subject_def_id: subject,
231 outlives_environment,
235 fn set_repeating_scope(&mut self, scope: hir::HirId) -> hir::HirId {
236 mem::replace(&mut self.repeating_scope, scope)
239 /// Try to resolve the type for the given node, returning `t_err` if an error results. Note that
240 /// we never care about the details of the error, the same error will be detected and reported
241 /// in the writeback phase.
243 /// Note one important point: we do not attempt to resolve *region variables* here. This is
244 /// because regionck is essentially adding constraints to those region variables and so may yet
245 /// influence how they are resolved.
247 /// Consider this silly example:
250 /// fn borrow(x: &i32) -> &i32 {x}
251 /// fn foo(x: @i32) -> i32 { // block: B
252 /// let b = borrow(x); // region: <R0>
257 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
258 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
259 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
260 /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
261 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
262 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
263 self.resolve_vars_if_possible(&unresolved_ty)
266 /// Try to resolve the type for the given node.
267 fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> {
268 let t = self.node_ty(id);
272 /// Try to resolve the type for the given node.
273 pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr<'_>) -> Ty<'tcx> {
274 let ty = self.tables.borrow().expr_ty_adjusted(expr);
275 self.resolve_type(ty)
278 /// This is the "main" function when region-checking a function item or a closure
279 /// within a function item. It begins by updating various fields (e.g., `call_site_scope`
280 /// and `outlives_environment`) to be appropriate to the function and then adds constraints
281 /// derived from the function body.
283 /// Note that it does **not** restore the state of the fields that
284 /// it updates! This is intentional, since -- for the main
285 /// function -- we wish to be able to read the final
286 /// `outlives_environment` and other fields from the caller. For
287 /// closures, however, we save and restore any "scoped state"
288 /// before we invoke this function. (See `visit_fn` in the
289 /// `intravisit::Visitor` impl below.)
292 id: hir::HirId, // the id of the fn itself
293 body: &'tcx hir::Body<'tcx>,
296 // When we enter a function, we can derive
297 debug!("visit_fn_body(id={:?})", id);
299 let body_id = body.id();
300 self.body_id = body_id.hir_id;
301 self.body_owner = self.tcx.hir().body_owner_def_id(body_id);
304 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
305 self.call_site_scope = Some(call_site);
308 match self.tables.borrow().liberated_fn_sigs().get(id) {
309 Some(f) => f.clone(),
311 bug!("No fn-sig entry for id={:?}", id);
316 // Collect the types from which we create inferred bounds.
317 // For the return type, if diverging, substitute `bool` just
318 // because it will have no effect.
320 // FIXME(#27579) return types should not be implied bounds
321 let fn_sig_tys: Vec<_> =
322 fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
324 self.outlives_environment.add_implied_bounds(
330 self.outlives_environment.save_implied_bounds(body_id.hir_id);
331 self.link_fn_params(&body.params);
332 self.visit_body(body);
333 self.visit_region_obligations(body_id.hir_id);
335 let call_site_scope = self.call_site_scope.unwrap();
336 debug!("visit_fn_body body.id {:?} call_site_scope: {:?}", body.id(), call_site_scope);
337 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
339 self.type_of_node_must_outlive(infer::CallReturn(span), body_id.hir_id, call_site_region);
341 self.constrain_opaque_types(
342 &self.fcx.opaque_types.borrow(),
343 self.outlives_environment.free_region_map(),
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, suppress: SuppressRegionErrors) {
357 self.infcx.process_registered_region_obligations(
358 self.outlives_environment.region_bound_pairs_map(),
359 self.implicit_region_bound,
363 self.fcx.resolve_regions_and_report_errors(
365 &self.region_scope_tree,
366 &self.outlives_environment,
371 fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>) {
372 debug!("regionck::visit_pat(pat={:?})", pat);
373 pat.each_binding(|_, hir_id, span, _| {
374 // If we have a variable that contains region'd data, that
375 // data will be accessible from anywhere that the variable is
376 // accessed. We must be wary of loops like this:
378 // // from src/test/compile-fail/borrowck-lend-flow.rs
379 // let mut v = box 3, w = box 4;
380 // let mut x = &mut w;
383 // borrow(v); //~ ERROR cannot borrow
384 // x = &mut v; // (1)
387 // Typically, we try to determine the region of a borrow from
388 // those points where it is dereferenced. In this case, one
389 // might imagine that the lifetime of `x` need only be the
390 // body of the loop. But of course this is incorrect because
391 // the pointer that is created at point (1) is consumed at
392 // point (2), meaning that it must be live across the loop
393 // iteration. The easiest way to guarantee this is to require
394 // that the lifetime of any regions that appear in a
395 // variable's type enclose at least the variable's scope.
396 let var_scope = self.region_scope_tree.var_scope(hir_id.local_id);
397 let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
399 let origin = infer::BindingTypeIsNotValidAtDecl(span);
400 self.type_of_node_must_outlive(origin, hir_id, var_region);
402 let typ = self.resolve_node_type(hir_id);
403 let body_id = self.body_id;
404 let _ = dropck::check_drop_obligations(self, typ, span, body_id);
409 impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> {
410 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
411 // However, right now we run into an issue whereby some free
412 // regions are not properly related if they appear within the
413 // types of arguments that must be inferred. This could be
414 // addressed by deferring the construction of the region
415 // hierarchy, and in particular the relationships between free
416 // regions, until regionck, as described in #3238.
418 type Map = Map<'tcx>;
420 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
421 NestedVisitorMap::None
426 fk: intravisit::FnKind<'tcx>,
427 _: &'tcx hir::FnDecl<'tcx>,
428 body_id: hir::BodyId,
434 intravisit::FnKind::Closure(..) => true,
437 "visit_fn invoked for something other than a closure"
440 // Save state of current function before invoking
441 // `visit_fn_body`. We will restore afterwards.
442 let old_body_id = self.body_id;
443 let old_body_owner = self.body_owner;
444 let old_call_site_scope = self.call_site_scope;
445 let env_snapshot = self.outlives_environment.push_snapshot_pre_closure();
447 let body = self.tcx.hir().body(body_id);
448 self.visit_fn_body(hir_id, body, span);
450 // Restore state from previous function.
451 self.outlives_environment.pop_snapshot_post_closure(env_snapshot);
452 self.call_site_scope = old_call_site_scope;
453 self.body_id = old_body_id;
454 self.body_owner = old_body_owner;
457 //visit_pat: visit_pat, // (..) see above
459 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
461 self.constrain_bindings_in_pat(&arm.pat);
462 intravisit::walk_arm(self, arm);
465 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
467 self.constrain_bindings_in_pat(&l.pat);
469 intravisit::walk_local(self, l);
472 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
473 debug!("regionck::visit_expr(e={:?}, repeating_scope={:?})", expr, self.repeating_scope);
475 // No matter what, the type of each expression must outlive the
476 // scope of that expression. This also guarantees basic WF.
477 let expr_ty = self.resolve_node_type(expr.hir_id);
478 // the region corresponding to this expression
479 let expr_region = self.tcx.mk_region(ty::ReScope(region::Scope {
480 id: expr.hir_id.local_id,
481 data: region::ScopeData::Node,
483 self.type_must_outlive(
484 infer::ExprTypeIsNotInScope(expr_ty, expr.span),
489 let is_method_call = self.tables.borrow().is_method_call(expr);
491 // If we are calling a method (either explicitly or via an
492 // overloaded operator), check that all of the types provided as
493 // arguments for its type parameters are well-formed, and all the regions
494 // provided as arguments outlive the call.
496 let origin = match expr.kind {
497 hir::ExprKind::MethodCall(..) => infer::ParameterOrigin::MethodCall,
498 hir::ExprKind::Unary(op, _) if op == hir::UnOp::UnDeref => {
499 infer::ParameterOrigin::OverloadedDeref
501 _ => infer::ParameterOrigin::OverloadedOperator,
504 let substs = self.tables.borrow().node_substs(expr.hir_id);
505 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
506 // Arguments (sub-expressions) are checked via `constrain_call`, below.
509 // Check any autoderefs or autorefs that appear.
510 let cmt_result = self.constrain_adjustments(expr);
512 // If necessary, constrain destructors in this expression. This will be
513 // the adjusted form if there is an adjustment.
516 self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span);
519 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
524 "regionck::visit_expr(e={:?}, repeating_scope={:?}) - visiting subexprs",
525 expr, self.repeating_scope
528 hir::ExprKind::Path(_) => {
529 let substs = self.tables.borrow().node_substs(expr.hir_id);
530 let origin = infer::ParameterOrigin::Path;
531 self.substs_wf_in_scope(origin, substs, expr.span, expr_region);
534 hir::ExprKind::Call(ref callee, ref args) => {
536 self.constrain_call(expr, Some(&callee), args.iter().map(|e| &*e));
538 self.constrain_callee(&callee);
539 self.constrain_call(expr, None, args.iter().map(|e| &*e));
542 intravisit::walk_expr(self, expr);
545 hir::ExprKind::MethodCall(.., ref args) => {
546 self.constrain_call(expr, Some(&args[0]), args[1..].iter().map(|e| &*e));
548 intravisit::walk_expr(self, expr);
551 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
553 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
556 intravisit::walk_expr(self, expr);
559 hir::ExprKind::Index(ref lhs, ref rhs) if is_method_call => {
560 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
562 intravisit::walk_expr(self, expr);
565 hir::ExprKind::Binary(_, ref lhs, ref rhs) if is_method_call => {
566 // As `ExprKind::MethodCall`, but the call is via an overloaded op.
567 self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter());
569 intravisit::walk_expr(self, expr);
572 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
573 // If you do `x OP y`, then the types of `x` and `y` must
574 // outlive the operation you are performing.
575 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
576 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
577 for &ty in &[lhs_ty, rhs_ty] {
578 self.type_must_outlive(infer::Operand(expr.span), ty, expr_region);
580 intravisit::walk_expr(self, expr);
583 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
584 // For *a, the lifetime of a must enclose the deref
586 self.constrain_call(expr, Some(base), None::<hir::Expr<'_>>.iter());
588 // For overloaded derefs, base_ty is the input to `Deref::deref`,
589 // but it's a reference type uing the same region as the output.
590 let base_ty = self.resolve_expr_type_adjusted(base);
591 if let ty::Ref(r_ptr, _, _) = base_ty.kind {
592 self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
595 intravisit::walk_expr(self, expr);
598 hir::ExprKind::Unary(_, ref lhs) if is_method_call => {
600 self.constrain_call(expr, Some(&lhs), None::<hir::Expr<'_>>.iter());
602 intravisit::walk_expr(self, expr);
605 hir::ExprKind::Index(ref vec_expr, _) => {
606 // For a[b], the lifetime of a must enclose the deref
607 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
608 self.constrain_index(expr, vec_type);
610 intravisit::walk_expr(self, expr);
613 hir::ExprKind::Cast(ref source, _) => {
614 // Determine if we are casting `source` to a trait
615 // instance. If so, we have to be sure that the type of
616 // the source obeys the trait's region bound.
617 self.constrain_cast(expr, &source);
618 intravisit::walk_expr(self, expr);
621 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref base) => {
622 self.link_addr_of(expr, m, &base);
624 // Require that when you write a `&expr` expression, the
625 // resulting pointer has a lifetime that encompasses the
626 // `&expr` expression itself. Note that we constraining
627 // the type of the node expr.id here *before applying
630 // FIXME(https://github.com/rust-lang/rfcs/issues/811)
631 // nested method calls requires that this rule change
632 let ty0 = self.resolve_node_type(expr.hir_id);
633 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
634 intravisit::walk_expr(self, expr);
637 hir::ExprKind::Match(ref discr, ref arms, _) => {
638 self.link_match(&discr, &arms[..]);
640 intravisit::walk_expr(self, expr);
643 hir::ExprKind::Closure(.., body_id, _, _) => {
644 self.check_expr_fn_block(expr, body_id);
647 hir::ExprKind::Loop(ref body, _, _) => {
648 let repeating_scope = self.set_repeating_scope(body.hir_id);
649 intravisit::walk_expr(self, expr);
650 self.set_repeating_scope(repeating_scope);
653 hir::ExprKind::Ret(Some(ref ret_expr)) => {
654 let call_site_scope = self.call_site_scope;
656 "visit_expr ExprKind::Ret ret_expr.hir_id {} call_site_scope: {:?}",
657 ret_expr.hir_id, call_site_scope
659 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
660 self.type_of_node_must_outlive(
661 infer::CallReturn(ret_expr.span),
665 intravisit::walk_expr(self, expr);
669 intravisit::walk_expr(self, expr);
675 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
676 fn constrain_cast(&mut self, cast_expr: &hir::Expr<'_>, source_expr: &hir::Expr<'_>) {
677 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})", cast_expr, source_expr);
679 let source_ty = self.resolve_node_type(source_expr.hir_id);
680 let target_ty = self.resolve_node_type(cast_expr.hir_id);
682 self.walk_cast(cast_expr, source_ty, target_ty);
685 fn walk_cast(&mut self, cast_expr: &hir::Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) {
686 debug!("walk_cast(from_ty={:?}, to_ty={:?})", from_ty, to_ty);
687 match (&from_ty.kind, &to_ty.kind) {
689 (&ty::Ref(from_r, from_ty, _), /*To: */ &ty::Ref(to_r, to_ty, _)) => {
690 // Target cannot outlive source, naturally.
691 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
692 self.walk_cast(cast_expr, from_ty, to_ty);
696 (_, /*To: */ &ty::Dynamic(.., r)) => {
697 // When T is existentially quantified as a trait
698 // `Foo+'to`, it must outlive the region bound `'to`.
699 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
703 (&ty::Adt(from_def, _), /*To: */ &ty::Adt(to_def, _))
704 if from_def.is_box() && to_def.is_box() =>
706 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
713 fn check_expr_fn_block(&mut self, expr: &'tcx hir::Expr<'tcx>, body_id: hir::BodyId) {
714 let repeating_scope = self.set_repeating_scope(body_id.hir_id);
715 intravisit::walk_expr(self, expr);
716 self.set_repeating_scope(repeating_scope);
719 fn constrain_callee(&mut self, callee_expr: &hir::Expr<'_>) {
720 let callee_ty = self.resolve_node_type(callee_expr.hir_id);
721 match callee_ty.kind {
722 ty::FnDef(..) | ty::FnPtr(_) => {}
724 // this should not happen, but it does if the program is
729 // "Calling non-function: {}",
735 fn constrain_call<'b, I: Iterator<Item = &'b hir::Expr<'b>>>(
737 call_expr: &hir::Expr<'_>,
738 receiver: Option<&hir::Expr<'_>>,
741 //! Invoked on every call site (i.e., normal calls, method calls,
742 //! and overloaded operators). Constrains the regions which appear
743 //! in the type of the function. Also constrains the regions that
744 //! appear in the arguments appropriately.
746 debug!("constrain_call(call_expr={:?}, receiver={:?})", call_expr, receiver);
748 // `callee_region` is the scope representing the time in which the
751 // FIXME(#6268) to support nested method calls, should be callee_id
753 region::Scope { id: call_expr.hir_id.local_id, data: region::ScopeData::Node };
754 let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
756 debug!("callee_region={:?}", callee_region);
758 for arg_expr in arg_exprs {
759 debug!("argument: {:?}", arg_expr);
761 // ensure that any regions appearing in the argument type are
762 // valid for at least the lifetime of the function:
763 self.type_of_node_must_outlive(
764 infer::CallArg(arg_expr.span),
770 // as loop above, but for receiver
771 if let Some(r) = receiver {
772 debug!("receiver: {:?}", r);
773 self.type_of_node_must_outlive(infer::CallRcvr(r.span), r.hir_id, callee_region);
777 /// Creates a temporary `MemCategorizationContext` and pass it to the closure.
778 fn with_mc<F, R>(&self, f: F) -> R
780 F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R,
782 f(mc::MemCategorizationContext::new(
784 self.outlives_environment.param_env,
786 &self.tables.borrow(),
790 /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
791 /// dereferenced, the lifetime of the pointer includes the deref expr.
792 fn constrain_adjustments(&mut self, expr: &hir::Expr<'_>) -> mc::McResult<mc::Place<'tcx>> {
793 debug!("constrain_adjustments(expr={:?})", expr);
795 let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
797 let tables = self.tables.borrow();
798 let adjustments = tables.expr_adjustments(&expr);
799 if adjustments.is_empty() {
803 debug!("constrain_adjustments: adjustments={:?}", adjustments);
805 // If necessary, constrain destructors in the unadjusted form of this
807 self.check_safety_of_rvalue_destructor_if_necessary(&cmt, expr.span);
809 let expr_region = self.tcx.mk_region(ty::ReScope(region::Scope {
810 id: expr.hir_id.local_id,
811 data: region::ScopeData::Node,
813 for adjustment in adjustments {
814 debug!("constrain_adjustments: adjustment={:?}, cmt={:?}", adjustment, cmt);
816 if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
817 debug!("constrain_adjustments: overloaded deref: {:?}", deref);
819 // Treat overloaded autoderefs as if an AutoBorrow adjustment
820 // was applied on the base type, as that is always the case.
823 .mk_ref(deref.region, ty::TypeAndMut { ty: cmt.ty, mutbl: deref.mutbl });
824 let output = self.tcx.mk_ref(
826 ty::TypeAndMut { ty: adjustment.target, mutbl: deref.mutbl },
832 ty::BorrowKind::from_mutbl(deref.mutbl),
836 // Specialized version of constrain_call.
837 self.type_must_outlive(infer::CallRcvr(expr.span), input, expr_region);
838 self.type_must_outlive(infer::CallReturn(expr.span), output, expr_region);
841 if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
842 self.link_autoref(expr, &cmt, autoref);
844 // Require that the resulting region encompasses
847 // FIXME(#6268) remove to support nested method calls
848 self.type_of_node_must_outlive(
849 infer::AutoBorrow(expr.span),
855 cmt = self.with_mc(|mc| mc.cat_expr_adjusted(expr, cmt, &adjustment))?;
861 pub fn mk_subregion_due_to_dereference(
864 minimum_lifetime: ty::Region<'tcx>,
865 maximum_lifetime: ty::Region<'tcx>,
867 self.sub_regions(infer::DerefPointer(deref_span), minimum_lifetime, maximum_lifetime)
870 fn check_safety_of_rvalue_destructor_if_necessary(
872 place: &mc::Place<'tcx>,
875 if let mc::PlaceBase::Rvalue = place.base {
876 if place.projections.is_empty() {
877 let typ = self.resolve_type(place.ty);
878 let body_id = self.body_id;
879 let _ = dropck::check_drop_obligations(self, typ, span, body_id);
884 /// Invoked on any index expression that occurs. Checks that if this is a slice
885 /// being indexed, the lifetime of the pointer includes the deref expr.
886 fn constrain_index(&mut self, index_expr: &hir::Expr<'_>, indexed_ty: Ty<'tcx>) {
887 debug!("constrain_index(index_expr=?, indexed_ty={}", self.ty_to_string(indexed_ty));
889 let r_index_expr = ty::ReScope(region::Scope {
890 id: index_expr.hir_id.local_id,
891 data: region::ScopeData::Node,
893 if let ty::Ref(r_ptr, r_ty, _) = indexed_ty.kind {
895 ty::Slice(_) | ty::Str => {
897 infer::IndexSlice(index_expr.span),
898 self.tcx.mk_region(r_index_expr),
907 /// Guarantees that any lifetimes that appear in the type of the node `id` (after applying
908 /// adjustments) are valid for at least `minimum_lifetime`.
909 fn type_of_node_must_outlive(
911 origin: infer::SubregionOrigin<'tcx>,
913 minimum_lifetime: ty::Region<'tcx>,
915 // Try to resolve the type. If we encounter an error, then typeck
916 // is going to fail anyway, so just stop here and let typeck
917 // report errors later on in the writeback phase.
918 let ty0 = self.resolve_node_type(hir_id);
925 .and_then(|adj| adj.last())
926 .map_or(ty0, |adj| adj.target);
927 let ty = self.resolve_type(ty);
929 "constrain_regions_in_type_of_node(\
930 ty={}, ty0={}, id={:?}, minimum_lifetime={:?})",
931 ty, ty0, hir_id, minimum_lifetime
933 self.type_must_outlive(origin, ty, minimum_lifetime);
936 /// Adds constraints to inference such that `T: 'a` holds (or
937 /// reports an error if it cannot).
941 /// - `origin`, the reason we need this constraint
942 /// - `ty`, the type `T`
943 /// - `region`, the region `'a`
944 pub fn type_must_outlive(
946 origin: infer::SubregionOrigin<'tcx>,
948 region: ty::Region<'tcx>,
950 self.infcx.register_region_obligation(
952 RegionObligation { sub_region: region, sup_type: ty, origin },
956 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
957 /// resulting pointer is linked to the lifetime of its guarantor (if any).
960 expr: &hir::Expr<'_>,
961 mutability: hir::Mutability,
962 base: &hir::Expr<'_>,
964 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
966 let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
968 debug!("link_addr_of: cmt={:?}", cmt);
970 self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt);
973 /// Computes the guarantors for any ref bindings in a `let` and
974 /// then ensures that the lifetime of the resulting pointer is
975 /// linked to the lifetime of the initialization expression.
976 fn link_local(&self, local: &hir::Local<'_>) {
977 debug!("regionck::for_local()");
978 let init_expr = match local.init {
982 Some(ref expr) => &**expr,
984 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
985 self.link_pattern(discr_cmt, &local.pat);
988 /// Computes the guarantors for any ref bindings in a match and
989 /// then ensures that the lifetime of the resulting pointer is
990 /// linked to the lifetime of its guarantor (if any).
991 fn link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>]) {
992 debug!("regionck::for_match()");
993 let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
994 debug!("discr_cmt={:?}", discr_cmt);
996 self.link_pattern(discr_cmt.clone(), &arm.pat);
1000 /// Computes the guarantors for any ref bindings in a match and
1001 /// then ensures that the lifetime of the resulting pointer is
1002 /// linked to the lifetime of its guarantor (if any).
1003 fn link_fn_params(&self, params: &[hir::Param<'_>]) {
1004 for param in params {
1005 let param_ty = self.node_ty(param.hir_id);
1007 self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty));
1008 debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param);
1009 self.link_pattern(param_cmt, ¶m.pat);
1013 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1014 /// in the discriminant, if needed.
1015 fn link_pattern(&self, discr_cmt: mc::Place<'tcx>, root_pat: &hir::Pat<'_>) {
1016 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat);
1017 ignore_err!(self.with_mc(|mc| {
1018 mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id }| {
1020 if let PatKind::Binding(..) = kind {
1021 if let Some(ty::BindByReference(mutbl)) =
1022 mc.tables.extract_binding_mode(self.tcx.sess, *hir_id, *span)
1024 self.link_region_from_node_type(*span, *hir_id, mutbl, &sub_cmt);
1031 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1035 expr: &hir::Expr<'_>,
1036 expr_cmt: &mc::Place<'tcx>,
1037 autoref: &adjustment::AutoBorrow<'tcx>,
1039 debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
1042 adjustment::AutoBorrow::Ref(r, m) => {
1043 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt);
1046 adjustment::AutoBorrow::RawPtr(m) => {
1047 let r = self.tcx.mk_region(ty::ReScope(region::Scope {
1048 id: expr.hir_id.local_id,
1049 data: region::ScopeData::Node,
1051 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1056 /// Like `link_region()`, except that the region is extracted from the type of `id`,
1057 /// which must be some reference (`&T`, `&str`, etc).
1058 fn link_region_from_node_type(
1062 mutbl: hir::Mutability,
1063 cmt_borrowed: &mc::Place<'tcx>,
1066 "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1067 id, mutbl, cmt_borrowed
1070 let rptr_ty = self.resolve_node_type(id);
1071 if let ty::Ref(r, _, _) = rptr_ty.kind {
1072 debug!("rptr_ty={}", rptr_ty);
1073 self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed);
1077 /// Informs the inference engine that `borrow_cmt` is being borrowed with
1078 /// kind `borrow_kind` and lifetime `borrow_region`.
1079 /// In order to ensure borrowck is satisfied, this may create constraints
1080 /// between regions, as explained in `link_reborrowed_region()`.
1084 borrow_region: ty::Region<'tcx>,
1085 borrow_kind: ty::BorrowKind,
1086 borrow_place: &mc::Place<'tcx>,
1088 let origin = infer::DataBorrowed(borrow_place.ty, span);
1089 self.type_must_outlive(origin, borrow_place.ty, borrow_region);
1091 for pointer_ty in borrow_place.deref_tys() {
1093 "link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})",
1094 borrow_region, borrow_kind, borrow_place
1096 match pointer_ty.kind {
1097 ty::RawPtr(_) => return,
1098 ty::Ref(ref_region, _, ref_mutability) => {
1099 if self.link_reborrowed_region(span, borrow_region, ref_region, ref_mutability)
1104 _ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty),
1107 if let mc::PlaceBase::Upvar(upvar_id) = borrow_place.base {
1108 self.link_upvar_region(span, borrow_region, upvar_id);
1112 /// This is the most complicated case: the path being borrowed is
1113 /// itself the referent of a borrowed pointer. Let me give an
1114 /// example fragment of code to make clear(er) the situation:
1116 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1118 /// &'z *r // the reborrow has lifetime 'z
1120 /// Now, in this case, our primary job is to add the inference
1121 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1122 /// parameters in (roughly) terms of the example:
1124 /// ```plain,ignore (pseudo-Rust)
1125 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1126 /// borrow_region ^~ ref_region ^~
1127 /// borrow_kind ^~ ref_kind ^~
1131 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1133 /// There is a complication beyond the simple scenario I just painted: there
1134 /// may in fact be more levels of reborrowing. In the example, I said the
1135 /// borrow was like `&'z *r`, but it might in fact be a borrow like
1136 /// `&'z **q` where `q` has type `&'a &'b mut T`. In that case, we want to
1137 /// ensure that `'z <= 'a` and `'z <= 'b`.
1139 /// The return value of this function indicates whether we *don't* need to
1140 /// the recurse to the next reference up.
1142 /// This is explained more below.
1143 fn link_reborrowed_region(
1146 borrow_region: ty::Region<'tcx>,
1147 ref_region: ty::Region<'tcx>,
1148 ref_mutability: hir::Mutability,
1150 debug!("link_reborrowed_region: {:?} <= {:?}", borrow_region, ref_region);
1151 self.sub_regions(infer::Reborrow(span), borrow_region, ref_region);
1153 // Decide whether we need to recurse and link any regions within
1154 // the `ref_cmt`. This is concerned for the case where the value
1155 // being reborrowed is in fact a borrowed pointer found within
1156 // another borrowed pointer. For example:
1158 // let p: &'b &'a mut T = ...;
1162 // What makes this case particularly tricky is that, if the data
1163 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1164 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1165 // (otherwise the user might mutate through the `&mut T` reference
1166 // after `'b` expires and invalidate the borrow we are looking at
1169 // So let's re-examine our parameters in light of this more
1170 // complicated (possible) scenario:
1172 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1173 // borrow_region ^~ ref_region ^~
1174 // borrow_kind ^~ ref_kind ^~
1177 // (Note that since we have not examined `ref_cmt.cat`, we don't
1178 // know whether this scenario has occurred; but I wanted to show
1179 // how all the types get adjusted.)
1180 match ref_mutability {
1181 hir::Mutability::Not => {
1182 // The reference being reborrowed is a shareable ref of
1183 // type `&'a T`. In this case, it doesn't matter where we
1184 // *found* the `&T` pointer, the memory it references will
1185 // be valid and immutable for `'a`. So we can stop here.
1189 hir::Mutability::Mut => {
1190 // The reference being reborrowed is either an `&mut T`. This is
1191 // the case where recursion is needed.
1197 /// An upvar may be behind up to 2 references:
1199 /// * One can come from the reference to a "by-reference" upvar.
1200 /// * Another one can come from the reference to the closure itself if it's
1201 /// a `FnMut` or `Fn` closure.
1203 /// This function links the lifetimes of those references to the lifetime
1204 /// of the borrow that's provided. See [link_reborrowed_region] for some
1205 /// more explanation of this in the general case.
1207 /// We also supply a *cause*, and in this case we set the cause to
1208 /// indicate that the reference being "reborrowed" is itself an upvar. This
1209 /// provides a nicer error message should something go wrong.
1210 fn link_upvar_region(
1213 borrow_region: ty::Region<'tcx>,
1214 upvar_id: ty::UpvarId,
1216 debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id);
1217 // A by-reference upvar can't be borrowed for longer than the
1218 // upvar is borrowed from the environment.
1219 match self.tables.borrow().upvar_capture(upvar_id) {
1220 ty::UpvarCapture::ByRef(upvar_borrow) => {
1222 infer::ReborrowUpvar(span, upvar_id),
1224 upvar_borrow.region,
1226 if let ty::ImmBorrow = upvar_borrow.kind {
1227 debug!("link_upvar_region: capture by shared ref");
1231 ty::UpvarCapture::ByValue => {}
1233 let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(upvar_id.closure_expr_id);
1234 let ty = self.resolve_node_type(fn_hir_id);
1235 debug!("link_upvar_region: ty={:?}", ty);
1237 // A closure capture can't be borrowed for longer than the
1238 // reference to the closure.
1239 if let ty::Closure(closure_def_id, substs) = ty.kind {
1240 match self.infcx.closure_kind(closure_def_id, substs) {
1241 Some(ty::ClosureKind::Fn) | Some(ty::ClosureKind::FnMut) => {
1242 // Region of environment pointer
1243 let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
1244 scope: upvar_id.closure_expr_id.to_def_id(),
1245 bound_region: ty::BrEnv,
1248 infer::ReborrowUpvar(span, upvar_id),
1253 Some(ty::ClosureKind::FnOnce) => {}
1255 span_bug!(span, "Have not inferred closure kind before regionck");
1261 /// Checks that the values provided for type/region arguments in a given
1262 /// expression are well-formed and in-scope.
1263 fn substs_wf_in_scope(
1265 origin: infer::ParameterOrigin,
1266 substs: SubstsRef<'tcx>,
1268 expr_region: ty::Region<'tcx>,
1271 "substs_wf_in_scope(substs={:?}, \
1275 substs, expr_region, origin, expr_span
1278 let origin = infer::ParameterInScope(origin, expr_span);
1280 for kind in substs {
1281 match kind.unpack() {
1282 GenericArgKind::Lifetime(lt) => {
1283 self.sub_regions(origin.clone(), expr_region, lt);
1285 GenericArgKind::Type(ty) => {
1286 let ty = self.resolve_type(ty);
1287 self.type_must_outlive(origin.clone(), ty, expr_region);
1289 GenericArgKind::Const(_) => {
1290 // Const parameters don't impose constraints.