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: int }
63 //! struct Bar { foo: Foo }
64 //! fn get_i(x: &'a Bar) -> &'a int {
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 owned pointers. We say that the guarantor
80 //! of such data it 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 check::regionmanip;
90 use middle::mem_categorization as mc;
91 use middle::region::CodeExtent;
93 use middle::ty::{ReScope};
94 use middle::ty::{self, Ty, MethodCall};
97 use util::ppaux::{ty_to_string, Repr};
99 use syntax::{ast, ast_util};
100 use syntax::codemap::Span;
102 use syntax::visit::Visitor;
104 use self::RepeatingScope::Repeating;
105 use self::SubjectNode::Subject;
107 // a variation on try that just returns unit
108 macro_rules! ignore_err {
109 ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () })
112 ///////////////////////////////////////////////////////////////////////////
113 // PUBLIC ENTRY POINTS
115 pub fn regionck_expr(fcx: &FnCtxt, e: &ast::Expr) {
116 let mut rcx = Rcx::new(fcx, Repeating(e.id), Subject(e.id));
117 if fcx.err_count_since_creation() == 0 {
118 // regionck assumes typeck succeeded
120 rcx.visit_region_obligations(e.id);
122 rcx.resolve_regions_and_report_errors();
125 pub fn regionck_item(fcx: &FnCtxt, item: &ast::Item) {
126 let mut rcx = Rcx::new(fcx, Repeating(item.id), Subject(item.id));
127 rcx.visit_region_obligations(item.id);
128 rcx.resolve_regions_and_report_errors();
131 pub fn regionck_fn(fcx: &FnCtxt, id: ast::NodeId, decl: &ast::FnDecl, blk: &ast::Block) {
132 let mut rcx = Rcx::new(fcx, Repeating(blk.id), Subject(id));
133 if fcx.err_count_since_creation() == 0 {
134 // regionck assumes typeck succeeded
135 rcx.visit_fn_body(id, decl, blk);
138 // Region checking a fn can introduce new trait obligations,
139 // particularly around closure bounds.
140 vtable::select_all_fcx_obligations_or_error(fcx);
142 rcx.resolve_regions_and_report_errors();
145 /// Checks that the types in `component_tys` are well-formed. This will add constraints into the
146 /// region graph. Does *not* run `resolve_regions_and_report_errors` and so forth.
147 pub fn regionck_ensure_component_tys_wf<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
149 component_tys: &[Ty<'tcx>]) {
150 let mut rcx = Rcx::new(fcx, Repeating(0), SubjectNode::None);
151 for &component_ty in component_tys.iter() {
152 // Check that each type outlives the empty region. Since the
153 // empty region is a subregion of all others, this can't fail
154 // unless the type does not meet the well-formedness
156 type_must_outlive(&mut rcx, infer::RelateRegionParamBound(span),
157 component_ty, ty::ReEmpty);
161 ///////////////////////////////////////////////////////////////////////////
164 pub struct Rcx<'a, 'tcx: 'a> {
165 fcx: &'a FnCtxt<'a, 'tcx>,
167 region_param_pairs: Vec<(ty::Region, ty::ParamTy)>,
169 // id of innermost fn or loop
170 repeating_scope: ast::NodeId,
172 // id of AST node being analyzed (the subject of the analysis).
173 subject: SubjectNode,
176 /// Returns the validity region of `def` -- that is, how long is `def` valid?
177 fn region_of_def(fcx: &FnCtxt, def: def::Def) -> ty::Region {
180 def::DefLocal(node_id) => {
181 tcx.region_maps.var_region(node_id)
183 def::DefUpvar(node_id, _, body_id) => {
184 if body_id == ast::DUMMY_NODE_ID {
185 tcx.region_maps.var_region(node_id)
187 ReScope(CodeExtent::from_node_id(body_id))
191 tcx.sess.bug(format!("unexpected def in region_of_def: {}",
197 pub enum RepeatingScope { Repeating(ast::NodeId) }
198 pub enum SubjectNode { Subject(ast::NodeId), None }
200 impl<'a, 'tcx> Rcx<'a, 'tcx> {
201 pub fn new(fcx: &'a FnCtxt<'a, 'tcx>,
202 initial_repeating_scope: RepeatingScope,
203 subject: SubjectNode) -> Rcx<'a, 'tcx> {
204 let Repeating(initial_repeating_scope) = initial_repeating_scope;
206 repeating_scope: initial_repeating_scope,
208 region_param_pairs: Vec::new() }
211 pub fn tcx(&self) -> &'a ty::ctxt<'tcx> {
215 pub fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
216 let old_scope = self.repeating_scope;
217 self.repeating_scope = scope;
221 /// Try to resolve the type for the given node, returning t_err if an error results. Note that
222 /// we never care about the details of the error, the same error will be detected and reported
223 /// in the writeback phase.
225 /// Note one important point: we do not attempt to resolve *region variables* here. This is
226 /// because regionck is essentially adding constraints to those region variables and so may yet
227 /// influence how they are resolved.
229 /// Consider this silly example:
232 /// fn borrow(x: &int) -> &int {x}
233 /// fn foo(x: @int) -> int { // block: B
234 /// let b = borrow(x); // region: <R0>
239 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrainted to be some subregion of the
240 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
241 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
242 /// of b will be `&<R0>.int` and then `*b` will require that `<R0>` be bigger than the let and
243 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
244 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
245 self.fcx.infcx().resolve_type_vars_if_possible(&unresolved_ty)
248 /// Try to resolve the type for the given node.
249 fn resolve_node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
250 let t = self.fcx.node_ty(id);
254 fn resolve_method_type(&self, method_call: MethodCall) -> Option<Ty<'tcx>> {
255 let method_ty = self.fcx.inh.method_map.borrow()
256 .get(&method_call).map(|method| method.ty);
257 method_ty.map(|method_ty| self.resolve_type(method_ty))
260 /// Try to resolve the type for the given node.
261 pub fn resolve_expr_type_adjusted(&mut self, expr: &ast::Expr) -> Ty<'tcx> {
262 let ty_unadjusted = self.resolve_node_type(expr.id);
263 if ty::type_is_error(ty_unadjusted) {
266 let tcx = self.fcx.tcx();
267 ty::adjust_ty(tcx, expr.span, expr.id, ty_unadjusted,
268 self.fcx.inh.adjustments.borrow().get(&expr.id),
269 |method_call| self.resolve_method_type(method_call))
273 fn visit_fn_body(&mut self,
275 fn_decl: &ast::FnDecl,
278 // When we enter a function, we can derive
280 let fn_sig_map = self.fcx.inh.fn_sig_map.borrow();
281 let fn_sig = match fn_sig_map.get(&id) {
285 format!("No fn-sig entry for id={}", id)[]);
289 let len = self.region_param_pairs.len();
290 self.relate_free_regions(fn_sig[], body.id);
291 link_fn_args(self, CodeExtent::from_node_id(body.id), fn_decl.inputs[]);
292 self.visit_block(body);
293 self.visit_region_obligations(body.id);
294 self.region_param_pairs.truncate(len);
297 fn visit_region_obligations(&mut self, node_id: ast::NodeId)
299 debug!("visit_region_obligations: node_id={}", node_id);
300 let fulfillment_cx = self.fcx.inh.fulfillment_cx.borrow();
301 for r_o in fulfillment_cx.region_obligations(node_id).iter() {
302 debug!("visit_region_obligations: r_o={}",
303 r_o.repr(self.tcx()));
304 let sup_type = self.resolve_type(r_o.sup_type);
305 let origin = infer::RelateRegionParamBound(r_o.cause.span);
306 type_must_outlive(self, origin, sup_type, r_o.sub_region);
310 /// This method populates the region map's `free_region_map`. It walks over the transformed
311 /// argument and return types for each function just before we check the body of that function,
312 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
313 /// [uint]`. We do not allow references to outlive the things they point at, so we can assume
314 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
315 /// the caller side, the caller is responsible for checking that the type of every expression
316 /// (including the actual values for the arguments, as well as the return type of the fn call)
319 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
320 fn relate_free_regions(&mut self,
321 fn_sig_tys: &[Ty<'tcx>],
322 body_id: ast::NodeId) {
323 debug!("relate_free_regions >>");
324 let tcx = self.tcx();
326 for &ty in fn_sig_tys.iter() {
327 let ty = self.resolve_type(ty);
328 debug!("relate_free_regions(t={})", ty.repr(tcx));
329 let body_scope = CodeExtent::from_node_id(body_id);
330 let body_scope = ty::ReScope(body_scope);
332 regionmanip::region_wf_constraints(
336 for constraint in constraints.iter() {
337 debug!("constraint: {}", constraint.repr(tcx));
339 regionmanip::RegionSubRegionConstraint(_,
341 ty::ReFree(free_b)) => {
342 tcx.region_maps.relate_free_regions(free_a, free_b);
344 regionmanip::RegionSubRegionConstraint(_,
346 ty::ReInfer(ty::ReVar(vid_b))) => {
347 self.fcx.inh.infcx.add_given(free_a, vid_b);
349 regionmanip::RegionSubRegionConstraint(..) => {
350 // In principle, we could record (and take
351 // advantage of) every relationship here, but
352 // we are also free not to -- it simply means
353 // strictly less that we can successfully type
354 // check. (It may also be that we should
355 // revise our inference system to be more
356 // general and to make use of *every*
357 // relationship that arises here, but
358 // presently we do not.)
360 regionmanip::RegionSubParamConstraint(_, r_a, p_b) => {
361 debug!("RegionSubParamConstraint: {} <= {}",
362 r_a.repr(tcx), p_b.repr(tcx));
364 self.region_param_pairs.push((r_a, p_b));
370 debug!("<< relate_free_regions");
373 fn resolve_regions_and_report_errors(&self) {
374 let subject_node_id = match self.subject {
376 SubjectNode::None => {
377 self.tcx().sess.bug("cannot resolve_regions_and_report_errors \
378 without subject node");
382 self.fcx.infcx().resolve_regions_and_report_errors(subject_node_id);
386 impl<'a, 'tcx, 'v> Visitor<'v> for Rcx<'a, 'tcx> {
387 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
388 // However, right now we run into an issue whereby some free
389 // regions are not properly related if they appear within the
390 // types of arguments that must be inferred. This could be
391 // addressed by deferring the construction of the region
392 // hierarchy, and in particular the relationships between free
393 // regions, until regionck, as described in #3238.
395 fn visit_fn(&mut self, _fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
396 b: &'v ast::Block, _s: Span, id: ast::NodeId) {
397 self.visit_fn_body(id, fd, b)
400 fn visit_item(&mut self, i: &ast::Item) { visit_item(self, i); }
402 fn visit_expr(&mut self, ex: &ast::Expr) { visit_expr(self, ex); }
404 //visit_pat: visit_pat, // (..) see above
406 fn visit_arm(&mut self, a: &ast::Arm) { visit_arm(self, a); }
408 fn visit_local(&mut self, l: &ast::Local) { visit_local(self, l); }
410 fn visit_block(&mut self, b: &ast::Block) { visit_block(self, b); }
413 fn visit_item(_rcx: &mut Rcx, _item: &ast::Item) {
417 fn visit_block(rcx: &mut Rcx, b: &ast::Block) {
418 visit::walk_block(rcx, b);
421 fn visit_arm(rcx: &mut Rcx, arm: &ast::Arm) {
423 for p in arm.pats.iter() {
424 constrain_bindings_in_pat(&**p, rcx);
427 visit::walk_arm(rcx, arm);
430 fn visit_local(rcx: &mut Rcx, l: &ast::Local) {
432 constrain_bindings_in_pat(&*l.pat, rcx);
434 visit::walk_local(rcx, l);
437 fn constrain_bindings_in_pat(pat: &ast::Pat, rcx: &mut Rcx) {
438 let tcx = rcx.fcx.tcx();
439 debug!("regionck::visit_pat(pat={})", pat.repr(tcx));
440 pat_util::pat_bindings(&tcx.def_map, pat, |_, id, span, _| {
441 // If we have a variable that contains region'd data, that
442 // data will be accessible from anywhere that the variable is
443 // accessed. We must be wary of loops like this:
445 // // from src/test/compile-fail/borrowck-lend-flow.rs
446 // let mut v = box 3, w = box 4;
447 // let mut x = &mut w;
450 // borrow(v); //~ ERROR cannot borrow
451 // x = &mut v; // (1)
454 // Typically, we try to determine the region of a borrow from
455 // those points where it is dereferenced. In this case, one
456 // might imagine that the lifetime of `x` need only be the
457 // body of the loop. But of course this is incorrect because
458 // the pointer that is created at point (1) is consumed at
459 // point (2), meaning that it must be live across the loop
460 // iteration. The easiest way to guarantee this is to require
461 // that the lifetime of any regions that appear in a
462 // variable's type enclose at least the variable's scope.
464 let var_region = tcx.region_maps.var_region(id);
465 type_of_node_must_outlive(
466 rcx, infer::BindingTypeIsNotValidAtDecl(span),
471 fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) {
472 debug!("regionck::visit_expr(e={}, repeating_scope={})",
473 expr.repr(rcx.fcx.tcx()), rcx.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 = rcx.resolve_node_type(expr.id);
479 type_must_outlive(rcx, infer::ExprTypeIsNotInScope(expr_ty, expr.span),
480 expr_ty, ty::ReScope(CodeExtent::from_node_id(expr.id)));
482 let method_call = MethodCall::expr(expr.id);
483 let has_method_map = rcx.fcx.inh.method_map.borrow().contains_key(&method_call);
485 // Check any autoderefs or autorefs that appear.
486 for &adjustment in rcx.fcx.inh.adjustments.borrow().get(&expr.id).iter() {
487 debug!("adjustment={}", adjustment);
489 ty::AdjustDerefRef(ty::AutoDerefRef {autoderefs, autoref: ref opt_autoref}) => {
490 let expr_ty = rcx.resolve_node_type(expr.id);
491 constrain_autoderefs(rcx, expr, autoderefs, expr_ty);
492 for autoref in opt_autoref.iter() {
493 link_autoref(rcx, expr, autoderefs, autoref);
495 // Require that the resulting region encompasses
498 // FIXME(#6268) remove to support nested method calls
499 type_of_node_must_outlive(
500 rcx, infer::AutoBorrow(expr.span),
501 expr.id, ty::ReScope(CodeExtent::from_node_id(expr.id)));
505 ty::AutoObject(_, ref bounds, _, _) => {
506 // Determine if we are casting `expr` to a trait
507 // instance. If so, we have to be sure that the type
508 // of the source obeys the new region bound.
509 let source_ty = rcx.resolve_node_type(expr.id);
510 type_must_outlive(rcx, infer::RelateObjectBound(expr.span),
511 source_ty, bounds.region_bound);
519 ast::ExprCall(ref callee, ref args) => {
521 constrain_call(rcx, expr, Some(&**callee),
522 args.iter().map(|e| &**e), false);
524 constrain_callee(rcx, callee.id, expr, &**callee);
525 constrain_call(rcx, expr, None,
526 args.iter().map(|e| &**e), false);
529 visit::walk_expr(rcx, expr);
532 ast::ExprMethodCall(_, _, ref args) => {
533 constrain_call(rcx, expr, Some(&*args[0]),
534 args.slice_from(1).iter().map(|e| &**e), false);
536 visit::walk_expr(rcx, expr);
539 ast::ExprAssignOp(_, ref lhs, ref rhs) => {
541 constrain_call(rcx, expr, Some(&**lhs),
542 Some(&**rhs).into_iter(), true);
545 visit::walk_expr(rcx, expr);
548 ast::ExprIndex(ref lhs, ref rhs) if has_method_map => {
549 constrain_call(rcx, expr, Some(&**lhs),
550 Some(&**rhs).into_iter(), true);
552 visit::walk_expr(rcx, expr);
555 ast::ExprBinary(op, ref lhs, ref rhs) if has_method_map => {
556 let implicitly_ref_args = !ast_util::is_by_value_binop(op);
558 // As `expr_method_call`, but the call is via an
559 // overloaded op. Note that we (sadly) currently use an
560 // implicit "by ref" sort of passing style here. This
561 // should be converted to an adjustment!
562 constrain_call(rcx, expr, Some(&**lhs),
563 Some(&**rhs).into_iter(), implicitly_ref_args);
565 visit::walk_expr(rcx, expr);
568 ast::ExprUnary(op, ref lhs) if has_method_map => {
569 let implicitly_ref_args = !ast_util::is_by_value_unop(op);
572 constrain_call(rcx, expr, Some(&**lhs),
573 None::<ast::Expr>.iter(), implicitly_ref_args);
575 visit::walk_expr(rcx, expr);
578 ast::ExprUnary(ast::UnDeref, ref base) => {
579 // For *a, the lifetime of a must enclose the deref
580 let method_call = MethodCall::expr(expr.id);
581 let base_ty = match rcx.fcx.inh.method_map.borrow().get(&method_call) {
583 constrain_call(rcx, expr, Some(&**base),
584 None::<ast::Expr>.iter(), true);
585 ty::ty_fn_ret(method.ty).unwrap()
587 None => rcx.resolve_node_type(base.id)
589 if let ty::ty_rptr(r_ptr, _) = base_ty.sty {
590 mk_subregion_due_to_dereference(
591 rcx, expr.span, ty::ReScope(CodeExtent::from_node_id(expr.id)), *r_ptr);
594 visit::walk_expr(rcx, expr);
597 ast::ExprIndex(ref vec_expr, _) => {
598 // For a[b], the lifetime of a must enclose the deref
599 let vec_type = rcx.resolve_expr_type_adjusted(&**vec_expr);
600 constrain_index(rcx, expr, vec_type);
602 visit::walk_expr(rcx, expr);
605 ast::ExprCast(ref source, _) => {
606 // Determine if we are casting `source` to a trait
607 // instance. If so, we have to be sure that the type of
608 // the source obeys the trait's region bound.
609 constrain_cast(rcx, expr, &**source);
610 visit::walk_expr(rcx, expr);
613 ast::ExprAddrOf(m, ref base) => {
614 link_addr_of(rcx, expr, m, &**base);
616 // Require that when you write a `&expr` expression, the
617 // resulting pointer has a lifetime that encompasses the
618 // `&expr` expression itself. Note that we constraining
619 // the type of the node expr.id here *before applying
622 // FIXME(#6268) nested method calls requires that this rule change
623 let ty0 = rcx.resolve_node_type(expr.id);
624 type_must_outlive(rcx, infer::AddrOf(expr.span),
625 ty0, ty::ReScope(CodeExtent::from_node_id(expr.id)));
626 visit::walk_expr(rcx, expr);
629 ast::ExprMatch(ref discr, ref arms, _) => {
630 link_match(rcx, &**discr, arms[]);
632 visit::walk_expr(rcx, expr);
635 ast::ExprClosure(_, _, _, ref body) => {
636 check_expr_fn_block(rcx, expr, &**body);
639 ast::ExprLoop(ref body, _) => {
640 let repeating_scope = rcx.set_repeating_scope(body.id);
641 visit::walk_expr(rcx, expr);
642 rcx.set_repeating_scope(repeating_scope);
645 ast::ExprWhile(ref cond, ref body, _) => {
646 let repeating_scope = rcx.set_repeating_scope(cond.id);
647 rcx.visit_expr(&**cond);
649 rcx.set_repeating_scope(body.id);
650 rcx.visit_block(&**body);
652 rcx.set_repeating_scope(repeating_scope);
655 ast::ExprForLoop(ref pat, ref head, ref body, _) => {
656 constrain_bindings_in_pat(&**pat, rcx);
659 let mc = mc::MemCategorizationContext::new(rcx.fcx);
660 let pat_ty = rcx.resolve_node_type(pat.id);
661 let pat_cmt = mc.cat_rvalue(pat.id,
663 ty::ReScope(CodeExtent::from_node_id(body.id)),
665 link_pattern(rcx, mc, pat_cmt, &**pat);
668 rcx.visit_expr(&**head);
669 type_of_node_must_outlive(rcx,
670 infer::AddrOf(expr.span),
672 ty::ReScope(CodeExtent::from_node_id(expr.id)));
674 let repeating_scope = rcx.set_repeating_scope(body.id);
675 rcx.visit_block(&**body);
676 rcx.set_repeating_scope(repeating_scope);
680 visit::walk_expr(rcx, expr);
685 fn constrain_cast(rcx: &mut Rcx,
686 cast_expr: &ast::Expr,
687 source_expr: &ast::Expr)
689 debug!("constrain_cast(cast_expr={}, source_expr={})",
690 cast_expr.repr(rcx.tcx()),
691 source_expr.repr(rcx.tcx()));
693 let source_ty = rcx.resolve_node_type(source_expr.id);
694 let target_ty = rcx.resolve_node_type(cast_expr.id);
696 walk_cast(rcx, cast_expr, source_ty, target_ty);
698 fn walk_cast<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
699 cast_expr: &ast::Expr,
702 debug!("walk_cast(from_ty={}, to_ty={})",
703 from_ty.repr(rcx.tcx()),
704 to_ty.repr(rcx.tcx()));
705 match (&from_ty.sty, &to_ty.sty) {
706 /*From:*/ (&ty::ty_rptr(from_r, ref from_mt),
707 /*To: */ &ty::ty_rptr(to_r, ref to_mt)) => {
708 // Target cannot outlive source, naturally.
709 rcx.fcx.mk_subr(infer::Reborrow(cast_expr.span), *to_r, *from_r);
710 walk_cast(rcx, cast_expr, from_mt.ty, to_mt.ty);
714 /*To: */ &ty::ty_trait(box ty::TyTrait { ref bounds, .. })) => {
715 // When T is existentially quantified as a trait
716 // `Foo+'to`, it must outlive the region bound `'to`.
717 type_must_outlive(rcx, infer::RelateObjectBound(cast_expr.span),
718 from_ty, bounds.region_bound);
721 /*From:*/ (&ty::ty_uniq(from_referent_ty),
722 /*To: */ &ty::ty_uniq(to_referent_ty)) => {
723 walk_cast(rcx, cast_expr, from_referent_ty, to_referent_ty);
731 fn check_expr_fn_block(rcx: &mut Rcx,
734 let tcx = rcx.fcx.tcx();
735 let function_type = rcx.resolve_node_type(expr.id);
737 match function_type.sty {
738 ty::ty_unboxed_closure(_, region, _) => {
739 if tcx.capture_modes.borrow()[expr.id].clone() == ast::CaptureByRef {
740 ty::with_freevars(tcx, expr.id, |freevars| {
741 if !freevars.is_empty() {
742 // Variables being referenced must be constrained and registered
743 // in the upvar borrow map
744 constrain_free_variables_in_by_ref_closure(
745 rcx, *region, expr, freevars);
753 let repeating_scope = rcx.set_repeating_scope(body.id);
754 visit::walk_expr(rcx, expr);
755 rcx.set_repeating_scope(repeating_scope);
757 match function_type.sty {
758 ty::ty_unboxed_closure(_, region, _) => {
759 ty::with_freevars(tcx, expr.id, |freevars| {
760 let bounds = ty::region_existential_bound(*region);
761 ensure_free_variable_types_outlive_closure_bound(rcx, &bounds, expr, freevars);
767 /// Make sure that the type of all free variables referenced inside a closure/proc outlive the
768 /// closure/proc's lifetime bound. This is just a special case of the usual rules about closed
769 /// over values outliving the object's lifetime bound.
770 fn ensure_free_variable_types_outlive_closure_bound(
772 bounds: &ty::ExistentialBounds,
774 freevars: &[ty::Freevar])
776 let tcx = rcx.fcx.ccx.tcx;
778 debug!("ensure_free_variable_types_outlive_closure_bound({}, {})",
779 bounds.region_bound.repr(tcx), expr.repr(tcx));
781 for freevar in freevars.iter() {
783 let def_id = freevar.def.def_id();
784 assert!(def_id.krate == ast::LOCAL_CRATE);
788 // Compute the type of the field in the environment that
789 // represents `var_node_id`. For a by-value closure, this
790 // will be the same as the type of the variable. For a
791 // by-reference closure, this will be `&T` where `T` is
792 // the type of the variable.
793 let raw_var_ty = rcx.resolve_node_type(var_node_id);
794 let upvar_id = ty::UpvarId { var_id: var_node_id,
795 closure_expr_id: expr.id };
796 let var_ty = match rcx.fcx.inh.upvar_borrow_map.borrow().get(&upvar_id) {
797 Some(upvar_borrow) => {
798 ty::mk_rptr(rcx.tcx(),
799 rcx.tcx().mk_region(upvar_borrow.region),
800 ty::mt { mutbl: upvar_borrow.kind.to_mutbl_lossy(),
806 // Check that the type meets the criteria of the existential bounds:
807 for builtin_bound in bounds.builtin_bounds.iter() {
808 let code = traits::ClosureCapture(var_node_id, expr.span, builtin_bound);
809 let cause = traits::ObligationCause::new(freevar.span, rcx.fcx.body_id, code);
810 rcx.fcx.register_builtin_bound(var_ty, builtin_bound, cause);
814 rcx, infer::FreeVariable(expr.span, var_node_id),
815 var_ty, bounds.region_bound);
819 /// Make sure that all free variables referenced inside the closure outlive the closure's
820 /// lifetime bound. Also, create an entry in the upvar_borrows map with a region.
821 fn constrain_free_variables_in_by_ref_closure(
823 region_bound: ty::Region,
825 freevars: &[ty::Freevar])
827 let tcx = rcx.fcx.ccx.tcx;
828 debug!("constrain_free_variables({}, {})",
829 region_bound.repr(tcx), expr.repr(tcx));
830 for freevar in freevars.iter() {
831 debug!("freevar def is {}", freevar.def);
833 // Identify the variable being closed over and its node-id.
834 let def = freevar.def;
836 let def_id = def.def_id();
837 assert!(def_id.krate == ast::LOCAL_CRATE);
840 let upvar_id = ty::UpvarId { var_id: var_node_id,
841 closure_expr_id: expr.id };
843 let upvar_borrow = rcx.fcx.inh.upvar_borrow_map.borrow()[upvar_id];
845 rcx.fcx.mk_subr(infer::FreeVariable(freevar.span, var_node_id),
846 region_bound, upvar_borrow.region);
848 // Guarantee that the closure does not outlive the variable itself.
849 let enclosing_region = region_of_def(rcx.fcx, def);
850 debug!("enclosing_region = {}", enclosing_region.repr(tcx));
851 rcx.fcx.mk_subr(infer::FreeVariable(freevar.span, var_node_id),
852 region_bound, enclosing_region);
857 fn constrain_callee(rcx: &mut Rcx,
858 callee_id: ast::NodeId,
859 _call_expr: &ast::Expr,
860 _callee_expr: &ast::Expr) {
861 let callee_ty = rcx.resolve_node_type(callee_id);
862 match callee_ty.sty {
863 ty::ty_bare_fn(..) => { }
865 // this should not happen, but it does if the program is
868 // tcx.sess.span_bug(
870 // format!("Calling non-function: {}", callee_ty.repr(tcx)));
875 fn constrain_call<'a, I: Iterator<Item=&'a ast::Expr>>(rcx: &mut Rcx,
876 call_expr: &ast::Expr,
877 receiver: Option<&ast::Expr>,
879 implicitly_ref_args: bool) {
880 //! Invoked on every call site (i.e., normal calls, method calls,
881 //! and overloaded operators). Constrains the regions which appear
882 //! in the type of the function. Also constrains the regions that
883 //! appear in the arguments appropriately.
885 let tcx = rcx.fcx.tcx();
886 debug!("constrain_call(call_expr={}, \
888 implicitly_ref_args={})",
891 implicitly_ref_args);
893 // `callee_region` is the scope representing the time in which the
896 // FIXME(#6268) to support nested method calls, should be callee_id
897 let callee_scope = CodeExtent::from_node_id(call_expr.id);
898 let callee_region = ty::ReScope(callee_scope);
900 debug!("callee_region={}", callee_region.repr(tcx));
902 for arg_expr in arg_exprs {
903 debug!("Argument: {}", arg_expr.repr(tcx));
905 // ensure that any regions appearing in the argument type are
906 // valid for at least the lifetime of the function:
907 type_of_node_must_outlive(
908 rcx, infer::CallArg(arg_expr.span),
909 arg_expr.id, callee_region);
911 // unfortunately, there are two means of taking implicit
912 // references, and we need to propagate constraints as a
913 // result. modes are going away and the "DerefArgs" code
914 // should be ported to use adjustments
915 if implicitly_ref_args {
916 link_by_ref(rcx, arg_expr, callee_scope);
920 // as loop above, but for receiver
921 for r in receiver.iter() {
922 debug!("receiver: {}", r.repr(tcx));
923 type_of_node_must_outlive(
924 rcx, infer::CallRcvr(r.span),
925 r.id, callee_region);
926 if implicitly_ref_args {
927 link_by_ref(rcx, &**r, callee_scope);
932 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
933 /// dereferenced, the lifetime of the pointer includes the deref expr.
934 fn constrain_autoderefs<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
935 deref_expr: &ast::Expr,
937 mut derefd_ty: Ty<'tcx>) {
938 let r_deref_expr = ty::ReScope(CodeExtent::from_node_id(deref_expr.id));
939 for i in range(0u, derefs) {
940 debug!("constrain_autoderefs(deref_expr=?, derefd_ty={}, derefs={}/{}",
941 rcx.fcx.infcx().ty_to_string(derefd_ty),
944 let method_call = MethodCall::autoderef(deref_expr.id, i);
945 derefd_ty = match rcx.fcx.inh.method_map.borrow().get(&method_call) {
947 // Treat overloaded autoderefs as if an AutoRef adjustment
948 // was applied on the base type, as that is always the case.
949 let fn_sig = ty::ty_fn_sig(method.ty);
950 let self_ty = fn_sig.0.inputs[0];
951 let (m, r) = match self_ty.sty {
952 ty::ty_rptr(r, ref m) => (m.mutbl, r),
953 _ => rcx.tcx().sess.span_bug(deref_expr.span,
954 format!("bad overloaded deref type {}",
955 method.ty.repr(rcx.tcx()))[])
958 let mc = mc::MemCategorizationContext::new(rcx.fcx);
959 let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i));
960 link_region(rcx, deref_expr.span, *r,
961 ty::BorrowKind::from_mutbl(m), self_cmt);
964 // Specialized version of constrain_call.
965 type_must_outlive(rcx, infer::CallRcvr(deref_expr.span),
966 self_ty, r_deref_expr);
967 match fn_sig.0.output {
968 ty::FnConverging(return_type) => {
969 type_must_outlive(rcx, infer::CallReturn(deref_expr.span),
970 return_type, r_deref_expr);
973 ty::FnDiverging => unreachable!()
979 if let ty::ty_rptr(r_ptr, _) = derefd_ty.sty {
980 mk_subregion_due_to_dereference(rcx, deref_expr.span,
981 r_deref_expr, *r_ptr);
984 match ty::deref(derefd_ty, true) {
985 Some(mt) => derefd_ty = mt.ty,
986 /* if this type can't be dereferenced, then there's already an error
987 in the session saying so. Just bail out for now */
993 pub fn mk_subregion_due_to_dereference(rcx: &mut Rcx,
995 minimum_lifetime: ty::Region,
996 maximum_lifetime: ty::Region) {
997 rcx.fcx.mk_subr(infer::DerefPointer(deref_span),
998 minimum_lifetime, maximum_lifetime)
1002 /// Invoked on any index expression that occurs. Checks that if this is a slice being indexed, the
1003 /// lifetime of the pointer includes the deref expr.
1004 fn constrain_index<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1005 index_expr: &ast::Expr,
1006 indexed_ty: Ty<'tcx>)
1008 debug!("constrain_index(index_expr=?, indexed_ty={}",
1009 rcx.fcx.infcx().ty_to_string(indexed_ty));
1011 let r_index_expr = ty::ReScope(CodeExtent::from_node_id(index_expr.id));
1012 if let ty::ty_rptr(r_ptr, mt) = indexed_ty.sty {
1014 ty::ty_vec(_, None) | ty::ty_str => {
1015 rcx.fcx.mk_subr(infer::IndexSlice(index_expr.span),
1016 r_index_expr, *r_ptr);
1023 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1024 /// adjustments) are valid for at least `minimum_lifetime`
1025 fn type_of_node_must_outlive<'a, 'tcx>(
1026 rcx: &mut Rcx<'a, 'tcx>,
1027 origin: infer::SubregionOrigin<'tcx>,
1029 minimum_lifetime: ty::Region)
1031 let tcx = rcx.fcx.tcx();
1033 // Try to resolve the type. If we encounter an error, then typeck
1034 // is going to fail anyway, so just stop here and let typeck
1035 // report errors later on in the writeback phase.
1036 let ty0 = rcx.resolve_node_type(id);
1037 let ty = ty::adjust_ty(tcx, origin.span(), id, ty0,
1038 rcx.fcx.inh.adjustments.borrow().get(&id),
1039 |method_call| rcx.resolve_method_type(method_call));
1040 debug!("constrain_regions_in_type_of_node(\
1041 ty={}, ty0={}, id={}, minimum_lifetime={})",
1042 ty_to_string(tcx, ty), ty_to_string(tcx, ty0),
1043 id, minimum_lifetime);
1044 type_must_outlive(rcx, origin, ty, minimum_lifetime);
1047 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1048 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1049 fn link_addr_of(rcx: &mut Rcx, expr: &ast::Expr,
1050 mutability: ast::Mutability, base: &ast::Expr) {
1051 debug!("link_addr_of(base=?)");
1054 let mc = mc::MemCategorizationContext::new(rcx.fcx);
1055 ignore_err!(mc.cat_expr(base))
1057 link_region_from_node_type(rcx, expr.span, expr.id, mutability, cmt);
1060 /// Computes the guarantors for any ref bindings in a `let` and
1061 /// then ensures that the lifetime of the resulting pointer is
1062 /// linked to the lifetime of the initialization expression.
1063 fn link_local(rcx: &Rcx, local: &ast::Local) {
1064 debug!("regionck::for_local()");
1065 let init_expr = match local.init {
1067 Some(ref expr) => &**expr,
1069 let mc = mc::MemCategorizationContext::new(rcx.fcx);
1070 let discr_cmt = ignore_err!(mc.cat_expr(init_expr));
1071 link_pattern(rcx, mc, discr_cmt, &*local.pat);
1074 /// Computes the guarantors for any ref bindings in a match and
1075 /// then ensures that the lifetime of the resulting pointer is
1076 /// linked to the lifetime of its guarantor (if any).
1077 fn link_match(rcx: &Rcx, discr: &ast::Expr, arms: &[ast::Arm]) {
1078 debug!("regionck::for_match()");
1079 let mc = mc::MemCategorizationContext::new(rcx.fcx);
1080 let discr_cmt = ignore_err!(mc.cat_expr(discr));
1081 debug!("discr_cmt={}", discr_cmt.repr(rcx.tcx()));
1082 for arm in arms.iter() {
1083 for root_pat in arm.pats.iter() {
1084 link_pattern(rcx, mc, discr_cmt.clone(), &**root_pat);
1089 /// Computes the guarantors for any ref bindings in a match and
1090 /// then ensures that the lifetime of the resulting pointer is
1091 /// linked to the lifetime of its guarantor (if any).
1092 fn link_fn_args(rcx: &Rcx, body_scope: CodeExtent, args: &[ast::Arg]) {
1093 debug!("regionck::link_fn_args(body_scope={})", body_scope);
1094 let mc = mc::MemCategorizationContext::new(rcx.fcx);
1095 for arg in args.iter() {
1096 let arg_ty = rcx.fcx.node_ty(arg.id);
1097 let re_scope = ty::ReScope(body_scope);
1098 let arg_cmt = mc.cat_rvalue(arg.id, arg.ty.span, re_scope, arg_ty);
1099 debug!("arg_ty={} arg_cmt={}",
1100 arg_ty.repr(rcx.tcx()),
1101 arg_cmt.repr(rcx.tcx()));
1102 link_pattern(rcx, mc, arg_cmt, &*arg.pat);
1106 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found in the discriminant, if
1108 fn link_pattern<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1109 mc: mc::MemCategorizationContext<FnCtxt<'a, 'tcx>>,
1110 discr_cmt: mc::cmt<'tcx>,
1111 root_pat: &ast::Pat) {
1112 debug!("link_pattern(discr_cmt={}, root_pat={})",
1113 discr_cmt.repr(rcx.tcx()),
1114 root_pat.repr(rcx.tcx()));
1115 let _ = mc.cat_pattern(discr_cmt, root_pat, |mc, sub_cmt, sub_pat| {
1116 match sub_pat.node {
1118 ast::PatIdent(ast::BindByRef(mutbl), _, _) => {
1119 link_region_from_node_type(
1120 rcx, sub_pat.span, sub_pat.id,
1124 // `[_, ..slice, _]` pattern
1125 ast::PatVec(_, Some(ref slice_pat), _) => {
1126 match mc.cat_slice_pattern(sub_cmt, &**slice_pat) {
1127 Ok((slice_cmt, slice_mutbl, slice_r)) => {
1128 link_region(rcx, sub_pat.span, slice_r,
1129 ty::BorrowKind::from_mutbl(slice_mutbl),
1140 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1142 fn link_autoref(rcx: &Rcx,
1145 autoref: &ty::AutoRef) {
1147 debug!("link_autoref(autoref={})", autoref);
1148 let mc = mc::MemCategorizationContext::new(rcx.fcx);
1149 let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs));
1150 debug!("expr_cmt={}", expr_cmt.repr(rcx.tcx()));
1153 ty::AutoPtr(r, m, _) => {
1154 link_region(rcx, expr.span, r,
1155 ty::BorrowKind::from_mutbl(m), expr_cmt);
1158 ty::AutoUnsafe(..) | ty::AutoUnsizeUniq(_) | ty::AutoUnsize(_) => {}
1162 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1163 /// must outlive `callee_scope`.
1164 fn link_by_ref(rcx: &Rcx,
1166 callee_scope: CodeExtent) {
1167 let tcx = rcx.tcx();
1168 debug!("link_by_ref(expr={}, callee_scope={})",
1169 expr.repr(tcx), callee_scope);
1170 let mc = mc::MemCategorizationContext::new(rcx.fcx);
1171 let expr_cmt = ignore_err!(mc.cat_expr(expr));
1172 let borrow_region = ty::ReScope(callee_scope);
1173 link_region(rcx, expr.span, borrow_region, ty::ImmBorrow, expr_cmt);
1176 /// Like `link_region()`, except that the region is extracted from the type of `id`, which must be
1177 /// some reference (`&T`, `&str`, etc).
1178 fn link_region_from_node_type<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1181 mutbl: ast::Mutability,
1182 cmt_borrowed: mc::cmt<'tcx>) {
1183 let rptr_ty = rcx.resolve_node_type(id);
1184 if !ty::type_is_error(rptr_ty) {
1185 let tcx = rcx.fcx.ccx.tcx;
1186 debug!("rptr_ty={}", ty_to_string(tcx, rptr_ty));
1187 let r = ty::ty_region(tcx, span, rptr_ty);
1188 link_region(rcx, span, r, ty::BorrowKind::from_mutbl(mutbl),
1193 /// Informs the inference engine that `borrow_cmt` is being borrowed with kind `borrow_kind` and
1194 /// lifetime `borrow_region`. In order to ensure borrowck is satisfied, this may create constraints
1195 /// between regions, as explained in `link_reborrowed_region()`.
1196 fn link_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1198 borrow_region: ty::Region,
1199 borrow_kind: ty::BorrowKind,
1200 borrow_cmt: mc::cmt<'tcx>) {
1201 let mut borrow_cmt = borrow_cmt;
1202 let mut borrow_kind = borrow_kind;
1205 debug!("link_region(borrow_region={}, borrow_kind={}, borrow_cmt={})",
1206 borrow_region.repr(rcx.tcx()),
1207 borrow_kind.repr(rcx.tcx()),
1208 borrow_cmt.repr(rcx.tcx()));
1209 match borrow_cmt.cat.clone() {
1210 mc::cat_deref(ref_cmt, _,
1211 mc::Implicit(ref_kind, ref_region)) |
1212 mc::cat_deref(ref_cmt, _,
1213 mc::BorrowedPtr(ref_kind, ref_region)) => {
1214 match link_reborrowed_region(rcx, span,
1215 borrow_region, borrow_kind,
1216 ref_cmt, ref_region, ref_kind,
1228 mc::cat_downcast(cmt_base, _) |
1229 mc::cat_deref(cmt_base, _, mc::Unique) |
1230 mc::cat_interior(cmt_base, _) => {
1231 // Borrowing interior or owned data requires the base
1232 // to be valid and borrowable in the same fashion.
1233 borrow_cmt = cmt_base;
1234 borrow_kind = borrow_kind;
1237 mc::cat_deref(_, _, mc::UnsafePtr(..)) |
1238 mc::cat_static_item |
1241 mc::cat_rvalue(..) => {
1242 // These are all "base cases" with independent lifetimes
1243 // that are not subject to inference
1250 /// This is the most complicated case: the path being borrowed is
1251 /// itself the referent of a borrowed pointer. Let me give an
1252 /// example fragment of code to make clear(er) the situation:
1254 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1256 /// &'z *r // the reborrow has lifetime 'z
1258 /// Now, in this case, our primary job is to add the inference
1259 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1260 /// parameters in (roughly) terms of the example:
1262 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1263 /// borrow_region ^~ ref_region ^~
1264 /// borrow_kind ^~ ref_kind ^~
1267 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1269 /// Unfortunately, there are some complications beyond the simple
1270 /// scenario I just painted:
1272 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1273 /// case, we have two jobs. First, we are inferring whether this reference
1274 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1275 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1276 /// then `r` must be an `&mut` reference). Second, whenever we link
1277 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1278 /// case we adjust the cause to indicate that the reference being
1279 /// "reborrowed" is itself an upvar. This provides a nicer error message
1280 /// should something go wrong.
1282 /// 2. There may in fact be more levels of reborrowing. In the
1283 /// example, I said the borrow was like `&'z *r`, but it might
1284 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1285 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1286 /// and `'z <= 'b`. This is explained more below.
1288 /// The return value of this function indicates whether we need to
1289 /// recurse and process `ref_cmt` (see case 2 above).
1290 fn link_reborrowed_region<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1292 borrow_region: ty::Region,
1293 borrow_kind: ty::BorrowKind,
1294 ref_cmt: mc::cmt<'tcx>,
1295 ref_region: ty::Region,
1296 mut ref_kind: ty::BorrowKind,
1298 -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1300 // Possible upvar ID we may need later to create an entry in the
1303 // Detect by-ref upvar `x`:
1304 let cause = match note {
1305 mc::NoteUpvarRef(ref upvar_id) => {
1306 let mut upvar_borrow_map =
1307 rcx.fcx.inh.upvar_borrow_map.borrow_mut();
1308 match upvar_borrow_map.get_mut(upvar_id) {
1309 Some(upvar_borrow) => {
1310 // The mutability of the upvar may have been modified
1311 // by the above adjustment, so update our local variable.
1312 ref_kind = upvar_borrow.kind;
1314 infer::ReborrowUpvar(span, *upvar_id)
1317 rcx.tcx().sess.span_bug(
1319 format!("Illegal upvar id: {}",
1325 mc::NoteClosureEnv(ref upvar_id) => {
1326 // We don't have any mutability changes to propagate, but
1327 // we do want to note that an upvar reborrow caused this
1329 infer::ReborrowUpvar(span, *upvar_id)
1332 infer::Reborrow(span)
1336 debug!("link_reborrowed_region: {} <= {}",
1337 borrow_region.repr(rcx.tcx()),
1338 ref_region.repr(rcx.tcx()));
1339 rcx.fcx.mk_subr(cause, borrow_region, ref_region);
1341 // If we end up needing to recurse and establish a region link
1342 // with `ref_cmt`, calculate what borrow kind we will end up
1343 // needing. This will be used below.
1345 // One interesting twist is that we can weaken the borrow kind
1346 // when we recurse: to reborrow an `&mut` referent as mutable,
1347 // borrowck requires a unique path to the `&mut` reference but not
1348 // necessarily a *mutable* path.
1349 let new_borrow_kind = match borrow_kind {
1352 ty::MutBorrow | ty::UniqueImmBorrow =>
1356 // Decide whether we need to recurse and link any regions within
1357 // the `ref_cmt`. This is concerned for the case where the value
1358 // being reborrowed is in fact a borrowed pointer found within
1359 // another borrowed pointer. For example:
1361 // let p: &'b &'a mut T = ...;
1365 // What makes this case particularly tricky is that, if the data
1366 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1367 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1368 // (otherwise the user might mutate through the `&mut T` reference
1369 // after `'b` expires and invalidate the borrow we are looking at
1372 // So let's re-examine our parameters in light of this more
1373 // complicated (possible) scenario:
1375 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1376 // borrow_region ^~ ref_region ^~
1377 // borrow_kind ^~ ref_kind ^~
1380 // (Note that since we have not examined `ref_cmt.cat`, we don't
1381 // know whether this scenario has occurred; but I wanted to show
1382 // how all the types get adjusted.)
1385 // The reference being reborrowed is a sharable ref of
1386 // type `&'a T`. In this case, it doesn't matter where we
1387 // *found* the `&T` pointer, the memory it references will
1388 // be valid and immutable for `'a`. So we can stop here.
1390 // (Note that the `borrow_kind` must also be ImmBorrow or
1391 // else the user is borrowed imm memory as mut memory,
1392 // which means they'll get an error downstream in borrowck
1397 ty::MutBorrow | ty::UniqueImmBorrow => {
1398 // The reference being reborrowed is either an `&mut T` or
1399 // `&uniq T`. This is the case where recursion is needed.
1400 return Some((ref_cmt, new_borrow_kind));
1405 /// Ensures that all borrowed data reachable via `ty` outlives `region`.
1406 fn type_must_outlive<'a, 'tcx>(rcx: &mut Rcx<'a, 'tcx>,
1407 origin: infer::SubregionOrigin<'tcx>,
1411 debug!("type_must_outlive(ty={}, region={})",
1413 region.repr(rcx.tcx()));
1416 regionmanip::region_wf_constraints(
1420 for constraint in constraints.iter() {
1421 debug!("constraint: {}", constraint.repr(rcx.tcx()));
1423 regionmanip::RegionSubRegionConstraint(None, r_a, r_b) => {
1424 rcx.fcx.mk_subr(origin.clone(), r_a, r_b);
1426 regionmanip::RegionSubRegionConstraint(Some(ty), r_a, r_b) => {
1427 let o1 = infer::ReferenceOutlivesReferent(ty, origin.span());
1428 rcx.fcx.mk_subr(o1, r_a, r_b);
1430 regionmanip::RegionSubParamConstraint(None, r_a, param_b) => {
1431 param_must_outlive(rcx, origin.clone(), r_a, param_b);
1433 regionmanip::RegionSubParamConstraint(Some(ty), r_a, param_b) => {
1434 let o1 = infer::ReferenceOutlivesReferent(ty, origin.span());
1435 param_must_outlive(rcx, o1, r_a, param_b);
1441 fn param_must_outlive<'a, 'tcx>(rcx: &Rcx<'a, 'tcx>,
1442 origin: infer::SubregionOrigin<'tcx>,
1444 param_ty: ty::ParamTy) {
1445 let param_env = &rcx.fcx.inh.param_env;
1447 debug!("param_must_outlive(region={}, param_ty={})",
1448 region.repr(rcx.tcx()),
1449 param_ty.repr(rcx.tcx()));
1451 // To start, collect bounds from user:
1452 let mut param_bounds =
1453 ty::required_region_bounds(rcx.tcx(),
1454 param_ty.to_ty(rcx.tcx()),
1455 param_env.caller_bounds.predicates.as_slice().to_vec());
1457 // Add in the default bound of fn body that applies to all in
1458 // scope type parameters:
1459 param_bounds.push(param_env.implicit_region_bound);
1461 // Finally, collect regions we scraped from the well-formedness
1462 // constraints in the fn signature. To do that, we walk the list
1463 // of known relations from the fn ctxt.
1465 // This is crucial because otherwise code like this fails:
1467 // fn foo<'a, A>(x: &'a A) { x.bar() }
1469 // The problem is that the type of `x` is `&'a A`. To be
1470 // well-formed, then, A must be lower-bounded by `'a`, but we
1471 // don't know that this holds from first principles.
1472 for &(ref r, ref p) in rcx.region_param_pairs.iter() {
1473 debug!("param_ty={} p={}",
1474 param_ty.repr(rcx.tcx()),
1477 param_bounds.push(*r);
1481 // Inform region inference that this parameter type must be
1482 // properly bounded.
1483 infer::verify_param_bound(rcx.fcx.infcx(),