]> git.proxmox.com Git - rustc.git/blob - src/librustc/middle/region.rs
New upstream version 1.24.1+dfsg1
[rustc.git] / src / librustc / middle / region.rs
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.
4 //
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.
10
11 //! This file builds up the `ScopeTree`, which describes
12 //! the parent links in the region hierarchy.
13 //!
14 //! Most of the documentation on regions can be found in
15 //! `middle/infer/region_constraints/README.md`
16
17 use ich::{StableHashingContext, NodeIdHashingMode};
18 use util::nodemap::{FxHashMap, FxHashSet};
19 use ty;
20
21 use std::fmt;
22 use std::mem;
23 use std::rc::Rc;
24 use syntax::codemap;
25 use syntax::ast;
26 use syntax_pos::{Span, DUMMY_SP};
27 use ty::TyCtxt;
28 use ty::maps::Providers;
29
30 use hir;
31 use hir::def_id::DefId;
32 use hir::intravisit::{self, Visitor, NestedVisitorMap};
33 use hir::{Block, Arm, Pat, PatKind, Stmt, Expr, Local};
34 use rustc_data_structures::indexed_vec::Idx;
35 use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
36 StableHasherResult};
37
38 /// Scope represents a statically-describable scope that can be
39 /// used to bound the lifetime/region for values.
40 ///
41 /// `Node(node_id)`: Any AST node that has any scope at all has the
42 /// `Node(node_id)` scope. Other variants represent special cases not
43 /// immediately derivable from the abstract syntax tree structure.
44 ///
45 /// `DestructionScope(node_id)` represents the scope of destructors
46 /// implicitly-attached to `node_id` that run immediately after the
47 /// expression for `node_id` itself. Not every AST node carries a
48 /// `DestructionScope`, but those that are `terminating_scopes` do;
49 /// see discussion with `ScopeTree`.
50 ///
51 /// `Remainder(BlockRemainder { block, statement_index })` represents
52 /// the scope of user code running immediately after the initializer
53 /// expression for the indexed statement, until the end of the block.
54 ///
55 /// So: the following code can be broken down into the scopes beneath:
56 ///
57 /// ```text
58 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
59 ///
60 /// +-+ (D12.)
61 /// +-+ (D11.)
62 /// +---------+ (R10.)
63 /// +-+ (D9.)
64 /// +----------+ (M8.)
65 /// +----------------------+ (R7.)
66 /// +-+ (D6.)
67 /// +----------+ (M5.)
68 /// +-----------------------------------+ (M4.)
69 /// +--------------------------------------------------+ (M3.)
70 /// +--+ (M2.)
71 /// +-----------------------------------------------------------+ (M1.)
72 ///
73 /// (M1.): Node scope of the whole `let a = ...;` statement.
74 /// (M2.): Node scope of the `f()` expression.
75 /// (M3.): Node scope of the `f().g(..)` expression.
76 /// (M4.): Node scope of the block labeled `'b:`.
77 /// (M5.): Node scope of the `let x = d();` statement
78 /// (D6.): DestructionScope for temporaries created during M5.
79 /// (R7.): Remainder scope for block `'b:`, stmt 0 (let x = ...).
80 /// (M8.): Node scope of the `let y = d();` statement.
81 /// (D9.): DestructionScope for temporaries created during M8.
82 /// (R10.): Remainder scope for block `'b:`, stmt 1 (let y = ...).
83 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
84 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
85 /// ```
86 ///
87 /// Note that while the above picture shows the destruction scopes
88 /// as following their corresponding node scopes, in the internal
89 /// data structures of the compiler the destruction scopes are
90 /// represented as enclosing parents. This is sound because we use the
91 /// enclosing parent relationship just to ensure that referenced
92 /// values live long enough; phrased another way, the starting point
93 /// of each range is not really the important thing in the above
94 /// picture, but rather the ending point.
95 ///
96 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
97 /// placate the same deriving in `ty::FreeRegion`, but we may want to
98 /// actually attach a more meaningful ordering to scopes than the one
99 /// generated via deriving here.
100 ///
101 /// Scope is a bit-packed to save space - if `code` is SCOPE_DATA_REMAINDER_MAX
102 /// or less, it is a `ScopeData::Remainder`, otherwise it is a type specified
103 /// by the bitpacking.
104 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy, RustcEncodable, RustcDecodable)]
105 pub struct Scope {
106 pub(crate) id: hir::ItemLocalId,
107 pub(crate) code: u32
108 }
109
110 const SCOPE_DATA_NODE: u32 = !0;
111 const SCOPE_DATA_CALLSITE: u32 = !1;
112 const SCOPE_DATA_ARGUMENTS: u32 = !2;
113 const SCOPE_DATA_DESTRUCTION: u32 = !3;
114 const SCOPE_DATA_REMAINDER_MAX: u32 = !4;
115
116 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, RustcEncodable, RustcDecodable)]
117 pub enum ScopeData {
118 Node(hir::ItemLocalId),
119
120 // Scope of the call-site for a function or closure
121 // (outlives the arguments as well as the body).
122 CallSite(hir::ItemLocalId),
123
124 // Scope of arguments passed to a function or closure
125 // (they outlive its body).
126 Arguments(hir::ItemLocalId),
127
128 // Scope of destructors for temporaries of node-id.
129 Destruction(hir::ItemLocalId),
130
131 // Scope following a `let id = expr;` binding in a block.
132 Remainder(BlockRemainder)
133 }
134
135 /// Represents a subscope of `block` for a binding that is introduced
136 /// by `block.stmts[first_statement_index]`. Such subscopes represent
137 /// a suffix of the block. Note that each subscope does not include
138 /// the initializer expression, if any, for the statement indexed by
139 /// `first_statement_index`.
140 ///
141 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
142 ///
143 /// * the subscope with `first_statement_index == 0` is scope of both
144 /// `a` and `b`; it does not include EXPR_1, but does include
145 /// everything after that first `let`. (If you want a scope that
146 /// includes EXPR_1 as well, then do not use `Scope::Remainder`,
147 /// but instead another `Scope` that encompasses the whole block,
148 /// e.g. `Scope::Node`.
149 ///
150 /// * the subscope with `first_statement_index == 1` is scope of `c`,
151 /// and thus does not include EXPR_2, but covers the `...`.
152 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
153 RustcDecodable, Debug, Copy)]
154 pub struct BlockRemainder {
155 pub block: hir::ItemLocalId,
156 pub first_statement_index: FirstStatementIndex,
157 }
158
159 newtype_index!(FirstStatementIndex
160 {
161 pub idx
162 MAX = SCOPE_DATA_REMAINDER_MAX
163 });
164
165 impl From<ScopeData> for Scope {
166 #[inline]
167 fn from(scope_data: ScopeData) -> Self {
168 let (id, code) = match scope_data {
169 ScopeData::Node(id) => (id, SCOPE_DATA_NODE),
170 ScopeData::CallSite(id) => (id, SCOPE_DATA_CALLSITE),
171 ScopeData::Arguments(id) => (id, SCOPE_DATA_ARGUMENTS),
172 ScopeData::Destruction(id) => (id, SCOPE_DATA_DESTRUCTION),
173 ScopeData::Remainder(r) => (r.block, r.first_statement_index.index() as u32)
174 };
175 Self { id, code }
176 }
177 }
178
179 impl fmt::Debug for Scope {
180 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
181 fmt::Debug::fmt(&self.data(), formatter)
182 }
183 }
184
185 #[allow(non_snake_case)]
186 impl Scope {
187 #[inline]
188 pub fn data(self) -> ScopeData {
189 match self.code {
190 SCOPE_DATA_NODE => ScopeData::Node(self.id),
191 SCOPE_DATA_CALLSITE => ScopeData::CallSite(self.id),
192 SCOPE_DATA_ARGUMENTS => ScopeData::Arguments(self.id),
193 SCOPE_DATA_DESTRUCTION => ScopeData::Destruction(self.id),
194 idx => ScopeData::Remainder(BlockRemainder {
195 block: self.id,
196 first_statement_index: FirstStatementIndex::new(idx as usize)
197 })
198 }
199 }
200
201 #[inline]
202 pub fn Node(id: hir::ItemLocalId) -> Self {
203 Self::from(ScopeData::Node(id))
204 }
205
206 #[inline]
207 pub fn CallSite(id: hir::ItemLocalId) -> Self {
208 Self::from(ScopeData::CallSite(id))
209 }
210
211 #[inline]
212 pub fn Arguments(id: hir::ItemLocalId) -> Self {
213 Self::from(ScopeData::Arguments(id))
214 }
215
216 #[inline]
217 pub fn Destruction(id: hir::ItemLocalId) -> Self {
218 Self::from(ScopeData::Destruction(id))
219 }
220
221 #[inline]
222 pub fn Remainder(r: BlockRemainder) -> Self {
223 Self::from(ScopeData::Remainder(r))
224 }
225 }
226
227 impl Scope {
228 /// Returns a item-local id associated with this scope.
229 ///
230 /// NB: likely to be replaced as API is refined; e.g. pnkfelix
231 /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
232 pub fn item_local_id(&self) -> hir::ItemLocalId {
233 self.id
234 }
235
236 pub fn node_id(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> ast::NodeId {
237 match scope_tree.root_body {
238 Some(hir_id) => {
239 tcx.hir.hir_to_node_id(hir::HirId {
240 owner: hir_id.owner,
241 local_id: self.item_local_id()
242 })
243 }
244 None => ast::DUMMY_NODE_ID
245 }
246 }
247
248 /// Returns the span of this Scope. Note that in general the
249 /// returned span may not correspond to the span of any node id in
250 /// the AST.
251 pub fn span(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> Span {
252 let node_id = self.node_id(tcx, scope_tree);
253 if node_id == ast::DUMMY_NODE_ID {
254 return DUMMY_SP;
255 }
256 let span = tcx.hir.span(node_id);
257 if let ScopeData::Remainder(r) = self.data() {
258 if let hir::map::NodeBlock(ref blk) = tcx.hir.get(node_id) {
259 // Want span for scope starting after the
260 // indexed statement and ending at end of
261 // `blk`; reuse span of `blk` and shift `lo`
262 // forward to end of indexed statement.
263 //
264 // (This is the special case aluded to in the
265 // doc-comment for this method)
266
267 let stmt_span = blk.stmts[r.first_statement_index.index()].span;
268
269 // To avoid issues with macro-generated spans, the span
270 // of the statement must be nested in that of the block.
271 if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() {
272 return Span::new(stmt_span.lo(), span.hi(), span.ctxt());
273 }
274 }
275 }
276 span
277 }
278 }
279
280 /// The region scope tree encodes information about region relationships.
281 #[derive(Default, Debug)]
282 pub struct ScopeTree {
283 /// If not empty, this body is the root of this region hierarchy.
284 root_body: Option<hir::HirId>,
285
286 /// The parent of the root body owner, if the latter is an
287 /// an associated const or method, as impls/traits can also
288 /// have lifetime parameters free in this body.
289 root_parent: Option<ast::NodeId>,
290
291 /// `parent_map` maps from a scope id to the enclosing scope id;
292 /// this is usually corresponding to the lexical nesting, though
293 /// in the case of closures the parent scope is the innermost
294 /// conditional expression or repeating block. (Note that the
295 /// enclosing scope id for the block associated with a closure is
296 /// the closure itself.)
297 parent_map: FxHashMap<Scope, Scope>,
298
299 /// `var_map` maps from a variable or binding id to the block in
300 /// which that variable is declared.
301 var_map: FxHashMap<hir::ItemLocalId, Scope>,
302
303 /// maps from a node-id to the associated destruction scope (if any)
304 destruction_scopes: FxHashMap<hir::ItemLocalId, Scope>,
305
306 /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
307 /// larger than the default. The map goes from the expression id
308 /// to the cleanup scope id. For rvalues not present in this
309 /// table, the appropriate cleanup scope is the innermost
310 /// enclosing statement, conditional expression, or repeating
311 /// block (see `terminating_scopes`).
312 /// In constants, None is used to indicate that certain expressions
313 /// escape into 'static and should have no local cleanup scope.
314 rvalue_scopes: FxHashMap<hir::ItemLocalId, Option<Scope>>,
315
316 /// Encodes the hierarchy of fn bodies. Every fn body (including
317 /// closures) forms its own distinct region hierarchy, rooted in
318 /// the block that is the fn body. This map points from the id of
319 /// that root block to the id of the root block for the enclosing
320 /// fn, if any. Thus the map structures the fn bodies into a
321 /// hierarchy based on their lexical mapping. This is used to
322 /// handle the relationships between regions in a fn and in a
323 /// closure defined by that fn. See the "Modeling closures"
324 /// section of the README in infer::region_constraints for
325 /// more details.
326 closure_tree: FxHashMap<hir::ItemLocalId, hir::ItemLocalId>,
327
328 /// If there are any `yield` nested within a scope, this map
329 /// stores the `Span` of the last one and its index in the
330 /// postorder of the Visitor traversal on the HIR.
331 ///
332 /// HIR Visitor postorder indexes might seem like a peculiar
333 /// thing to care about. but it turns out that HIR bindings
334 /// and the temporary results of HIR expressions are never
335 /// storage-live at the end of HIR nodes with postorder indexes
336 /// lower than theirs, and therefore don't need to be suspended
337 /// at yield-points at these indexes.
338 ///
339 /// For an example, suppose we have some code such as:
340 /// ```rust,ignore (example)
341 /// foo(f(), yield y, bar(g()))
342 /// ```
343 ///
344 /// With the HIR tree (calls numbered for expository purposes)
345 /// ```
346 /// Call#0(foo, [Call#1(f), Yield(y), Call#2(bar, Call#3(g))])
347 /// ```
348 ///
349 /// Obviously, the result of `f()` was created before the yield
350 /// (and therefore needs to be kept valid over the yield) while
351 /// the result of `g()` occurs after the yield (and therefore
352 /// doesn't). If we want to infer that, we can look at the
353 /// postorder traversal:
354 /// ```
355 /// `foo` `f` Call#1 `y` Yield `bar` `g` Call#3 Call#2 Call#0
356 /// ```
357 ///
358 /// In which we can easily see that `Call#1` occurs before the yield,
359 /// and `Call#3` after it.
360 ///
361 /// To see that this method works, consider:
362 ///
363 /// Let `D` be our binding/temporary and `U` be our other HIR node, with
364 /// `HIR-postorder(U) < HIR-postorder(D)` (in our example, U would be
365 /// the yield and D would be one of the calls). Let's show that
366 /// `D` is storage-dead at `U`.
367 ///
368 /// Remember that storage-live/storage-dead refers to the state of
369 /// the *storage*, and does not consider moves/drop flags.
370 ///
371 /// Then:
372 /// 1. From the ordering guarantee of HIR visitors (see
373 /// `rustc::hir::intravisit`), `D` does not dominate `U`.
374 /// 2. Therefore, `D` is *potentially* storage-dead at `U` (because
375 /// we might visit `U` without ever getting to `D`).
376 /// 3. However, we guarantee that at each HIR point, each
377 /// binding/temporary is always either always storage-live
378 /// or always storage-dead. This is what is being guaranteed
379 /// by `terminating_scopes` including all blocks where the
380 /// count of executions is not guaranteed.
381 /// 4. By `2.` and `3.`, `D` is *statically* storage-dead at `U`,
382 /// QED.
383 ///
384 /// I don't think this property relies on `3.` in an essential way - it
385 /// is probably still correct even if we have "unrestricted" terminating
386 /// scopes. However, why use the complicated proof when a simple one
387 /// works?
388 ///
389 /// A subtle thing: `box` expressions, such as `box (&x, yield 2, &y)`. It
390 /// might seem that a `box` expression creates a `Box<T>` temporary
391 /// when it *starts* executing, at `HIR-preorder(BOX-EXPR)`. That might
392 /// be true in the MIR desugaring, but it is not important in the semantics.
393 ///
394 /// The reason is that semantically, until the `box` expression returns,
395 /// the values are still owned by their containing expressions. So
396 /// we'll see that `&x`.
397 yield_in_scope: FxHashMap<Scope, (Span, usize)>,
398
399 /// The number of visit_expr and visit_pat calls done in the body.
400 /// Used to sanity check visit_expr/visit_pat call count when
401 /// calculating generator interiors.
402 body_expr_count: FxHashMap<hir::BodyId, usize>,
403 }
404
405 #[derive(Debug, Copy, Clone)]
406 pub struct Context {
407 /// the root of the current region tree. This is typically the id
408 /// of the innermost fn body. Each fn forms its own disjoint tree
409 /// in the region hierarchy. These fn bodies are themselves
410 /// arranged into a tree. See the "Modeling closures" section of
411 /// the README in infer::region_constraints for more
412 /// details.
413 root_id: Option<hir::ItemLocalId>,
414
415 /// the scope that contains any new variables declared
416 var_parent: Option<Scope>,
417
418 /// region parent of expressions etc
419 parent: Option<Scope>,
420 }
421
422 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
423 tcx: TyCtxt<'a, 'tcx, 'tcx>,
424
425 // The number of expressions and patterns visited in the current body
426 expr_and_pat_count: usize,
427
428 // Generated scope tree:
429 scope_tree: ScopeTree,
430
431 cx: Context,
432
433 /// `terminating_scopes` is a set containing the ids of each
434 /// statement, or conditional/repeating expression. These scopes
435 /// are calling "terminating scopes" because, when attempting to
436 /// find the scope of a temporary, by default we search up the
437 /// enclosing scopes until we encounter the terminating scope. A
438 /// conditional/repeating expression is one which is not
439 /// guaranteed to execute exactly once upon entering the parent
440 /// scope. This could be because the expression only executes
441 /// conditionally, such as the expression `b` in `a && b`, or
442 /// because the expression may execute many times, such as a loop
443 /// body. The reason that we distinguish such expressions is that,
444 /// upon exiting the parent scope, we cannot statically know how
445 /// many times the expression executed, and thus if the expression
446 /// creates temporaries we cannot know statically how many such
447 /// temporaries we would have to cleanup. Therefore we ensure that
448 /// the temporaries never outlast the conditional/repeating
449 /// expression, preventing the need for dynamic checks and/or
450 /// arbitrary amounts of stack space. Terminating scopes end
451 /// up being contained in a DestructionScope that contains the
452 /// destructor's execution.
453 terminating_scopes: FxHashSet<hir::ItemLocalId>,
454 }
455
456
457 impl<'tcx> ScopeTree {
458 pub fn record_scope_parent(&mut self, child: Scope, parent: Option<Scope>) {
459 debug!("{:?}.parent = {:?}", child, parent);
460
461 if let Some(p) = parent {
462 let prev = self.parent_map.insert(child, p);
463 assert!(prev.is_none());
464 }
465
466 // record the destruction scopes for later so we can query them
467 if let ScopeData::Destruction(n) = child.data() {
468 self.destruction_scopes.insert(n, child);
469 }
470 }
471
472 pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(Scope, Scope) {
473 for (&child, &parent) in &self.parent_map {
474 e(child, parent)
475 }
476 }
477
478 pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&hir::ItemLocalId, Scope) {
479 for (child, &parent) in self.var_map.iter() {
480 e(child, parent)
481 }
482 }
483
484 pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
485 self.destruction_scopes.get(&n).cloned()
486 }
487
488 /// Records that `sub_closure` is defined within `sup_closure`. These ids
489 /// should be the id of the block that is the fn body, which is
490 /// also the root of the region hierarchy for that fn.
491 fn record_closure_parent(&mut self,
492 sub_closure: hir::ItemLocalId,
493 sup_closure: hir::ItemLocalId) {
494 debug!("record_closure_parent(sub_closure={:?}, sup_closure={:?})",
495 sub_closure, sup_closure);
496 assert!(sub_closure != sup_closure);
497 let previous = self.closure_tree.insert(sub_closure, sup_closure);
498 assert!(previous.is_none());
499 }
500
501 fn closure_is_enclosed_by(&self,
502 mut sub_closure: hir::ItemLocalId,
503 sup_closure: hir::ItemLocalId) -> bool {
504 loop {
505 if sub_closure == sup_closure { return true; }
506 match self.closure_tree.get(&sub_closure) {
507 Some(&s) => { sub_closure = s; }
508 None => { return false; }
509 }
510 }
511 }
512
513 fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) {
514 debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
515 assert!(var != lifetime.item_local_id());
516 self.var_map.insert(var, lifetime);
517 }
518
519 fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option<Scope>) {
520 debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
521 if let Some(lifetime) = lifetime {
522 assert!(var != lifetime.item_local_id());
523 }
524 self.rvalue_scopes.insert(var, lifetime);
525 }
526
527 pub fn opt_encl_scope(&self, id: Scope) -> Option<Scope> {
528 //! Returns the narrowest scope that encloses `id`, if any.
529 self.parent_map.get(&id).cloned()
530 }
531
532 #[allow(dead_code)] // used in cfg
533 pub fn encl_scope(&self, id: Scope) -> Scope {
534 //! Returns the narrowest scope that encloses `id`, if any.
535 self.opt_encl_scope(id).unwrap()
536 }
537
538 /// Returns the lifetime of the local variable `var_id`
539 pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
540 match self.var_map.get(&var_id) {
541 Some(&r) => r,
542 None => { bug!("no enclosing scope for id {:?}", var_id); }
543 }
544 }
545
546 pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
547 //! Returns the scope when temp created by expr_id will be cleaned up
548
549 // check for a designated rvalue scope
550 if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
551 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
552 return s;
553 }
554
555 // else, locate the innermost terminating scope
556 // if there's one. Static items, for instance, won't
557 // have an enclosing scope, hence no scope will be
558 // returned.
559 let mut id = Scope::Node(expr_id);
560
561 while let Some(&p) = self.parent_map.get(&id) {
562 match p.data() {
563 ScopeData::Destruction(..) => {
564 debug!("temporary_scope({:?}) = {:?} [enclosing]",
565 expr_id, id);
566 return Some(id);
567 }
568 _ => id = p
569 }
570 }
571
572 debug!("temporary_scope({:?}) = None", expr_id);
573 return None;
574 }
575
576 pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind {
577 //! Returns the lifetime of the variable `id`.
578
579 let scope = ty::ReScope(self.var_scope(id));
580 debug!("var_region({:?}) = {:?}", id, scope);
581 scope
582 }
583
584 pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope)
585 -> bool {
586 self.is_subscope_of(scope1, scope2) ||
587 self.is_subscope_of(scope2, scope1)
588 }
589
590 /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
591 /// otherwise.
592 pub fn is_subscope_of(&self,
593 subscope: Scope,
594 superscope: Scope)
595 -> bool {
596 let mut s = subscope;
597 debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
598 while superscope != s {
599 match self.opt_encl_scope(s) {
600 None => {
601 debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
602 subscope, superscope, s);
603 return false;
604 }
605 Some(scope) => s = scope
606 }
607 }
608
609 debug!("is_subscope_of({:?}, {:?})=true",
610 subscope, superscope);
611
612 return true;
613 }
614
615 /// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
616 /// scope which is greater than or equal to both `scope_a` and `scope_b`.
617 pub fn nearest_common_ancestor(&self,
618 scope_a: Scope,
619 scope_b: Scope)
620 -> Scope {
621 if scope_a == scope_b { return scope_a; }
622
623 // [1] The initial values for `a_buf` and `b_buf` are not used.
624 // The `ancestors_of` function will return some prefix that
625 // is re-initialized with new values (or else fallback to a
626 // heap-allocated vector).
627 let mut a_buf: [Scope; 32] = [scope_a /* [1] */; 32];
628 let mut a_vec: Vec<Scope> = vec![];
629 let mut b_buf: [Scope; 32] = [scope_b /* [1] */; 32];
630 let mut b_vec: Vec<Scope> = vec![];
631 let parent_map = &self.parent_map;
632 let a_ancestors = ancestors_of(parent_map, scope_a, &mut a_buf, &mut a_vec);
633 let b_ancestors = ancestors_of(parent_map, scope_b, &mut b_buf, &mut b_vec);
634 let mut a_index = a_ancestors.len() - 1;
635 let mut b_index = b_ancestors.len() - 1;
636
637 // Here, [ab]_ancestors is a vector going from narrow to broad.
638 // The end of each vector will be the item where the scope is
639 // defined; if there are any common ancestors, then the tails of
640 // the vector will be the same. So basically we want to walk
641 // backwards from the tail of each vector and find the first point
642 // where they diverge. If one vector is a suffix of the other,
643 // then the corresponding scope is a superscope of the other.
644
645 if a_ancestors[a_index] != b_ancestors[b_index] {
646 // In this case, the two regions belong to completely
647 // different functions. Compare those fn for lexical
648 // nesting. The reasoning behind this is subtle. See the
649 // "Modeling closures" section of the README in
650 // infer::region_constraints for more details.
651 let a_root_scope = a_ancestors[a_index];
652 let b_root_scope = a_ancestors[a_index];
653 return match (a_root_scope.data(), b_root_scope.data()) {
654 (ScopeData::Destruction(a_root_id),
655 ScopeData::Destruction(b_root_id)) => {
656 if self.closure_is_enclosed_by(a_root_id, b_root_id) {
657 // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
658 scope_b
659 } else if self.closure_is_enclosed_by(b_root_id, a_root_id) {
660 // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
661 scope_a
662 } else {
663 // neither fn encloses the other
664 bug!()
665 }
666 }
667 _ => {
668 // root ids are always Node right now
669 bug!()
670 }
671 };
672 }
673
674 loop {
675 // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
676 // for all indices between a_index and the end of the array
677 if a_index == 0 { return scope_a; }
678 if b_index == 0 { return scope_b; }
679 a_index -= 1;
680 b_index -= 1;
681 if a_ancestors[a_index] != b_ancestors[b_index] {
682 return a_ancestors[a_index + 1];
683 }
684 }
685
686 fn ancestors_of<'a, 'tcx>(parent_map: &FxHashMap<Scope, Scope>,
687 scope: Scope,
688 buf: &'a mut [Scope; 32],
689 vec: &'a mut Vec<Scope>)
690 -> &'a [Scope] {
691 // debug!("ancestors_of(scope={:?})", scope);
692 let mut scope = scope;
693
694 let mut i = 0;
695 while i < 32 {
696 buf[i] = scope;
697 match parent_map.get(&scope) {
698 Some(&superscope) => scope = superscope,
699 _ => return &buf[..i+1]
700 }
701 i += 1;
702 }
703
704 *vec = Vec::with_capacity(64);
705 vec.extend_from_slice(buf);
706 loop {
707 vec.push(scope);
708 match parent_map.get(&scope) {
709 Some(&superscope) => scope = superscope,
710 _ => return &*vec
711 }
712 }
713 }
714 }
715
716 /// Assuming that the provided region was defined within this `ScopeTree`,
717 /// returns the outermost `Scope` that the region outlives.
718 pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
719 br: &ty::EarlyBoundRegion)
720 -> Scope {
721 let param_owner = tcx.parent_def_id(br.def_id).unwrap();
722
723 let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
724 let scope = tcx.hir.maybe_body_owned_by(param_owner_id).map(|body_id| {
725 tcx.hir.body(body_id).value.hir_id.local_id
726 }).unwrap_or_else(|| {
727 // The lifetime was defined on node that doesn't own a body,
728 // which in practice can only mean a trait or an impl, that
729 // is the parent of a method, and that is enforced below.
730 assert_eq!(Some(param_owner_id), self.root_parent,
731 "free_scope: {:?} not recognized by the \
732 region scope tree for {:?} / {:?}",
733 param_owner,
734 self.root_parent.map(|id| tcx.hir.local_def_id(id)),
735 self.root_body.map(|hir_id| DefId::local(hir_id.owner)));
736
737 // The trait/impl lifetime is in scope for the method's body.
738 self.root_body.unwrap().local_id
739 });
740
741 Scope::CallSite(scope)
742 }
743
744 /// Assuming that the provided region was defined within this `ScopeTree`,
745 /// returns the outermost `Scope` that the region outlives.
746 pub fn free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
747 -> Scope {
748 let param_owner = match fr.bound_region {
749 ty::BoundRegion::BrNamed(def_id, _) => {
750 tcx.parent_def_id(def_id).unwrap()
751 }
752 _ => fr.scope
753 };
754
755 // Ensure that the named late-bound lifetimes were defined
756 // on the same function that they ended up being freed in.
757 assert_eq!(param_owner, fr.scope);
758
759 let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
760 let body_id = tcx.hir.body_owned_by(param_owner_id);
761 Scope::CallSite(tcx.hir.body(body_id).value.hir_id.local_id)
762 }
763
764 /// Checks whether the given scope contains a `yield`. If so,
765 /// returns `Some((span, expr_count))` with the span of a yield we found and
766 /// the number of expressions appearing before the `yield` in the body.
767 pub fn yield_in_scope(&self, scope: Scope) -> Option<(Span, usize)> {
768 self.yield_in_scope.get(&scope).cloned()
769 }
770
771 /// Gives the number of expressions visited in a body.
772 /// Used to sanity check visit_expr call count when
773 /// calculating generator interiors.
774 pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> {
775 self.body_expr_count.get(&body_id).map(|r| *r)
776 }
777 }
778
779 /// Records the lifetime of a local variable as `cx.var_parent`
780 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
781 var_id: hir::ItemLocalId,
782 _sp: Span) {
783 match visitor.cx.var_parent {
784 None => {
785 // this can happen in extern fn declarations like
786 //
787 // extern fn isalnum(c: c_int) -> c_int
788 }
789 Some(parent_scope) =>
790 visitor.scope_tree.record_var_scope(var_id, parent_scope),
791 }
792 }
793
794 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
795 debug!("resolve_block(blk.id={:?})", blk.id);
796
797 let prev_cx = visitor.cx;
798
799 // We treat the tail expression in the block (if any) somewhat
800 // differently from the statements. The issue has to do with
801 // temporary lifetimes. Consider the following:
802 //
803 // quux({
804 // let inner = ... (&bar()) ...;
805 //
806 // (... (&foo()) ...) // (the tail expression)
807 // }, other_argument());
808 //
809 // Each of the statements within the block is a terminating
810 // scope, and thus a temporary (e.g. the result of calling
811 // `bar()` in the initalizer expression for `let inner = ...;`)
812 // will be cleaned up immediately after its corresponding
813 // statement (i.e. `let inner = ...;`) executes.
814 //
815 // On the other hand, temporaries associated with evaluating the
816 // tail expression for the block are assigned lifetimes so that
817 // they will be cleaned up as part of the terminating scope
818 // *surrounding* the block expression. Here, the terminating
819 // scope for the block expression is the `quux(..)` call; so
820 // those temporaries will only be cleaned up *after* both
821 // `other_argument()` has run and also the call to `quux(..)`
822 // itself has returned.
823
824 visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
825 visitor.cx.var_parent = visitor.cx.parent;
826
827 {
828 // This block should be kept approximately in sync with
829 // `intravisit::walk_block`. (We manually walk the block, rather
830 // than call `walk_block`, in order to maintain precise
831 // index information.)
832
833 for (i, statement) in blk.stmts.iter().enumerate() {
834 if let hir::StmtDecl(..) = statement.node {
835 // Each StmtDecl introduces a subscope for bindings
836 // introduced by the declaration; this subscope covers
837 // a suffix of the block . Each subscope in a block
838 // has the previous subscope in the block as a parent,
839 // except for the first such subscope, which has the
840 // block itself as a parent.
841 visitor.enter_scope(
842 Scope::Remainder(BlockRemainder {
843 block: blk.hir_id.local_id,
844 first_statement_index: FirstStatementIndex::new(i)
845 })
846 );
847 visitor.cx.var_parent = visitor.cx.parent;
848 }
849 visitor.visit_stmt(statement)
850 }
851 walk_list!(visitor, visit_expr, &blk.expr);
852 }
853
854 visitor.cx = prev_cx;
855 }
856
857 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
858 visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
859
860 if let Some(ref expr) = arm.guard {
861 visitor.terminating_scopes.insert(expr.hir_id.local_id);
862 }
863
864 intravisit::walk_arm(visitor, arm);
865 }
866
867 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
868 visitor.record_child_scope(Scope::Node(pat.hir_id.local_id));
869
870 // If this is a binding then record the lifetime of that binding.
871 if let PatKind::Binding(..) = pat.node {
872 record_var_lifetime(visitor, pat.hir_id.local_id, pat.span);
873 }
874
875 intravisit::walk_pat(visitor, pat);
876
877 visitor.expr_and_pat_count += 1;
878 }
879
880 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
881 let stmt_id = visitor.tcx.hir.node_to_hir_id(stmt.node.id()).local_id;
882 debug!("resolve_stmt(stmt.id={:?})", stmt_id);
883
884 // Every statement will clean up the temporaries created during
885 // execution of that statement. Therefore each statement has an
886 // associated destruction scope that represents the scope of the
887 // statement plus its destructors, and thus the scope for which
888 // regions referenced by the destructors need to survive.
889 visitor.terminating_scopes.insert(stmt_id);
890
891 let prev_parent = visitor.cx.parent;
892 visitor.enter_node_scope_with_dtor(stmt_id);
893
894 intravisit::walk_stmt(visitor, stmt);
895
896 visitor.cx.parent = prev_parent;
897 }
898
899 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
900 debug!("resolve_expr(expr.id={:?})", expr.id);
901
902 let prev_cx = visitor.cx;
903 visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
904
905 {
906 let terminating_scopes = &mut visitor.terminating_scopes;
907 let mut terminating = |id: hir::ItemLocalId| {
908 terminating_scopes.insert(id);
909 };
910 match expr.node {
911 // Conditional or repeating scopes are always terminating
912 // scopes, meaning that temporaries cannot outlive them.
913 // This ensures fixed size stacks.
914
915 hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
916 hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
917 // For shortcircuiting operators, mark the RHS as a terminating
918 // scope since it only executes conditionally.
919 terminating(r.hir_id.local_id);
920 }
921
922 hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
923 terminating(expr.hir_id.local_id);
924 terminating(then.hir_id.local_id);
925 terminating(otherwise.hir_id.local_id);
926 }
927
928 hir::ExprIf(ref expr, ref then, None) => {
929 terminating(expr.hir_id.local_id);
930 terminating(then.hir_id.local_id);
931 }
932
933 hir::ExprLoop(ref body, _, _) => {
934 terminating(body.hir_id.local_id);
935 }
936
937 hir::ExprWhile(ref expr, ref body, _) => {
938 terminating(expr.hir_id.local_id);
939 terminating(body.hir_id.local_id);
940 }
941
942 hir::ExprMatch(..) => {
943 visitor.cx.var_parent = visitor.cx.parent;
944 }
945
946 hir::ExprAssignOp(..) | hir::ExprIndex(..) |
947 hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
948 // FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls
949 //
950 // The lifetimes for a call or method call look as follows:
951 //
952 // call.id
953 // - arg0.id
954 // - ...
955 // - argN.id
956 // - call.callee_id
957 //
958 // The idea is that call.callee_id represents *the time when
959 // the invoked function is actually running* and call.id
960 // represents *the time to prepare the arguments and make the
961 // call*. See the section "Borrows in Calls" borrowck/README.md
962 // for an extended explanation of why this distinction is
963 // important.
964 //
965 // record_superlifetime(new_cx, expr.callee_id);
966 }
967
968 _ => {}
969 }
970 }
971
972 match expr.node {
973 // Manually recurse over closures, because they are the only
974 // case of nested bodies that share the parent environment.
975 hir::ExprClosure(.., body, _, _) => {
976 let body = visitor.tcx.hir.body(body);
977 visitor.visit_body(body);
978 }
979
980 _ => intravisit::walk_expr(visitor, expr)
981 }
982
983 visitor.expr_and_pat_count += 1;
984
985 if let hir::ExprYield(..) = expr.node {
986 // Mark this expr's scope and all parent scopes as containing `yield`.
987 let mut scope = Scope::Node(expr.hir_id.local_id);
988 loop {
989 visitor.scope_tree.yield_in_scope.insert(scope,
990 (expr.span, visitor.expr_and_pat_count));
991
992 // Keep traversing up while we can.
993 match visitor.scope_tree.parent_map.get(&scope) {
994 // Don't cross from closure bodies to their parent.
995 Some(&superscope) => match superscope.data() {
996 ScopeData::CallSite(_) => break,
997 _ => scope = superscope
998 },
999 None => break
1000 }
1001 }
1002 }
1003
1004 visitor.cx = prev_cx;
1005 }
1006
1007 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1008 pat: Option<&'tcx hir::Pat>,
1009 init: Option<&'tcx hir::Expr>) {
1010 debug!("resolve_local(pat={:?}, init={:?})", pat, init);
1011
1012 let blk_scope = visitor.cx.var_parent;
1013
1014 // As an exception to the normal rules governing temporary
1015 // lifetimes, initializers in a let have a temporary lifetime
1016 // of the enclosing block. This means that e.g. a program
1017 // like the following is legal:
1018 //
1019 // let ref x = HashMap::new();
1020 //
1021 // Because the hash map will be freed in the enclosing block.
1022 //
1023 // We express the rules more formally based on 3 grammars (defined
1024 // fully in the helpers below that implement them):
1025 //
1026 // 1. `E&`, which matches expressions like `&<rvalue>` that
1027 // own a pointer into the stack.
1028 //
1029 // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
1030 // y)` that produce ref bindings into the value they are
1031 // matched against or something (at least partially) owned by
1032 // the value they are matched against. (By partially owned,
1033 // I mean that creating a binding into a ref-counted or managed value
1034 // would still count.)
1035 //
1036 // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
1037 // based on rvalues like `foo().x[2].y`.
1038 //
1039 // A subexpression `<rvalue>` that appears in a let initializer
1040 // `let pat [: ty] = expr` has an extended temporary lifetime if
1041 // any of the following conditions are met:
1042 //
1043 // A. `pat` matches `P&` and `expr` matches `ET`
1044 // (covers cases where `pat` creates ref bindings into an rvalue
1045 // produced by `expr`)
1046 // B. `ty` is a borrowed pointer and `expr` matches `ET`
1047 // (covers cases where coercion creates a borrow)
1048 // C. `expr` matches `E&`
1049 // (covers cases `expr` borrows an rvalue that is then assigned
1050 // to memory (at least partially) owned by the binding)
1051 //
1052 // Here are some examples hopefully giving an intuition where each
1053 // rule comes into play and why:
1054 //
1055 // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
1056 // would have an extended lifetime, but not `foo()`.
1057 //
1058 // Rule B. `let x = &foo().x`. The rvalue ``foo()` would have extended
1059 // lifetime.
1060 //
1061 // In some cases, multiple rules may apply (though not to the same
1062 // rvalue). For example:
1063 //
1064 // let ref x = [&a(), &b()];
1065 //
1066 // Here, the expression `[...]` has an extended lifetime due to rule
1067 // A, but the inner rvalues `a()` and `b()` have an extended lifetime
1068 // due to rule C.
1069
1070 if let Some(expr) = init {
1071 record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
1072
1073 if let Some(pat) = pat {
1074 if is_binding_pat(pat) {
1075 record_rvalue_scope(visitor, &expr, blk_scope);
1076 }
1077 }
1078 }
1079
1080 if let Some(pat) = pat {
1081 visitor.visit_pat(pat);
1082 }
1083 if let Some(expr) = init {
1084 visitor.visit_expr(expr);
1085 }
1086
1087 /// True if `pat` match the `P&` nonterminal:
1088 ///
1089 /// P& = ref X
1090 /// | StructName { ..., P&, ... }
1091 /// | VariantName(..., P&, ...)
1092 /// | [ ..., P&, ... ]
1093 /// | ( ..., P&, ... )
1094 /// | box P&
1095 fn is_binding_pat(pat: &hir::Pat) -> bool {
1096 // Note that the code below looks for *explicit* refs only, that is, it won't
1097 // know about *implicit* refs as introduced in #42640.
1098 //
1099 // This is not a problem. For example, consider
1100 //
1101 // let (ref x, ref y) = (Foo { .. }, Bar { .. });
1102 //
1103 // Due to the explicit refs on the left hand side, the below code would signal
1104 // that the temporary value on the right hand side should live until the end of
1105 // the enclosing block (as opposed to being dropped after the let is complete).
1106 //
1107 // To create an implicit ref, however, you must have a borrowed value on the RHS
1108 // already, as in this example (which won't compile before #42640):
1109 //
1110 // let Foo { x, .. } = &Foo { x: ..., ... };
1111 //
1112 // in place of
1113 //
1114 // let Foo { ref x, .. } = Foo { ... };
1115 //
1116 // In the former case (the implicit ref version), the temporary is created by the
1117 // & expression, and its lifetime would be extended to the end of the block (due
1118 // to a different rule, not the below code).
1119 match pat.node {
1120 PatKind::Binding(hir::BindingAnnotation::Ref, ..) |
1121 PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true,
1122
1123 PatKind::Struct(_, ref field_pats, _) => {
1124 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
1125 }
1126
1127 PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
1128 pats1.iter().any(|p| is_binding_pat(&p)) ||
1129 pats2.iter().any(|p| is_binding_pat(&p)) ||
1130 pats3.iter().any(|p| is_binding_pat(&p))
1131 }
1132
1133 PatKind::TupleStruct(_, ref subpats, _) |
1134 PatKind::Tuple(ref subpats, _) => {
1135 subpats.iter().any(|p| is_binding_pat(&p))
1136 }
1137
1138 PatKind::Box(ref subpat) => {
1139 is_binding_pat(&subpat)
1140 }
1141
1142 _ => false,
1143 }
1144 }
1145
1146 /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
1147 ///
1148 /// E& = & ET
1149 /// | StructName { ..., f: E&, ... }
1150 /// | [ ..., E&, ... ]
1151 /// | ( ..., E&, ... )
1152 /// | {...; E&}
1153 /// | box E&
1154 /// | E& as ...
1155 /// | ( E& )
1156 fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
1157 visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1158 expr: &hir::Expr,
1159 blk_id: Option<Scope>)
1160 {
1161 match expr.node {
1162 hir::ExprAddrOf(_, ref subexpr) => {
1163 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
1164 record_rvalue_scope(visitor, &subexpr, blk_id);
1165 }
1166 hir::ExprStruct(_, ref fields, _) => {
1167 for field in fields {
1168 record_rvalue_scope_if_borrow_expr(
1169 visitor, &field.expr, blk_id);
1170 }
1171 }
1172 hir::ExprArray(ref subexprs) |
1173 hir::ExprTup(ref subexprs) => {
1174 for subexpr in subexprs {
1175 record_rvalue_scope_if_borrow_expr(
1176 visitor, &subexpr, blk_id);
1177 }
1178 }
1179 hir::ExprCast(ref subexpr, _) => {
1180 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1181 }
1182 hir::ExprBlock(ref block) => {
1183 if let Some(ref subexpr) = block.expr {
1184 record_rvalue_scope_if_borrow_expr(
1185 visitor, &subexpr, blk_id);
1186 }
1187 }
1188 _ => {}
1189 }
1190 }
1191
1192 /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1193 /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1194 /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1195 /// statement.
1196 ///
1197 /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1198 /// `<rvalue>` as `blk_id`:
1199 ///
1200 /// ET = *ET
1201 /// | ET[...]
1202 /// | ET.f
1203 /// | (ET)
1204 /// | <rvalue>
1205 ///
1206 /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1207 fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1208 expr: &hir::Expr,
1209 blk_scope: Option<Scope>) {
1210 let mut expr = expr;
1211 loop {
1212 // Note: give all the expressions matching `ET` with the
1213 // extended temporary lifetime, not just the innermost rvalue,
1214 // because in trans if we must compile e.g. `*rvalue()`
1215 // into a temporary, we request the temporary scope of the
1216 // outer expression.
1217 visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope);
1218
1219 match expr.node {
1220 hir::ExprAddrOf(_, ref subexpr) |
1221 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1222 hir::ExprField(ref subexpr, _) |
1223 hir::ExprTupField(ref subexpr, _) |
1224 hir::ExprIndex(ref subexpr, _) => {
1225 expr = &subexpr;
1226 }
1227 _ => {
1228 return;
1229 }
1230 }
1231 }
1232 }
1233 }
1234
1235 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1236 /// Records the current parent (if any) as the parent of `child_scope`.
1237 fn record_child_scope(&mut self, child_scope: Scope) {
1238 let parent = self.cx.parent;
1239 self.scope_tree.record_scope_parent(child_scope, parent);
1240 }
1241
1242 /// Records the current parent (if any) as the parent of `child_scope`,
1243 /// and sets `child_scope` as the new current parent.
1244 fn enter_scope(&mut self, child_scope: Scope) {
1245 self.record_child_scope(child_scope);
1246 self.cx.parent = Some(child_scope);
1247 }
1248
1249 fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) {
1250 // If node was previously marked as a terminating scope during the
1251 // recursive visit of its parent node in the AST, then we need to
1252 // account for the destruction scope representing the scope of
1253 // the destructors that run immediately after it completes.
1254 if self.terminating_scopes.contains(&id) {
1255 self.enter_scope(Scope::Destruction(id));
1256 }
1257 self.enter_scope(Scope::Node(id));
1258 }
1259 }
1260
1261 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1262 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1263 NestedVisitorMap::None
1264 }
1265
1266 fn visit_block(&mut self, b: &'tcx Block) {
1267 resolve_block(self, b);
1268 }
1269
1270 fn visit_body(&mut self, body: &'tcx hir::Body) {
1271 let body_id = body.id();
1272 let owner_id = self.tcx.hir.body_owner(body_id);
1273
1274 debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1275 owner_id,
1276 self.tcx.sess.codemap().span_to_string(body.value.span),
1277 body_id,
1278 self.cx.parent);
1279
1280 let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0);
1281 let outer_cx = self.cx;
1282 let outer_ts = mem::replace(&mut self.terminating_scopes, FxHashSet());
1283 self.terminating_scopes.insert(body.value.hir_id.local_id);
1284
1285 if let Some(root_id) = self.cx.root_id {
1286 self.scope_tree.record_closure_parent(body.value.hir_id.local_id, root_id);
1287 }
1288 self.cx.root_id = Some(body.value.hir_id.local_id);
1289
1290 self.enter_scope(Scope::CallSite(body.value.hir_id.local_id));
1291 self.enter_scope(Scope::Arguments(body.value.hir_id.local_id));
1292
1293 // The arguments and `self` are parented to the fn.
1294 self.cx.var_parent = self.cx.parent.take();
1295 for argument in &body.arguments {
1296 self.visit_pat(&argument.pat);
1297 }
1298
1299 // The body of the every fn is a root scope.
1300 self.cx.parent = self.cx.var_parent;
1301 if let hir::BodyOwnerKind::Fn = self.tcx.hir.body_owner_kind(owner_id) {
1302 self.visit_expr(&body.value);
1303 } else {
1304 // Only functions have an outer terminating (drop) scope, while
1305 // temporaries in constant initializers may be 'static, but only
1306 // according to rvalue lifetime semantics, using the same
1307 // syntactical rules used for let initializers.
1308 //
1309 // E.g. in `let x = &f();`, the temporary holding the result from
1310 // the `f()` call lives for the entirety of the surrounding block.
1311 //
1312 // Similarly, `const X: ... = &f();` would have the result of `f()`
1313 // live for `'static`, implying (if Drop restrictions on constants
1314 // ever get lifted) that the value *could* have a destructor, but
1315 // it'd get leaked instead of the destructor running during the
1316 // evaluation of `X` (if at all allowed by CTFE).
1317 //
1318 // However, `const Y: ... = g(&f());`, like `let y = g(&f());`,
1319 // would *not* let the `f()` temporary escape into an outer scope
1320 // (i.e. `'static`), which means that after `g` returns, it drops,
1321 // and all the associated destruction scope rules apply.
1322 self.cx.var_parent = None;
1323 resolve_local(self, None, Some(&body.value));
1324 }
1325
1326 if body.is_generator {
1327 self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count);
1328 }
1329
1330 // Restore context we had at the start.
1331 self.expr_and_pat_count = outer_ec;
1332 self.cx = outer_cx;
1333 self.terminating_scopes = outer_ts;
1334 }
1335
1336 fn visit_arm(&mut self, a: &'tcx Arm) {
1337 resolve_arm(self, a);
1338 }
1339 fn visit_pat(&mut self, p: &'tcx Pat) {
1340 resolve_pat(self, p);
1341 }
1342 fn visit_stmt(&mut self, s: &'tcx Stmt) {
1343 resolve_stmt(self, s);
1344 }
1345 fn visit_expr(&mut self, ex: &'tcx Expr) {
1346 resolve_expr(self, ex);
1347 }
1348 fn visit_local(&mut self, l: &'tcx Local) {
1349 resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e));
1350 }
1351 }
1352
1353 fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1354 -> Rc<ScopeTree>
1355 {
1356 let closure_base_def_id = tcx.closure_base_def_id(def_id);
1357 if closure_base_def_id != def_id {
1358 return tcx.region_scope_tree(closure_base_def_id);
1359 }
1360
1361 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1362 let scope_tree = if let Some(body_id) = tcx.hir.maybe_body_owned_by(id) {
1363 let mut visitor = RegionResolutionVisitor {
1364 tcx,
1365 scope_tree: ScopeTree::default(),
1366 expr_and_pat_count: 0,
1367 cx: Context {
1368 root_id: None,
1369 parent: None,
1370 var_parent: None,
1371 },
1372 terminating_scopes: FxHashSet(),
1373 };
1374
1375 let body = tcx.hir.body(body_id);
1376 visitor.scope_tree.root_body = Some(body.value.hir_id);
1377
1378 // If the item is an associated const or a method,
1379 // record its impl/trait parent, as it can also have
1380 // lifetime parameters free in this body.
1381 match tcx.hir.get(id) {
1382 hir::map::NodeImplItem(_) |
1383 hir::map::NodeTraitItem(_) => {
1384 visitor.scope_tree.root_parent = Some(tcx.hir.get_parent(id));
1385 }
1386 _ => {}
1387 }
1388
1389 visitor.visit_body(body);
1390
1391 visitor.scope_tree
1392 } else {
1393 ScopeTree::default()
1394 };
1395
1396 Rc::new(scope_tree)
1397 }
1398
1399 pub fn provide(providers: &mut Providers) {
1400 *providers = Providers {
1401 region_scope_tree,
1402 ..*providers
1403 };
1404 }
1405
1406 impl<'gcx> HashStable<StableHashingContext<'gcx>> for ScopeTree {
1407 fn hash_stable<W: StableHasherResult>(&self,
1408 hcx: &mut StableHashingContext<'gcx>,
1409 hasher: &mut StableHasher<W>) {
1410 let ScopeTree {
1411 root_body,
1412 root_parent,
1413 ref body_expr_count,
1414 ref parent_map,
1415 ref var_map,
1416 ref destruction_scopes,
1417 ref rvalue_scopes,
1418 ref closure_tree,
1419 ref yield_in_scope,
1420 } = *self;
1421
1422 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
1423 root_body.hash_stable(hcx, hasher);
1424 root_parent.hash_stable(hcx, hasher);
1425 });
1426
1427 body_expr_count.hash_stable(hcx, hasher);
1428 parent_map.hash_stable(hcx, hasher);
1429 var_map.hash_stable(hcx, hasher);
1430 destruction_scopes.hash_stable(hcx, hasher);
1431 rvalue_scopes.hash_stable(hcx, hasher);
1432 closure_tree.hash_stable(hcx, hasher);
1433 yield_in_scope.hash_stable(hcx, hasher);
1434 }
1435 }