1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The region check is a final pass that runs over the AST after we have
12 //! inferred the type constraints but before we have actually finalized
13 //! the types. Its purpose is to embed a variety of region constraints.
14 //! Inserting these constraints as a separate pass is good because (1) it
15 //! localizes the code that has to do with region inference and (2) often
16 //! we cannot know what constraints are needed until the basic types have
19 //! ### Interaction with the borrow checker
21 //! In general, the job of the borrowck module (which runs later) is to
22 //! check that all soundness criteria are met, given a particular set of
23 //! regions. The job of *this* module is to anticipate the needs of the
24 //! borrow checker and infer regions that will satisfy its requirements.
25 //! It is generally true that the inference doesn't need to be sound,
26 //! meaning that if there is a bug and we inferred bad regions, the borrow
27 //! checker should catch it. This is not entirely true though; for
28 //! example, the borrow checker doesn't check subtyping, and it doesn't
29 //! check that region pointers are always live when they are used. It
30 //! might be worthwhile to fix this so that borrowck serves as a kind of
31 //! verification step -- that would add confidence in the overall
32 //! correctness of the compiler, at the cost of duplicating some type
33 //! checks and effort.
35 //! ### Inferring the duration of borrows, automatic and otherwise
37 //! Whenever we introduce a borrowed pointer, for example as the result of
38 //! a borrow expression `let x = &data`, the lifetime of the pointer `x`
39 //! is always specified as a region inference variable. `regionck` has the
40 //! job of adding constraints such that this inference variable is as
41 //! narrow as possible while still accommodating all uses (that is, every
42 //! dereference of the resulting pointer must be within the lifetime).
46 //! Generally speaking, `regionck` does NOT try to ensure that the data
47 //! `data` will outlive the pointer `x`. That is the job of borrowck. The
48 //! one exception is when "re-borrowing" the contents of another borrowed
49 //! pointer. For example, imagine you have a borrowed pointer `b` with
50 //! lifetime L1 and you have an expression `&*b`. The result of this
51 //! expression will be another borrowed pointer with lifetime L2 (which is
52 //! an inference variable). The borrow checker is going to enforce the
53 //! constraint that L2 < L1, because otherwise you are re-borrowing data
54 //! for a lifetime larger than the original loan. However, without the
55 //! routines in this module, the region inferencer would not know of this
56 //! dependency and thus it might infer the lifetime of L2 to be greater
57 //! than L1 (issue #3148).
59 //! There are a number of troublesome scenarios in the tests
60 //! `region-dependent-*.rs`, but here is one example:
62 //! struct Foo { i: i32 }
63 //! struct Bar { foo: Foo }
64 //! fn get_i<'a>(x: &'a Bar) -> &'a i32 {
65 //! let foo = &x.foo; // Lifetime L1
66 //! &foo.i // Lifetime L2
69 //! Note that this comes up either with `&` expressions, `ref`
70 //! bindings, and `autorefs`, which are the three ways to introduce
73 //! The key point here is that when you are borrowing a value that
74 //! is "guaranteed" by a borrowed pointer, you must link the
75 //! lifetime of that borrowed pointer (L1, here) to the lifetime of
76 //! the borrow itself (L2). What do I mean by "guaranteed" by a
77 //! borrowed pointer? I mean any data that is reached by first
78 //! dereferencing a borrowed pointer and then either traversing
79 //! interior offsets or boxes. We say that the guarantor
80 //! of such data is the region of the borrowed pointer that was
81 //! traversed. This is essentially the same as the ownership
82 //! relation, except that a borrowed pointer never owns its
87 use middle::free_region::FreeRegionMap;
88 use middle::mem_categorization as mc;
89 use middle::mem_categorization::Categorization;
90 use middle::region::{self, CodeExtent};
91 use rustc::ty::subst::Substs;
93 use rustc::ty::{self, Ty, MethodCall, TypeFoldable};
94 use rustc::infer::{self, GenericKind, SubregionOrigin, VerifyBound};
95 use rustc::ty::adjustment;
96 use rustc::ty::wf::ImpliedBound;
101 use syntax_pos::Span;
102 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
103 use rustc::hir::{self, PatKind};
105 // a variation on try that just returns unit
106 macro_rules! ignore_err {
107 ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () })
110 ///////////////////////////////////////////////////////////////////////////
111 // PUBLIC ENTRY POINTS
113 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
114 pub fn regionck_expr(&self, body: &'gcx hir::Body) {
115 let id = body.value.id;
116 let mut rcx = RegionCtxt::new(self, RepeatingScope(id), id, Subject(id));
117 if self.err_count_since_creation() == 0 {
118 // regionck assumes typeck succeeded
119 rcx.visit_body(body);
120 rcx.visit_region_obligations(id);
122 rcx.resolve_regions_and_report_errors();
124 assert!(self.tables.borrow().free_region_map.is_empty());
125 self.tables.borrow_mut().free_region_map = rcx.free_region_map;
128 /// Region checking during the WF phase for items. `wf_tys` are the
129 /// types from which we should derive implied bounds, if any.
130 pub fn regionck_item(&self,
131 item_id: ast::NodeId,
133 wf_tys: &[Ty<'tcx>]) {
134 debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys);
135 let mut rcx = RegionCtxt::new(self, RepeatingScope(item_id), item_id, Subject(item_id));
136 rcx.free_region_map.relate_free_regions_from_predicates(
137 &self.parameter_environment.caller_bounds);
138 rcx.relate_free_regions(wf_tys, item_id, span);
139 rcx.visit_region_obligations(item_id);
140 rcx.resolve_regions_and_report_errors();
143 pub fn regionck_fn(&self,
145 body: &'gcx hir::Body) {
146 debug!("regionck_fn(id={})", fn_id);
147 let node_id = body.value.id;
148 let mut rcx = RegionCtxt::new(self, RepeatingScope(node_id), node_id, Subject(fn_id));
150 if self.err_count_since_creation() == 0 {
151 // regionck assumes typeck succeeded
152 rcx.visit_fn_body(fn_id, body, self.tcx.hir.span(fn_id));
155 rcx.free_region_map.relate_free_regions_from_predicates(
156 &self.parameter_environment.caller_bounds);
158 rcx.resolve_regions_and_report_errors();
160 // In this mode, we also copy the free-region-map into the
161 // tables of the enclosing fcx. In the other regionck modes
162 // (e.g., `regionck_item`), we don't have an enclosing tables.
163 assert!(self.tables.borrow().free_region_map.is_empty());
164 self.tables.borrow_mut().free_region_map = rcx.free_region_map;
168 ///////////////////////////////////////////////////////////////////////////
171 pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
172 pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
174 region_bound_pairs: Vec<(ty::Region<'tcx>, GenericKind<'tcx>)>,
176 free_region_map: FreeRegionMap<'tcx>,
178 // id of innermost fn body id
179 body_id: ast::NodeId,
181 // call_site scope of innermost fn
182 call_site_scope: Option<CodeExtent<'tcx>>,
184 // id of innermost fn or loop
185 repeating_scope: ast::NodeId,
187 // id of AST node being analyzed (the subject of the analysis).
188 subject: ast::NodeId,
192 impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> {
193 type Target = FnCtxt<'a, 'gcx, 'tcx>;
194 fn deref(&self) -> &Self::Target {
199 pub struct RepeatingScope(ast::NodeId);
200 pub struct Subject(ast::NodeId);
202 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
203 pub fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
204 RepeatingScope(initial_repeating_scope): RepeatingScope,
205 initial_body_id: ast::NodeId,
206 Subject(subject): Subject) -> RegionCtxt<'a, 'gcx, 'tcx> {
209 repeating_scope: initial_repeating_scope,
210 body_id: initial_body_id,
211 call_site_scope: None,
213 region_bound_pairs: Vec::new(),
214 free_region_map: FreeRegionMap::new(),
218 fn set_call_site_scope(&mut self, call_site_scope: Option<CodeExtent<'tcx>>)
219 -> Option<CodeExtent<'tcx>> {
220 mem::replace(&mut self.call_site_scope, call_site_scope)
223 fn set_body_id(&mut self, body_id: ast::NodeId) -> ast::NodeId {
224 mem::replace(&mut self.body_id, body_id)
227 fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
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_type_vars_if_possible(&unresolved_ty)
258 /// Try to resolve the type for the given node.
259 fn resolve_node_type(&self, id: ast::NodeId) -> 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 fn visit_fn_body(&mut self,
271 id: ast::NodeId, // the id of the fn itself
272 body: &'gcx hir::Body,
275 // When we enter a function, we can derive
276 debug!("visit_fn_body(id={})", id);
278 let body_id = body.id();
280 let call_site = self.tcx.intern_code_extent(
281 region::CodeExtentData::CallSiteScope { fn_id: id, body_id: body_id.node_id });
282 let old_call_site_scope = self.set_call_site_scope(Some(call_site));
285 let fn_sig_map = &self.tables.borrow().liberated_fn_sigs;
286 match fn_sig_map.get(&id) {
287 Some(f) => f.clone(),
289 bug!("No fn-sig entry for id={}", id);
294 let old_region_bounds_pairs_len = self.region_bound_pairs.len();
296 // Collect the types from which we create inferred bounds.
297 // For the return type, if diverging, substitute `bool` just
298 // because it will have no effect.
300 // FIXME(#27579) return types should not be implied bounds
301 let fn_sig_tys: Vec<_> =
302 fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
304 let old_body_id = self.set_body_id(body_id.node_id);
305 self.relate_free_regions(&fn_sig_tys[..], body_id.node_id, span);
306 self.link_fn_args(self.tcx.node_extent(body_id.node_id), &body.arguments);
307 self.visit_body(body);
308 self.visit_region_obligations(body_id.node_id);
310 let call_site_scope = self.call_site_scope.unwrap();
311 debug!("visit_fn_body body.id {:?} call_site_scope: {:?}",
312 body.id(), call_site_scope);
313 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
314 self.type_of_node_must_outlive(infer::CallReturn(span),
318 self.region_bound_pairs.truncate(old_region_bounds_pairs_len);
320 self.set_body_id(old_body_id);
321 self.set_call_site_scope(old_call_site_scope);
324 fn visit_region_obligations(&mut self, node_id: ast::NodeId)
326 debug!("visit_region_obligations: node_id={}", node_id);
328 // region checking can introduce new pending obligations
329 // which, when processed, might generate new region
330 // obligations. So make sure we process those.
331 self.select_all_obligations_or_error();
333 // Make a copy of the region obligations vec because we'll need
334 // to be able to borrow the fulfillment-cx below when projecting.
335 let region_obligations =
338 .region_obligations(node_id)
341 for r_o in ®ion_obligations {
342 debug!("visit_region_obligations: r_o={:?} cause={:?}",
344 let sup_type = self.resolve_type(r_o.sup_type);
345 let origin = self.code_to_origin(&r_o.cause, sup_type);
346 self.type_must_outlive(origin, sup_type, r_o.sub_region);
349 // Processing the region obligations should not cause the list to grow further:
350 assert_eq!(region_obligations.len(),
351 self.fulfillment_cx.borrow().region_obligations(node_id).len());
354 fn code_to_origin(&self,
355 cause: &traits::ObligationCause<'tcx>,
357 -> SubregionOrigin<'tcx> {
358 SubregionOrigin::from_obligation_cause(cause,
359 || infer::RelateParamBound(cause.span, sup_type))
362 /// This method populates the region map's `free_region_map`. It walks over the transformed
363 /// argument and return types for each function just before we check the body of that function,
364 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
365 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
366 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
367 /// the caller side, the caller is responsible for checking that the type of every expression
368 /// (including the actual values for the arguments, as well as the return type of the fn call)
371 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
372 fn relate_free_regions(&mut self,
373 fn_sig_tys: &[Ty<'tcx>],
374 body_id: ast::NodeId,
376 debug!("relate_free_regions >>");
378 for &ty in fn_sig_tys {
379 let ty = self.resolve_type(ty);
380 debug!("relate_free_regions(t={:?})", ty);
381 let implied_bounds = ty::wf::implied_bounds(self, body_id, ty, span);
383 // Record any relations between free regions that we observe into the free-region-map.
384 self.free_region_map.relate_free_regions_from_implied_bounds(&implied_bounds);
386 // But also record other relationships, such as `T:'x`,
387 // that don't go into the free-region-map but which we use
389 for implication in implied_bounds {
390 debug!("implication: {:?}", implication);
392 ImpliedBound::RegionSubRegion(&ty::ReFree(free_a),
393 &ty::ReVar(vid_b)) => {
394 self.add_given(free_a, vid_b);
396 ImpliedBound::RegionSubParam(r_a, param_b) => {
397 self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
399 ImpliedBound::RegionSubProjection(r_a, projection_b) => {
400 self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
402 ImpliedBound::RegionSubRegion(..) => {
403 // In principle, we could record (and take
404 // advantage of) every relationship here, but
405 // we are also free not to -- it simply means
406 // strictly less that we can successfully type
407 // check. (It may also be that we should
408 // revise our inference system to be more
409 // general and to make use of *every*
410 // relationship that arises here, but
411 // presently we do not.)
417 debug!("<< relate_free_regions");
420 fn resolve_regions_and_report_errors(&self) {
421 let subject_node_id = self.subject;
423 self.fcx.resolve_regions_and_report_errors(&self.free_region_map,
427 fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) {
429 debug!("regionck::visit_pat(pat={:?})", pat);
430 pat.each_binding(|_, id, span, _| {
431 // If we have a variable that contains region'd data, that
432 // data will be accessible from anywhere that the variable is
433 // accessed. We must be wary of loops like this:
435 // // from src/test/compile-fail/borrowck-lend-flow.rs
436 // let mut v = box 3, w = box 4;
437 // let mut x = &mut w;
440 // borrow(v); //~ ERROR cannot borrow
441 // x = &mut v; // (1)
444 // Typically, we try to determine the region of a borrow from
445 // those points where it is dereferenced. In this case, one
446 // might imagine that the lifetime of `x` need only be the
447 // body of the loop. But of course this is incorrect because
448 // the pointer that is created at point (1) is consumed at
449 // point (2), meaning that it must be live across the loop
450 // iteration. The easiest way to guarantee this is to require
451 // that the lifetime of any regions that appear in a
452 // variable's type enclose at least the variable's scope.
454 let var_scope = tcx.region_maps().var_scope(id);
455 let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
457 let origin = infer::BindingTypeIsNotValidAtDecl(span);
458 self.type_of_node_must_outlive(origin, id, var_region);
460 let typ = self.resolve_node_type(id);
461 let _ = dropck::check_safety_of_destructor_if_necessary(
462 self, typ, span, var_scope);
467 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for RegionCtxt<'a, 'gcx, 'tcx> {
468 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
469 // However, right now we run into an issue whereby some free
470 // regions are not properly related if they appear within the
471 // types of arguments that must be inferred. This could be
472 // addressed by deferring the construction of the region
473 // hierarchy, and in particular the relationships between free
474 // regions, until regionck, as described in #3238.
476 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
477 NestedVisitorMap::None
480 fn visit_fn(&mut self, _fk: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
481 b: hir::BodyId, span: Span, id: ast::NodeId) {
482 let body = self.tcx.hir.body(b);
483 self.visit_fn_body(id, body, span)
486 //visit_pat: visit_pat, // (..) see above
488 fn visit_arm(&mut self, arm: &'gcx hir::Arm) {
491 self.constrain_bindings_in_pat(p);
493 intravisit::walk_arm(self, arm);
496 fn visit_local(&mut self, l: &'gcx hir::Local) {
498 self.constrain_bindings_in_pat(&l.pat);
500 intravisit::walk_local(self, l);
503 fn visit_expr(&mut self, expr: &'gcx hir::Expr) {
504 debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
505 expr, self.repeating_scope);
507 // No matter what, the type of each expression must outlive the
508 // scope of that expression. This also guarantees basic WF.
509 let expr_ty = self.resolve_node_type(expr.id);
510 // the region corresponding to this expression
511 let expr_region = self.tcx.node_scope_region(expr.id);
512 self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span),
513 expr_ty, expr_region);
515 let method_call = MethodCall::expr(expr.id);
516 let opt_method_callee = self.tables.borrow().method_map.get(&method_call).cloned();
517 let has_method_map = opt_method_callee.is_some();
519 // If we are calling a method (either explicitly or via an
520 // overloaded operator), check that all of the types provided as
521 // arguments for its type parameters are well-formed, and all the regions
522 // provided as arguments outlive the call.
523 if let Some(callee) = opt_method_callee {
524 let origin = match expr.node {
525 hir::ExprMethodCall(..) =>
526 infer::ParameterOrigin::MethodCall,
527 hir::ExprUnary(op, _) if op == hir::UnDeref =>
528 infer::ParameterOrigin::OverloadedDeref,
530 infer::ParameterOrigin::OverloadedOperator
533 self.substs_wf_in_scope(origin, &callee.substs, expr.span, expr_region);
534 self.type_must_outlive(infer::ExprTypeIsNotInScope(callee.ty, expr.span),
535 callee.ty, expr_region);
538 // Check any autoderefs or autorefs that appear.
539 let adjustment = self.tables.borrow().adjustments.get(&expr.id).map(|a| a.clone());
540 if let Some(adjustment) = adjustment {
541 debug!("adjustment={:?}", adjustment);
542 match adjustment.kind {
543 adjustment::Adjust::DerefRef { autoderefs, ref autoref, .. } => {
544 let expr_ty = self.resolve_node_type(expr.id);
545 self.constrain_autoderefs(expr, autoderefs, expr_ty);
546 if let Some(ref autoref) = *autoref {
547 self.link_autoref(expr, autoderefs, autoref);
549 // Require that the resulting region encompasses
552 // FIXME(#6268) remove to support nested method calls
553 self.type_of_node_must_outlive(infer::AutoBorrow(expr.span),
554 expr.id, expr_region);
558 adjustment::AutoObject(_, ref bounds, ..) => {
559 // Determine if we are casting `expr` to a trait
560 // instance. If so, we have to be sure that the type
561 // of the source obeys the new region bound.
562 let source_ty = self.resolve_node_type(expr.id);
563 self.type_must_outlive(infer::RelateObjectBound(expr.span),
564 source_ty, bounds.region_bound);
570 // If necessary, constrain destructors in the unadjusted form of this
573 let mc = mc::MemCategorizationContext::new(self);
574 mc.cat_expr_unadjusted(expr)
578 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt,
582 self.tcx.sess.delay_span_bug(expr.span, "cat_expr_unadjusted Errd");
587 // If necessary, constrain destructors in this expression. This will be
588 // the adjusted form if there is an adjustment.
590 let mc = mc::MemCategorizationContext::new(self);
595 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, expr.span);
598 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
602 debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
603 expr, self.repeating_scope);
605 hir::ExprPath(_) => {
606 self.fcx.opt_node_ty_substs(expr.id, |item_substs| {
607 let origin = infer::ParameterOrigin::Path;
608 self.substs_wf_in_scope(origin, &item_substs.substs, expr.span, expr_region);
612 hir::ExprCall(ref callee, ref args) => {
614 self.constrain_call(expr, Some(&callee),
615 args.iter().map(|e| &*e), false);
617 self.constrain_callee(callee.id, expr, &callee);
618 self.constrain_call(expr, None,
619 args.iter().map(|e| &*e), false);
622 intravisit::walk_expr(self, expr);
625 hir::ExprMethodCall(.., ref args) => {
626 self.constrain_call(expr, Some(&args[0]),
627 args[1..].iter().map(|e| &*e), false);
629 intravisit::walk_expr(self, expr);
632 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
634 self.constrain_call(expr, Some(&lhs),
635 Some(&**rhs).into_iter(), false);
638 intravisit::walk_expr(self, expr);
641 hir::ExprIndex(ref lhs, ref rhs) if has_method_map => {
642 self.constrain_call(expr, Some(&lhs),
643 Some(&**rhs).into_iter(), true);
645 intravisit::walk_expr(self, expr);
648 hir::ExprBinary(op, ref lhs, ref rhs) if has_method_map => {
649 let implicitly_ref_args = !op.node.is_by_value();
651 // As `expr_method_call`, but the call is via an
652 // overloaded op. Note that we (sadly) currently use an
653 // implicit "by ref" sort of passing style here. This
654 // should be converted to an adjustment!
655 self.constrain_call(expr, Some(&lhs),
656 Some(&**rhs).into_iter(), implicitly_ref_args);
658 intravisit::walk_expr(self, expr);
661 hir::ExprBinary(_, ref lhs, ref rhs) => {
662 // If you do `x OP y`, then the types of `x` and `y` must
663 // outlive the operation you are performing.
664 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
665 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
666 for &ty in &[lhs_ty, rhs_ty] {
667 self.type_must_outlive(infer::Operand(expr.span),
670 intravisit::walk_expr(self, expr);
673 hir::ExprUnary(op, ref lhs) if has_method_map => {
674 let implicitly_ref_args = !op.is_by_value();
677 self.constrain_call(expr, Some(&lhs),
678 None::<hir::Expr>.iter(), implicitly_ref_args);
680 intravisit::walk_expr(self, expr);
683 hir::ExprUnary(hir::UnDeref, ref base) => {
684 // For *a, the lifetime of a must enclose the deref
685 let method_call = MethodCall::expr(expr.id);
686 let base_ty = match self.tables.borrow().method_map.get(&method_call) {
688 self.constrain_call(expr, Some(&base),
689 None::<hir::Expr>.iter(), true);
690 // late-bound regions in overloaded method calls are instantiated
691 let fn_ret = self.tcx.no_late_bound_regions(&method.ty.fn_ret());
694 None => self.resolve_node_type(base.id)
696 if let ty::TyRef(r_ptr, _) = base_ty.sty {
697 self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
700 intravisit::walk_expr(self, expr);
703 hir::ExprIndex(ref vec_expr, _) => {
704 // For a[b], the lifetime of a must enclose the deref
705 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
706 self.constrain_index(expr, vec_type);
708 intravisit::walk_expr(self, expr);
711 hir::ExprCast(ref source, _) => {
712 // Determine if we are casting `source` to a trait
713 // instance. If so, we have to be sure that the type of
714 // the source obeys the trait's region bound.
715 self.constrain_cast(expr, &source);
716 intravisit::walk_expr(self, expr);
719 hir::ExprAddrOf(m, ref base) => {
720 self.link_addr_of(expr, m, &base);
722 // Require that when you write a `&expr` expression, the
723 // resulting pointer has a lifetime that encompasses the
724 // `&expr` expression itself. Note that we constraining
725 // the type of the node expr.id here *before applying
728 // FIXME(#6268) nested method calls requires that this rule change
729 let ty0 = self.resolve_node_type(expr.id);
730 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
731 intravisit::walk_expr(self, expr);
734 hir::ExprMatch(ref discr, ref arms, _) => {
735 self.link_match(&discr, &arms[..]);
737 intravisit::walk_expr(self, expr);
740 hir::ExprClosure(.., body_id, _) => {
741 self.check_expr_fn_block(expr, body_id);
744 hir::ExprLoop(ref body, _, _) => {
745 let repeating_scope = self.set_repeating_scope(body.id);
746 intravisit::walk_expr(self, expr);
747 self.set_repeating_scope(repeating_scope);
750 hir::ExprWhile(ref cond, ref body, _) => {
751 let repeating_scope = self.set_repeating_scope(cond.id);
752 self.visit_expr(&cond);
754 self.set_repeating_scope(body.id);
755 self.visit_block(&body);
757 self.set_repeating_scope(repeating_scope);
760 hir::ExprRet(Some(ref ret_expr)) => {
761 let call_site_scope = self.call_site_scope;
762 debug!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}",
763 ret_expr.id, call_site_scope);
764 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
765 self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span),
768 intravisit::walk_expr(self, expr);
772 intravisit::walk_expr(self, expr);
778 impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
779 fn constrain_cast(&mut self,
780 cast_expr: &hir::Expr,
781 source_expr: &hir::Expr)
783 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
787 let source_ty = self.resolve_node_type(source_expr.id);
788 let target_ty = self.resolve_node_type(cast_expr.id);
790 self.walk_cast(cast_expr, source_ty, target_ty);
793 fn walk_cast(&mut self,
794 cast_expr: &hir::Expr,
797 debug!("walk_cast(from_ty={:?}, to_ty={:?})",
800 match (&from_ty.sty, &to_ty.sty) {
801 /*From:*/ (&ty::TyRef(from_r, ref from_mt),
802 /*To: */ &ty::TyRef(to_r, ref to_mt)) => {
803 // Target cannot outlive source, naturally.
804 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
805 self.walk_cast(cast_expr, from_mt.ty, to_mt.ty);
809 /*To: */ &ty::TyDynamic(.., r)) => {
810 // When T is existentially quantified as a trait
811 // `Foo+'to`, it must outlive the region bound `'to`.
812 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span), from_ty, r);
815 /*From:*/ (&ty::TyAdt(from_def, _),
816 /*To: */ &ty::TyAdt(to_def, _)) if from_def.is_box() && to_def.is_box() => {
817 self.walk_cast(cast_expr, from_ty.boxed_ty(), to_ty.boxed_ty());
824 fn check_expr_fn_block(&mut self,
825 expr: &'gcx hir::Expr,
826 body_id: hir::BodyId) {
827 let repeating_scope = self.set_repeating_scope(body_id.node_id);
828 intravisit::walk_expr(self, expr);
829 self.set_repeating_scope(repeating_scope);
832 fn constrain_callee(&mut self,
833 callee_id: ast::NodeId,
834 _call_expr: &hir::Expr,
835 _callee_expr: &hir::Expr) {
836 let callee_ty = self.resolve_node_type(callee_id);
837 match callee_ty.sty {
838 ty::TyFnDef(..) | ty::TyFnPtr(_) => { }
840 // this should not happen, but it does if the program is
845 // "Calling non-function: {}",
851 fn constrain_call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
852 call_expr: &hir::Expr,
853 receiver: Option<&hir::Expr>,
855 implicitly_ref_args: bool) {
856 //! Invoked on every call site (i.e., normal calls, method calls,
857 //! and overloaded operators). Constrains the regions which appear
858 //! in the type of the function. Also constrains the regions that
859 //! appear in the arguments appropriately.
861 debug!("constrain_call(call_expr={:?}, \
863 implicitly_ref_args={})",
866 implicitly_ref_args);
868 // `callee_region` is the scope representing the time in which the
871 // FIXME(#6268) to support nested method calls, should be callee_id
872 let callee_scope = self.tcx.node_extent(call_expr.id);
873 let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
875 debug!("callee_region={:?}", callee_region);
877 for arg_expr in arg_exprs {
878 debug!("Argument: {:?}", arg_expr);
880 // ensure that any regions appearing in the argument type are
881 // valid for at least the lifetime of the function:
882 self.type_of_node_must_outlive(infer::CallArg(arg_expr.span),
883 arg_expr.id, callee_region);
885 // unfortunately, there are two means of taking implicit
886 // references, and we need to propagate constraints as a
887 // result. modes are going away and the "DerefArgs" code
888 // should be ported to use adjustments
889 if implicitly_ref_args {
890 self.link_by_ref(arg_expr, callee_scope);
894 // as loop above, but for receiver
895 if let Some(r) = receiver {
896 debug!("receiver: {:?}", r);
897 self.type_of_node_must_outlive(infer::CallRcvr(r.span),
898 r.id, callee_region);
899 if implicitly_ref_args {
900 self.link_by_ref(&r, callee_scope);
905 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
906 /// dereferenced, the lifetime of the pointer includes the deref expr.
907 fn constrain_autoderefs(&mut self,
908 deref_expr: &hir::Expr,
910 mut derefd_ty: Ty<'tcx>)
912 debug!("constrain_autoderefs(deref_expr={:?}, derefs={}, derefd_ty={:?})",
917 let r_deref_expr = self.tcx.node_scope_region(deref_expr.id);
919 let method_call = MethodCall::autoderef(deref_expr.id, i as u32);
920 debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call, derefs);
922 let method = self.tables.borrow().method_map.get(&method_call).map(|m| m.clone());
924 derefd_ty = match method {
926 debug!("constrain_autoderefs: #{} is overloaded, method={:?}",
929 let origin = infer::ParameterOrigin::OverloadedDeref;
930 self.substs_wf_in_scope(origin, method.substs, deref_expr.span, r_deref_expr);
932 // Treat overloaded autoderefs as if an AutoBorrow adjustment
933 // was applied on the base type, as that is always the case.
934 let fn_sig = method.ty.fn_sig();
935 let fn_sig = // late-bound regions should have been instantiated
936 self.tcx.no_late_bound_regions(&fn_sig).unwrap();
937 let self_ty = fn_sig.inputs()[0];
938 let (m, r) = match self_ty.sty {
939 ty::TyRef(r, ref m) => (m.mutbl, r),
943 "bad overloaded deref type {:?}",
948 debug!("constrain_autoderefs: receiver r={:?} m={:?}",
952 let mc = mc::MemCategorizationContext::new(self);
953 let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i));
954 debug!("constrain_autoderefs: self_cmt={:?}",
956 self.link_region(deref_expr.span, r,
957 ty::BorrowKind::from_mutbl(m), self_cmt);
960 // Specialized version of constrain_call.
961 self.type_must_outlive(infer::CallRcvr(deref_expr.span),
962 self_ty, r_deref_expr);
963 self.type_must_outlive(infer::CallReturn(deref_expr.span),
964 fn_sig.output(), r_deref_expr);
970 if let ty::TyRef(r_ptr, _) = derefd_ty.sty {
971 self.mk_subregion_due_to_dereference(deref_expr.span,
972 r_deref_expr, r_ptr);
975 match derefd_ty.builtin_deref(true, ty::NoPreference) {
976 Some(mt) => derefd_ty = mt.ty,
977 /* if this type can't be dereferenced, then there's already an error
978 in the session saying so. Just bail out for now */
984 pub fn mk_subregion_due_to_dereference(&mut self,
986 minimum_lifetime: ty::Region<'tcx>,
987 maximum_lifetime: ty::Region<'tcx>) {
988 self.sub_regions(infer::DerefPointer(deref_span),
989 minimum_lifetime, maximum_lifetime)
992 fn check_safety_of_rvalue_destructor_if_necessary(&mut self,
996 Categorization::Rvalue(region, _) => {
998 ty::ReScope(rvalue_scope) => {
999 let typ = self.resolve_type(cmt.ty);
1000 let _ = dropck::check_safety_of_destructor_if_necessary(
1001 self, typ, span, rvalue_scope);
1006 "unexpected rvalue region in rvalue \
1007 destructor safety checking: `{:?}`",
1016 /// Invoked on any index expression that occurs. Checks that if this is a slice
1017 /// being indexed, the lifetime of the pointer includes the deref expr.
1018 fn constrain_index(&mut self,
1019 index_expr: &hir::Expr,
1020 indexed_ty: Ty<'tcx>)
1022 debug!("constrain_index(index_expr=?, indexed_ty={}",
1023 self.ty_to_string(indexed_ty));
1025 let r_index_expr = ty::ReScope(self.tcx.node_extent(index_expr.id));
1026 if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
1028 ty::TySlice(_) | ty::TyStr => {
1029 self.sub_regions(infer::IndexSlice(index_expr.span),
1030 self.tcx.mk_region(r_index_expr), r_ptr);
1037 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1038 /// adjustments) are valid for at least `minimum_lifetime`
1039 fn type_of_node_must_outlive(&mut self,
1040 origin: infer::SubregionOrigin<'tcx>,
1042 minimum_lifetime: ty::Region<'tcx>)
1044 // Try to resolve the type. If we encounter an error, then typeck
1045 // is going to fail anyway, so just stop here and let typeck
1046 // report errors later on in the writeback phase.
1047 let ty0 = self.resolve_node_type(id);
1048 let ty = self.tables.borrow().adjustments.get(&id).map_or(ty0, |adj| adj.target);
1049 let ty = self.resolve_type(ty);
1050 debug!("constrain_regions_in_type_of_node(\
1051 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
1053 id, minimum_lifetime);
1054 self.type_must_outlive(origin, ty, minimum_lifetime);
1057 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1058 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1059 fn link_addr_of(&mut self, expr: &hir::Expr,
1060 mutability: hir::Mutability, base: &hir::Expr) {
1061 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
1064 let mc = mc::MemCategorizationContext::new(self);
1065 ignore_err!(mc.cat_expr(base))
1068 debug!("link_addr_of: cmt={:?}", cmt);
1070 self.link_region_from_node_type(expr.span, expr.id, mutability, cmt);
1073 /// Computes the guarantors for any ref bindings in a `let` and
1074 /// then ensures that the lifetime of the resulting pointer is
1075 /// linked to the lifetime of the initialization expression.
1076 fn link_local(&self, local: &hir::Local) {
1077 debug!("regionck::for_local()");
1078 let init_expr = match local.init {
1080 Some(ref expr) => &**expr,
1082 let mc = mc::MemCategorizationContext::new(self);
1083 let discr_cmt = ignore_err!(mc.cat_expr(init_expr));
1084 self.link_pattern(mc, discr_cmt, &local.pat);
1087 /// Computes the guarantors for any ref bindings in a match and
1088 /// then ensures that the lifetime of the resulting pointer is
1089 /// linked to the lifetime of its guarantor (if any).
1090 fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) {
1091 debug!("regionck::for_match()");
1092 let mc = mc::MemCategorizationContext::new(self);
1093 let discr_cmt = ignore_err!(mc.cat_expr(discr));
1094 debug!("discr_cmt={:?}", discr_cmt);
1096 for root_pat in &arm.pats {
1097 self.link_pattern(mc, discr_cmt.clone(), &root_pat);
1102 /// Computes the guarantors for any ref bindings in a match and
1103 /// then ensures that the lifetime of the resulting pointer is
1104 /// linked to the lifetime of its guarantor (if any).
1105 fn link_fn_args(&self, body_scope: CodeExtent<'tcx>, args: &[hir::Arg]) {
1106 debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1107 let mc = mc::MemCategorizationContext::new(self);
1109 let arg_ty = self.node_ty(arg.id);
1110 let re_scope = self.tcx.mk_region(ty::ReScope(body_scope));
1111 let arg_cmt = mc.cat_rvalue(
1112 arg.id, arg.pat.span, re_scope, re_scope, arg_ty);
1113 debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1117 self.link_pattern(mc, arg_cmt, &arg.pat);
1121 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1122 /// in the discriminant, if needed.
1123 fn link_pattern<'t>(&self,
1124 mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
1125 discr_cmt: mc::cmt<'tcx>,
1126 root_pat: &hir::Pat) {
1127 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1130 let _ = mc.cat_pattern(discr_cmt, root_pat, |_, sub_cmt, sub_pat| {
1131 match sub_pat.node {
1133 PatKind::Binding(hir::BindByRef(mutbl), ..) => {
1134 self.link_region_from_node_type(sub_pat.span, sub_pat.id,
1142 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1144 fn link_autoref(&self,
1147 autoref: &adjustment::AutoBorrow<'tcx>)
1149 debug!("link_autoref(autoderefs={}, autoref={:?})", autoderefs, autoref);
1150 let mc = mc::MemCategorizationContext::new(self);
1151 let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs));
1152 debug!("expr_cmt={:?}", expr_cmt);
1155 adjustment::AutoBorrow::Ref(r, m) => {
1156 self.link_region(expr.span, r,
1157 ty::BorrowKind::from_mutbl(m), expr_cmt);
1160 adjustment::AutoBorrow::RawPtr(m) => {
1161 let r = self.tcx.node_scope_region(expr.id);
1162 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
1167 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1168 /// must outlive `callee_scope`.
1169 fn link_by_ref(&self,
1171 callee_scope: CodeExtent<'tcx>) {
1172 debug!("link_by_ref(expr={:?}, callee_scope={:?})",
1173 expr, callee_scope);
1174 let mc = mc::MemCategorizationContext::new(self);
1175 let expr_cmt = ignore_err!(mc.cat_expr(expr));
1176 let borrow_region = self.tcx.mk_region(ty::ReScope(callee_scope));
1177 self.link_region(expr.span, borrow_region, ty::ImmBorrow, expr_cmt);
1180 /// Like `link_region()`, except that the region is extracted from the type of `id`,
1181 /// which must be some reference (`&T`, `&str`, etc).
1182 fn link_region_from_node_type(&self,
1185 mutbl: hir::Mutability,
1186 cmt_borrowed: mc::cmt<'tcx>) {
1187 debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1188 id, mutbl, cmt_borrowed);
1190 let rptr_ty = self.resolve_node_type(id);
1191 if let ty::TyRef(r, _) = rptr_ty.sty {
1192 debug!("rptr_ty={}", rptr_ty);
1193 self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl),
1198 /// Informs the inference engine that `borrow_cmt` is being borrowed with
1199 /// kind `borrow_kind` and lifetime `borrow_region`.
1200 /// In order to ensure borrowck is satisfied, this may create constraints
1201 /// between regions, as explained in `link_reborrowed_region()`.
1202 fn link_region(&self,
1204 borrow_region: ty::Region<'tcx>,
1205 borrow_kind: ty::BorrowKind,
1206 borrow_cmt: mc::cmt<'tcx>) {
1207 let mut borrow_cmt = borrow_cmt;
1208 let mut borrow_kind = borrow_kind;
1210 let origin = infer::DataBorrowed(borrow_cmt.ty, span);
1211 self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
1214 debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1218 match borrow_cmt.cat.clone() {
1219 Categorization::Deref(ref_cmt, _,
1220 mc::Implicit(ref_kind, ref_region)) |
1221 Categorization::Deref(ref_cmt, _,
1222 mc::BorrowedPtr(ref_kind, ref_region)) => {
1223 match self.link_reborrowed_region(span,
1224 borrow_region, borrow_kind,
1225 ref_cmt, ref_region, ref_kind,
1237 Categorization::Downcast(cmt_base, _) |
1238 Categorization::Deref(cmt_base, _, mc::Unique) |
1239 Categorization::Interior(cmt_base, _) => {
1240 // Borrowing interior or owned data requires the base
1241 // to be valid and borrowable in the same fashion.
1242 borrow_cmt = cmt_base;
1243 borrow_kind = borrow_kind;
1246 Categorization::Deref(.., mc::UnsafePtr(..)) |
1247 Categorization::StaticItem |
1248 Categorization::Upvar(..) |
1249 Categorization::Local(..) |
1250 Categorization::Rvalue(..) => {
1251 // These are all "base cases" with independent lifetimes
1252 // that are not subject to inference
1259 /// This is the most complicated case: the path being borrowed is
1260 /// itself the referent of a borrowed pointer. Let me give an
1261 /// example fragment of code to make clear(er) the situation:
1263 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1265 /// &'z *r // the reborrow has lifetime 'z
1267 /// Now, in this case, our primary job is to add the inference
1268 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1269 /// parameters in (roughly) terms of the example:
1271 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1272 /// borrow_region ^~ ref_region ^~
1273 /// borrow_kind ^~ ref_kind ^~
1276 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1278 /// Unfortunately, there are some complications beyond the simple
1279 /// scenario I just painted:
1281 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1282 /// case, we have two jobs. First, we are inferring whether this reference
1283 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1284 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1285 /// then `r` must be an `&mut` reference). Second, whenever we link
1286 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1287 /// case we adjust the cause to indicate that the reference being
1288 /// "reborrowed" is itself an upvar. This provides a nicer error message
1289 /// should something go wrong.
1291 /// 2. There may in fact be more levels of reborrowing. In the
1292 /// example, I said the borrow was like `&'z *r`, but it might
1293 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1294 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1295 /// and `'z <= 'b`. This is explained more below.
1297 /// The return value of this function indicates whether we need to
1298 /// recurse and process `ref_cmt` (see case 2 above).
1299 fn link_reborrowed_region(&self,
1301 borrow_region: ty::Region<'tcx>,
1302 borrow_kind: ty::BorrowKind,
1303 ref_cmt: mc::cmt<'tcx>,
1304 ref_region: ty::Region<'tcx>,
1305 mut ref_kind: ty::BorrowKind,
1307 -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1309 // Possible upvar ID we may need later to create an entry in the
1312 // Detect by-ref upvar `x`:
1313 let cause = match note {
1314 mc::NoteUpvarRef(ref upvar_id) => {
1315 let upvar_capture_map = &self.tables.borrow_mut().upvar_capture_map;
1316 match upvar_capture_map.get(upvar_id) {
1317 Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1318 // The mutability of the upvar may have been modified
1319 // by the above adjustment, so update our local variable.
1320 ref_kind = upvar_borrow.kind;
1322 infer::ReborrowUpvar(span, *upvar_id)
1325 span_bug!( span, "Illegal upvar id: {:?}", upvar_id);
1329 mc::NoteClosureEnv(ref upvar_id) => {
1330 // We don't have any mutability changes to propagate, but
1331 // we do want to note that an upvar reborrow caused this
1333 infer::ReborrowUpvar(span, *upvar_id)
1336 infer::Reborrow(span)
1340 debug!("link_reborrowed_region: {:?} <= {:?}",
1343 self.sub_regions(cause, borrow_region, ref_region);
1345 // If we end up needing to recurse and establish a region link
1346 // with `ref_cmt`, calculate what borrow kind we will end up
1347 // needing. This will be used below.
1349 // One interesting twist is that we can weaken the borrow kind
1350 // when we recurse: to reborrow an `&mut` referent as mutable,
1351 // borrowck requires a unique path to the `&mut` reference but not
1352 // necessarily a *mutable* path.
1353 let new_borrow_kind = match borrow_kind {
1356 ty::MutBorrow | ty::UniqueImmBorrow =>
1360 // Decide whether we need to recurse and link any regions within
1361 // the `ref_cmt`. This is concerned for the case where the value
1362 // being reborrowed is in fact a borrowed pointer found within
1363 // another borrowed pointer. For example:
1365 // let p: &'b &'a mut T = ...;
1369 // What makes this case particularly tricky is that, if the data
1370 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1371 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1372 // (otherwise the user might mutate through the `&mut T` reference
1373 // after `'b` expires and invalidate the borrow we are looking at
1376 // So let's re-examine our parameters in light of this more
1377 // complicated (possible) scenario:
1379 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1380 // borrow_region ^~ ref_region ^~
1381 // borrow_kind ^~ ref_kind ^~
1384 // (Note that since we have not examined `ref_cmt.cat`, we don't
1385 // know whether this scenario has occurred; but I wanted to show
1386 // how all the types get adjusted.)
1389 // The reference being reborrowed is a sharable ref of
1390 // type `&'a T`. In this case, it doesn't matter where we
1391 // *found* the `&T` pointer, the memory it references will
1392 // be valid and immutable for `'a`. So we can stop here.
1394 // (Note that the `borrow_kind` must also be ImmBorrow or
1395 // else the user is borrowed imm memory as mut memory,
1396 // which means they'll get an error downstream in borrowck
1401 ty::MutBorrow | ty::UniqueImmBorrow => {
1402 // The reference being reborrowed is either an `&mut T` or
1403 // `&uniq T`. This is the case where recursion is needed.
1404 return Some((ref_cmt, new_borrow_kind));
1409 /// Checks that the values provided for type/region arguments in a given
1410 /// expression are well-formed and in-scope.
1411 fn substs_wf_in_scope(&mut self,
1412 origin: infer::ParameterOrigin,
1413 substs: &Substs<'tcx>,
1415 expr_region: ty::Region<'tcx>) {
1416 debug!("substs_wf_in_scope(substs={:?}, \
1420 substs, expr_region, origin, expr_span);
1422 let origin = infer::ParameterInScope(origin, expr_span);
1424 for region in substs.regions() {
1425 self.sub_regions(origin.clone(), expr_region, region);
1428 for ty in substs.types() {
1429 let ty = self.resolve_type(ty);
1430 self.type_must_outlive(origin.clone(), ty, expr_region);
1434 /// Ensures that type is well-formed in `region`, which implies (among
1435 /// other things) that all borrowed data reachable via `ty` outlives
1437 pub fn type_must_outlive(&self,
1438 origin: infer::SubregionOrigin<'tcx>,
1440 region: ty::Region<'tcx>)
1442 let ty = self.resolve_type(ty);
1444 debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1449 assert!(!ty.has_escaping_regions());
1451 let components = self.tcx.outlives_components(ty);
1452 self.components_must_outlive(origin, components, region);
1455 fn components_must_outlive(&self,
1456 origin: infer::SubregionOrigin<'tcx>,
1457 components: Vec<ty::outlives::Component<'tcx>>,
1458 region: ty::Region<'tcx>)
1460 for component in components {
1461 let origin = origin.clone();
1463 ty::outlives::Component::Region(region1) => {
1464 self.sub_regions(origin, region, region1);
1466 ty::outlives::Component::Param(param_ty) => {
1467 self.param_ty_must_outlive(origin, region, param_ty);
1469 ty::outlives::Component::Projection(projection_ty) => {
1470 self.projection_must_outlive(origin, region, projection_ty);
1472 ty::outlives::Component::EscapingProjection(subcomponents) => {
1473 self.components_must_outlive(origin, subcomponents, region);
1475 ty::outlives::Component::UnresolvedInferenceVariable(v) => {
1476 // ignore this, we presume it will yield an error
1477 // later, since if a type variable is not resolved by
1478 // this point it never will be
1479 self.tcx.sess.delay_span_bug(
1481 &format!("unresolved inference variable in outlives: {:?}", v));
1487 fn param_ty_must_outlive(&self,
1488 origin: infer::SubregionOrigin<'tcx>,
1489 region: ty::Region<'tcx>,
1490 param_ty: ty::ParamTy) {
1491 debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1492 region, param_ty, origin);
1494 let verify_bound = self.param_bound(param_ty);
1495 let generic = GenericKind::Param(param_ty);
1496 self.verify_generic_bound(origin, generic, region, verify_bound);
1499 fn projection_must_outlive(&self,
1500 origin: infer::SubregionOrigin<'tcx>,
1501 region: ty::Region<'tcx>,
1502 projection_ty: ty::ProjectionTy<'tcx>)
1504 debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1505 region, projection_ty, origin);
1507 // This case is thorny for inference. The fundamental problem is
1508 // that there are many cases where we have choice, and inference
1509 // doesn't like choice (the current region inference in
1510 // particular). :) First off, we have to choose between using the
1511 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1512 // OutlivesProjectionComponent rules, any one of which is
1513 // sufficient. If there are no inference variables involved, it's
1514 // not hard to pick the right rule, but if there are, we're in a
1515 // bit of a catch 22: if we picked which rule we were going to
1516 // use, we could add constraints to the region inference graph
1517 // that make it apply, but if we don't add those constraints, the
1518 // rule might not apply (but another rule might). For now, we err
1519 // on the side of adding too few edges into the graph.
1521 // Compute the bounds we can derive from the environment or trait
1522 // definition. We know that the projection outlives all the
1523 // regions in this list.
1524 let env_bounds = self.projection_declared_bounds(origin.span(), projection_ty);
1526 debug!("projection_must_outlive: env_bounds={:?}",
1529 // If we know that the projection outlives 'static, then we're
1531 if env_bounds.contains(&&ty::ReStatic) {
1532 debug!("projection_must_outlive: 'static as declared bound");
1536 // If declared bounds list is empty, the only applicable rule is
1537 // OutlivesProjectionComponent. If there are inference variables,
1538 // then, we can break down the outlives into more primitive
1539 // components without adding unnecessary edges.
1541 // If there are *no* inference variables, however, we COULD do
1542 // this, but we choose not to, because the error messages are less
1543 // good. For example, a requirement like `T::Item: 'r` would be
1544 // translated to a requirement that `T: 'r`; when this is reported
1545 // to the user, it will thus say "T: 'r must hold so that T::Item:
1546 // 'r holds". But that makes it sound like the only way to fix
1547 // the problem is to add `T: 'r`, which isn't true. So, if there are no
1548 // inference variables, we use a verify constraint instead of adding
1549 // edges, which winds up enforcing the same condition.
1550 let needs_infer = projection_ty.trait_ref.needs_infer();
1551 if env_bounds.is_empty() && needs_infer {
1552 debug!("projection_must_outlive: no declared bounds");
1554 for component_ty in projection_ty.trait_ref.substs.types() {
1555 self.type_must_outlive(origin.clone(), component_ty, region);
1558 for r in projection_ty.trait_ref.substs.regions() {
1559 self.sub_regions(origin.clone(), region, r);
1565 // If we find that there is a unique declared bound `'b`, and this bound
1566 // appears in the trait reference, then the best action is to require that `'b:'r`,
1567 // so do that. This is best no matter what rule we use:
1569 // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1570 // the requirement that `'b:'r`
1571 // - OutlivesProjectionComponent: this would require `'b:'r` in addition to
1573 if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1574 let unique_bound = env_bounds[0];
1575 debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
1576 if projection_ty.trait_ref.substs.regions().any(|r| env_bounds.contains(&r)) {
1577 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1578 self.sub_regions(origin.clone(), region, unique_bound);
1583 // Fallback to verifying after the fact that there exists a
1584 // declared bound, or that all the components appearing in the
1585 // projection outlive; in some cases, this may add insufficient
1586 // edges into the inference graph, leading to inference failures
1587 // even though a satisfactory solution exists.
1588 let verify_bound = self.projection_bound(origin.span(), env_bounds, projection_ty);
1589 let generic = GenericKind::Projection(projection_ty);
1590 self.verify_generic_bound(origin, generic.clone(), region, verify_bound);
1593 fn type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1598 ty::TyProjection(data) => {
1599 let declared_bounds = self.projection_declared_bounds(span, data);
1600 self.projection_bound(span, declared_bounds, data)
1603 self.recursive_type_bound(span, ty)
1608 fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound<'tcx> {
1609 let param_env = &self.parameter_environment;
1611 debug!("param_bound(param_ty={:?})",
1614 let mut param_bounds = self.declared_generic_bounds_from_env(GenericKind::Param(param_ty));
1616 // Add in the default bound of fn body that applies to all in
1617 // scope type parameters:
1618 param_bounds.extend(param_env.implicit_region_bound);
1620 VerifyBound::AnyRegion(param_bounds)
1623 fn projection_declared_bounds(&self,
1625 projection_ty: ty::ProjectionTy<'tcx>)
1626 -> Vec<ty::Region<'tcx>>
1628 // First assemble bounds from where clauses and traits.
1630 let mut declared_bounds =
1631 self.declared_generic_bounds_from_env(GenericKind::Projection(projection_ty));
1633 declared_bounds.extend_from_slice(
1634 &self.declared_projection_bounds_from_trait(span, projection_ty));
1639 fn projection_bound(&self,
1641 declared_bounds: Vec<ty::Region<'tcx>>,
1642 projection_ty: ty::ProjectionTy<'tcx>)
1643 -> VerifyBound<'tcx> {
1644 debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1645 declared_bounds, projection_ty);
1647 // see the extensive comment in projection_must_outlive
1649 let ty = self.tcx.mk_projection(projection_ty.trait_ref, projection_ty.item_name);
1650 let recursive_bound = self.recursive_type_bound(span, ty);
1652 VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1655 fn recursive_type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
1656 let mut bounds = vec![];
1658 for subty in ty.walk_shallow() {
1659 bounds.push(self.type_bound(span, subty));
1662 let mut regions = ty.regions();
1663 regions.retain(|r| !r.is_bound()); // ignore late-bound regions
1664 bounds.push(VerifyBound::AllRegions(regions));
1666 // remove bounds that must hold, since they are not interesting
1667 bounds.retain(|b| !b.must_hold());
1669 if bounds.len() == 1 {
1670 bounds.pop().unwrap()
1672 VerifyBound::AllBounds(bounds)
1676 fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>)
1677 -> Vec<ty::Region<'tcx>>
1679 let param_env = &self.parameter_environment;
1681 // To start, collect bounds from user:
1682 let mut param_bounds = self.tcx.required_region_bounds(generic.to_ty(self.tcx),
1683 param_env.caller_bounds.clone());
1685 // Next, collect regions we scraped from the well-formedness
1686 // constraints in the fn signature. To do that, we walk the list
1687 // of known relations from the fn ctxt.
1689 // This is crucial because otherwise code like this fails:
1691 // fn foo<'a, A>(x: &'a A) { x.bar() }
1693 // The problem is that the type of `x` is `&'a A`. To be
1694 // well-formed, then, A must be lower-generic by `'a`, but we
1695 // don't know that this holds from first principles.
1696 for &(r, p) in &self.region_bound_pairs {
1697 debug!("generic={:?} p={:?}",
1701 param_bounds.push(r);
1708 fn declared_projection_bounds_from_trait(&self,
1710 projection_ty: ty::ProjectionTy<'tcx>)
1711 -> Vec<ty::Region<'tcx>>
1713 debug!("projection_bounds(projection_ty={:?})",
1716 let ty = self.tcx.mk_projection(projection_ty.trait_ref.clone(),
1717 projection_ty.item_name);
1719 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1720 // in looking for a trait definition like:
1723 // trait SomeTrait<'a> {
1724 // type SomeType : 'a;
1728 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1729 let trait_predicates = self.tcx.predicates_of(projection_ty.trait_ref.def_id);
1730 assert_eq!(trait_predicates.parent, None);
1731 let predicates = trait_predicates.predicates.as_slice().to_vec();
1732 traits::elaborate_predicates(self.tcx, predicates)
1733 .filter_map(|predicate| {
1734 // we're only interesting in `T : 'a` style predicates:
1735 let outlives = match predicate {
1736 ty::Predicate::TypeOutlives(data) => data,
1737 _ => { return None; }
1740 debug!("projection_bounds: outlives={:?} (1)",
1743 // apply the substitutions (and normalize any projected types)
1744 let outlives = self.instantiate_type_scheme(span,
1745 projection_ty.trait_ref.substs,
1748 debug!("projection_bounds: outlives={:?} (2)",
1751 let region_result = self.commit_if_ok(|_| {
1753 self.replace_late_bound_regions_with_fresh_var(
1755 infer::AssocTypeProjection(projection_ty.item_name),
1758 debug!("projection_bounds: outlives={:?} (3)",
1761 // check whether this predicate applies to our current projection
1762 let cause = self.fcx.misc(span);
1763 match self.eq_types(false, &cause, ty, outlives.0) {
1765 self.register_infer_ok_obligations(ok);
1768 Err(_) => { Err(()) }
1772 debug!("projection_bounds: region_result={:?}",