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/infer/region_inference/README.md`
19 use dep_graph::DepNode;
20 use hir::map as ast_map;
22 use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
25 use std::cell::RefCell;
26 use std::collections::hash_map::Entry;
30 use syntax::ast::{self, NodeId};
34 use hir::intravisit::{self, Visitor, FnKind};
35 use hir::{Block, Item, FnDecl, Arm, Pat, PatKind, Stmt, Expr, Local};
37 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
38 RustcDecodable, Copy)]
39 pub struct CodeExtent(u32);
41 impl fmt::Debug for CodeExtent {
42 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43 write!(f, "CodeExtent({:?}", self.0)?;
45 ty::tls::with_opt(|opt_tcx| {
46 if let Some(tcx) = opt_tcx {
47 if let Some(data) = tcx.region_maps.code_extents.borrow().get(self.0 as usize) {
48 write!(f, "/{:?}", data)?;
58 /// The root of everything. I should be using NonZero or profiling
59 /// instead of this (probably).
60 pub const ROOT_CODE_EXTENT : CodeExtent = CodeExtent(0);
61 /// A placeholder used in trans to stand for real code extents
62 pub const DUMMY_CODE_EXTENT : CodeExtent = CodeExtent(1);
64 /// CodeExtent represents a statically-describable extent that can be
65 /// used to bound the lifetime/region for values.
67 /// `Misc(node_id)`: Any AST node that has any extent at all has the
68 /// `Misc(node_id)` extent. Other variants represent special cases not
69 /// immediately derivable from the abstract syntax tree structure.
71 /// `DestructionScope(node_id)` represents the extent of destructors
72 /// implicitly-attached to `node_id` that run immediately after the
73 /// expression for `node_id` itself. Not every AST node carries a
74 /// `DestructionScope`, but those that are `terminating_scopes` do;
75 /// see discussion with `RegionMaps`.
77 /// `Remainder(BlockRemainder { block, statement_index })` represents
78 /// the extent of user code running immediately after the initializer
79 /// expression for the indexed statement, until the end of the block.
81 /// So: the following code can be broken down into the extents beneath:
83 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
88 /// +---------+ (R10.)
90 /// +----------+ (M8.)
91 /// +----------------------+ (R7.)
93 /// +----------+ (M5.)
94 /// +-----------------------------------+ (M4.)
95 /// +--------------------------------------------------+ (M3.)
97 /// +-----------------------------------------------------------+ (M1.)
99 /// (M1.): Misc extent of the whole `let a = ...;` statement.
100 /// (M2.): Misc extent of the `f()` expression.
101 /// (M3.): Misc extent of the `f().g(..)` expression.
102 /// (M4.): Misc extent of the block labelled `'b:`.
103 /// (M5.): Misc extent of the `let x = d();` statement
104 /// (D6.): DestructionScope for temporaries created during M5.
105 /// (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
106 /// (M8.): Misc Extent of the `let y = d();` statement.
107 /// (D9.): DestructionScope for temporaries created during M8.
108 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
109 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
110 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
112 /// Note that while the above picture shows the destruction scopes
113 /// as following their corresponding misc extents, in the internal
114 /// data structures of the compiler the destruction scopes are
115 /// represented as enclosing parents. This is sound because we use the
116 /// enclosing parent relationship just to ensure that referenced
117 /// values live long enough; phrased another way, the starting point
118 /// of each range is not really the important thing in the above
119 /// picture, but rather the ending point.
121 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
122 /// placate the same deriving in `ty::FreeRegion`, but we may want to
123 /// actually attach a more meaningful ordering to scopes than the one
124 /// generated via deriving here.
125 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy)]
126 pub enum CodeExtentData {
129 // extent of the call-site for a function or closure (outlives
130 // the parameters as well as the body).
131 CallSiteScope { fn_id: ast::NodeId, body_id: ast::NodeId },
133 // extent of parameters passed to a function or closure (they
135 ParameterScope { fn_id: ast::NodeId, body_id: ast::NodeId },
137 // extent of destructors for temporaries of node-id
138 DestructionScope(ast::NodeId),
140 // extent of code following a `let id = expr;` binding in a block
141 Remainder(BlockRemainder)
144 /// extent of call-site for a function/method.
145 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
146 RustcDecodable, Debug, Copy)]
147 pub struct CallSiteScopeData {
148 pub fn_id: ast::NodeId, pub body_id: ast::NodeId,
151 impl CallSiteScopeData {
152 pub fn to_code_extent(&self, region_maps: &RegionMaps) -> CodeExtent {
153 region_maps.lookup_code_extent(
155 CallSiteScopeData { fn_id, body_id } =>
156 CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body_id },
161 /// Represents a subscope of `block` for a binding that is introduced
162 /// by `block.stmts[first_statement_index]`. Such subscopes represent
163 /// a suffix of the block. Note that each subscope does not include
164 /// the initializer expression, if any, for the statement indexed by
165 /// `first_statement_index`.
167 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
169 /// * the subscope with `first_statement_index == 0` is scope of both
170 /// `a` and `b`; it does not include EXPR_1, but does include
171 /// everything after that first `let`. (If you want a scope that
172 /// includes EXPR_1 as well, then do not use `CodeExtentData::Remainder`,
173 /// but instead another `CodeExtent` that encompasses the whole block,
174 /// e.g. `CodeExtentData::Misc`.
176 /// * the subscope with `first_statement_index == 1` is scope of `c`,
177 /// and thus does not include EXPR_2, but covers the `...`.
178 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
179 RustcDecodable, Debug, Copy)]
180 pub struct BlockRemainder {
181 pub block: ast::NodeId,
182 pub first_statement_index: u32,
185 impl CodeExtentData {
186 /// Returns a node id associated with this scope.
188 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
189 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
190 pub fn node_id(&self) -> ast::NodeId {
192 CodeExtentData::Misc(node_id) => node_id,
194 // These cases all return rough approximations to the
195 // precise extent denoted by `self`.
196 CodeExtentData::Remainder(br) => br.block,
197 CodeExtentData::DestructionScope(node_id) => node_id,
198 CodeExtentData::CallSiteScope { fn_id: _, body_id } |
199 CodeExtentData::ParameterScope { fn_id: _, body_id } => body_id,
206 fn into_option(self) -> Option<CodeExtent> {
207 if self == ROOT_CODE_EXTENT {
213 pub fn node_id(&self, region_maps: &RegionMaps) -> ast::NodeId {
214 region_maps.code_extent_data(*self).node_id()
217 /// Returns the span of this CodeExtent. Note that in general the
218 /// returned span may not correspond to the span of any node id in
220 pub fn span(&self, region_maps: &RegionMaps, ast_map: &ast_map::Map) -> Option<Span> {
221 match ast_map.find(self.node_id(region_maps)) {
222 Some(ast_map::NodeBlock(ref blk)) => {
223 match region_maps.code_extent_data(*self) {
224 CodeExtentData::CallSiteScope { .. } |
225 CodeExtentData::ParameterScope { .. } |
226 CodeExtentData::Misc(_) |
227 CodeExtentData::DestructionScope(_) => Some(blk.span),
229 CodeExtentData::Remainder(r) => {
230 assert_eq!(r.block, blk.id);
231 // Want span for extent starting after the
232 // indexed statement and ending at end of
233 // `blk`; reuse span of `blk` and shift `lo`
234 // forward to end of indexed statement.
236 // (This is the special case aluded to in the
237 // doc-comment for this method)
238 let stmt_span = blk.stmts[r.first_statement_index as usize].span;
239 Some(Span { lo: stmt_span.hi, hi: blk.span.hi, expn_id: stmt_span.expn_id })
243 Some(ast_map::NodeExpr(ref expr)) => Some(expr.span),
244 Some(ast_map::NodeStmt(ref stmt)) => Some(stmt.span),
245 Some(ast_map::NodeItem(ref item)) => Some(item.span),
246 Some(_) | None => None,
251 /// The region maps encode information about region relationships.
252 pub struct RegionMaps {
253 code_extents: RefCell<Vec<CodeExtentData>>,
254 code_extent_interner: RefCell<FnvHashMap<CodeExtentData, CodeExtent>>,
255 /// `scope_map` maps from a scope id to the enclosing scope id;
256 /// this is usually corresponding to the lexical nesting, though
257 /// in the case of closures the parent scope is the innermost
258 /// conditional expression or repeating block. (Note that the
259 /// enclosing scope id for the block associated with a closure is
260 /// the closure itself.)
261 scope_map: RefCell<Vec<CodeExtent>>,
263 /// `var_map` maps from a variable or binding id to the block in
264 /// which that variable is declared.
265 var_map: RefCell<NodeMap<CodeExtent>>,
267 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
268 /// larger than the default. The map goes from the expression id
269 /// to the cleanup scope id. For rvalues not present in this
270 /// table, the appropriate cleanup scope is the innermost
271 /// enclosing statement, conditional expression, or repeating
272 /// block (see `terminating_scopes`).
273 rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
275 /// Encodes the hierarchy of fn bodies. Every fn body (including
276 /// closures) forms its own distinct region hierarchy, rooted in
277 /// the block that is the fn body. This map points from the id of
278 /// that root block to the id of the root block for the enclosing
279 /// fn, if any. Thus the map structures the fn bodies into a
280 /// hierarchy based on their lexical mapping. This is used to
281 /// handle the relationships between regions in a fn and in a
282 /// closure defined by that fn. See the "Modeling closures"
283 /// section of the README in infer::region_inference for
285 fn_tree: RefCell<NodeMap<ast::NodeId>>,
288 #[derive(Debug, Copy, Clone)]
290 /// the root of the current region tree. This is typically the id
291 /// of the innermost fn body. Each fn forms its own disjoint tree
292 /// in the region hierarchy. These fn bodies are themselves
293 /// arranged into a tree. See the "Modeling closures" section of
294 /// the README in infer::region_inference for more
296 root_id: Option<ast::NodeId>,
298 /// the scope that contains any new variables declared
299 var_parent: CodeExtent,
301 /// region parent of expressions etc
305 struct RegionResolutionVisitor<'a> {
309 region_maps: &'a RegionMaps,
313 /// `terminating_scopes` is a set containing the ids of each
314 /// statement, or conditional/repeating expression. These scopes
315 /// are calling "terminating scopes" because, when attempting to
316 /// find the scope of a temporary, by default we search up the
317 /// enclosing scopes until we encounter the terminating scope. A
318 /// conditional/repeating expression is one which is not
319 /// guaranteed to execute exactly once upon entering the parent
320 /// scope. This could be because the expression only executes
321 /// conditionally, such as the expression `b` in `a && b`, or
322 /// because the expression may execute many times, such as a loop
323 /// body. The reason that we distinguish such expressions is that,
324 /// upon exiting the parent scope, we cannot statically know how
325 /// many times the expression executed, and thus if the expression
326 /// creates temporaries we cannot know statically how many such
327 /// temporaries we would have to cleanup. Therefore we ensure that
328 /// the temporaries never outlast the conditional/repeating
329 /// expression, preventing the need for dynamic checks and/or
330 /// arbitrary amounts of stack space. Terminating scopes end
331 /// up being contained in a DestructionScope that contains the
332 /// destructor's execution.
333 terminating_scopes: NodeSet
338 /// create a bogus code extent for the regions in astencode types. Nobody
339 /// really cares about the contents of these.
340 pub fn bogus_code_extent(&self, e: CodeExtentData) -> CodeExtent {
341 self.intern_code_extent(e, DUMMY_CODE_EXTENT)
343 pub fn lookup_code_extent(&self, e: CodeExtentData) -> CodeExtent {
344 match self.code_extent_interner.borrow().get(&e) {
346 None => bug!("unknown code extent {:?}", e)
349 pub fn node_extent(&self, n: ast::NodeId) -> CodeExtent {
350 self.lookup_code_extent(CodeExtentData::Misc(n))
352 // Returns the code extent for an item - the destruction scope.
353 pub fn item_extent(&self, n: ast::NodeId) -> CodeExtent {
354 self.lookup_code_extent(CodeExtentData::DestructionScope(n))
356 pub fn call_site_extent(&self, fn_id: ast::NodeId, body_id: ast::NodeId) -> CodeExtent {
357 assert!(fn_id != body_id);
358 self.lookup_code_extent(CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body_id })
360 pub fn opt_destruction_extent(&self, n: ast::NodeId) -> Option<CodeExtent> {
361 self.code_extent_interner.borrow().get(&CodeExtentData::DestructionScope(n)).cloned()
363 pub fn intern_code_extent(&self,
365 parent: CodeExtent) -> CodeExtent {
366 match self.code_extent_interner.borrow_mut().entry(e) {
367 Entry::Occupied(o) => {
368 // this can happen when the bogus code extents from tydecode
369 // have (bogus) NodeId-s that overlap items created during
371 // We probably shouldn't be creating bogus code extents
374 if parent == DUMMY_CODE_EXTENT {
375 info!("CodeExtent({}) = {:?} [parent={}] BOGUS!",
378 assert_eq!(self.scope_map.borrow()[idx.0 as usize],
380 info!("CodeExtent({}) = {:?} [parent={}] RECLAIMED!",
382 self.scope_map.borrow_mut()[idx.0 as usize] = parent;
386 Entry::Vacant(v) => {
387 if self.code_extents.borrow().len() > 0xffffffffusize {
388 bug!() // should pass a sess,
389 // but this isn't the only place
391 let idx = CodeExtent(self.code_extents.borrow().len() as u32);
392 debug!("CodeExtent({}) = {:?} [parent={}]", idx.0, e, parent.0);
393 self.code_extents.borrow_mut().push(e);
394 self.scope_map.borrow_mut().push(parent);
399 pub fn intern_node(&self,
401 parent: CodeExtent) -> CodeExtent {
402 self.intern_code_extent(CodeExtentData::Misc(n), parent)
404 pub fn code_extent_data(&self, e: CodeExtent) -> CodeExtentData {
405 self.code_extents.borrow()[e.0 as usize]
407 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(&CodeExtent, &CodeExtent) {
408 for child_id in 1..self.code_extents.borrow().len() {
409 let child = CodeExtent(child_id as u32);
410 if let Some(parent) = self.opt_encl_scope(child) {
415 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
416 for (child, parent) in self.var_map.borrow().iter() {
420 pub fn each_rvalue_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, &CodeExtent) {
421 for (child, parent) in self.rvalue_scopes.borrow().iter() {
425 /// Records that `sub_fn` is defined within `sup_fn`. These ids
426 /// should be the id of the block that is the fn body, which is
427 /// also the root of the region hierarchy for that fn.
428 fn record_fn_parent(&self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
429 debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
430 assert!(sub_fn != sup_fn);
431 let previous = self.fn_tree.borrow_mut().insert(sub_fn, sup_fn);
432 assert!(previous.is_none());
435 fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
436 let fn_tree = self.fn_tree.borrow();
438 if sub_fn == sup_fn { return true; }
439 match fn_tree.get(&sub_fn) {
440 Some(&s) => { sub_fn = s; }
441 None => { return false; }
446 fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
447 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
448 assert!(var != lifetime.node_id(self));
449 self.var_map.borrow_mut().insert(var, lifetime);
452 fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
453 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
454 assert!(var != lifetime.node_id(self));
455 self.rvalue_scopes.borrow_mut().insert(var, lifetime);
458 pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
459 //! Returns the narrowest scope that encloses `id`, if any.
460 self.scope_map.borrow()[id.0 as usize].into_option()
463 #[allow(dead_code)] // used in cfg
464 pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
465 //! Returns the narrowest scope that encloses `id`, if any.
466 self.opt_encl_scope(id).unwrap()
469 /// Returns the lifetime of the local variable `var_id`
470 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
471 match self.var_map.borrow().get(&var_id) {
473 None => { bug!("no enclosing scope for id {:?}", var_id); }
477 pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
478 //! Returns the scope when temp created by expr_id will be cleaned up
480 // check for a designated rvalue scope
481 match self.rvalue_scopes.borrow().get(&expr_id) {
483 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
489 let scope_map : &[CodeExtent] = &self.scope_map.borrow();
490 let code_extents: &[CodeExtentData] = &self.code_extents.borrow();
492 // else, locate the innermost terminating scope
493 // if there's one. Static items, for instance, won't
494 // have an enclosing scope, hence no scope will be
496 let expr_extent = self.node_extent(expr_id);
497 // For some reason, the expr's scope itself is skipped here.
498 let mut id = match scope_map[expr_extent.0 as usize].into_option() {
503 while let Some(p) = scope_map[id.0 as usize].into_option() {
504 match code_extents[p.0 as usize] {
505 CodeExtentData::DestructionScope(..) => {
506 debug!("temporary_scope({:?}) = {:?} [enclosing]",
514 debug!("temporary_scope({:?}) = None", expr_id);
518 pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
519 //! Returns the lifetime of the variable `id`.
521 let scope = ty::ReScope(self.var_scope(id));
522 debug!("var_region({:?}) = {:?}", id, scope);
526 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
528 self.is_subscope_of(scope1, scope2) ||
529 self.is_subscope_of(scope2, scope1)
532 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
534 pub fn is_subscope_of(&self,
535 subscope: CodeExtent,
536 superscope: CodeExtent)
538 let mut s = subscope;
539 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
540 while superscope != s {
541 match self.opt_encl_scope(s) {
543 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
544 subscope, superscope, s);
547 Some(scope) => s = scope
551 debug!("is_subscope_of({:?}, {:?})=true",
552 subscope, superscope);
557 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
558 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
559 pub fn nearest_common_ancestor(&self,
563 if scope_a == scope_b { return scope_a; }
565 let mut a_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
566 let mut a_vec: Vec<CodeExtent> = vec![];
567 let mut b_buf: [CodeExtent; 32] = [ROOT_CODE_EXTENT; 32];
568 let mut b_vec: Vec<CodeExtent> = vec![];
569 let scope_map : &[CodeExtent] = &self.scope_map.borrow();
570 let a_ancestors = ancestors_of(scope_map,
571 scope_a, &mut a_buf, &mut a_vec);
572 let b_ancestors = ancestors_of(scope_map,
573 scope_b, &mut b_buf, &mut b_vec);
574 let mut a_index = a_ancestors.len() - 1;
575 let mut b_index = b_ancestors.len() - 1;
577 // Here, [ab]_ancestors is a vector going from narrow to broad.
578 // The end of each vector will be the item where the scope is
579 // defined; if there are any common ancestors, then the tails of
580 // the vector will be the same. So basically we want to walk
581 // backwards from the tail of each vector and find the first point
582 // where they diverge. If one vector is a suffix of the other,
583 // then the corresponding scope is a superscope of the other.
585 if a_ancestors[a_index] != b_ancestors[b_index] {
586 // In this case, the two regions belong to completely
587 // different functions. Compare those fn for lexical
588 // nesting. The reasoning behind this is subtle. See the
589 // "Modeling closures" section of the README in
590 // infer::region_inference for more details.
591 let a_root_scope = self.code_extent_data(a_ancestors[a_index]);
592 let b_root_scope = self.code_extent_data(a_ancestors[a_index]);
593 return match (a_root_scope, b_root_scope) {
594 (CodeExtentData::DestructionScope(a_root_id),
595 CodeExtentData::DestructionScope(b_root_id)) => {
596 if self.fn_is_enclosed_by(a_root_id, b_root_id) {
597 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
599 } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
600 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
603 // neither fn encloses the other
608 // root ids are always Misc right now
615 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
616 // for all indices between a_index and the end of the array
617 if a_index == 0 { return scope_a; }
618 if b_index == 0 { return scope_b; }
621 if a_ancestors[a_index] != b_ancestors[b_index] {
622 return a_ancestors[a_index + 1];
626 fn ancestors_of<'a>(scope_map: &[CodeExtent],
628 buf: &'a mut [CodeExtent; 32],
629 vec: &'a mut Vec<CodeExtent>) -> &'a [CodeExtent] {
630 // debug!("ancestors_of(scope={:?})", scope);
631 let mut scope = scope;
636 match scope_map[scope.0 as usize].into_option() {
637 Some(superscope) => scope = superscope,
638 _ => return &buf[..i+1]
643 *vec = Vec::with_capacity(64);
644 vec.extend_from_slice(buf);
647 match scope_map[scope.0 as usize].into_option() {
648 Some(superscope) => scope = superscope,
656 /// Records the lifetime of a local variable as `cx.var_parent`
657 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
660 match visitor.cx.var_parent {
661 ROOT_CODE_EXTENT => {
662 // this can happen in extern fn declarations like
664 // extern fn isalnum(c: c_int) -> c_int
667 visitor.region_maps.record_var_scope(var_id, parent_scope),
671 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &hir::Block) {
672 debug!("resolve_block(blk.id={:?})", blk.id);
674 let prev_cx = visitor.cx;
675 let block_extent = visitor.new_node_extent_with_dtor(blk.id);
677 // We treat the tail expression in the block (if any) somewhat
678 // differently from the statements. The issue has to do with
679 // temporary lifetimes. Consider the following:
682 // let inner = ... (&bar()) ...;
684 // (... (&foo()) ...) // (the tail expression)
685 // }, other_argument());
687 // Each of the statements within the block is a terminating
688 // scope, and thus a temporary (e.g. the result of calling
689 // `bar()` in the initalizer expression for `let inner = ...;`)
690 // will be cleaned up immediately after its corresponding
691 // statement (i.e. `let inner = ...;`) executes.
693 // On the other hand, temporaries associated with evaluating the
694 // tail expression for the block are assigned lifetimes so that
695 // they will be cleaned up as part of the terminating scope
696 // *surrounding* the block expression. Here, the terminating
697 // scope for the block expression is the `quux(..)` call; so
698 // those temporaries will only be cleaned up *after* both
699 // `other_argument()` has run and also the call to `quux(..)`
700 // itself has returned.
702 visitor.cx = Context {
703 root_id: prev_cx.root_id,
704 var_parent: block_extent,
705 parent: block_extent,
709 // This block should be kept approximately in sync with
710 // `intravisit::walk_block`. (We manually walk the block, rather
711 // than call `walk_block`, in order to maintain precise
712 // index information.)
714 for (i, statement) in blk.stmts.iter().enumerate() {
715 if let hir::StmtDecl(..) = statement.node {
716 // Each StmtDecl introduces a subscope for bindings
717 // introduced by the declaration; this subscope covers
718 // a suffix of the block . Each subscope in a block
719 // has the previous subscope in the block as a parent,
720 // except for the first such subscope, which has the
721 // block itself as a parent.
722 let stmt_extent = visitor.new_code_extent(
723 CodeExtentData::Remainder(BlockRemainder {
725 first_statement_index: i as u32
728 visitor.cx = Context {
729 root_id: prev_cx.root_id,
730 var_parent: stmt_extent,
734 visitor.visit_stmt(statement)
736 walk_list!(visitor, visit_expr, &blk.expr);
739 visitor.cx = prev_cx;
742 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &hir::Arm) {
743 visitor.terminating_scopes.insert(arm.body.id);
745 if let Some(ref expr) = arm.guard {
746 visitor.terminating_scopes.insert(expr.id);
749 intravisit::walk_arm(visitor, arm);
752 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &hir::Pat) {
753 visitor.new_node_extent(pat.id);
755 // If this is a binding then record the lifetime of that binding.
756 if let PatKind::Binding(..) = pat.node {
757 record_var_lifetime(visitor, pat.id, pat.span);
760 intravisit::walk_pat(visitor, pat);
763 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &hir::Stmt) {
764 let stmt_id = stmt.node.id();
765 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
767 // Every statement will clean up the temporaries created during
768 // execution of that statement. Therefore each statement has an
769 // associated destruction scope that represents the extent of the
770 // statement plus its destructors, and thus the extent for which
771 // regions referenced by the destructors need to survive.
772 visitor.terminating_scopes.insert(stmt_id);
773 let stmt_extent = visitor.new_node_extent_with_dtor(stmt_id);
775 let prev_parent = visitor.cx.parent;
776 visitor.cx.parent = stmt_extent;
777 intravisit::walk_stmt(visitor, stmt);
778 visitor.cx.parent = prev_parent;
781 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &hir::Expr) {
782 debug!("resolve_expr(expr.id={:?})", expr.id);
784 let expr_extent = visitor.new_node_extent_with_dtor(expr.id);
785 let prev_cx = visitor.cx;
786 visitor.cx.parent = expr_extent;
789 let terminating_scopes = &mut visitor.terminating_scopes;
790 let mut terminating = |id: ast::NodeId| {
791 terminating_scopes.insert(id);
794 // Conditional or repeating scopes are always terminating
795 // scopes, meaning that temporaries cannot outlive them.
796 // This ensures fixed size stacks.
798 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
799 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
800 // For shortcircuiting operators, mark the RHS as a terminating
801 // scope since it only executes conditionally.
805 hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
806 terminating(expr.id);
807 terminating(then.id);
808 terminating(otherwise.id);
811 hir::ExprIf(ref expr, ref then, None) => {
812 terminating(expr.id);
813 terminating(then.id);
816 hir::ExprLoop(ref body, _) => {
817 terminating(body.id);
820 hir::ExprWhile(ref expr, ref body, _) => {
821 terminating(expr.id);
822 terminating(body.id);
825 hir::ExprMatch(..) => {
826 visitor.cx.var_parent = expr_extent;
829 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
830 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
831 // FIXME(#6268) Nested method calls
833 // The lifetimes for a call or method call look as follows:
841 // The idea is that call.callee_id represents *the time when
842 // the invoked function is actually running* and call.id
843 // represents *the time to prepare the arguments and make the
844 // call*. See the section "Borrows in Calls" borrowck/README.md
845 // for an extended explanation of why this distinction is
848 // record_superlifetime(new_cx, expr.callee_id);
855 intravisit::walk_expr(visitor, expr);
856 visitor.cx = prev_cx;
859 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &hir::Local) {
860 debug!("resolve_local(local.id={:?},local.init={:?})",
861 local.id,local.init.is_some());
863 // For convenience in trans, associate with the local-id the var
864 // scope that will be used for any bindings declared in this
866 let blk_scope = visitor.cx.var_parent;
867 assert!(blk_scope != ROOT_CODE_EXTENT); // locals must be within a block
868 visitor.region_maps.record_var_scope(local.id, blk_scope);
870 // As an exception to the normal rules governing temporary
871 // lifetimes, initializers in a let have a temporary lifetime
872 // of the enclosing block. This means that e.g. a program
873 // like the following is legal:
875 // let ref x = HashMap::new();
877 // Because the hash map will be freed in the enclosing block.
879 // We express the rules more formally based on 3 grammars (defined
880 // fully in the helpers below that implement them):
882 // 1. `E&`, which matches expressions like `&<rvalue>` that
883 // own a pointer into the stack.
885 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
886 // y)` that produce ref bindings into the value they are
887 // matched against or something (at least partially) owned by
888 // the value they are matched against. (By partially owned,
889 // I mean that creating a binding into a ref-counted or managed value
890 // would still count.)
892 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
893 // based on rvalues like `foo().x[2].y`.
895 // A subexpression `<rvalue>` that appears in a let initializer
896 // `let pat [: ty] = expr` has an extended temporary lifetime if
897 // any of the following conditions are met:
899 // A. `pat` matches `P&` and `expr` matches `ET`
900 // (covers cases where `pat` creates ref bindings into an rvalue
901 // produced by `expr`)
902 // B. `ty` is a borrowed pointer and `expr` matches `ET`
903 // (covers cases where coercion creates a borrow)
904 // C. `expr` matches `E&`
905 // (covers cases `expr` borrows an rvalue that is then assigned
906 // to memory (at least partially) owned by the binding)
908 // Here are some examples hopefully giving an intuition where each
909 // rule comes into play and why:
911 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
912 // would have an extended lifetime, but not `foo()`.
914 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
915 // would have an extended lifetime, but not `foo()`.
917 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
920 // In some cases, multiple rules may apply (though not to the same
921 // rvalue). For example:
923 // let ref x = [&a(), &b()];
925 // Here, the expression `[...]` has an extended lifetime due to rule
926 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
929 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
933 record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
936 if let Some(ref ty) = local.ty { is_borrowed_ty(&ty) } else { false };
938 if is_binding_pat(&local.pat) || is_borrow {
939 record_rvalue_scope(visitor, &expr, blk_scope);
946 intravisit::walk_local(visitor, local);
948 /// True if `pat` match the `P&` nonterminal:
951 /// | StructName { ..., P&, ... }
952 /// | VariantName(..., P&, ...)
953 /// | [ ..., P&, ... ]
954 /// | ( ..., P&, ... )
956 fn is_binding_pat(pat: &hir::Pat) -> bool {
958 PatKind::Binding(hir::BindByRef(_), ..) => true,
960 PatKind::Struct(_, ref field_pats, _) => {
961 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
964 PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
965 pats1.iter().any(|p| is_binding_pat(&p)) ||
966 pats2.iter().any(|p| is_binding_pat(&p)) ||
967 pats3.iter().any(|p| is_binding_pat(&p))
970 PatKind::TupleStruct(_, ref subpats, _) |
971 PatKind::Tuple(ref subpats, _) => {
972 subpats.iter().any(|p| is_binding_pat(&p))
975 PatKind::Box(ref subpat) => {
976 is_binding_pat(&subpat)
983 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
984 fn is_borrowed_ty(ty: &hir::Ty) -> bool {
986 hir::TyRptr(..) => true,
991 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
994 /// | StructName { ..., f: E&, ... }
995 /// | [ ..., E&, ... ]
996 /// | ( ..., E&, ... )
1001 fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
1003 blk_id: CodeExtent) {
1005 hir::ExprAddrOf(_, ref subexpr) => {
1006 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1007 record_rvalue_scope(visitor, &subexpr, blk_id);
1009 hir::ExprStruct(_, ref fields, _) => {
1010 for field in fields {
1011 record_rvalue_scope_if_borrow_expr(
1012 visitor, &field.expr, blk_id);
1015 hir::ExprArray(ref subexprs) |
1016 hir::ExprTup(ref subexprs) => {
1017 for subexpr in subexprs {
1018 record_rvalue_scope_if_borrow_expr(
1019 visitor, &subexpr, blk_id);
1022 hir::ExprCast(ref subexpr, _) => {
1023 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1025 hir::ExprBlock(ref block) => {
1027 Some(ref subexpr) => {
1028 record_rvalue_scope_if_borrow_expr(
1029 visitor, &subexpr, blk_id);
1039 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1040 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1041 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1044 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1045 /// `<rvalue>` as `blk_id`:
1053 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1054 fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
1055 expr: &'a hir::Expr,
1056 blk_scope: CodeExtent) {
1057 let mut expr = expr;
1059 // Note: give all the expressions matching `ET` with the
1060 // extended temporary lifetime, not just the innermost rvalue,
1061 // because in trans if we must compile e.g. `*rvalue()`
1062 // into a temporary, we request the temporary scope of the
1063 // outer expression.
1064 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1067 hir::ExprAddrOf(_, ref subexpr) |
1068 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1069 hir::ExprField(ref subexpr, _) |
1070 hir::ExprTupField(ref subexpr, _) |
1071 hir::ExprIndex(ref subexpr, _) => {
1082 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &hir::Item) {
1083 // Items create a new outer block scope as far as we're concerned.
1084 let prev_cx = visitor.cx;
1085 let prev_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1086 visitor.cx = Context {
1088 var_parent: ROOT_CODE_EXTENT,
1089 parent: ROOT_CODE_EXTENT
1091 intravisit::walk_item(visitor, item);
1092 visitor.create_item_scope_if_needed(item.id);
1093 visitor.cx = prev_cx;
1094 visitor.terminating_scopes = prev_ts;
1097 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
1103 debug!("region::resolve_fn(id={:?}, \
1108 visitor.sess.codemap().span_to_string(sp),
1112 visitor.cx.parent = visitor.new_code_extent(
1113 CodeExtentData::CallSiteScope { fn_id: id, body_id: body.id });
1115 let fn_decl_scope = visitor.new_code_extent(
1116 CodeExtentData::ParameterScope { fn_id: id, body_id: body.id });
1118 if let Some(root_id) = visitor.cx.root_id {
1119 visitor.region_maps.record_fn_parent(body.id, root_id);
1122 let outer_cx = visitor.cx;
1123 let outer_ts = mem::replace(&mut visitor.terminating_scopes, NodeSet());
1124 visitor.terminating_scopes.insert(body.id);
1126 // The arguments and `self` are parented to the fn.
1127 visitor.cx = Context {
1128 root_id: Some(body.id),
1129 parent: ROOT_CODE_EXTENT,
1130 var_parent: fn_decl_scope,
1133 intravisit::walk_fn_decl(visitor, decl);
1134 intravisit::walk_fn_kind(visitor, kind);
1136 // The body of the every fn is a root scope.
1137 visitor.cx = Context {
1138 root_id: Some(body.id),
1139 parent: fn_decl_scope,
1140 var_parent: fn_decl_scope
1142 visitor.visit_block(body);
1144 // Restore context we had at the start.
1145 visitor.cx = outer_cx;
1146 visitor.terminating_scopes = outer_ts;
1149 impl<'a> RegionResolutionVisitor<'a> {
1150 /// Records the current parent (if any) as the parent of `child_scope`.
1151 fn new_code_extent(&mut self, child_scope: CodeExtentData) -> CodeExtent {
1152 self.region_maps.intern_code_extent(child_scope, self.cx.parent)
1155 fn new_node_extent(&mut self, child_scope: ast::NodeId) -> CodeExtent {
1156 self.new_code_extent(CodeExtentData::Misc(child_scope))
1159 fn new_node_extent_with_dtor(&mut self, id: ast::NodeId) -> CodeExtent {
1160 // If node was previously marked as a terminating scope during the
1161 // recursive visit of its parent node in the AST, then we need to
1162 // account for the destruction scope representing the extent of
1163 // the destructors that run immediately after it completes.
1164 if self.terminating_scopes.contains(&id) {
1165 let ds = self.new_code_extent(
1166 CodeExtentData::DestructionScope(id));
1167 self.region_maps.intern_node(id, ds)
1169 self.new_node_extent(id)
1173 fn create_item_scope_if_needed(&mut self, id: ast::NodeId) {
1174 // create a region for the destruction scope - this is needed
1175 // for constructing parameter environments based on the item.
1176 // functions put their destruction scopes *inside* their parameter
1178 let scope = CodeExtentData::DestructionScope(id);
1179 if !self.region_maps.code_extent_interner.borrow().contains_key(&scope) {
1180 self.region_maps.intern_code_extent(scope, ROOT_CODE_EXTENT);
1185 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
1186 fn visit_block(&mut self, b: &Block) {
1187 resolve_block(self, b);
1190 fn visit_item(&mut self, i: &Item) {
1191 resolve_item(self, i);
1194 fn visit_impl_item(&mut self, ii: &hir::ImplItem) {
1195 intravisit::walk_impl_item(self, ii);
1196 self.create_item_scope_if_needed(ii.id);
1199 fn visit_trait_item(&mut self, ti: &hir::TraitItem) {
1200 intravisit::walk_trait_item(self, ti);
1201 self.create_item_scope_if_needed(ti.id);
1204 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
1205 b: &'v Block, s: Span, n: NodeId) {
1206 resolve_fn(self, fk, fd, b, s, n);
1208 fn visit_arm(&mut self, a: &Arm) {
1209 resolve_arm(self, a);
1211 fn visit_pat(&mut self, p: &Pat) {
1212 resolve_pat(self, p);
1214 fn visit_stmt(&mut self, s: &Stmt) {
1215 resolve_stmt(self, s);
1217 fn visit_expr(&mut self, ex: &Expr) {
1218 resolve_expr(self, ex);
1220 fn visit_local(&mut self, l: &Local) {
1221 resolve_local(self, l);
1225 pub fn resolve_crate(sess: &Session, map: &ast_map::Map) -> RegionMaps {
1226 let _task = map.dep_graph.in_task(DepNode::RegionResolveCrate);
1227 let krate = map.krate();
1229 let maps = RegionMaps {
1230 code_extents: RefCell::new(vec![]),
1231 code_extent_interner: RefCell::new(FnvHashMap()),
1232 scope_map: RefCell::new(vec![]),
1233 var_map: RefCell::new(NodeMap()),
1234 rvalue_scopes: RefCell::new(NodeMap()),
1235 fn_tree: RefCell::new(NodeMap()),
1237 let root_extent = maps.bogus_code_extent(
1238 CodeExtentData::DestructionScope(ast::DUMMY_NODE_ID));
1239 assert_eq!(root_extent, ROOT_CODE_EXTENT);
1240 let bogus_extent = maps.bogus_code_extent(
1241 CodeExtentData::Misc(ast::DUMMY_NODE_ID));
1242 assert_eq!(bogus_extent, DUMMY_CODE_EXTENT);
1244 let mut visitor = RegionResolutionVisitor {
1249 parent: ROOT_CODE_EXTENT,
1250 var_parent: ROOT_CODE_EXTENT
1252 terminating_scopes: NodeSet()
1254 krate.visit_all_items(&mut visitor);