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(hir::BodyId),
112 // extent of parameters passed to a function or closure (they
114 ParameterScope(hir::BodyId),
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 /// Represents a subscope of `block` for a binding that is introduced
124 /// by `block.stmts[first_statement_index]`. Such subscopes represent
125 /// a suffix of the block. Note that each subscope does not include
126 /// the initializer expression, if any, for the statement indexed by
127 /// `first_statement_index`.
129 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
131 /// * the subscope with `first_statement_index == 0` is scope of both
132 /// `a` and `b`; it does not include EXPR_1, but does include
133 /// everything after that first `let`. (If you want a scope that
134 /// includes EXPR_1 as well, then do not use `CodeExtentData::Remainder`,
135 /// but instead another `CodeExtent` that encompasses the whole block,
136 /// e.g. `CodeExtentData::Misc`.
138 /// * the subscope with `first_statement_index == 1` is scope of `c`,
139 /// and thus does not include EXPR_2, but covers the `...`.
140 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
141 RustcDecodable, Debug, Copy)]
142 pub struct BlockRemainder {
143 pub block: ast::NodeId,
144 pub first_statement_index: u32,
147 impl CodeExtentData {
148 /// Returns a node id associated with this scope.
150 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
151 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
152 pub fn node_id(&self) -> ast::NodeId {
154 CodeExtentData::Misc(node_id) => node_id,
156 // These cases all return rough approximations to the
157 // precise extent denoted by `self`.
158 CodeExtentData::Remainder(br) => br.block,
159 CodeExtentData::DestructionScope(node_id) => node_id,
160 CodeExtentData::CallSiteScope(body_id) |
161 CodeExtentData::ParameterScope(body_id) => body_id.node_id,
165 /// Returns the span of this CodeExtent. Note that in general the
166 /// returned span may not correspond to the span of any node id in
168 pub fn span(&self, hir_map: &hir_map::Map) -> Option<Span> {
169 match hir_map.find(self.node_id()) {
170 Some(hir_map::NodeBlock(ref blk)) => {
172 CodeExtentData::CallSiteScope(_) |
173 CodeExtentData::ParameterScope(_) |
174 CodeExtentData::Misc(_) |
175 CodeExtentData::DestructionScope(_) => Some(blk.span),
177 CodeExtentData::Remainder(r) => {
178 assert_eq!(r.block, blk.id);
179 // Want span for extent starting after the
180 // indexed statement and ending at end of
181 // `blk`; reuse span of `blk` and shift `lo`
182 // forward to end of indexed statement.
184 // (This is the special case aluded to in the
185 // doc-comment for this method)
186 let stmt_span = blk.stmts[r.first_statement_index as usize].span;
187 Some(Span { lo: stmt_span.hi, hi: blk.span.hi, ctxt: stmt_span.ctxt })
191 Some(hir_map::NodeExpr(ref expr)) => Some(expr.span),
192 Some(hir_map::NodeStmt(ref stmt)) => Some(stmt.span),
193 Some(hir_map::NodeItem(ref item)) => Some(item.span),
194 Some(_) | None => None,
199 /// The region maps encode information about region relationships.
200 pub struct RegionMaps<'tcx> {
201 /// If not empty, this body is the root of this region hierarchy.
202 root_body: Option<hir::BodyId>,
204 /// The parent of the root body owner, if the latter is an
205 /// an associated const or method, as impls/traits can also
206 /// have lifetime parameters free in this body.
207 root_parent: Option<ast::NodeId>,
209 /// `scope_map` maps from a scope id to the enclosing scope id;
210 /// this is usually corresponding to the lexical nesting, though
211 /// in the case of closures the parent scope is the innermost
212 /// conditional expression or repeating block. (Note that the
213 /// enclosing scope id for the block associated with a closure is
214 /// the closure itself.)
215 scope_map: FxHashMap<CodeExtent<'tcx>, CodeExtent<'tcx>>,
217 /// `var_map` maps from a variable or binding id to the block in
218 /// which that variable is declared.
219 var_map: NodeMap<CodeExtent<'tcx>>,
221 /// maps from a node-id to the associated destruction scope (if any)
222 destruction_scopes: NodeMap<CodeExtent<'tcx>>,
224 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
225 /// larger than the default. The map goes from the expression id
226 /// to the cleanup scope id. For rvalues not present in this
227 /// table, the appropriate cleanup scope is the innermost
228 /// enclosing statement, conditional expression, or repeating
229 /// block (see `terminating_scopes`).
230 rvalue_scopes: NodeMap<CodeExtent<'tcx>>,
232 /// Records the value of rvalue scopes before they were shrunk by
233 /// #36082, for error reporting.
235 /// FIXME: this should be temporary. Remove this by 1.18.0 or
237 shrunk_rvalue_scopes: NodeMap<CodeExtent<'tcx>>,
239 /// Encodes the hierarchy of fn bodies. Every fn body (including
240 /// closures) forms its own distinct region hierarchy, rooted in
241 /// the block that is the fn body. This map points from the id of
242 /// that root block to the id of the root block for the enclosing
243 /// fn, if any. Thus the map structures the fn bodies into a
244 /// hierarchy based on their lexical mapping. This is used to
245 /// handle the relationships between regions in a fn and in a
246 /// closure defined by that fn. See the "Modeling closures"
247 /// section of the README in infer::region_inference for
249 fn_tree: NodeMap<ast::NodeId>,
252 #[derive(Debug, Copy, Clone)]
253 pub struct Context<'tcx> {
254 /// the root of the current region tree. This is typically the id
255 /// of the innermost fn body. Each fn forms its own disjoint tree
256 /// in the region hierarchy. These fn bodies are themselves
257 /// arranged into a tree. See the "Modeling closures" section of
258 /// the README in infer::region_inference for more
260 root_id: Option<ast::NodeId>,
262 /// the scope that contains any new variables declared
263 var_parent: Option<CodeExtent<'tcx>>,
265 /// region parent of expressions etc
266 parent: Option<CodeExtent<'tcx>>,
269 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
270 tcx: TyCtxt<'a, 'tcx, 'tcx>,
273 region_maps: &'a mut RegionMaps<'tcx>,
277 map: &'a hir_map::Map<'tcx>,
279 /// `terminating_scopes` is a set containing the ids of each
280 /// statement, or conditional/repeating expression. These scopes
281 /// are calling "terminating scopes" because, when attempting to
282 /// find the scope of a temporary, by default we search up the
283 /// enclosing scopes until we encounter the terminating scope. A
284 /// conditional/repeating expression is one which is not
285 /// guaranteed to execute exactly once upon entering the parent
286 /// scope. This could be because the expression only executes
287 /// conditionally, such as the expression `b` in `a && b`, or
288 /// because the expression may execute many times, such as a loop
289 /// body. The reason that we distinguish such expressions is that,
290 /// upon exiting the parent scope, we cannot statically know how
291 /// many times the expression executed, and thus if the expression
292 /// creates temporaries we cannot know statically how many such
293 /// temporaries we would have to cleanup. Therefore we ensure that
294 /// the temporaries never outlast the conditional/repeating
295 /// expression, preventing the need for dynamic checks and/or
296 /// arbitrary amounts of stack space. Terminating scopes end
297 /// up being contained in a DestructionScope that contains the
298 /// destructor's execution.
299 terminating_scopes: NodeSet,
303 impl<'tcx> RegionMaps<'tcx> {
304 pub fn new() -> Self {
308 scope_map: FxHashMap(),
309 destruction_scopes: FxHashMap(),
311 rvalue_scopes: NodeMap(),
312 shrunk_rvalue_scopes: NodeMap(),
317 pub fn record_code_extent(&mut self,
318 child: CodeExtent<'tcx>,
319 parent: Option<CodeExtent<'tcx>>) {
320 debug!("{:?}.parent = {:?}", child, parent);
322 if let Some(p) = parent {
323 let prev = self.scope_map.insert(child, p);
324 assert!(prev.is_none());
327 // record the destruction scopes for later so we can query them
328 if let &CodeExtentData::DestructionScope(n) = child {
329 self.destruction_scopes.insert(n, child);
333 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(CodeExtent<'tcx>, CodeExtent<'tcx>) {
334 for (&child, &parent) in &self.scope_map {
339 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, CodeExtent<'tcx>) {
340 for (child, parent) in self.var_map.iter() {
345 pub fn opt_destruction_extent(&self, n: ast::NodeId) -> Option<CodeExtent<'tcx>> {
346 self.destruction_scopes.get(&n).cloned()
349 /// Records that `sub_fn` is defined within `sup_fn`. These ids
350 /// should be the id of the block that is the fn body, which is
351 /// also the root of the region hierarchy for that fn.
352 fn record_fn_parent(&mut self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
353 debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
354 assert!(sub_fn != sup_fn);
355 let previous = self.fn_tree.insert(sub_fn, sup_fn);
356 assert!(previous.is_none());
359 fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
361 if sub_fn == sup_fn { return true; }
362 match self.fn_tree.get(&sub_fn) {
363 Some(&s) => { sub_fn = s; }
364 None => { return false; }
369 fn record_var_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent<'tcx>) {
370 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
371 assert!(var != lifetime.node_id());
372 self.var_map.insert(var, lifetime);
375 fn record_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent<'tcx>) {
376 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
377 assert!(var != lifetime.node_id());
378 self.rvalue_scopes.insert(var, lifetime);
381 fn record_shrunk_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent<'tcx>) {
382 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
383 assert!(var != lifetime.node_id());
384 self.shrunk_rvalue_scopes.insert(var, lifetime);
387 pub fn opt_encl_scope(&self, id: CodeExtent<'tcx>) -> Option<CodeExtent<'tcx>> {
388 //! Returns the narrowest scope that encloses `id`, if any.
389 self.scope_map.get(&id).cloned()
392 #[allow(dead_code)] // used in cfg
393 pub fn encl_scope(&self, id: CodeExtent<'tcx>) -> CodeExtent<'tcx> {
394 //! Returns the narrowest scope that encloses `id`, if any.
395 self.opt_encl_scope(id).unwrap()
398 /// Returns the lifetime of the local variable `var_id`
399 pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent<'tcx> {
400 match self.var_map.get(&var_id) {
402 None => { bug!("no enclosing scope for id {:?}", var_id); }
406 pub fn temporary_scope2<'a, 'gcx: 'tcx>(&self,
407 tcx: TyCtxt<'a, 'gcx, 'tcx>,
408 expr_id: ast::NodeId)
409 -> (Option<CodeExtent<'tcx>>, bool) {
410 let temporary_scope = self.temporary_scope(tcx, expr_id);
411 let was_shrunk = match self.shrunk_rvalue_scopes.get(&expr_id) {
413 info!("temporary_scope2({:?}, scope={:?}, shrunk={:?})",
414 expr_id, temporary_scope, s);
415 temporary_scope != Some(s)
419 info!("temporary_scope2({:?}) - was_shrunk={:?}", expr_id, was_shrunk);
420 (temporary_scope, was_shrunk)
423 pub fn old_and_new_temporary_scope<'a, 'gcx: 'tcx>(&self,
424 tcx: TyCtxt<'a, 'gcx, 'tcx>,
425 expr_id: ast::NodeId)
426 -> (Option<CodeExtent<'tcx>>,
427 Option<CodeExtent<'tcx>>)
429 let temporary_scope = self.temporary_scope(tcx, expr_id);
431 self.shrunk_rvalue_scopes
432 .get(&expr_id).cloned()
433 .or(temporary_scope))
436 pub fn temporary_scope<'a, 'gcx: 'tcx>(&self,
437 tcx: TyCtxt<'a, 'gcx, 'tcx>,
438 expr_id: ast::NodeId)
439 -> Option<CodeExtent<'tcx>> {
440 //! Returns the scope when temp created by expr_id will be cleaned up
442 // check for a designated rvalue scope
443 if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
444 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
448 // else, locate the innermost terminating scope
449 // if there's one. Static items, for instance, won't
450 // have an enclosing scope, hence no scope will be
452 let mut id = tcx.node_extent(expr_id);
454 while let Some(&p) = self.scope_map.get(id) {
456 CodeExtentData::DestructionScope(..) => {
457 debug!("temporary_scope({:?}) = {:?} [enclosing]",
465 debug!("temporary_scope({:?}) = None", expr_id);
469 pub fn var_region(&self, id: ast::NodeId) -> ty::RegionKind<'tcx> {
470 //! Returns the lifetime of the variable `id`.
472 let scope = ty::ReScope(self.var_scope(id));
473 debug!("var_region({:?}) = {:?}", id, scope);
477 pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
479 self.is_subscope_of(scope1, scope2) ||
480 self.is_subscope_of(scope2, scope1)
483 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
485 pub fn is_subscope_of(&self,
486 subscope: CodeExtent,
487 superscope: CodeExtent)
489 let mut s = subscope;
490 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
491 while superscope != s {
492 match self.opt_encl_scope(s) {
494 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
495 subscope, superscope, s);
498 Some(scope) => s = scope
502 debug!("is_subscope_of({:?}, {:?})=true",
503 subscope, superscope);
508 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
509 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
510 pub fn nearest_common_ancestor(&self,
511 scope_a: CodeExtent<'tcx>,
512 scope_b: CodeExtent<'tcx>)
513 -> CodeExtent<'tcx> {
514 if scope_a == scope_b { return scope_a; }
516 /// [1] The initial values for `a_buf` and `b_buf` are not used.
517 /// The `ancestors_of` function will return some prefix that
518 /// is re-initialized with new values (or else fallback to a
519 /// heap-allocated vector).
520 let mut a_buf: [CodeExtent; 32] = [scope_a /* [1] */; 32];
521 let mut a_vec: Vec<CodeExtent<'tcx>> = vec![];
522 let mut b_buf: [CodeExtent; 32] = [scope_b /* [1] */; 32];
523 let mut b_vec: Vec<CodeExtent<'tcx>> = vec![];
524 let scope_map = &self.scope_map;
525 let a_ancestors = ancestors_of(scope_map, scope_a, &mut a_buf, &mut a_vec);
526 let b_ancestors = ancestors_of(scope_map, scope_b, &mut b_buf, &mut b_vec);
527 let mut a_index = a_ancestors.len() - 1;
528 let mut b_index = b_ancestors.len() - 1;
530 // Here, [ab]_ancestors is a vector going from narrow to broad.
531 // The end of each vector will be the item where the scope is
532 // defined; if there are any common ancestors, then the tails of
533 // the vector will be the same. So basically we want to walk
534 // backwards from the tail of each vector and find the first point
535 // where they diverge. If one vector is a suffix of the other,
536 // then the corresponding scope is a superscope of the other.
538 if a_ancestors[a_index] != b_ancestors[b_index] {
539 // In this case, the two regions belong to completely
540 // different functions. Compare those fn for lexical
541 // nesting. The reasoning behind this is subtle. See the
542 // "Modeling closures" section of the README in
543 // infer::region_inference for more details.
544 let a_root_scope = a_ancestors[a_index];
545 let b_root_scope = a_ancestors[a_index];
546 return match (a_root_scope, b_root_scope) {
547 (&CodeExtentData::DestructionScope(a_root_id),
548 &CodeExtentData::DestructionScope(b_root_id)) => {
549 if self.fn_is_enclosed_by(a_root_id, b_root_id) {
550 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
552 } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
553 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
556 // neither fn encloses the other
561 // root ids are always Misc right now
568 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
569 // for all indices between a_index and the end of the array
570 if a_index == 0 { return scope_a; }
571 if b_index == 0 { return scope_b; }
574 if a_ancestors[a_index] != b_ancestors[b_index] {
575 return a_ancestors[a_index + 1];
579 fn ancestors_of<'a, 'tcx>(scope_map: &FxHashMap<CodeExtent<'tcx>, CodeExtent<'tcx>>,
580 scope: CodeExtent<'tcx>,
581 buf: &'a mut [CodeExtent<'tcx>; 32],
582 vec: &'a mut Vec<CodeExtent<'tcx>>)
583 -> &'a [CodeExtent<'tcx>] {
584 // debug!("ancestors_of(scope={:?})", scope);
585 let mut scope = scope;
590 match scope_map.get(&scope) {
591 Some(superscope) => scope = superscope,
592 _ => return &buf[..i+1]
597 *vec = Vec::with_capacity(64);
598 vec.extend_from_slice(buf);
601 match scope_map.get(&scope) {
602 Some(superscope) => scope = superscope,
609 /// Assuming that the provided region was defined within this `RegionMaps`,
610 /// returns the outermost `CodeExtent` that the region outlives.
611 pub fn early_free_extent<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
612 br: &ty::EarlyBoundRegion)
613 -> CodeExtent<'tcx> {
614 let param_owner = tcx.parent_def_id(br.def_id).unwrap();
616 let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
617 let body_id = tcx.hir.maybe_body_owned_by(param_owner_id).unwrap_or_else(|| {
618 // The lifetime was defined on node that doesn't own a body,
619 // which in practice can only mean a trait or an impl, that
620 // is the parent of a method, and that is enforced below.
621 assert_eq!(Some(param_owner_id), self.root_parent,
622 "free_extent: {:?} not recognized by the region maps for {:?}",
624 self.root_body.map(|body| tcx.hir.body_owner_def_id(body)));
626 // The trait/impl lifetime is in scope for the method's body.
627 self.root_body.unwrap()
630 tcx.intern_code_extent(CodeExtentData::CallSiteScope(body_id))
633 /// Assuming that the provided region was defined within this `RegionMaps`,
634 /// returns the outermost `CodeExtent` that the region outlives.
635 pub fn free_extent<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
636 -> CodeExtent<'tcx> {
637 let param_owner = match fr.bound_region {
638 ty::BoundRegion::BrNamed(def_id, _) => {
639 tcx.parent_def_id(def_id).unwrap()
644 // Ensure that the named late-bound lifetimes were defined
645 // on the same function that they ended up being freed in.
646 assert_eq!(param_owner, fr.scope);
648 let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
649 let body_id = tcx.hir.body_owned_by(param_owner_id);
651 tcx.intern_code_extent(CodeExtentData::CallSiteScope(body_id))
655 /// Records the lifetime of a local variable as `cx.var_parent`
656 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
659 match visitor.cx.var_parent {
661 // this can happen in extern fn declarations like
663 // extern fn isalnum(c: c_int) -> c_int
665 Some(parent_scope) =>
666 visitor.region_maps.record_var_scope(var_id, parent_scope),
670 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
671 debug!("resolve_block(blk.id={:?})", blk.id);
673 let prev_cx = visitor.cx;
674 let block_extent = visitor.new_node_extent_with_dtor(blk.id);
676 // We treat the tail expression in the block (if any) somewhat
677 // differently from the statements. The issue has to do with
678 // temporary lifetimes. Consider the following:
681 // let inner = ... (&bar()) ...;
683 // (... (&foo()) ...) // (the tail expression)
684 // }, other_argument());
686 // Each of the statements within the block is a terminating
687 // scope, and thus a temporary (e.g. the result of calling
688 // `bar()` in the initalizer expression for `let inner = ...;`)
689 // will be cleaned up immediately after its corresponding
690 // statement (i.e. `let inner = ...;`) executes.
692 // On the other hand, temporaries associated with evaluating the
693 // tail expression for the block are assigned lifetimes so that
694 // they will be cleaned up as part of the terminating scope
695 // *surrounding* the block expression. Here, the terminating
696 // scope for the block expression is the `quux(..)` call; so
697 // those temporaries will only be cleaned up *after* both
698 // `other_argument()` has run and also the call to `quux(..)`
699 // itself has returned.
701 visitor.cx = Context {
702 root_id: prev_cx.root_id,
703 var_parent: Some(block_extent),
704 parent: Some(block_extent),
708 // This block should be kept approximately in sync with
709 // `intravisit::walk_block`. (We manually walk the block, rather
710 // than call `walk_block`, in order to maintain precise
711 // index information.)
713 for (i, statement) in blk.stmts.iter().enumerate() {
714 if let hir::StmtDecl(..) = statement.node {
715 // Each StmtDecl introduces a subscope for bindings
716 // introduced by the declaration; this subscope covers
717 // a suffix of the block . Each subscope in a block
718 // has the previous subscope in the block as a parent,
719 // except for the first such subscope, which has the
720 // block itself as a parent.
721 let stmt_extent = visitor.new_code_extent(
722 CodeExtentData::Remainder(BlockRemainder {
724 first_statement_index: i as u32
727 visitor.cx = Context {
728 root_id: prev_cx.root_id,
729 var_parent: Some(stmt_extent),
730 parent: Some(stmt_extent),
733 visitor.visit_stmt(statement)
735 walk_list!(visitor, visit_expr, &blk.expr);
738 visitor.cx = prev_cx;
741 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
742 visitor.terminating_scopes.insert(arm.body.id);
744 if let Some(ref expr) = arm.guard {
745 visitor.terminating_scopes.insert(expr.id);
748 intravisit::walk_arm(visitor, arm);
751 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
752 visitor.new_node_extent(pat.id);
754 // If this is a binding then record the lifetime of that binding.
755 if let PatKind::Binding(..) = pat.node {
756 record_var_lifetime(visitor, pat.id, pat.span);
759 intravisit::walk_pat(visitor, pat);
762 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
763 let stmt_id = stmt.node.id();
764 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
766 // Every statement will clean up the temporaries created during
767 // execution of that statement. Therefore each statement has an
768 // associated destruction scope that represents the extent of the
769 // statement plus its destructors, and thus the extent for which
770 // regions referenced by the destructors need to survive.
771 visitor.terminating_scopes.insert(stmt_id);
772 let stmt_extent = visitor.new_node_extent_with_dtor(stmt_id);
774 let prev_parent = visitor.cx.parent;
775 visitor.cx.parent = Some(stmt_extent);
776 intravisit::walk_stmt(visitor, stmt);
777 visitor.cx.parent = prev_parent;
780 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
781 debug!("resolve_expr(expr.id={:?})", expr.id);
783 let expr_extent = visitor.new_node_extent_with_dtor(expr.id);
784 let prev_cx = visitor.cx;
785 visitor.cx.parent = Some(expr_extent);
788 let terminating_scopes = &mut visitor.terminating_scopes;
789 let mut terminating = |id: ast::NodeId| {
790 terminating_scopes.insert(id);
793 // Conditional or repeating scopes are always terminating
794 // scopes, meaning that temporaries cannot outlive them.
795 // This ensures fixed size stacks.
797 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
798 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
799 // For shortcircuiting operators, mark the RHS as a terminating
800 // scope since it only executes conditionally.
804 hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
805 terminating(expr.id);
806 terminating(then.id);
807 terminating(otherwise.id);
810 hir::ExprIf(ref expr, ref then, None) => {
811 terminating(expr.id);
812 terminating(then.id);
815 hir::ExprLoop(ref body, _, _) => {
816 terminating(body.id);
819 hir::ExprWhile(ref expr, ref body, _) => {
820 terminating(expr.id);
821 terminating(body.id);
824 hir::ExprMatch(..) => {
825 visitor.cx.var_parent = Some(expr_extent);
828 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
829 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
830 // FIXME(#6268) Nested method calls
832 // The lifetimes for a call or method call look as follows:
840 // The idea is that call.callee_id represents *the time when
841 // the invoked function is actually running* and call.id
842 // represents *the time to prepare the arguments and make the
843 // call*. See the section "Borrows in Calls" borrowck/README.md
844 // for an extended explanation of why this distinction is
847 // record_superlifetime(new_cx, expr.callee_id);
855 // Manually recurse over closures, because they are the only
856 // case of nested bodies that share the parent environment.
857 hir::ExprClosure(.., body, _) => {
858 let body = visitor.tcx.hir.body(body);
859 visitor.visit_body(body);
862 _ => intravisit::walk_expr(visitor, expr)
865 visitor.cx = prev_cx;
868 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
869 local: &'tcx hir::Local) {
870 debug!("resolve_local(local.id={:?},local.init={:?})",
871 local.id,local.init.is_some());
873 // For convenience in trans, associate with the local-id the var
874 // scope that will be used for any bindings declared in this
876 let blk_scope = visitor.cx.var_parent;
877 let blk_scope = blk_scope.expect("locals must be within a block");
878 visitor.region_maps.record_var_scope(local.id, blk_scope);
880 // As an exception to the normal rules governing temporary
881 // lifetimes, initializers in a let have a temporary lifetime
882 // of the enclosing block. This means that e.g. a program
883 // like the following is legal:
885 // let ref x = HashMap::new();
887 // Because the hash map will be freed in the enclosing block.
889 // We express the rules more formally based on 3 grammars (defined
890 // fully in the helpers below that implement them):
892 // 1. `E&`, which matches expressions like `&<rvalue>` that
893 // own a pointer into the stack.
895 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
896 // y)` that produce ref bindings into the value they are
897 // matched against or something (at least partially) owned by
898 // the value they are matched against. (By partially owned,
899 // I mean that creating a binding into a ref-counted or managed value
900 // would still count.)
902 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
903 // based on rvalues like `foo().x[2].y`.
905 // A subexpression `<rvalue>` that appears in a let initializer
906 // `let pat [: ty] = expr` has an extended temporary lifetime if
907 // any of the following conditions are met:
909 // A. `pat` matches `P&` and `expr` matches `ET`
910 // (covers cases where `pat` creates ref bindings into an rvalue
911 // produced by `expr`)
912 // B. `ty` is a borrowed pointer and `expr` matches `ET`
913 // (covers cases where coercion creates a borrow)
914 // C. `expr` matches `E&`
915 // (covers cases `expr` borrows an rvalue that is then assigned
916 // to memory (at least partially) owned by the binding)
918 // Here are some examples hopefully giving an intuition where each
919 // rule comes into play and why:
921 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
922 // would have an extended lifetime, but not `foo()`.
924 // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
925 // would have an extended lifetime, but not `foo()`.
927 // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
930 // In some cases, multiple rules may apply (though not to the same
931 // rvalue). For example:
933 // let ref x = [&a(), &b()];
935 // Here, the expression `[...]` has an extended lifetime due to rule
936 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
939 // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
941 if let Some(ref expr) = local.init {
942 record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
945 if let Some(ref ty) = local.ty { is_borrowed_ty(&ty) } else { false };
947 if is_binding_pat(&local.pat) {
948 record_rvalue_scope(visitor, &expr, blk_scope, false);
949 } else if is_borrow {
950 record_rvalue_scope(visitor, &expr, blk_scope, true);
954 intravisit::walk_local(visitor, local);
956 /// True if `pat` match the `P&` nonterminal:
959 /// | StructName { ..., P&, ... }
960 /// | VariantName(..., P&, ...)
961 /// | [ ..., P&, ... ]
962 /// | ( ..., P&, ... )
964 fn is_binding_pat(pat: &hir::Pat) -> bool {
966 PatKind::Binding(hir::BindByRef(_), ..) => true,
968 PatKind::Struct(_, ref field_pats, _) => {
969 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
972 PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
973 pats1.iter().any(|p| is_binding_pat(&p)) ||
974 pats2.iter().any(|p| is_binding_pat(&p)) ||
975 pats3.iter().any(|p| is_binding_pat(&p))
978 PatKind::TupleStruct(_, ref subpats, _) |
979 PatKind::Tuple(ref subpats, _) => {
980 subpats.iter().any(|p| is_binding_pat(&p))
983 PatKind::Box(ref subpat) => {
984 is_binding_pat(&subpat)
991 /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
992 fn is_borrowed_ty(ty: &hir::Ty) -> bool {
994 hir::TyRptr(..) => true,
999 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1002 /// | StructName { ..., f: E&, ... }
1003 /// | [ ..., E&, ... ]
1004 /// | ( ..., E&, ... )
1009 fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
1010 visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1012 blk_id: CodeExtent<'tcx>)
1015 hir::ExprAddrOf(_, ref subexpr) => {
1016 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1017 record_rvalue_scope(visitor, &subexpr, blk_id, false);
1019 hir::ExprStruct(_, ref fields, _) => {
1020 for field in fields {
1021 record_rvalue_scope_if_borrow_expr(
1022 visitor, &field.expr, blk_id);
1025 hir::ExprArray(ref subexprs) |
1026 hir::ExprTup(ref subexprs) => {
1027 for subexpr in subexprs {
1028 record_rvalue_scope_if_borrow_expr(
1029 visitor, &subexpr, blk_id);
1032 hir::ExprCast(ref subexpr, _) => {
1033 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1035 hir::ExprBlock(ref block) => {
1036 if let Some(ref subexpr) = block.expr {
1037 record_rvalue_scope_if_borrow_expr(
1038 visitor, &subexpr, blk_id);
1045 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1046 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1047 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1050 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1051 /// `<rvalue>` as `blk_id`:
1059 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1060 fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1062 blk_scope: CodeExtent<'tcx>,
1064 let mut expr = expr;
1066 // Note: give all the expressions matching `ET` with the
1067 // extended temporary lifetime, not just the innermost rvalue,
1068 // because in trans if we must compile e.g. `*rvalue()`
1069 // into a temporary, we request the temporary scope of the
1070 // outer expression.
1072 // this changed because of #36082
1073 visitor.region_maps.record_shrunk_rvalue_scope(expr.id, blk_scope);
1075 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1079 hir::ExprAddrOf(_, ref subexpr) |
1080 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1081 hir::ExprField(ref subexpr, _) |
1082 hir::ExprTupField(ref subexpr, _) |
1083 hir::ExprIndex(ref subexpr, _) => {
1094 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1095 pub fn intern_code_extent(&mut self,
1096 data: CodeExtentData,
1097 parent: Option<CodeExtent<'tcx>>)
1098 -> CodeExtent<'tcx> {
1099 let code_extent = self.tcx.intern_code_extent(data);
1100 self.region_maps.record_code_extent(code_extent, parent);
1104 pub fn intern_node(&mut self,
1106 parent: Option<CodeExtent<'tcx>>) -> CodeExtent<'tcx> {
1107 self.intern_code_extent(CodeExtentData::Misc(n), parent)
1110 /// Records the current parent (if any) as the parent of `child_scope`.
1111 fn new_code_extent(&mut self, child_scope: CodeExtentData) -> CodeExtent<'tcx> {
1112 let parent = self.cx.parent;
1113 self.intern_code_extent(child_scope, parent)
1116 fn new_node_extent(&mut self, child_scope: ast::NodeId) -> CodeExtent<'tcx> {
1117 self.new_code_extent(CodeExtentData::Misc(child_scope))
1120 fn new_node_extent_with_dtor(&mut self, id: ast::NodeId) -> CodeExtent<'tcx> {
1121 // If node was previously marked as a terminating scope during the
1122 // recursive visit of its parent node in the AST, then we need to
1123 // account for the destruction scope representing the extent of
1124 // the destructors that run immediately after it completes.
1125 if self.terminating_scopes.contains(&id) {
1126 let ds = self.new_code_extent(
1127 CodeExtentData::DestructionScope(id));
1128 self.intern_node(id, Some(ds))
1130 self.new_node_extent(id)
1135 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1136 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1137 NestedVisitorMap::None
1140 fn visit_block(&mut self, b: &'tcx Block) {
1141 resolve_block(self, b);
1144 fn visit_body(&mut self, body: &'tcx hir::Body) {
1145 let body_id = body.id();
1146 let owner_id = self.map.body_owner(body_id);
1148 debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1150 self.tcx.sess.codemap().span_to_string(body.value.span),
1154 let outer_cx = self.cx;
1155 let outer_ts = mem::replace(&mut self.terminating_scopes, NodeSet());
1157 // Only functions have an outer terminating (drop) scope,
1158 // while temporaries in constant initializers are 'static.
1159 if let MirSource::Fn(_) = MirSource::from_node(self.tcx, owner_id) {
1160 self.terminating_scopes.insert(body_id.node_id);
1163 if let Some(root_id) = self.cx.root_id {
1164 self.region_maps.record_fn_parent(body_id.node_id, root_id);
1166 self.cx.root_id = Some(body_id.node_id);
1168 self.cx.parent = Some(self.new_code_extent(
1169 CodeExtentData::CallSiteScope(body_id)));
1170 self.cx.parent = Some(self.new_code_extent(
1171 CodeExtentData::ParameterScope(body_id)));
1173 // The arguments and `self` are parented to the fn.
1174 self.cx.var_parent = self.cx.parent.take();
1175 for argument in &body.arguments {
1176 self.visit_pat(&argument.pat);
1179 // The body of the every fn is a root scope.
1180 self.cx.parent = self.cx.var_parent;
1181 self.visit_expr(&body.value);
1183 // Restore context we had at the start.
1185 self.terminating_scopes = outer_ts;
1188 fn visit_arm(&mut self, a: &'tcx Arm) {
1189 resolve_arm(self, a);
1191 fn visit_pat(&mut self, p: &'tcx Pat) {
1192 resolve_pat(self, p);
1194 fn visit_stmt(&mut self, s: &'tcx Stmt) {
1195 resolve_stmt(self, s);
1197 fn visit_expr(&mut self, ex: &'tcx Expr) {
1198 resolve_expr(self, ex);
1200 fn visit_local(&mut self, l: &'tcx Local) {
1201 resolve_local(self, l);
1205 fn region_maps<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1206 -> Rc<RegionMaps<'tcx>>
1208 let closure_base_def_id = tcx.closure_base_def_id(def_id);
1209 if closure_base_def_id != def_id {
1210 return tcx.region_maps(closure_base_def_id);
1213 let mut maps = RegionMaps::new();
1215 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1216 if let Some(body) = tcx.hir.maybe_body_owned_by(id) {
1217 maps.root_body = Some(body);
1219 // If the item is an associated const or a method,
1220 // record its impl/trait parent, as it can also have
1221 // lifetime parameters free in this body.
1222 match tcx.hir.get(id) {
1223 hir::map::NodeImplItem(_) |
1224 hir::map::NodeTraitItem(_) => {
1225 maps.root_parent = Some(tcx.hir.get_parent(id));
1230 let mut visitor = RegionResolutionVisitor {
1232 region_maps: &mut maps,
1239 terminating_scopes: NodeSet(),
1242 visitor.visit_body(tcx.hir.body(body));
1248 pub fn provide(providers: &mut Providers) {
1249 *providers = Providers {