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 hir::map as hir_map;
20 use util::nodemap::{FxHashMap, NodeMap, NodeSet};
30 use ty::maps::Providers;
33 use hir::def_id::DefId;
34 use hir::intravisit::{self, Visitor, NestedVisitorMap};
35 use hir::{Block, Arm, Pat, PatKind, Stmt, Expr, Local};
36 use mir::transform::MirSource;
38 pub type CodeExtent<'tcx> = &'tcx CodeExtentData;
40 impl<'tcx> serialize::UseSpecializedEncodable for CodeExtent<'tcx> {}
41 impl<'tcx> serialize::UseSpecializedDecodable for CodeExtent<'tcx> {}
43 /// CodeExtent represents a statically-describable extent that can be
44 /// used to bound the lifetime/region for values.
46 /// `Misc(node_id)`: Any AST node that has any extent at all has the
47 /// `Misc(node_id)` extent. Other variants represent special cases not
48 /// immediately derivable from the abstract syntax tree structure.
50 /// `DestructionScope(node_id)` represents the extent of destructors
51 /// implicitly-attached to `node_id` that run immediately after the
52 /// expression for `node_id` itself. Not every AST node carries a
53 /// `DestructionScope`, but those that are `terminating_scopes` do;
54 /// see discussion with `RegionMaps`.
56 /// `Remainder(BlockRemainder { block, statement_index })` represents
57 /// the extent of user code running immediately after the initializer
58 /// expression for the indexed statement, until the end of the block.
60 /// So: the following code can be broken down into the extents beneath:
62 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
67 /// +---------+ (R10.)
69 /// +----------+ (M8.)
70 /// +----------------------+ (R7.)
72 /// +----------+ (M5.)
73 /// +-----------------------------------+ (M4.)
74 /// +--------------------------------------------------+ (M3.)
76 /// +-----------------------------------------------------------+ (M1.)
78 /// (M1.): Misc extent of the whole `let a = ...;` statement.
79 /// (M2.): Misc extent of the `f()` expression.
80 /// (M3.): Misc extent of the `f().g(..)` expression.
81 /// (M4.): Misc extent of the block labelled `'b:`.
82 /// (M5.): Misc extent of the `let x = d();` statement
83 /// (D6.): DestructionScope for temporaries created during M5.
84 /// (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
85 /// (M8.): Misc Extent of the `let y = d();` statement.
86 /// (D9.): DestructionScope for temporaries created during M8.
87 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
88 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
89 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
91 /// Note that while the above picture shows the destruction scopes
92 /// as following their corresponding misc extents, in the internal
93 /// data structures of the compiler the destruction scopes are
94 /// represented as enclosing parents. This is sound because we use the
95 /// enclosing parent relationship just to ensure that referenced
96 /// values live long enough; phrased another way, the starting point
97 /// of each range is not really the important thing in the above
98 /// picture, but rather the ending point.
100 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
101 /// placate the same deriving in `ty::FreeRegion`, but we may want to
102 /// actually attach a more meaningful ordering to scopes than the one
103 /// generated via deriving here.
104 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, RustcEncodable, RustcDecodable)]
105 pub enum CodeExtentData {
108 // extent of the call-site for a function or closure (outlives
109 // the parameters as well as the body).
110 CallSiteScope { fn_id: ast::NodeId, body_id: ast::NodeId },
112 // extent of parameters passed to a function or closure (they
114 ParameterScope { fn_id: ast::NodeId, body_id: ast::NodeId },
116 // extent of destructors for temporaries of node-id
117 DestructionScope(ast::NodeId),
119 // extent of code following a `let id = expr;` binding in a block
120 Remainder(BlockRemainder)
123 /// extent of call-site for a function/method.
124 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
125 RustcDecodable, Debug, Copy)]
126 pub struct CallSiteScopeData {
127 pub fn_id: ast::NodeId, pub body_id: ast::NodeId,
130 impl CallSiteScopeData {
131 pub fn to_code_extent<'a, 'tcx, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> CodeExtent<'tcx> {
132 tcx.intern_code_extent(
134 CallSiteScopeData { fn_id, body_id } =>
135 CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body_id },
140 /// Represents a subscope of `block` for a binding that is introduced
141 /// by `block.stmts[first_statement_index]`. Such subscopes represent
142 /// a suffix of the block. Note that each subscope does not include
143 /// the initializer expression, if any, for the statement indexed by
144 /// `first_statement_index`.
146 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
148 /// * the subscope with `first_statement_index == 0` is scope of both
149 /// `a` and `b`; it does not include EXPR_1, but does include
150 /// everything after that first `let`. (If you want a scope that
151 /// includes EXPR_1 as well, then do not use `CodeExtentData::Remainder`,
152 /// but instead another `CodeExtent` that encompasses the whole block,
153 /// e.g. `CodeExtentData::Misc`.
155 /// * the subscope with `first_statement_index == 1` is scope of `c`,
156 /// and thus does not include EXPR_2, but covers the `...`.
157 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
158 RustcDecodable, Debug, Copy)]
159 pub struct BlockRemainder {
160 pub block: ast::NodeId,
161 pub first_statement_index: u32,
164 impl CodeExtentData {
165 /// Returns a node id associated with this scope.
167 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
168 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
169 pub fn node_id(&self) -> ast::NodeId {
171 CodeExtentData::Misc(node_id) => node_id,
173 // These cases all return rough approximations to the
174 // precise extent denoted by `self`.
175 CodeExtentData::Remainder(br) => br.block,
176 CodeExtentData::DestructionScope(node_id) => node_id,
177 CodeExtentData::CallSiteScope { fn_id: _, body_id } |
178 CodeExtentData::ParameterScope { fn_id: _, body_id } => body_id,
182 /// Returns the span of this CodeExtent. Note that in general the
183 /// returned span may not correspond to the span of any node id in
185 pub fn span(&self, hir_map: &hir_map::Map) -> Option<Span> {
186 match hir_map.find(self.node_id()) {
187 Some(hir_map::NodeBlock(ref blk)) => {
189 CodeExtentData::CallSiteScope { .. } |
190 CodeExtentData::ParameterScope { .. } |
191 CodeExtentData::Misc(_) |
192 CodeExtentData::DestructionScope(_) => Some(blk.span),
194 CodeExtentData::Remainder(r) => {
195 assert_eq!(r.block, blk.id);
196 // Want span for extent starting after the
197 // indexed statement and ending at end of
198 // `blk`; reuse span of `blk` and shift `lo`
199 // forward to end of indexed statement.
201 // (This is the special case aluded to in the
202 // doc-comment for this method)
203 let stmt_span = blk.stmts[r.first_statement_index as usize].span;
204 Some(Span { lo: stmt_span.hi, hi: blk.span.hi, ctxt: stmt_span.ctxt })
208 Some(hir_map::NodeExpr(ref expr)) => Some(expr.span),
209 Some(hir_map::NodeStmt(ref stmt)) => Some(stmt.span),
210 Some(hir_map::NodeItem(ref item)) => Some(item.span),
211 Some(_) | None => None,
216 /// The region maps encode information about region relationships.
217 pub struct RegionMaps<'tcx> {
218 /// `scope_map` maps from a scope id to the enclosing scope id;
219 /// this is usually corresponding to the lexical nesting, though
220 /// in the case of closures the parent scope is the innermost
221 /// conditional expression or repeating block. (Note that the
222 /// enclosing scope id for the block associated with a closure is
223 /// the closure itself.)
224 scope_map: FxHashMap<CodeExtent<'tcx>, CodeExtent<'tcx>>,
226 /// `var_map` maps from a variable or binding id to the block in
227 /// which that variable is declared.
228 var_map: NodeMap<CodeExtent<'tcx>>,
230 /// maps from a node-id to the associated destruction scope (if any)
231 destruction_scopes: NodeMap<CodeExtent<'tcx>>,
233 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
234 /// larger than the default. The map goes from the expression id
235 /// to the cleanup scope id. For rvalues not present in this
236 /// table, the appropriate cleanup scope is the innermost
237 /// enclosing statement, conditional expression, or repeating
238 /// block (see `terminating_scopes`).
239 rvalue_scopes: NodeMap<CodeExtent<'tcx>>,
241 /// Records the value of rvalue scopes before they were shrunk by
242 /// #36082, for error reporting.
244 /// FIXME: this should be temporary. Remove this by 1.18.0 or
246 shrunk_rvalue_scopes: NodeMap<CodeExtent<'tcx>>,
248 /// Encodes the hierarchy of fn bodies. Every fn body (including
249 /// closures) forms its own distinct region hierarchy, rooted in
250 /// the block that is the fn body. This map points from the id of
251 /// that root block to the id of the root block for the enclosing
252 /// fn, if any. Thus the map structures the fn bodies into a
253 /// hierarchy based on their lexical mapping. This is used to
254 /// handle the relationships between regions in a fn and in a
255 /// closure defined by that fn. See the "Modeling closures"
256 /// section of the README in infer::region_inference for
258 fn_tree: NodeMap<ast::NodeId>,
261 #[derive(Debug, Copy, Clone)]
262 pub struct Context<'tcx> {
263 /// the root of the current region tree. This is typically the id
264 /// of the innermost fn body. Each fn forms its own disjoint tree
265 /// in the region hierarchy. These fn bodies are themselves
266 /// arranged into a tree. See the "Modeling closures" section of
267 /// the README in infer::region_inference for more
269 root_id: Option<ast::NodeId>,
271 /// the scope that contains any new variables declared
272 var_parent: Option<CodeExtent<'tcx>>,
274 /// region parent of expressions etc
275 parent: Option<CodeExtent<'tcx>>,
278 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
279 tcx: TyCtxt<'a, 'tcx, 'tcx>,
282 region_maps: &'a mut RegionMaps<'tcx>,
286 map: &'a hir_map::Map<'tcx>,
288 /// `terminating_scopes` is a set containing the ids of each
289 /// statement, or conditional/repeating expression. These scopes
290 /// are calling "terminating scopes" because, when attempting to
291 /// find the scope of a temporary, by default we search up the
292 /// enclosing scopes until we encounter the terminating scope. A
293 /// conditional/repeating expression is one which is not
294 /// guaranteed to execute exactly once upon entering the parent
295 /// scope. This could be because the expression only executes
296 /// conditionally, such as the expression `b` in `a && b`, or
297 /// because the expression may execute many times, such as a loop
298 /// body. The reason that we distinguish such expressions is that,
299 /// upon exiting the parent scope, we cannot statically know how
300 /// many times the expression executed, and thus if the expression
301 /// creates temporaries we cannot know statically how many such
302 /// temporaries we would have to cleanup. Therefore we ensure that
303 /// the temporaries never outlast the conditional/repeating
304 /// expression, preventing the need for dynamic checks and/or
305 /// arbitrary amounts of stack space. Terminating scopes end
306 /// up being contained in a DestructionScope that contains the
307 /// destructor's execution.
308 terminating_scopes: NodeSet,
312 impl<'tcx> RegionMaps<'tcx> {
313 pub fn new() -> Self {
315 scope_map: FxHashMap(),
316 destruction_scopes: FxHashMap(),
318 rvalue_scopes: NodeMap(),
319 shrunk_rvalue_scopes: NodeMap(),
324 pub fn record_code_extent(&mut self,
325 child: CodeExtent<'tcx>,
326 parent: Option<CodeExtent<'tcx>>) {
327 debug!("{:?}.parent = {:?}", child, parent);
329 if let Some(p) = parent {
330 let prev = self.scope_map.insert(child, p);
331 assert!(prev.is_none());
334 // record the destruction scopes for later so we can query them
335 if let &CodeExtentData::DestructionScope(n) = child {
336 self.destruction_scopes.insert(n, child);
340 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(CodeExtent<'tcx>, CodeExtent<'tcx>) {
341 for (&child, &parent) in &self.scope_map {
346 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, CodeExtent<'tcx>) {
347 for (child, parent) in self.var_map.iter() {
352 pub fn opt_destruction_extent(&self, n: ast::NodeId) -> Option<CodeExtent<'tcx>> {
353 self.destruction_scopes.get(&n).cloned()
356 /// Records that `sub_fn` is defined within `sup_fn`. These ids
357 /// should be the id of the block that is the fn body, which is
358 /// also the root of the region hierarchy for that fn.
359 fn record_fn_parent(&mut self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
360 debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
361 assert!(sub_fn != sup_fn);
362 let previous = self.fn_tree.insert(sub_fn, sup_fn);
363 assert!(previous.is_none());
366 fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
368 if sub_fn == sup_fn { return true; }
369 match self.fn_tree.get(&sub_fn) {
370 Some(&s) => { sub_fn = s; }
371 None => { return false; }
376 fn record_var_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent<'tcx>) {
377 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
378 assert!(var != lifetime.node_id());
379 self.var_map.insert(var, lifetime);
382 fn record_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent<'tcx>) {
383 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
384 assert!(var != lifetime.node_id());
385 self.rvalue_scopes.insert(var, lifetime);
388 fn record_shrunk_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent<'tcx>) {
389 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
390 assert!(var != lifetime.node_id());
391 self.shrunk_rvalue_scopes.insert(var, lifetime);
394 pub fn opt_encl_scope(&self, id: CodeExtent<'tcx>) -> Option<CodeExtent<'tcx>> {
395 //! Returns the narrowest scope that encloses `id`, if any.
396 self.scope_map.get(&id).cloned()
399 #[allow(dead_code)] // used in cfg
400 pub fn encl_scope(&self, id: CodeExtent<'tcx>) -> CodeExtent<'tcx> {
401 //! Returns the narrowest scope that encloses `id`, if any.
402 self.opt_encl_scope(id).unwrap()
405 /// Returns the lifetime of the local variable `var_id`
406 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent<'tcx> {
407 match self.var_map.get(&var_id) {
409 None => { bug!("no enclosing scope for id {:?}", var_id); }
413 pub fn temporary_scope2<'a, 'gcx: 'tcx>(&self,
414 tcx: TyCtxt<'a, 'gcx, 'tcx>,
415 expr_id: ast::NodeId)
416 -> (Option<CodeExtent<'tcx>>, bool) {
417 let temporary_scope = self.temporary_scope(tcx, expr_id);
418 let was_shrunk = match self.shrunk_rvalue_scopes.get(&expr_id) {
420 info!("temporary_scope2({:?}, scope={:?}, shrunk={:?})",
421 expr_id, temporary_scope, s);
422 temporary_scope != Some(s)
426 info!("temporary_scope2({:?}) - was_shrunk={:?}", expr_id, was_shrunk);
427 (temporary_scope, was_shrunk)
430 pub fn old_and_new_temporary_scope<'a, 'gcx: 'tcx>(&self,
431 tcx: TyCtxt<'a, 'gcx, 'tcx>,
432 expr_id: ast::NodeId)
433 -> (Option<CodeExtent<'tcx>>,
434 Option<CodeExtent<'tcx>>)
436 let temporary_scope = self.temporary_scope(tcx, expr_id);
438 self.shrunk_rvalue_scopes
439 .get(&expr_id).cloned()
440 .or(temporary_scope))
443 pub fn temporary_scope<'a, 'gcx: 'tcx>(&self,
444 tcx: TyCtxt<'a, 'gcx, 'tcx>,
445 expr_id: ast::NodeId)
446 -> Option<CodeExtent<'tcx>> {
447 //! Returns the scope when temp created by expr_id will be cleaned up
449 // check for a designated rvalue scope
450 if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
451 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
455 // else, locate the innermost terminating scope
456 // if there's one. Static items, for instance, won't
457 // have an enclosing scope, hence no scope will be
459 let mut id = tcx.node_extent(expr_id);
461 while let Some(&p) = self.scope_map.get(id) {
463 CodeExtentData::DestructionScope(..) => {
464 debug!("temporary_scope({:?}) = {:?} [enclosing]",
472 debug!("temporary_scope({:?}) = None", expr_id);
476 pub fn var_region(&self, id: ast::NodeId) -> ty::RegionKind<'tcx> {
477 //! Returns the lifetime of the variable `id`.
479 let scope = ty::ReScope(self.var_scope(id));
480 debug!("var_region({:?}) = {:?}", id, scope);
484 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
486 self.is_subscope_of(scope1, scope2) ||
487 self.is_subscope_of(scope2, scope1)
490 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
492 pub fn is_subscope_of(&self,
493 subscope: CodeExtent,
494 superscope: CodeExtent)
496 let mut s = subscope;
497 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
498 while superscope != s {
499 match self.opt_encl_scope(s) {
501 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
502 subscope, superscope, s);
505 Some(scope) => s = scope
509 debug!("is_subscope_of({:?}, {:?})=true",
510 subscope, superscope);
515 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
516 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
517 pub fn nearest_common_ancestor(&self,
518 scope_a: CodeExtent<'tcx>,
519 scope_b: CodeExtent<'tcx>)
520 -> CodeExtent<'tcx> {
521 if scope_a == scope_b { return scope_a; }
523 /// [1] The initial values for `a_buf` and `b_buf` are not used.
524 /// The `ancestors_of` function will return some prefix that
525 /// is re-initialized with new values (or else fallback to a
526 /// heap-allocated vector).
527 let mut a_buf: [CodeExtent; 32] = [scope_a /* [1] */; 32];
528 let mut a_vec: Vec<CodeExtent<'tcx>> = vec![];
529 let mut b_buf: [CodeExtent; 32] = [scope_b /* [1] */; 32];
530 let mut b_vec: Vec<CodeExtent<'tcx>> = vec![];
531 let scope_map = &self.scope_map;
532 let a_ancestors = ancestors_of(scope_map, scope_a, &mut a_buf, &mut a_vec);
533 let b_ancestors = ancestors_of(scope_map, scope_b, &mut b_buf, &mut b_vec);
534 let mut a_index = a_ancestors.len() - 1;
535 let mut b_index = b_ancestors.len() - 1;
537 // Here, [ab]_ancestors is a vector going from narrow to broad.
538 // The end of each vector will be the item where the scope is
539 // defined; if there are any common ancestors, then the tails of
540 // the vector will be the same. So basically we want to walk
541 // backwards from the tail of each vector and find the first point
542 // where they diverge. If one vector is a suffix of the other,
543 // then the corresponding scope is a superscope of the other.
545 if a_ancestors[a_index] != b_ancestors[b_index] {
546 // In this case, the two regions belong to completely
547 // different functions. Compare those fn for lexical
548 // nesting. The reasoning behind this is subtle. See the
549 // "Modeling closures" section of the README in
550 // infer::region_inference for more details.
551 let a_root_scope = a_ancestors[a_index];
552 let b_root_scope = a_ancestors[a_index];
553 return match (a_root_scope, b_root_scope) {
554 (&CodeExtentData::DestructionScope(a_root_id),
555 &CodeExtentData::DestructionScope(b_root_id)) => {
556 if self.fn_is_enclosed_by(a_root_id, b_root_id) {
557 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
559 } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
560 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
563 // neither fn encloses the other
568 // root ids are always Misc right now
575 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
576 // for all indices between a_index and the end of the array
577 if a_index == 0 { return scope_a; }
578 if b_index == 0 { return scope_b; }
581 if a_ancestors[a_index] != b_ancestors[b_index] {
582 return a_ancestors[a_index + 1];
586 fn ancestors_of<'a, 'tcx>(scope_map: &FxHashMap<CodeExtent<'tcx>, CodeExtent<'tcx>>,
587 scope: CodeExtent<'tcx>,
588 buf: &'a mut [CodeExtent<'tcx>; 32],
589 vec: &'a mut Vec<CodeExtent<'tcx>>)
590 -> &'a [CodeExtent<'tcx>] {
591 // debug!("ancestors_of(scope={:?})", scope);
592 let mut scope = scope;
597 match scope_map.get(&scope) {
598 Some(superscope) => scope = superscope,
599 _ => return &buf[..i+1]
604 *vec = Vec::with_capacity(64);
605 vec.extend_from_slice(buf);
608 match scope_map.get(&scope) {
609 Some(superscope) => scope = superscope,
617 /// Records the lifetime of a local variable as `cx.var_parent`
618 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
621 match visitor.cx.var_parent {
623 // this can happen in extern fn declarations like
625 // extern fn isalnum(c: c_int) -> c_int
627 Some(parent_scope) =>
628 visitor.region_maps.record_var_scope(var_id, parent_scope),
632 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
633 debug!("resolve_block(blk.id={:?})", blk.id);
635 let prev_cx = visitor.cx;
636 let block_extent = visitor.new_node_extent_with_dtor(blk.id);
638 // We treat the tail expression in the block (if any) somewhat
639 // differently from the statements. The issue has to do with
640 // temporary lifetimes. Consider the following:
643 // let inner = ... (&bar()) ...;
645 // (... (&foo()) ...) // (the tail expression)
646 // }, other_argument());
648 // Each of the statements within the block is a terminating
649 // scope, and thus a temporary (e.g. the result of calling
650 // `bar()` in the initalizer expression for `let inner = ...;`)
651 // will be cleaned up immediately after its corresponding
652 // statement (i.e. `let inner = ...;`) executes.
654 // On the other hand, temporaries associated with evaluating the
655 // tail expression for the block are assigned lifetimes so that
656 // they will be cleaned up as part of the terminating scope
657 // *surrounding* the block expression. Here, the terminating
658 // scope for the block expression is the `quux(..)` call; so
659 // those temporaries will only be cleaned up *after* both
660 // `other_argument()` has run and also the call to `quux(..)`
661 // itself has returned.
663 visitor.cx = Context {
664 root_id: prev_cx.root_id,
665 var_parent: Some(block_extent),
666 parent: Some(block_extent),
670 // This block should be kept approximately in sync with
671 // `intravisit::walk_block`. (We manually walk the block, rather
672 // than call `walk_block`, in order to maintain precise
673 // index information.)
675 for (i, statement) in blk.stmts.iter().enumerate() {
676 if let hir::StmtDecl(..) = statement.node {
677 // Each StmtDecl introduces a subscope for bindings
678 // introduced by the declaration; this subscope covers
679 // a suffix of the block . Each subscope in a block
680 // has the previous subscope in the block as a parent,
681 // except for the first such subscope, which has the
682 // block itself as a parent.
683 let stmt_extent = visitor.new_code_extent(
684 CodeExtentData::Remainder(BlockRemainder {
686 first_statement_index: i as u32
689 visitor.cx = Context {
690 root_id: prev_cx.root_id,
691 var_parent: Some(stmt_extent),
692 parent: Some(stmt_extent),
695 visitor.visit_stmt(statement)
697 walk_list!(visitor, visit_expr, &blk.expr);
700 visitor.cx = prev_cx;
703 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
704 visitor.terminating_scopes.insert(arm.body.id);
706 if let Some(ref expr) = arm.guard {
707 visitor.terminating_scopes.insert(expr.id);
710 intravisit::walk_arm(visitor, arm);
713 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
714 visitor.new_node_extent(pat.id);
716 // If this is a binding then record the lifetime of that binding.
717 if let PatKind::Binding(..) = pat.node {
718 record_var_lifetime(visitor, pat.id, pat.span);
721 intravisit::walk_pat(visitor, pat);
724 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
725 let stmt_id = stmt.node.id();
726 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
728 // Every statement will clean up the temporaries created during
729 // execution of that statement. Therefore each statement has an
730 // associated destruction scope that represents the extent of the
731 // statement plus its destructors, and thus the extent for which
732 // regions referenced by the destructors need to survive.
733 visitor.terminating_scopes.insert(stmt_id);
734 let stmt_extent = visitor.new_node_extent_with_dtor(stmt_id);
736 let prev_parent = visitor.cx.parent;
737 visitor.cx.parent = Some(stmt_extent);
738 intravisit::walk_stmt(visitor, stmt);
739 visitor.cx.parent = prev_parent;
742 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
743 debug!("resolve_expr(expr.id={:?})", expr.id);
745 let expr_extent = visitor.new_node_extent_with_dtor(expr.id);
746 let prev_cx = visitor.cx;
747 visitor.cx.parent = Some(expr_extent);
750 let terminating_scopes = &mut visitor.terminating_scopes;
751 let mut terminating = |id: ast::NodeId| {
752 terminating_scopes.insert(id);
755 // Conditional or repeating scopes are always terminating
756 // scopes, meaning that temporaries cannot outlive them.
757 // This ensures fixed size stacks.
759 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
760 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
761 // For shortcircuiting operators, mark the RHS as a terminating
762 // scope since it only executes conditionally.
766 hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
767 terminating(expr.id);
768 terminating(then.id);
769 terminating(otherwise.id);
772 hir::ExprIf(ref expr, ref then, None) => {
773 terminating(expr.id);
774 terminating(then.id);
777 hir::ExprLoop(ref body, _, _) => {
778 terminating(body.id);
781 hir::ExprWhile(ref expr, ref body, _) => {
782 terminating(expr.id);
783 terminating(body.id);
786 hir::ExprMatch(..) => {
787 visitor.cx.var_parent = Some(expr_extent);
790 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
791 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
792 // FIXME(#6268) Nested method calls
794 // The lifetimes for a call or method call look as follows:
802 // The idea is that call.callee_id represents *the time when
803 // the invoked function is actually running* and call.id
804 // represents *the time to prepare the arguments and make the
805 // call*. See the section "Borrows in Calls" borrowck/README.md
806 // for an extended explanation of why this distinction is
809 // record_superlifetime(new_cx, expr.callee_id);
817 // Manually recurse over closures, because they are the only
818 // case of nested bodies that share the parent environment.
819 hir::ExprClosure(.., body, _) => {
820 let body = visitor.tcx.hir.body(body);
821 visitor.visit_body(body);
824 _ => intravisit::walk_expr(visitor, expr)
827 visitor.cx = prev_cx;
830 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
831 local: &'tcx hir::Local) {
832 debug!("resolve_local(local.id={:?},local.init={:?})",
833 local.id,local.init.is_some());
835 // For convenience in trans, associate with the local-id the var
836 // scope that will be used for any bindings declared in this
838 let blk_scope = visitor.cx.var_parent;
839 let blk_scope = blk_scope.expect("locals must be within a block");
840 visitor.region_maps.record_var_scope(local.id, blk_scope);
842 // As an exception to the normal rules governing temporary
843 // lifetimes, initializers in a let have a temporary lifetime
844 // of the enclosing block. This means that e.g. a program
845 // like the following is legal:
847 // let ref x = HashMap::new();
849 // Because the hash map will be freed in the enclosing block.
851 // We express the rules more formally based on 3 grammars (defined
852 // fully in the helpers below that implement them):
854 // 1. `E&`, which matches expressions like `&<rvalue>` that
855 // own a pointer into the stack.
857 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
858 // y)` that produce ref bindings into the value they are
859 // matched against or something (at least partially) owned by
860 // the value they are matched against. (By partially owned,
861 // I mean that creating a binding into a ref-counted or managed value
862 // would still count.)
864 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
865 // based on rvalues like `foo().x[2].y`.
867 // A subexpression `<rvalue>` that appears in a let initializer
868 // `let pat [: ty] = expr` has an extended temporary lifetime if
869 // any of the following conditions are met:
871 // A. `pat` matches `P&` and `expr` matches `ET`
872 // (covers cases where `pat` creates ref bindings into an rvalue
873 // produced by `expr`)
874 // B. `ty` is a borrowed pointer and `expr` matches `ET`
875 // (covers cases where coercion creates a borrow)
876 // C. `expr` matches `E&`
877 // (covers cases `expr` borrows an rvalue that is then assigned
878 // to memory (at least partially) owned by the binding)
880 // Here are some examples hopefully giving an intuition where each
881 // rule comes into play and why:
883 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
884 // would have an extended lifetime, but not `foo()`.
886 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
887 // would have an extended lifetime, but not `foo()`.
889 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
892 // In some cases, multiple rules may apply (though not to the same
893 // rvalue). For example:
895 // let ref x = [&a(), &b()];
897 // Here, the expression `[...]` has an extended lifetime due to rule
898 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
901 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
903 if let Some(ref expr) = local.init {
904 record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
907 if let Some(ref ty) = local.ty { is_borrowed_ty(&ty) } else { false };
909 if is_binding_pat(&local.pat) {
910 record_rvalue_scope(visitor, &expr, blk_scope, false);
911 } else if is_borrow {
912 record_rvalue_scope(visitor, &expr, blk_scope, true);
916 intravisit::walk_local(visitor, local);
918 /// True if `pat` match the `P&` nonterminal:
921 /// | StructName { ..., P&, ... }
922 /// | VariantName(..., P&, ...)
923 /// | [ ..., P&, ... ]
924 /// | ( ..., P&, ... )
926 fn is_binding_pat(pat: &hir::Pat) -> bool {
928 PatKind::Binding(hir::BindByRef(_), ..) => true,
930 PatKind::Struct(_, ref field_pats, _) => {
931 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
934 PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
935 pats1.iter().any(|p| is_binding_pat(&p)) ||
936 pats2.iter().any(|p| is_binding_pat(&p)) ||
937 pats3.iter().any(|p| is_binding_pat(&p))
940 PatKind::TupleStruct(_, ref subpats, _) |
941 PatKind::Tuple(ref subpats, _) => {
942 subpats.iter().any(|p| is_binding_pat(&p))
945 PatKind::Box(ref subpat) => {
946 is_binding_pat(&subpat)
953 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
954 fn is_borrowed_ty(ty: &hir::Ty) -> bool {
956 hir::TyRptr(..) => true,
961 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
964 /// | StructName { ..., f: E&, ... }
965 /// | [ ..., E&, ... ]
966 /// | ( ..., E&, ... )
971 fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
972 visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
974 blk_id: CodeExtent<'tcx>)
977 hir::ExprAddrOf(_, ref subexpr) => {
978 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
979 record_rvalue_scope(visitor, &subexpr, blk_id, false);
981 hir::ExprStruct(_, ref fields, _) => {
982 for field in fields {
983 record_rvalue_scope_if_borrow_expr(
984 visitor, &field.expr, blk_id);
987 hir::ExprArray(ref subexprs) |
988 hir::ExprTup(ref subexprs) => {
989 for subexpr in subexprs {
990 record_rvalue_scope_if_borrow_expr(
991 visitor, &subexpr, blk_id);
994 hir::ExprCast(ref subexpr, _) => {
995 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
997 hir::ExprBlock(ref block) => {
998 if let Some(ref subexpr) = block.expr {
999 record_rvalue_scope_if_borrow_expr(
1000 visitor, &subexpr, blk_id);
1007 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1008 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1009 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1012 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1013 /// `<rvalue>` as `blk_id`:
1021 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1022 fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1024 blk_scope: CodeExtent<'tcx>,
1026 let mut expr = expr;
1028 // Note: give all the expressions matching `ET` with the
1029 // extended temporary lifetime, not just the innermost rvalue,
1030 // because in trans if we must compile e.g. `*rvalue()`
1031 // into a temporary, we request the temporary scope of the
1032 // outer expression.
1034 // this changed because of #36082
1035 visitor.region_maps.record_shrunk_rvalue_scope(expr.id, blk_scope);
1037 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1041 hir::ExprAddrOf(_, ref subexpr) |
1042 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1043 hir::ExprField(ref subexpr, _) |
1044 hir::ExprTupField(ref subexpr, _) |
1045 hir::ExprIndex(ref subexpr, _) => {
1056 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1057 pub fn intern_code_extent(&mut self,
1058 data: CodeExtentData,
1059 parent: Option<CodeExtent<'tcx>>)
1060 -> CodeExtent<'tcx> {
1061 let code_extent = self.tcx.intern_code_extent(data);
1062 self.region_maps.record_code_extent(code_extent, parent);
1066 pub fn intern_node(&mut self,
1068 parent: Option<CodeExtent<'tcx>>) -> CodeExtent<'tcx> {
1069 self.intern_code_extent(CodeExtentData::Misc(n), parent)
1072 /// Records the current parent (if any) as the parent of `child_scope`.
1073 fn new_code_extent(&mut self, child_scope: CodeExtentData) -> CodeExtent<'tcx> {
1074 let parent = self.cx.parent;
1075 self.intern_code_extent(child_scope, parent)
1078 fn new_node_extent(&mut self, child_scope: ast::NodeId) -> CodeExtent<'tcx> {
1079 self.new_code_extent(CodeExtentData::Misc(child_scope))
1082 fn new_node_extent_with_dtor(&mut self, id: ast::NodeId) -> CodeExtent<'tcx> {
1083 // If node was previously marked as a terminating scope during the
1084 // recursive visit of its parent node in the AST, then we need to
1085 // account for the destruction scope representing the extent of
1086 // the destructors that run immediately after it completes.
1087 if self.terminating_scopes.contains(&id) {
1088 let ds = self.new_code_extent(
1089 CodeExtentData::DestructionScope(id));
1090 self.intern_node(id, Some(ds))
1092 self.new_node_extent(id)
1097 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1098 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1099 NestedVisitorMap::None
1102 fn visit_block(&mut self, b: &'tcx Block) {
1103 resolve_block(self, b);
1106 fn visit_body(&mut self, body: &'tcx hir::Body) {
1107 let body_id = body.id();
1108 let owner_id = self.map.body_owner(body_id);
1110 debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1112 self.tcx.sess.codemap().span_to_string(body.value.span),
1116 let outer_cx = self.cx;
1117 let outer_ts = mem::replace(&mut self.terminating_scopes, NodeSet());
1119 // Only functions have an outer terminating (drop) scope,
1120 // while temporaries in constant initializers are 'static.
1121 if let MirSource::Fn(_) = MirSource::from_node(self.tcx, owner_id) {
1122 self.terminating_scopes.insert(body_id.node_id);
1125 if let Some(root_id) = self.cx.root_id {
1126 self.region_maps.record_fn_parent(body_id.node_id, root_id);
1128 self.cx.root_id = Some(body_id.node_id);
1130 self.cx.parent = Some(self.new_code_extent(
1131 CodeExtentData::CallSiteScope { fn_id: owner_id, body_id: body_id.node_id }));
1132 self.cx.parent = Some(self.new_code_extent(
1133 CodeExtentData::ParameterScope { fn_id: owner_id, body_id: body_id.node_id }));
1135 // The arguments and `self` are parented to the fn.
1136 self.cx.var_parent = self.cx.parent.take();
1137 for argument in &body.arguments {
1138 self.visit_pat(&argument.pat);
1141 // The body of the every fn is a root scope.
1142 self.cx.parent = self.cx.var_parent;
1143 self.visit_expr(&body.value);
1145 // Restore context we had at the start.
1147 self.terminating_scopes = outer_ts;
1150 fn visit_arm(&mut self, a: &'tcx Arm) {
1151 resolve_arm(self, a);
1153 fn visit_pat(&mut self, p: &'tcx Pat) {
1154 resolve_pat(self, p);
1156 fn visit_stmt(&mut self, s: &'tcx Stmt) {
1157 resolve_stmt(self, s);
1159 fn visit_expr(&mut self, ex: &'tcx Expr) {
1160 resolve_expr(self, ex);
1162 fn visit_local(&mut self, l: &'tcx Local) {
1163 resolve_local(self, l);
1167 fn region_maps<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1168 -> Rc<RegionMaps<'tcx>>
1170 let closure_base_def_id = tcx.closure_base_def_id(def_id);
1171 if closure_base_def_id != def_id {
1172 return tcx.region_maps(closure_base_def_id);
1175 let mut maps = RegionMaps::new();
1177 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1178 if let Some(body) = tcx.hir.maybe_body_owned_by(id) {
1179 let mut visitor = RegionResolutionVisitor {
1181 region_maps: &mut maps,
1188 terminating_scopes: NodeSet(),
1191 visitor.visit_body(tcx.hir.body(body));
1197 pub fn provide(providers: &mut Providers) {
1198 *providers = Providers {