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 //! This file actually contains two passes related to regions. The first
12 //! pass builds up the `scope_map`, which describes the parent links in
13 //! the region hierarchy. The second pass infers which types must be
14 //! region parameterized.
16 //! Most of the documentation on regions can be found in
17 //! `middle/typeck/infer/region_inference.rs`
20 use middle::ty::{self, Ty, FreeRegion};
21 use util::nodemap::{FnvHashMap, FnvHashSet, NodeMap};
22 use util::common::can_reach;
24 use std::cell::RefCell;
25 use syntax::codemap::{self, Span};
26 use syntax::{ast, visit};
27 use syntax::ast::{Block, Item, FnDecl, NodeId, Arm, Pat, Stmt, Expr, Local};
28 use syntax::ast_util::{stmt_id};
30 use syntax::visit::{Visitor, FnKind};
32 /// CodeExtent represents a statically-describable extent that can be
33 /// used to bound the lifetime/region for values.
35 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
36 /// placate the same deriving in `ty::FreeRegion`, but we may want to
37 /// actually attach a more meaningful ordering to scopes than the one
38 /// generated via deriving here.
39 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
40 RustcDecodable, Debug, Copy)]
43 Remainder(BlockRemainder),
46 /// Represents a subscope of `block` for a binding that is introduced
47 /// by `block.stmts[first_statement_index]`. Such subscopes represent
48 /// a suffix of the block. Note that each subscope does not include
49 /// the initializer expression, if any, for the statement indexed by
50 /// `first_statement_index`.
52 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
54 /// * the subscope with `first_statement_index == 0` is scope of both
55 /// `a` and `b`; it does not include EXPR_1, but does include
56 /// everything after that first `let`. (If you want a scope that
57 /// includes EXPR_1 as well, then do not use `CodeExtent::Remainder`,
58 /// but instead another `CodeExtent` that encompasses the whole block,
59 /// e.g. `CodeExtent::Misc`.
61 /// * the subscope with `first_statement_index == 1` is scope of `c`,
62 /// and thus does not include EXPR_2, but covers the `...`.
63 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
64 RustcDecodable, Debug, Copy)]
65 pub struct BlockRemainder {
66 pub block: ast::NodeId,
67 pub first_statement_index: uint,
71 /// Creates a scope that represents the dynamic extent associated
73 pub fn from_node_id(node_id: ast::NodeId) -> CodeExtent {
74 CodeExtent::Misc(node_id)
77 /// Returns a node id associated with this scope.
79 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
80 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
81 pub fn node_id(&self) -> ast::NodeId {
83 CodeExtent::Misc(node_id) => node_id,
84 CodeExtent::Remainder(br) => br.block,
88 /// Maps this scope to a potentially new one according to the
89 /// NodeId transformer `f_id`.
90 pub fn map_id<F>(&self, f_id: F) -> CodeExtent where
91 F: FnOnce(ast::NodeId) -> ast::NodeId,
94 CodeExtent::Misc(node_id) => CodeExtent::Misc(f_id(node_id)),
95 CodeExtent::Remainder(br) =>
96 CodeExtent::Remainder(BlockRemainder {
97 block: f_id(br.block), first_statement_index: br.first_statement_index }),
101 /// Returns the span of this CodeExtent. Note that in general the
102 /// returned span may not correspond to the span of any node id in
104 pub fn span(&self, ast_map: &ast_map::Map) -> Option<Span> {
105 match ast_map.find(self.node_id()) {
106 Some(ast_map::NodeBlock(ref blk)) => {
108 CodeExtent::Misc(_) => Some(blk.span),
110 CodeExtent::Remainder(r) => {
111 assert_eq!(r.block, blk.id);
112 // Want span for extent starting after the
113 // indexed statement and ending at end of
114 // `blk`; reuse span of `blk` and shift `lo`
115 // forward to end of indexed statement.
117 // (This is the special case aluded to in the
118 // doc-comment for this method)
119 let stmt_span = blk.stmts[r.first_statement_index].span;
120 Some(Span { lo: stmt_span.hi, ..blk.span })
124 Some(ast_map::NodeExpr(ref expr)) => Some(expr.span),
125 Some(ast_map::NodeStmt(ref stmt)) => Some(stmt.span),
126 Some(ast_map::NodeItem(ref item)) => Some(item.span),
127 Some(_) | None => None,
132 /// The region maps encode information about region relationships.
134 /// - `scope_map` maps from a scope id to the enclosing scope id; this is
135 /// usually corresponding to the lexical nesting, though in the case of
136 /// closures the parent scope is the innermost conditional expression or repeating
137 /// block. (Note that the enclosing scope id for the block
138 /// associated with a closure is the closure itself.)
140 /// - `var_map` maps from a variable or binding id to the block in which
141 /// that variable is declared.
143 /// - `free_region_map` maps from a free region `a` to a list of free
144 /// regions `bs` such that `a <= b for all b in bs`
145 /// - the free region map is populated during type check as we check
146 /// each function. See the function `relate_free_regions` for
147 /// more information.
149 /// - `rvalue_scopes` includes entries for those expressions whose cleanup
150 /// scope is larger than the default. The map goes from the expression
151 /// id to the cleanup scope id. For rvalues not present in this table,
152 /// the appropriate cleanup scope is the innermost enclosing statement,
153 /// conditional expression, or repeating block (see `terminating_scopes`).
155 /// - `terminating_scopes` is a set containing the ids of each statement,
156 /// or conditional/repeating expression. These scopes are calling "terminating
157 /// scopes" because, when attempting to find the scope of a temporary, by
158 /// default we search up the enclosing scopes until we encounter the
159 /// terminating scope. A conditional/repeating
160 /// expression is one which is not guaranteed to execute exactly once
161 /// upon entering the parent scope. This could be because the expression
162 /// only executes conditionally, such as the expression `b` in `a && b`,
163 /// or because the expression may execute many times, such as a loop
164 /// body. The reason that we distinguish such expressions is that, upon
165 /// exiting the parent scope, we cannot statically know how many times
166 /// the expression executed, and thus if the expression creates
167 /// temporaries we cannot know statically how many such temporaries we
168 /// would have to cleanup. Therefore we ensure that the temporaries never
169 /// outlast the conditional/repeating expression, preventing the need
170 /// for dynamic checks and/or arbitrary amounts of stack space.
171 pub struct RegionMaps {
172 scope_map: RefCell<FnvHashMap<CodeExtent, CodeExtent>>,
173 var_map: RefCell<NodeMap<CodeExtent>>,
174 free_region_map: RefCell<FnvHashMap<FreeRegion, Vec<FreeRegion>>>,
175 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
176 terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
179 /// Carries the node id for the innermost block or match expression,
180 /// for building up the `var_map` which maps ids to the blocks in
181 /// which they were declared.
182 #[derive(PartialEq, Eq, Debug, Copy)]
183 enum InnermostDeclaringBlock {
186 Statement(DeclaringStatementContext),
190 impl InnermostDeclaringBlock {
191 fn to_code_extent(&self) -> Option<CodeExtent> {
192 let extent = match *self {
193 InnermostDeclaringBlock::None => {
196 InnermostDeclaringBlock::Block(id) |
197 InnermostDeclaringBlock::Match(id) => CodeExtent::from_node_id(id),
198 InnermostDeclaringBlock::Statement(s) => s.to_code_extent(),
204 /// Contextual information for declarations introduced by a statement
205 /// (i.e. `let`). It carries node-id's for statement and enclosing
206 /// block both, as well as the statement's index within the block.
207 #[derive(PartialEq, Eq, Debug, Copy)]
208 struct DeclaringStatementContext {
209 stmt_id: ast::NodeId,
210 block_id: ast::NodeId,
214 impl DeclaringStatementContext {
215 fn to_code_extent(&self) -> CodeExtent {
216 CodeExtent::Remainder(BlockRemainder {
217 block: self.block_id,
218 first_statement_index: self.stmt_index,
223 #[derive(PartialEq, Eq, Debug, Copy)]
224 enum InnermostEnclosingExpr {
227 Statement(DeclaringStatementContext),
230 impl InnermostEnclosingExpr {
231 fn to_code_extent(&self) -> Option<CodeExtent> {
232 let extent = match *self {
233 InnermostEnclosingExpr::None => {
236 InnermostEnclosingExpr::Statement(s) =>
238 InnermostEnclosingExpr::Some(parent_id) =>
239 CodeExtent::from_node_id(parent_id),
245 #[derive(Debug, Copy)]
247 var_parent: InnermostDeclaringBlock,
249 parent: InnermostEnclosingExpr,
252 struct RegionResolutionVisitor<'a> {
256 region_maps: &'a RegionMaps,
263 pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) {
264 match self.free_region_map.borrow_mut().get_mut(&sub) {
266 if !sups.iter().any(|x| x == &sup) {
274 debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup);
275 self.free_region_map.borrow_mut().insert(sub, vec!(sup));
278 pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
279 debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
281 self.scope_map.borrow_mut().insert(sub, sup);
284 pub fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
285 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
286 assert!(var != lifetime.node_id());
287 self.var_map.borrow_mut().insert(var, lifetime);
290 pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
291 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
292 assert!(var != lifetime.node_id());
293 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
296 /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
297 /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
299 pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
300 debug!("record_terminating_scope(scope_id={:?})", scope_id);
301 self.terminating_scopes.borrow_mut().insert(scope_id);
304 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
305 //! Returns the narrowest scope that encloses `id`, if any.
306 self.scope_map.borrow().get(&id).map(|x| *x)
309 #[allow(dead_code)] // used in middle::cfg
310 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
311 //! Returns the narrowest scope that encloses `id`, if any.
312 match self.scope_map.borrow().get(&id) {
314 None => { panic!("no enclosing scope for id {:?}", id); }
318 /// Returns the lifetime of the local variable `var_id`
319 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
320 match self.var_map.borrow().get(&var_id) {
322 None => { panic!("no enclosing scope for id {:?}", var_id); }
326 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
327 //! Returns the scope when temp created by expr_id will be cleaned up
329 // check for a designated rvalue scope
330 match self.rvalue_scopes.borrow().get(&expr_id) {
332 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
338 // else, locate the innermost terminating scope
339 // if there's one. Static items, for instance, won't
340 // have an enclosing scope, hence no scope will be
342 let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) {
344 None => { return None; }
347 while !self.terminating_scopes.borrow().contains(&id) {
348 match self.opt_encl_scope(id) {
353 debug!("temporary_scope({:?}) = None", expr_id);
358 debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
362 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
363 //! Returns the lifetime of the variable `id`.
365 let scope = ty::ReScope(self.var_scope(id));
366 debug!("var_region({:?}) = {:?}", id, scope);
370 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
372 self.is_subscope_of(scope1, scope2) ||
373 self.is_subscope_of(scope2, scope1)
376 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
378 pub fn is_subscope_of(&self,
379 subscope: CodeExtent,
380 superscope: CodeExtent)
382 let mut s = subscope;
383 while superscope != s {
384 match self.scope_map.borrow().get(&s) {
386 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
387 subscope, superscope, s);
391 Some(&scope) => s = scope
395 debug!("is_subscope_of({:?}, {:?})=true",
396 subscope, superscope);
401 /// Determines whether two free regions have a subregion relationship
402 /// by walking the graph encoded in `free_region_map`. Note that
403 /// it is possible that `sub != sup` and `sub <= sup` and `sup <= sub`
404 /// (that is, the user can give two different names to the same lifetime).
405 pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool {
406 can_reach(&*self.free_region_map.borrow(), sub, sup)
409 /// Determines whether one region is a subregion of another. This is intended to run *after
410 /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs.
411 pub fn is_subregion_of(&self,
412 sub_region: ty::Region,
413 super_region: ty::Region)
415 debug!("is_subregion_of(sub_region={:?}, super_region={:?})",
416 sub_region, super_region);
418 sub_region == super_region || {
419 match (sub_region, super_region) {
421 (_, ty::ReStatic) => {
425 (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => {
426 self.is_subscope_of(sub_scope, super_scope)
429 (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => {
430 self.is_subscope_of(sub_scope, fr.scope)
433 (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => {
434 self.sub_free_region(sub_fr, super_fr)
437 (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _),
438 ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => {
439 // This case is used only to make sure that explicitly-
440 // specified `Self` types match the real self type in
442 param_id_a == param_id_b &&
443 param_space_a == param_space_b &&
454 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
455 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
456 pub fn nearest_common_ancestor(&self,
459 -> Option<CodeExtent> {
460 if scope_a == scope_b { return Some(scope_a); }
462 let a_ancestors = ancestors_of(self, scope_a);
463 let b_ancestors = ancestors_of(self, scope_b);
464 let mut a_index = a_ancestors.len() - 1;
465 let mut b_index = b_ancestors.len() - 1;
467 // Here, ~[ab]_ancestors is a vector going from narrow to broad.
468 // The end of each vector will be the item where the scope is
469 // defined; if there are any common ancestors, then the tails of
470 // the vector will be the same. So basically we want to walk
471 // backwards from the tail of each vector and find the first point
472 // where they diverge. If one vector is a suffix of the other,
473 // then the corresponding scope is a superscope of the other.
475 if a_ancestors[a_index] != b_ancestors[b_index] {
480 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
481 // for all indices between a_index and the end of the array
482 if a_index == 0 { return Some(scope_a); }
483 if b_index == 0 { return Some(scope_b); }
486 if a_ancestors[a_index] != b_ancestors[b_index] {
487 return Some(a_ancestors[a_index + 1]);
491 fn ancestors_of(this: &RegionMaps, scope: CodeExtent)
493 // debug!("ancestors_of(scope={:?})", scope);
494 let mut result = vec!(scope);
495 let mut scope = scope;
497 match this.scope_map.borrow().get(&scope) {
498 None => return result,
499 Some(&superscope) => {
500 result.push(superscope);
504 // debug!("ancestors_of_loop(scope={:?})", scope);
510 /// Records the current parent (if any) as the parent of `child_scope`.
511 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
512 child_scope: CodeExtent,
514 match visitor.cx.parent.to_code_extent() {
515 Some(parent_scope) =>
516 visitor.region_maps.record_encl_scope(child_scope, parent_scope),
521 /// Records the lifetime of a local variable as `cx.var_parent`
522 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
525 match visitor.cx.var_parent.to_code_extent() {
526 Some(parent_scope) =>
527 visitor.region_maps.record_var_scope(var_id, parent_scope),
529 // this can happen in extern fn declarations like
531 // extern fn isalnum(c: c_int) -> c_int
536 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
537 debug!("resolve_block(blk.id={:?})", blk.id);
539 let prev_cx = visitor.cx;
541 let blk_scope = CodeExtent::Misc(blk.id);
542 record_superlifetime(visitor, blk_scope, blk.span);
544 // We treat the tail expression in the block (if any) somewhat
545 // differently from the statements. The issue has to do with
546 // temporary lifetimes. Consider the following:
549 // let inner = ... (&bar()) ...;
551 // (... (&foo()) ...) // (the tail expression)
552 // }, other_argument());
554 // Each of the statements within the block is a terminating
555 // scope, and thus a temporary (e.g. the result of calling
556 // `bar()` in the initalizer expression for `let inner = ...;`)
557 // will be cleaned up immediately after its corresponding
558 // statement (i.e. `let inner = ...;`) executes.
560 // On the other hand, temporaries associated with evaluating the
561 // tail expression for the block are assigned lifetimes so that
562 // they will be cleaned up as part of the terminating scope
563 // *surrounding* the block expression. Here, the terminating
564 // scope for the block expression is the `quux(..)` call; so
565 // those temporaries will only be cleaned up *after* both
566 // `other_argument()` has run and also the call to `quux(..)`
567 // itself has returned.
569 visitor.cx = Context {
570 var_parent: InnermostDeclaringBlock::Block(blk.id),
571 parent: InnermostEnclosingExpr::Some(blk.id),
575 // This block should be kept approximately in sync with
576 // `visit::walk_block`. (We manually walk the block, rather
577 // than call `walk_block`, in order to maintain precise
578 // `InnermostDeclaringBlock` information.)
580 for (i, statement) in blk.stmts.iter().enumerate() {
581 if let ast::StmtDecl(_, stmt_id) = statement.node {
582 // Each StmtDecl introduces a subscope for bindings
583 // introduced by the declaration; this subscope covers
584 // a suffix of the block . Each subscope in a block
585 // has the previous subscope in the block as a parent,
586 // except for the first such subscope, which has the
587 // block itself as a parent.
588 let declaring = DeclaringStatementContext {
593 record_superlifetime(
594 visitor, declaring.to_code_extent(), statement.span);
595 visitor.cx = Context {
596 var_parent: InnermostDeclaringBlock::Statement(declaring),
597 parent: InnermostEnclosingExpr::Statement(declaring),
600 visitor.visit_stmt(&**statement)
602 visit::walk_expr_opt(visitor, &blk.expr)
605 visitor.cx = prev_cx;
608 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
609 let arm_body_scope = CodeExtent::from_node_id(arm.body.id);
610 visitor.region_maps.mark_as_terminating_scope(arm_body_scope);
614 let guard_scope = CodeExtent::from_node_id(expr.id);
615 visitor.region_maps.mark_as_terminating_scope(guard_scope);
620 visit::walk_arm(visitor, arm);
623 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
624 record_superlifetime(visitor, CodeExtent::from_node_id(pat.id), pat.span);
626 // If this is a binding (or maybe a binding, I'm too lazy to check
627 // the def map) then record the lifetime of that binding.
629 ast::PatIdent(..) => {
630 record_var_lifetime(visitor, pat.id, pat.span);
635 visit::walk_pat(visitor, pat);
638 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
639 let stmt_id = stmt_id(stmt);
640 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
642 let stmt_scope = CodeExtent::from_node_id(stmt_id);
644 // Every statement will clean up the temporaries created during
645 // execution of that statement. Therefore each statement has an
646 // associated destruction scope that represents the extent of the
647 // statement plus its destructors, and thus the extent for which
648 // regions referenced by the destructors need to survive.
649 visitor.region_maps.mark_as_terminating_scope(stmt_scope);
650 record_superlifetime(visitor, stmt_scope, stmt.span);
652 let prev_parent = visitor.cx.parent;
653 visitor.cx.parent = InnermostEnclosingExpr::Some(stmt_id);
654 visit::walk_stmt(visitor, stmt);
655 visitor.cx.parent = prev_parent;
658 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
659 debug!("resolve_expr(expr.id={:?})", expr.id);
661 let expr_scope = CodeExtent::Misc(expr.id);
662 record_superlifetime(visitor, expr_scope, expr.span);
664 let prev_cx = visitor.cx;
665 visitor.cx.parent = InnermostEnclosingExpr::Some(expr.id);
668 let region_maps = &mut visitor.region_maps;
669 let terminating = |id| {
670 let scope = CodeExtent::from_node_id(id);
671 region_maps.mark_as_terminating_scope(scope)
674 // Conditional or repeating scopes are always terminating
675 // scopes, meaning that temporaries cannot outlive them.
676 // This ensures fixed size stacks.
678 ast::ExprBinary(codemap::Spanned { node: ast::BiAnd, .. }, _, ref r) |
679 ast::ExprBinary(codemap::Spanned { node: ast::BiOr, .. }, _, ref r) => {
680 // For shortcircuiting operators, mark the RHS as a terminating
681 // scope since it only executes conditionally.
685 ast::ExprIf(_, ref then, Some(ref otherwise)) => {
686 terminating(then.id);
687 terminating(otherwise.id);
690 ast::ExprIf(ref expr, ref then, None) => {
691 terminating(expr.id);
692 terminating(then.id);
695 ast::ExprLoop(ref body, _) => {
696 terminating(body.id);
699 ast::ExprWhile(ref expr, ref body, _) => {
700 terminating(expr.id);
701 terminating(body.id);
704 ast::ExprMatch(..) => {
705 visitor.cx.var_parent = InnermostDeclaringBlock::Match(expr.id);
708 ast::ExprAssignOp(..) | ast::ExprIndex(..) |
709 ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => {
710 // FIXME(#6268) Nested method calls
712 // The lifetimes for a call or method call look as follows:
720 // The idea is that call.callee_id represents *the time when
721 // the invoked function is actually running* and call.id
722 // represents *the time to prepare the arguments and make the
723 // call*. See the section "Borrows in Calls" borrowck/doc.rs
724 // for an extended explanation of why this distinction is
727 // record_superlifetime(new_cx, expr.callee_id);
734 visit::walk_expr(visitor, expr);
735 visitor.cx = prev_cx;
738 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
739 debug!("resolve_local(local.id={:?},local.init={:?})",
740 local.id,local.init.is_some());
742 // For convenience in trans, associate with the local-id the var
743 // scope that will be used for any bindings declared in this
745 let blk_scope = visitor.cx.var_parent.to_code_extent()
746 .unwrap_or_else(|| visitor.sess.span_bug(
747 local.span, "local without enclosing block"));
749 visitor.region_maps.record_var_scope(local.id, blk_scope);
751 // As an exception to the normal rules governing temporary
752 // lifetimes, initializers in a let have a temporary lifetime
753 // of the enclosing block. This means that e.g. a program
754 // like the following is legal:
756 // let ref x = HashMap::new();
758 // Because the hash map will be freed in the enclosing block.
760 // We express the rules more formally based on 3 grammars (defined
761 // fully in the helpers below that implement them):
763 // 1. `E&`, which matches expressions like `&<rvalue>` that
764 // own a pointer into the stack.
766 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
767 // y)` that produce ref bindings into the value they are
768 // matched against or something (at least partially) owned by
769 // the value they are matched against. (By partially owned,
770 // I mean that creating a binding into a ref-counted or managed value
771 // would still count.)
773 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
774 // based on rvalues like `foo().x[2].y`.
776 // A subexpression `<rvalue>` that appears in a let initializer
777 // `let pat [: ty] = expr` has an extended temporary lifetime if
778 // any of the following conditions are met:
780 // A. `pat` matches `P&` and `expr` matches `ET`
781 // (covers cases where `pat` creates ref bindings into an rvalue
782 // produced by `expr`)
783 // B. `ty` is a borrowed pointer and `expr` matches `ET`
784 // (covers cases where coercion creates a borrow)
785 // C. `expr` matches `E&`
786 // (covers cases `expr` borrows an rvalue that is then assigned
787 // to memory (at least partially) owned by the binding)
789 // Here are some examples hopefully giving an intuition where each
790 // rule comes into play and why:
792 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
793 // would have an extended lifetime, but not `foo()`.
795 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
796 // would have an extended lifetime, but not `foo()`.
798 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
801 // In some cases, multiple rules may apply (though not to the same
802 // rvalue). For example:
804 // let ref x = [&a(), &b()];
806 // Here, the expression `[...]` has an extended lifetime due to rule
807 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
810 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
814 record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
817 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
819 if is_binding_pat(&*local.pat) || is_borrow {
820 record_rvalue_scope(visitor, &**expr, blk_scope);
827 visit::walk_local(visitor, local);
829 /// True if `pat` match the `P&` nonterminal:
832 /// | StructName { ..., P&, ... }
833 /// | VariantName(..., P&, ...)
834 /// | [ ..., P&, ... ]
835 /// | ( ..., P&, ... )
837 fn is_binding_pat(pat: &ast::Pat) -> bool {
839 ast::PatIdent(ast::BindByRef(_), _, _) => true,
841 ast::PatStruct(_, ref field_pats, _) => {
842 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
845 ast::PatVec(ref pats1, ref pats2, ref pats3) => {
846 pats1.iter().any(|p| is_binding_pat(&**p)) ||
847 pats2.iter().any(|p| is_binding_pat(&**p)) ||
848 pats3.iter().any(|p| is_binding_pat(&**p))
851 ast::PatEnum(_, Some(ref subpats)) |
852 ast::PatTup(ref subpats) => {
853 subpats.iter().any(|p| is_binding_pat(&**p))
856 ast::PatBox(ref subpat) => {
857 is_binding_pat(&**subpat)
864 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
865 fn is_borrowed_ty(ty: &ast::Ty) -> bool {
867 ast::TyRptr(..) => true,
872 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
875 /// | StructName { ..., f: E&, ... }
876 /// | [ ..., E&, ... ]
877 /// | ( ..., E&, ... )
882 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
884 blk_id: CodeExtent) {
886 ast::ExprAddrOf(_, ref subexpr) => {
887 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
888 record_rvalue_scope(visitor, &**subexpr, blk_id);
890 ast::ExprStruct(_, ref fields, _) => {
891 for field in fields {
892 record_rvalue_scope_if_borrow_expr(
893 visitor, &*field.expr, blk_id);
896 ast::ExprVec(ref subexprs) |
897 ast::ExprTup(ref subexprs) => {
898 for subexpr in subexprs {
899 record_rvalue_scope_if_borrow_expr(
900 visitor, &**subexpr, blk_id);
903 ast::ExprUnary(ast::UnUniq, ref subexpr) => {
904 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
906 ast::ExprCast(ref subexpr, _) |
907 ast::ExprParen(ref subexpr) => {
908 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
910 ast::ExprBlock(ref block) => {
912 Some(ref subexpr) => {
913 record_rvalue_scope_if_borrow_expr(
914 visitor, &**subexpr, blk_id);
924 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
925 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
926 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
929 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
930 /// `<rvalue>` as `blk_id`:
938 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
939 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
941 blk_scope: CodeExtent) {
944 // Note: give all the expressions matching `ET` with the
945 // extended temporary lifetime, not just the innermost rvalue,
946 // because in trans if we must compile e.g. `*rvalue()`
947 // into a temporary, we request the temporary scope of the
949 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
952 ast::ExprAddrOf(_, ref subexpr) |
953 ast::ExprUnary(ast::UnDeref, ref subexpr) |
954 ast::ExprField(ref subexpr, _) |
955 ast::ExprTupField(ref subexpr, _) |
956 ast::ExprIndex(ref subexpr, _) |
957 ast::ExprParen(ref subexpr) => {
968 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
969 // Items create a new outer block scope as far as we're concerned.
970 let prev_cx = visitor.cx;
971 visitor.cx = Context {
972 var_parent: InnermostDeclaringBlock::None,
973 parent: InnermostEnclosingExpr::None
975 visit::walk_item(visitor, item);
976 visitor.cx = prev_cx;
979 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
985 debug!("region::resolve_fn(id={:?}, \
990 visitor.sess.codemap().span_to_string(sp),
994 let body_scope = CodeExtent::from_node_id(body.id);
995 visitor.region_maps.mark_as_terminating_scope(body_scope);
997 let outer_cx = visitor.cx;
999 // The arguments and `self` are parented to the body of the fn.
1000 visitor.cx = Context {
1001 parent: InnermostEnclosingExpr::Some(body.id),
1002 var_parent: InnermostDeclaringBlock::Block(body.id)
1004 visit::walk_fn_decl(visitor, decl);
1006 // The body of the fn itself is either a root scope (top-level fn)
1007 // or it continues with the inherited scope (closures).
1009 visit::FkItemFn(..) | visit::FkMethod(..) => {
1010 visitor.cx = Context {
1011 parent: InnermostEnclosingExpr::None,
1012 var_parent: InnermostDeclaringBlock::None
1014 visitor.visit_block(body);
1015 visitor.cx = outer_cx;
1017 visit::FkFnBlock(..) => {
1018 // FIXME(#3696) -- at present we are place the closure body
1019 // within the region hierarchy exactly where it appears lexically.
1020 // This is wrong because the closure may live longer
1021 // than the enclosing expression. We should probably fix this,
1022 // but the correct fix is a bit subtle, and I am also not sure
1023 // that the present approach is unsound -- it may not permit
1024 // any illegal programs. See issue for more details.
1025 visitor.cx = outer_cx;
1026 visitor.visit_block(body);
1031 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
1033 fn visit_block(&mut self, b: &Block) {
1034 resolve_block(self, b);
1037 fn visit_item(&mut self, i: &Item) {
1038 resolve_item(self, i);
1041 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
1042 b: &'v Block, s: Span, n: NodeId) {
1043 resolve_fn(self, fk, fd, b, s, n);
1045 fn visit_arm(&mut self, a: &Arm) {
1046 resolve_arm(self, a);
1048 fn visit_pat(&mut self, p: &Pat) {
1049 resolve_pat(self, p);
1051 fn visit_stmt(&mut self, s: &Stmt) {
1052 resolve_stmt(self, s);
1054 fn visit_expr(&mut self, ex: &Expr) {
1055 resolve_expr(self, ex);
1057 fn visit_local(&mut self, l: &Local) {
1058 resolve_local(self, l);
1062 pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
1063 let maps = RegionMaps {
1064 scope_map: RefCell::new(FnvHashMap()),
1065 var_map: RefCell::new(NodeMap()),
1066 free_region_map: RefCell::new(FnvHashMap()),
1067 rvalue_scopes: RefCell::new(NodeMap()),
1068 terminating_scopes: RefCell::new(FnvHashSet()),
1071 let mut visitor = RegionResolutionVisitor {
1075 parent: InnermostEnclosingExpr::None,
1076 var_parent: InnermostDeclaringBlock::None,
1079 visit::walk_crate(&mut visitor, krate);
1084 pub fn resolve_inlined_item(sess: &Session,
1085 region_maps: &RegionMaps,
1086 item: &ast::InlinedItem) {
1087 let mut visitor = RegionResolutionVisitor {
1089 region_maps: region_maps,
1091 parent: InnermostEnclosingExpr::None,
1092 var_parent: InnermostDeclaringBlock::None
1095 visit::walk_inlined_item(&mut visitor, item);