]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/region.rs
Rollup merge of #42006 - jseyfried:fix_include_regression, r=nrc
[rust.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 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.
15 //!
16 //! Most of the documentation on regions can be found in
17 //! `middle/infer/region_inference/README.md`
18
19 use hir::map as hir_map;
20 use util::nodemap::{FxHashMap, NodeMap, NodeSet};
21 use ty;
22
23 use std::mem;
24 use std::rc::Rc;
25 use syntax::codemap;
26 use syntax::ast;
27 use syntax_pos::Span;
28 use ty::TyCtxt;
29 use ty::maps::Providers;
30
31 use hir;
32 use hir::def_id::DefId;
33 use hir::intravisit::{self, Visitor, NestedVisitorMap};
34 use hir::{Block, Arm, Pat, PatKind, Stmt, Expr, Local};
35 use mir::transform::MirSource;
36
37 /// CodeExtent represents a statically-describable extent that can be
38 /// used to bound the lifetime/region for values.
39 ///
40 /// `Misc(node_id)`: Any AST node that has any extent at all has the
41 /// `Misc(node_id)` extent. Other variants represent special cases not
42 /// immediately derivable from the abstract syntax tree structure.
43 ///
44 /// `DestructionScope(node_id)` represents the extent of destructors
45 /// implicitly-attached to `node_id` that run immediately after the
46 /// expression for `node_id` itself. Not every AST node carries a
47 /// `DestructionScope`, but those that are `terminating_scopes` do;
48 /// see discussion with `RegionMaps`.
49 ///
50 /// `Remainder(BlockRemainder { block, statement_index })` represents
51 /// the extent of user code running immediately after the initializer
52 /// expression for the indexed statement, until the end of the block.
53 ///
54 /// So: the following code can be broken down into the extents beneath:
55 /// ```
56 /// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y)  }   ) ;
57 /// ```
58 ///
59 ///                                                              +-+ (D12.)
60 ///                                                        +-+       (D11.)
61 ///                                              +---------+         (R10.)
62 ///                                              +-+                  (D9.)
63 ///                                   +----------+                    (M8.)
64 ///                                 +----------------------+          (R7.)
65 ///                                 +-+                               (D6.)
66 ///                      +----------+                                 (M5.)
67 ///                    +-----------------------------------+          (M4.)
68 ///         +--------------------------------------------------+      (M3.)
69 ///         +--+                                                      (M2.)
70 /// +-----------------------------------------------------------+     (M1.)
71 ///
72 ///  (M1.): Misc extent of the whole `let a = ...;` statement.
73 ///  (M2.): Misc extent of the `f()` expression.
74 ///  (M3.): Misc extent of the `f().g(..)` expression.
75 ///  (M4.): Misc extent of the block labelled `'b:`.
76 ///  (M5.): Misc extent of the `let x = d();` statement
77 ///  (D6.): DestructionScope for temporaries created during M5.
78 ///  (R7.): Remainder extent for block `'b:`, stmt 0 (let x = ...).
79 ///  (M8.): Misc Extent of the `let y = d();` statement.
80 ///  (D9.): DestructionScope for temporaries created during M8.
81 /// (R10.): Remainder extent for block `'b:`, stmt 1 (let y = ...).
82 /// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
83 /// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
84 ///
85 /// Note that while the above picture shows the destruction scopes
86 /// as following their corresponding misc extents, in the internal
87 /// data structures of the compiler the destruction scopes are
88 /// represented as enclosing parents. This is sound because we use the
89 /// enclosing parent relationship just to ensure that referenced
90 /// values live long enough; phrased another way, the starting point
91 /// of each range is not really the important thing in the above
92 /// picture, but rather the ending point.
93 ///
94 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
95 /// placate the same deriving in `ty::FreeRegion`, but we may want to
96 /// actually attach a more meaningful ordering to scopes than the one
97 /// generated via deriving here.
98 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, RustcEncodable, RustcDecodable)]
99 pub enum CodeExtent {
100     Misc(ast::NodeId),
101
102     // extent of the call-site for a function or closure (outlives
103     // the parameters as well as the body).
104     CallSiteScope(hir::BodyId),
105
106     // extent of parameters passed to a function or closure (they
107     // outlive its body)
108     ParameterScope(hir::BodyId),
109
110     // extent of destructors for temporaries of node-id
111     DestructionScope(ast::NodeId),
112
113     // extent of code following a `let id = expr;` binding in a block
114     Remainder(BlockRemainder)
115 }
116
117 /// Represents a subscope of `block` for a binding that is introduced
118 /// by `block.stmts[first_statement_index]`. Such subscopes represent
119 /// a suffix of the block. Note that each subscope does not include
120 /// the initializer expression, if any, for the statement indexed by
121 /// `first_statement_index`.
122 ///
123 /// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
124 ///
125 /// * the subscope with `first_statement_index == 0` is scope of both
126 ///   `a` and `b`; it does not include EXPR_1, but does include
127 ///   everything after that first `let`. (If you want a scope that
128 ///   includes EXPR_1 as well, then do not use `CodeExtent::Remainder`,
129 ///   but instead another `CodeExtent` that encompasses the whole block,
130 ///   e.g. `CodeExtent::Misc`.
131 ///
132 /// * the subscope with `first_statement_index == 1` is scope of `c`,
133 ///   and thus does not include EXPR_2, but covers the `...`.
134 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
135          RustcDecodable, Debug, Copy)]
136 pub struct BlockRemainder {
137     pub block: ast::NodeId,
138     pub first_statement_index: u32,
139 }
140
141 impl CodeExtent {
142     /// Returns a node id associated with this scope.
143     ///
144     /// NB: likely to be replaced as API is refined; e.g. pnkfelix
145     /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
146     pub fn node_id(&self) -> ast::NodeId {
147         match *self {
148             CodeExtent::Misc(node_id) => node_id,
149
150             // These cases all return rough approximations to the
151             // precise extent denoted by `self`.
152             CodeExtent::Remainder(br) => br.block,
153             CodeExtent::DestructionScope(node_id) => node_id,
154             CodeExtent::CallSiteScope(body_id) |
155             CodeExtent::ParameterScope(body_id) => body_id.node_id,
156         }
157     }
158
159     /// Returns the span of this CodeExtent.  Note that in general the
160     /// returned span may not correspond to the span of any node id in
161     /// the AST.
162     pub fn span(&self, hir_map: &hir_map::Map) -> Option<Span> {
163         match hir_map.find(self.node_id()) {
164             Some(hir_map::NodeBlock(ref blk)) => {
165                 match *self {
166                     CodeExtent::CallSiteScope(_) |
167                     CodeExtent::ParameterScope(_) |
168                     CodeExtent::Misc(_) |
169                     CodeExtent::DestructionScope(_) => Some(blk.span),
170
171                     CodeExtent::Remainder(r) => {
172                         assert_eq!(r.block, blk.id);
173                         // Want span for extent starting after the
174                         // indexed statement and ending at end of
175                         // `blk`; reuse span of `blk` and shift `lo`
176                         // forward to end of indexed statement.
177                         //
178                         // (This is the special case aluded to in the
179                         // doc-comment for this method)
180                         let stmt_span = blk.stmts[r.first_statement_index as usize].span;
181                         Some(Span { lo: stmt_span.hi, hi: blk.span.hi, ctxt: stmt_span.ctxt })
182                     }
183                 }
184             }
185             Some(hir_map::NodeExpr(ref expr)) => Some(expr.span),
186             Some(hir_map::NodeStmt(ref stmt)) => Some(stmt.span),
187             Some(hir_map::NodeItem(ref item)) => Some(item.span),
188             Some(_) | None => None,
189          }
190     }
191 }
192
193 /// The region maps encode information about region relationships.
194 pub struct RegionMaps {
195     /// If not empty, this body is the root of this region hierarchy.
196     root_body: Option<hir::BodyId>,
197
198     /// The parent of the root body owner, if the latter is an
199     /// an associated const or method, as impls/traits can also
200     /// have lifetime parameters free in this body.
201     root_parent: Option<ast::NodeId>,
202
203     /// `scope_map` maps from a scope id to the enclosing scope id;
204     /// this is usually corresponding to the lexical nesting, though
205     /// in the case of closures the parent scope is the innermost
206     /// conditional expression or repeating block. (Note that the
207     /// enclosing scope id for the block associated with a closure is
208     /// the closure itself.)
209     scope_map: FxHashMap<CodeExtent, CodeExtent>,
210
211     /// `var_map` maps from a variable or binding id to the block in
212     /// which that variable is declared.
213     var_map: NodeMap<CodeExtent>,
214
215     /// maps from a node-id to the associated destruction scope (if any)
216     destruction_scopes: NodeMap<CodeExtent>,
217
218     /// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
219     /// larger than the default. The map goes from the expression id
220     /// to the cleanup scope id. For rvalues not present in this
221     /// table, the appropriate cleanup scope is the innermost
222     /// enclosing statement, conditional expression, or repeating
223     /// block (see `terminating_scopes`).
224     rvalue_scopes: NodeMap<CodeExtent>,
225
226     /// Records the value of rvalue scopes before they were shrunk by
227     /// #36082, for error reporting.
228     ///
229     /// FIXME: this should be temporary. Remove this by 1.18.0 or
230     /// so.
231     shrunk_rvalue_scopes: NodeMap<CodeExtent>,
232
233     /// Encodes the hierarchy of fn bodies. Every fn body (including
234     /// closures) forms its own distinct region hierarchy, rooted in
235     /// the block that is the fn body. This map points from the id of
236     /// that root block to the id of the root block for the enclosing
237     /// fn, if any. Thus the map structures the fn bodies into a
238     /// hierarchy based on their lexical mapping. This is used to
239     /// handle the relationships between regions in a fn and in a
240     /// closure defined by that fn. See the "Modeling closures"
241     /// section of the README in infer::region_inference for
242     /// more details.
243     fn_tree: NodeMap<ast::NodeId>,
244 }
245
246 #[derive(Debug, Copy, Clone)]
247 pub struct Context {
248     /// the root of the current region tree. This is typically the id
249     /// of the innermost fn body. Each fn forms its own disjoint tree
250     /// in the region hierarchy. These fn bodies are themselves
251     /// arranged into a tree. See the "Modeling closures" section of
252     /// the README in infer::region_inference for more
253     /// details.
254     root_id: Option<ast::NodeId>,
255
256     /// the scope that contains any new variables declared
257     var_parent: Option<CodeExtent>,
258
259     /// region parent of expressions etc
260     parent: Option<CodeExtent>,
261 }
262
263 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
264     tcx: TyCtxt<'a, 'tcx, 'tcx>,
265
266     // Generated maps:
267     region_maps: RegionMaps,
268
269     cx: Context,
270
271     /// `terminating_scopes` is a set containing the ids of each
272     /// statement, or conditional/repeating expression. These scopes
273     /// are calling "terminating scopes" because, when attempting to
274     /// find the scope of a temporary, by default we search up the
275     /// enclosing scopes until we encounter the terminating scope. A
276     /// conditional/repeating expression is one which is not
277     /// guaranteed to execute exactly once upon entering the parent
278     /// scope. This could be because the expression only executes
279     /// conditionally, such as the expression `b` in `a && b`, or
280     /// because the expression may execute many times, such as a loop
281     /// body. The reason that we distinguish such expressions is that,
282     /// upon exiting the parent scope, we cannot statically know how
283     /// many times the expression executed, and thus if the expression
284     /// creates temporaries we cannot know statically how many such
285     /// temporaries we would have to cleanup. Therefore we ensure that
286     /// the temporaries never outlast the conditional/repeating
287     /// expression, preventing the need for dynamic checks and/or
288     /// arbitrary amounts of stack space. Terminating scopes end
289     /// up being contained in a DestructionScope that contains the
290     /// destructor's execution.
291     terminating_scopes: NodeSet,
292 }
293
294
295 impl<'tcx> RegionMaps {
296     pub fn new() -> Self {
297         RegionMaps {
298             root_body: None,
299             root_parent: None,
300             scope_map: FxHashMap(),
301             destruction_scopes: FxHashMap(),
302             var_map: NodeMap(),
303             rvalue_scopes: NodeMap(),
304             shrunk_rvalue_scopes: NodeMap(),
305             fn_tree: NodeMap(),
306         }
307     }
308
309     pub fn record_code_extent(&mut self,
310                               child: CodeExtent,
311                               parent: Option<CodeExtent>) {
312         debug!("{:?}.parent = {:?}", child, parent);
313
314         if let Some(p) = parent {
315             let prev = self.scope_map.insert(child, p);
316             assert!(prev.is_none());
317         }
318
319         // record the destruction scopes for later so we can query them
320         if let CodeExtent::DestructionScope(n) = child {
321             self.destruction_scopes.insert(n, child);
322         }
323     }
324
325     pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(CodeExtent, CodeExtent) {
326         for (&child, &parent) in &self.scope_map {
327             e(child, parent)
328         }
329     }
330
331     pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, CodeExtent) {
332         for (child, &parent) in self.var_map.iter() {
333             e(child, parent)
334         }
335     }
336
337     pub fn opt_destruction_extent(&self, n: ast::NodeId) -> Option<CodeExtent> {
338         self.destruction_scopes.get(&n).cloned()
339     }
340
341     /// Records that `sub_fn` is defined within `sup_fn`. These ids
342     /// should be the id of the block that is the fn body, which is
343     /// also the root of the region hierarchy for that fn.
344     fn record_fn_parent(&mut self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
345         debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
346         assert!(sub_fn != sup_fn);
347         let previous = self.fn_tree.insert(sub_fn, sup_fn);
348         assert!(previous.is_none());
349     }
350
351     fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
352         loop {
353             if sub_fn == sup_fn { return true; }
354             match self.fn_tree.get(&sub_fn) {
355                 Some(&s) => { sub_fn = s; }
356                 None => { return false; }
357             }
358         }
359     }
360
361     fn record_var_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent) {
362         debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
363         assert!(var != lifetime.node_id());
364         self.var_map.insert(var, lifetime);
365     }
366
367     fn record_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent) {
368         debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
369         assert!(var != lifetime.node_id());
370         self.rvalue_scopes.insert(var, lifetime);
371     }
372
373     fn record_shrunk_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent) {
374         debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
375         assert!(var != lifetime.node_id());
376         self.shrunk_rvalue_scopes.insert(var, lifetime);
377     }
378
379     pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
380         //! Returns the narrowest scope that encloses `id`, if any.
381         self.scope_map.get(&id).cloned()
382     }
383
384     #[allow(dead_code)] // used in cfg
385     pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
386         //! Returns the narrowest scope that encloses `id`, if any.
387         self.opt_encl_scope(id).unwrap()
388     }
389
390     /// Returns the lifetime of the local variable `var_id`
391     pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
392         match self.var_map.get(&var_id) {
393             Some(&r) => r,
394             None => { bug!("no enclosing scope for id {:?}", var_id); }
395         }
396     }
397
398     pub fn temporary_scope2(&self, expr_id: ast::NodeId)
399                             -> (Option<CodeExtent>, bool) {
400         let temporary_scope = self.temporary_scope(expr_id);
401         let was_shrunk = match self.shrunk_rvalue_scopes.get(&expr_id) {
402             Some(&s) => {
403                 info!("temporary_scope2({:?}, scope={:?}, shrunk={:?})",
404                       expr_id, temporary_scope, s);
405                 temporary_scope != Some(s)
406             }
407             _ => false
408         };
409         info!("temporary_scope2({:?}) - was_shrunk={:?}", expr_id, was_shrunk);
410         (temporary_scope, was_shrunk)
411     }
412
413     pub fn old_and_new_temporary_scope(&self, expr_id: ast::NodeId)
414                                        -> (Option<CodeExtent>,
415                                            Option<CodeExtent>)
416     {
417         let temporary_scope = self.temporary_scope(expr_id);
418         (temporary_scope,
419          self.shrunk_rvalue_scopes
420              .get(&expr_id).cloned()
421              .or(temporary_scope))
422     }
423
424     pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
425         //! Returns the scope when temp created by expr_id will be cleaned up
426
427         // check for a designated rvalue scope
428         if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
429             debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
430             return Some(s);
431         }
432
433         // else, locate the innermost terminating scope
434         // if there's one. Static items, for instance, won't
435         // have an enclosing scope, hence no scope will be
436         // returned.
437         let mut id = CodeExtent::Misc(expr_id);
438
439         while let Some(&p) = self.scope_map.get(&id) {
440             match p {
441                 CodeExtent::DestructionScope(..) => {
442                     debug!("temporary_scope({:?}) = {:?} [enclosing]",
443                            expr_id, id);
444                     return Some(id);
445                 }
446                 _ => id = p
447             }
448         }
449
450         debug!("temporary_scope({:?}) = None", expr_id);
451         return None;
452     }
453
454     pub fn var_region(&self, id: ast::NodeId) -> ty::RegionKind {
455         //! Returns the lifetime of the variable `id`.
456
457         let scope = ty::ReScope(self.var_scope(id));
458         debug!("var_region({:?}) = {:?}", id, scope);
459         scope
460     }
461
462     pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
463                             -> bool {
464         self.is_subscope_of(scope1, scope2) ||
465         self.is_subscope_of(scope2, scope1)
466     }
467
468     /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
469     /// otherwise.
470     pub fn is_subscope_of(&self,
471                           subscope: CodeExtent,
472                           superscope: CodeExtent)
473                           -> bool {
474         let mut s = subscope;
475         debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
476         while superscope != s {
477             match self.opt_encl_scope(s) {
478                 None => {
479                     debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
480                            subscope, superscope, s);
481                     return false;
482                 }
483                 Some(scope) => s = scope
484             }
485         }
486
487         debug!("is_subscope_of({:?}, {:?})=true",
488                subscope, superscope);
489
490         return true;
491     }
492
493     /// Finds the nearest common ancestor (if any) of two scopes.  That is, finds the smallest
494     /// scope which is greater than or equal to both `scope_a` and `scope_b`.
495     pub fn nearest_common_ancestor(&self,
496                                    scope_a: CodeExtent,
497                                    scope_b: CodeExtent)
498                                    -> CodeExtent {
499         if scope_a == scope_b { return scope_a; }
500
501         /// [1] The initial values for `a_buf` and `b_buf` are not used.
502         /// The `ancestors_of` function will return some prefix that
503         /// is re-initialized with new values (or else fallback to a
504         /// heap-allocated vector).
505         let mut a_buf: [CodeExtent; 32] = [scope_a /* [1] */; 32];
506         let mut a_vec: Vec<CodeExtent> = vec![];
507         let mut b_buf: [CodeExtent; 32] = [scope_b /* [1] */; 32];
508         let mut b_vec: Vec<CodeExtent> = vec![];
509         let scope_map = &self.scope_map;
510         let a_ancestors = ancestors_of(scope_map, scope_a, &mut a_buf, &mut a_vec);
511         let b_ancestors = ancestors_of(scope_map, scope_b, &mut b_buf, &mut b_vec);
512         let mut a_index = a_ancestors.len() - 1;
513         let mut b_index = b_ancestors.len() - 1;
514
515         // Here, [ab]_ancestors is a vector going from narrow to broad.
516         // The end of each vector will be the item where the scope is
517         // defined; if there are any common ancestors, then the tails of
518         // the vector will be the same.  So basically we want to walk
519         // backwards from the tail of each vector and find the first point
520         // where they diverge.  If one vector is a suffix of the other,
521         // then the corresponding scope is a superscope of the other.
522
523         if a_ancestors[a_index] != b_ancestors[b_index] {
524             // In this case, the two regions belong to completely
525             // different functions.  Compare those fn for lexical
526             // nesting. The reasoning behind this is subtle.  See the
527             // "Modeling closures" section of the README in
528             // infer::region_inference for more details.
529             let a_root_scope = a_ancestors[a_index];
530             let b_root_scope = a_ancestors[a_index];
531             return match (a_root_scope, b_root_scope) {
532                 (CodeExtent::DestructionScope(a_root_id),
533                  CodeExtent::DestructionScope(b_root_id)) => {
534                     if self.fn_is_enclosed_by(a_root_id, b_root_id) {
535                         // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
536                         scope_b
537                     } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
538                         // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
539                         scope_a
540                     } else {
541                         // neither fn encloses the other
542                         bug!()
543                     }
544                 }
545                 _ => {
546                     // root ids are always Misc right now
547                     bug!()
548                 }
549             };
550         }
551
552         loop {
553             // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
554             // for all indices between a_index and the end of the array
555             if a_index == 0 { return scope_a; }
556             if b_index == 0 { return scope_b; }
557             a_index -= 1;
558             b_index -= 1;
559             if a_ancestors[a_index] != b_ancestors[b_index] {
560                 return a_ancestors[a_index + 1];
561             }
562         }
563
564         fn ancestors_of<'a, 'tcx>(scope_map: &FxHashMap<CodeExtent, CodeExtent>,
565                                   scope: CodeExtent,
566                                   buf: &'a mut [CodeExtent; 32],
567                                   vec: &'a mut Vec<CodeExtent>)
568                                   -> &'a [CodeExtent] {
569             // debug!("ancestors_of(scope={:?})", scope);
570             let mut scope = scope;
571
572             let mut i = 0;
573             while i < 32 {
574                 buf[i] = scope;
575                 match scope_map.get(&scope) {
576                     Some(&superscope) => scope = superscope,
577                     _ => return &buf[..i+1]
578                 }
579                 i += 1;
580             }
581
582             *vec = Vec::with_capacity(64);
583             vec.extend_from_slice(buf);
584             loop {
585                 vec.push(scope);
586                 match scope_map.get(&scope) {
587                     Some(&superscope) => scope = superscope,
588                     _ => return &*vec
589                 }
590             }
591         }
592     }
593
594     /// Assuming that the provided region was defined within this `RegionMaps`,
595     /// returns the outermost `CodeExtent` that the region outlives.
596     pub fn early_free_extent<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
597                                        br: &ty::EarlyBoundRegion)
598                                        -> CodeExtent {
599         let param_owner = tcx.parent_def_id(br.def_id).unwrap();
600
601         let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
602         let body_id = tcx.hir.maybe_body_owned_by(param_owner_id).unwrap_or_else(|| {
603             // The lifetime was defined on node that doesn't own a body,
604             // which in practice can only mean a trait or an impl, that
605             // is the parent of a method, and that is enforced below.
606             assert_eq!(Some(param_owner_id), self.root_parent,
607                        "free_extent: {:?} not recognized by the region maps for {:?}",
608                        param_owner,
609                        self.root_body.map(|body| tcx.hir.body_owner_def_id(body)));
610
611             // The trait/impl lifetime is in scope for the method's body.
612             self.root_body.unwrap()
613         });
614
615         CodeExtent::CallSiteScope(body_id)
616     }
617
618     /// Assuming that the provided region was defined within this `RegionMaps`,
619     /// returns the outermost `CodeExtent` that the region outlives.
620     pub fn free_extent<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
621                                  -> CodeExtent {
622         let param_owner = match fr.bound_region {
623             ty::BoundRegion::BrNamed(def_id, _) => {
624                 tcx.parent_def_id(def_id).unwrap()
625             }
626             _ => fr.scope
627         };
628
629         // Ensure that the named late-bound lifetimes were defined
630         // on the same function that they ended up being freed in.
631         assert_eq!(param_owner, fr.scope);
632
633         let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
634         CodeExtent::CallSiteScope(tcx.hir.body_owned_by(param_owner_id))
635     }
636 }
637
638 /// Records the lifetime of a local variable as `cx.var_parent`
639 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
640                        var_id: ast::NodeId,
641                        _sp: Span) {
642     match visitor.cx.var_parent {
643         None => {
644             // this can happen in extern fn declarations like
645             //
646             // extern fn isalnum(c: c_int) -> c_int
647         }
648         Some(parent_scope) =>
649             visitor.region_maps.record_var_scope(var_id, parent_scope),
650     }
651 }
652
653 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
654     debug!("resolve_block(blk.id={:?})", blk.id);
655
656     let prev_cx = visitor.cx;
657
658     // We treat the tail expression in the block (if any) somewhat
659     // differently from the statements. The issue has to do with
660     // temporary lifetimes. Consider the following:
661     //
662     //    quux({
663     //        let inner = ... (&bar()) ...;
664     //
665     //        (... (&foo()) ...) // (the tail expression)
666     //    }, other_argument());
667     //
668     // Each of the statements within the block is a terminating
669     // scope, and thus a temporary (e.g. the result of calling
670     // `bar()` in the initalizer expression for `let inner = ...;`)
671     // will be cleaned up immediately after its corresponding
672     // statement (i.e. `let inner = ...;`) executes.
673     //
674     // On the other hand, temporaries associated with evaluating the
675     // tail expression for the block are assigned lifetimes so that
676     // they will be cleaned up as part of the terminating scope
677     // *surrounding* the block expression. Here, the terminating
678     // scope for the block expression is the `quux(..)` call; so
679     // those temporaries will only be cleaned up *after* both
680     // `other_argument()` has run and also the call to `quux(..)`
681     // itself has returned.
682
683     visitor.enter_node_extent_with_dtor(blk.id);
684     visitor.cx.var_parent = visitor.cx.parent;
685
686     {
687         // This block should be kept approximately in sync with
688         // `intravisit::walk_block`. (We manually walk the block, rather
689         // than call `walk_block`, in order to maintain precise
690         // index information.)
691
692         for (i, statement) in blk.stmts.iter().enumerate() {
693             if let hir::StmtDecl(..) = statement.node {
694                 // Each StmtDecl introduces a subscope for bindings
695                 // introduced by the declaration; this subscope covers
696                 // a suffix of the block . Each subscope in a block
697                 // has the previous subscope in the block as a parent,
698                 // except for the first such subscope, which has the
699                 // block itself as a parent.
700                 visitor.enter_code_extent(
701                     CodeExtent::Remainder(BlockRemainder {
702                         block: blk.id,
703                         first_statement_index: i as u32
704                     })
705                 );
706                 visitor.cx.var_parent = visitor.cx.parent;
707             }
708             visitor.visit_stmt(statement)
709         }
710         walk_list!(visitor, visit_expr, &blk.expr);
711     }
712
713     visitor.cx = prev_cx;
714 }
715
716 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
717     visitor.terminating_scopes.insert(arm.body.id);
718
719     if let Some(ref expr) = arm.guard {
720         visitor.terminating_scopes.insert(expr.id);
721     }
722
723     intravisit::walk_arm(visitor, arm);
724 }
725
726 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
727     visitor.record_code_extent(CodeExtent::Misc(pat.id));
728
729     // If this is a binding then record the lifetime of that binding.
730     if let PatKind::Binding(..) = pat.node {
731         record_var_lifetime(visitor, pat.id, pat.span);
732     }
733
734     intravisit::walk_pat(visitor, pat);
735 }
736
737 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
738     let stmt_id = stmt.node.id();
739     debug!("resolve_stmt(stmt.id={:?})", stmt_id);
740
741     // Every statement will clean up the temporaries created during
742     // execution of that statement. Therefore each statement has an
743     // associated destruction scope that represents the extent of the
744     // statement plus its destructors, and thus the extent for which
745     // regions referenced by the destructors need to survive.
746     visitor.terminating_scopes.insert(stmt_id);
747
748     let prev_parent = visitor.cx.parent;
749     visitor.enter_node_extent_with_dtor(stmt_id);
750
751     intravisit::walk_stmt(visitor, stmt);
752
753     visitor.cx.parent = prev_parent;
754 }
755
756 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
757     debug!("resolve_expr(expr.id={:?})", expr.id);
758
759     let prev_cx = visitor.cx;
760     visitor.enter_node_extent_with_dtor(expr.id);
761
762     {
763         let terminating_scopes = &mut visitor.terminating_scopes;
764         let mut terminating = |id: ast::NodeId| {
765             terminating_scopes.insert(id);
766         };
767         match expr.node {
768             // Conditional or repeating scopes are always terminating
769             // scopes, meaning that temporaries cannot outlive them.
770             // This ensures fixed size stacks.
771
772             hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
773             hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
774                 // For shortcircuiting operators, mark the RHS as a terminating
775                 // scope since it only executes conditionally.
776                 terminating(r.id);
777             }
778
779             hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
780                 terminating(expr.id);
781                 terminating(then.id);
782                 terminating(otherwise.id);
783             }
784
785             hir::ExprIf(ref expr, ref then, None) => {
786                 terminating(expr.id);
787                 terminating(then.id);
788             }
789
790             hir::ExprLoop(ref body, _, _) => {
791                 terminating(body.id);
792             }
793
794             hir::ExprWhile(ref expr, ref body, _) => {
795                 terminating(expr.id);
796                 terminating(body.id);
797             }
798
799             hir::ExprMatch(..) => {
800                 visitor.cx.var_parent = visitor.cx.parent;
801             }
802
803             hir::ExprAssignOp(..) | hir::ExprIndex(..) |
804             hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
805                 // FIXME(#6268) Nested method calls
806                 //
807                 // The lifetimes for a call or method call look as follows:
808                 //
809                 // call.id
810                 // - arg0.id
811                 // - ...
812                 // - argN.id
813                 // - call.callee_id
814                 //
815                 // The idea is that call.callee_id represents *the time when
816                 // the invoked function is actually running* and call.id
817                 // represents *the time to prepare the arguments and make the
818                 // call*.  See the section "Borrows in Calls" borrowck/README.md
819                 // for an extended explanation of why this distinction is
820                 // important.
821                 //
822                 // record_superlifetime(new_cx, expr.callee_id);
823             }
824
825             _ => {}
826         }
827     }
828
829     match expr.node {
830         // Manually recurse over closures, because they are the only
831         // case of nested bodies that share the parent environment.
832         hir::ExprClosure(.., body, _) => {
833             let body = visitor.tcx.hir.body(body);
834             visitor.visit_body(body);
835         }
836
837         _ => intravisit::walk_expr(visitor, expr)
838     }
839
840     visitor.cx = prev_cx;
841 }
842
843 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
844                            local: &'tcx hir::Local) {
845     debug!("resolve_local(local.id={:?},local.init={:?})",
846            local.id,local.init.is_some());
847
848     // For convenience in trans, associate with the local-id the var
849     // scope that will be used for any bindings declared in this
850     // pattern.
851     let blk_scope = visitor.cx.var_parent;
852     let blk_scope = blk_scope.expect("locals must be within a block");
853     visitor.region_maps.record_var_scope(local.id, blk_scope);
854
855     // As an exception to the normal rules governing temporary
856     // lifetimes, initializers in a let have a temporary lifetime
857     // of the enclosing block. This means that e.g. a program
858     // like the following is legal:
859     //
860     //     let ref x = HashMap::new();
861     //
862     // Because the hash map will be freed in the enclosing block.
863     //
864     // We express the rules more formally based on 3 grammars (defined
865     // fully in the helpers below that implement them):
866     //
867     // 1. `E&`, which matches expressions like `&<rvalue>` that
868     //    own a pointer into the stack.
869     //
870     // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
871     //    y)` that produce ref bindings into the value they are
872     //    matched against or something (at least partially) owned by
873     //    the value they are matched against. (By partially owned,
874     //    I mean that creating a binding into a ref-counted or managed value
875     //    would still count.)
876     //
877     // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
878     //    based on rvalues like `foo().x[2].y`.
879     //
880     // A subexpression `<rvalue>` that appears in a let initializer
881     // `let pat [: ty] = expr` has an extended temporary lifetime if
882     // any of the following conditions are met:
883     //
884     // A. `pat` matches `P&` and `expr` matches `ET`
885     //    (covers cases where `pat` creates ref bindings into an rvalue
886     //     produced by `expr`)
887     // B. `ty` is a borrowed pointer and `expr` matches `ET`
888     //    (covers cases where coercion creates a borrow)
889     // C. `expr` matches `E&`
890     //    (covers cases `expr` borrows an rvalue that is then assigned
891     //     to memory (at least partially) owned by the binding)
892     //
893     // Here are some examples hopefully giving an intuition where each
894     // rule comes into play and why:
895     //
896     // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
897     // would have an extended lifetime, but not `foo()`.
898     //
899     // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
900     // would have an extended lifetime, but not `foo()`.
901     //
902     // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
903     // lifetime.
904     //
905     // In some cases, multiple rules may apply (though not to the same
906     // rvalue). For example:
907     //
908     //     let ref x = [&a(), &b()];
909     //
910     // Here, the expression `[...]` has an extended lifetime due to rule
911     // A, but the inner rvalues `a()` and `b()` have an extended lifetime
912     // due to rule C.
913     //
914     // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
915
916     if let Some(ref expr) = local.init {
917         record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
918
919         let is_borrow =
920             if let Some(ref ty) = local.ty { is_borrowed_ty(&ty) } else { false };
921
922         if is_binding_pat(&local.pat) {
923             record_rvalue_scope(visitor, &expr, blk_scope, false);
924         } else if is_borrow {
925             record_rvalue_scope(visitor, &expr, blk_scope, true);
926         }
927     }
928
929     intravisit::walk_local(visitor, local);
930
931     /// True if `pat` match the `P&` nonterminal:
932     ///
933     ///     P& = ref X
934     ///        | StructName { ..., P&, ... }
935     ///        | VariantName(..., P&, ...)
936     ///        | [ ..., P&, ... ]
937     ///        | ( ..., P&, ... )
938     ///        | box P&
939     fn is_binding_pat(pat: &hir::Pat) -> bool {
940         match pat.node {
941             PatKind::Binding(hir::BindByRef(_), ..) => true,
942
943             PatKind::Struct(_, ref field_pats, _) => {
944                 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
945             }
946
947             PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
948                 pats1.iter().any(|p| is_binding_pat(&p)) ||
949                 pats2.iter().any(|p| is_binding_pat(&p)) ||
950                 pats3.iter().any(|p| is_binding_pat(&p))
951             }
952
953             PatKind::TupleStruct(_, ref subpats, _) |
954             PatKind::Tuple(ref subpats, _) => {
955                 subpats.iter().any(|p| is_binding_pat(&p))
956             }
957
958             PatKind::Box(ref subpat) => {
959                 is_binding_pat(&subpat)
960             }
961
962             _ => false,
963         }
964     }
965
966     /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
967     fn is_borrowed_ty(ty: &hir::Ty) -> bool {
968         match ty.node {
969             hir::TyRptr(..) => true,
970             _ => false
971         }
972     }
973
974     /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
975     ///
976     ///     E& = & ET
977     ///        | StructName { ..., f: E&, ... }
978     ///        | [ ..., E&, ... ]
979     ///        | ( ..., E&, ... )
980     ///        | {...; E&}
981     ///        | box E&
982     ///        | E& as ...
983     ///        | ( E& )
984     fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
985         visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
986         expr: &hir::Expr,
987         blk_id: CodeExtent)
988     {
989         match expr.node {
990             hir::ExprAddrOf(_, ref subexpr) => {
991                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
992                 record_rvalue_scope(visitor, &subexpr, blk_id, false);
993             }
994             hir::ExprStruct(_, ref fields, _) => {
995                 for field in fields {
996                     record_rvalue_scope_if_borrow_expr(
997                         visitor, &field.expr, blk_id);
998                 }
999             }
1000             hir::ExprArray(ref subexprs) |
1001             hir::ExprTup(ref subexprs) => {
1002                 for subexpr in subexprs {
1003                     record_rvalue_scope_if_borrow_expr(
1004                         visitor, &subexpr, blk_id);
1005                 }
1006             }
1007             hir::ExprCast(ref subexpr, _) => {
1008                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
1009             }
1010             hir::ExprBlock(ref block) => {
1011                 if let Some(ref subexpr) = block.expr {
1012                     record_rvalue_scope_if_borrow_expr(
1013                         visitor, &subexpr, blk_id);
1014                 }
1015             }
1016             _ => {}
1017         }
1018     }
1019
1020     /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
1021     /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
1022     /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
1023     /// statement.
1024     ///
1025     /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
1026     /// `<rvalue>` as `blk_id`:
1027     ///
1028     ///     ET = *ET
1029     ///        | ET[...]
1030     ///        | ET.f
1031     ///        | (ET)
1032     ///        | <rvalue>
1033     ///
1034     /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
1035     fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
1036                                      expr: &hir::Expr,
1037                                      blk_scope: CodeExtent,
1038                                      is_shrunk: bool) {
1039         let mut expr = expr;
1040         loop {
1041             // Note: give all the expressions matching `ET` with the
1042             // extended temporary lifetime, not just the innermost rvalue,
1043             // because in trans if we must compile e.g. `*rvalue()`
1044             // into a temporary, we request the temporary scope of the
1045             // outer expression.
1046             if is_shrunk {
1047                 // this changed because of #36082
1048                 visitor.region_maps.record_shrunk_rvalue_scope(expr.id, blk_scope);
1049             } else {
1050                 visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
1051             }
1052
1053             match expr.node {
1054                 hir::ExprAddrOf(_, ref subexpr) |
1055                 hir::ExprUnary(hir::UnDeref, ref subexpr) |
1056                 hir::ExprField(ref subexpr, _) |
1057                 hir::ExprTupField(ref subexpr, _) |
1058                 hir::ExprIndex(ref subexpr, _) => {
1059                     expr = &subexpr;
1060                 }
1061                 _ => {
1062                     return;
1063                 }
1064             }
1065         }
1066     }
1067 }
1068
1069 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1070     /// Records the current parent (if any) as the parent of `child_scope`.
1071     fn record_code_extent(&mut self, child_scope: CodeExtent) {
1072         let parent = self.cx.parent;
1073         self.region_maps.record_code_extent(child_scope, parent);
1074     }
1075
1076     /// Records the current parent (if any) as the parent of `child_scope`,
1077     /// and sets `child_scope` as the new current parent.
1078     fn enter_code_extent(&mut self, child_scope: CodeExtent) {
1079         self.record_code_extent(child_scope);
1080         self.cx.parent = Some(child_scope);
1081     }
1082
1083     fn enter_node_extent_with_dtor(&mut self, id: ast::NodeId) {
1084         // If node was previously marked as a terminating scope during the
1085         // recursive visit of its parent node in the AST, then we need to
1086         // account for the destruction scope representing the extent of
1087         // the destructors that run immediately after it completes.
1088         if self.terminating_scopes.contains(&id) {
1089             self.enter_code_extent(CodeExtent::DestructionScope(id));
1090         }
1091         self.enter_code_extent(CodeExtent::Misc(id));
1092     }
1093 }
1094
1095 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1096     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1097         NestedVisitorMap::None
1098     }
1099
1100     fn visit_block(&mut self, b: &'tcx Block) {
1101         resolve_block(self, b);
1102     }
1103
1104     fn visit_body(&mut self, body: &'tcx hir::Body) {
1105         let body_id = body.id();
1106         let owner_id = self.tcx.hir.body_owner(body_id);
1107
1108         debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1109                owner_id,
1110                self.tcx.sess.codemap().span_to_string(body.value.span),
1111                body_id,
1112                self.cx.parent);
1113
1114         let outer_cx = self.cx;
1115         let outer_ts = mem::replace(&mut self.terminating_scopes, NodeSet());
1116
1117         // Only functions have an outer terminating (drop) scope,
1118         // while temporaries in constant initializers are 'static.
1119         if let MirSource::Fn(_) = MirSource::from_node(self.tcx, owner_id) {
1120             self.terminating_scopes.insert(body_id.node_id);
1121         }
1122
1123         if let Some(root_id) = self.cx.root_id {
1124             self.region_maps.record_fn_parent(body_id.node_id, root_id);
1125         }
1126         self.cx.root_id = Some(body_id.node_id);
1127
1128         self.enter_code_extent(CodeExtent::CallSiteScope(body_id));
1129         self.enter_code_extent(CodeExtent::ParameterScope(body_id));
1130
1131         // The arguments and `self` are parented to the fn.
1132         self.cx.var_parent = self.cx.parent.take();
1133         for argument in &body.arguments {
1134             self.visit_pat(&argument.pat);
1135         }
1136
1137         // The body of the every fn is a root scope.
1138         self.cx.parent = self.cx.var_parent;
1139         self.visit_expr(&body.value);
1140
1141         // Restore context we had at the start.
1142         self.cx = outer_cx;
1143         self.terminating_scopes = outer_ts;
1144     }
1145
1146     fn visit_arm(&mut self, a: &'tcx Arm) {
1147         resolve_arm(self, a);
1148     }
1149     fn visit_pat(&mut self, p: &'tcx Pat) {
1150         resolve_pat(self, p);
1151     }
1152     fn visit_stmt(&mut self, s: &'tcx Stmt) {
1153         resolve_stmt(self, s);
1154     }
1155     fn visit_expr(&mut self, ex: &'tcx Expr) {
1156         resolve_expr(self, ex);
1157     }
1158     fn visit_local(&mut self, l: &'tcx Local) {
1159         resolve_local(self, l);
1160     }
1161 }
1162
1163 fn region_maps<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1164     -> Rc<RegionMaps>
1165 {
1166     let closure_base_def_id = tcx.closure_base_def_id(def_id);
1167     if closure_base_def_id != def_id {
1168         return tcx.region_maps(closure_base_def_id);
1169     }
1170
1171     let id = tcx.hir.as_local_node_id(def_id).unwrap();
1172     let maps = if let Some(body) = tcx.hir.maybe_body_owned_by(id) {
1173         let mut visitor = RegionResolutionVisitor {
1174             tcx,
1175             region_maps: RegionMaps::new(),
1176             cx: Context {
1177                 root_id: None,
1178                 parent: None,
1179                 var_parent: None,
1180             },
1181             terminating_scopes: NodeSet(),
1182         };
1183
1184         visitor.region_maps.root_body = Some(body);
1185
1186         // If the item is an associated const or a method,
1187         // record its impl/trait parent, as it can also have
1188         // lifetime parameters free in this body.
1189         match tcx.hir.get(id) {
1190             hir::map::NodeImplItem(_) |
1191             hir::map::NodeTraitItem(_) => {
1192                 visitor.region_maps.root_parent = Some(tcx.hir.get_parent(id));
1193             }
1194             _ => {}
1195         }
1196
1197         visitor.visit_body(tcx.hir.body(body));
1198
1199         visitor.region_maps
1200     } else {
1201         RegionMaps::new()
1202     };
1203
1204     Rc::new(maps)
1205 }
1206
1207 pub fn provide(providers: &mut Providers) {
1208     *providers = Providers {
1209         region_maps,
1210         ..*providers
1211     };
1212 }