]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/region.rs
Fix checking for missing stability annotations
[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     /// Encodes the hierarchy of fn bodies. Every fn body (including
227     /// closures) forms its own distinct region hierarchy, rooted in
228     /// the block that is the fn body. This map points from the id of
229     /// that root block to the id of the root block for the enclosing
230     /// fn, if any. Thus the map structures the fn bodies into a
231     /// hierarchy based on their lexical mapping. This is used to
232     /// handle the relationships between regions in a fn and in a
233     /// closure defined by that fn. See the "Modeling closures"
234     /// section of the README in infer::region_inference for
235     /// more details.
236     fn_tree: NodeMap<ast::NodeId>,
237 }
238
239 #[derive(Debug, Copy, Clone)]
240 pub struct Context {
241     /// the root of the current region tree. This is typically the id
242     /// of the innermost fn body. Each fn forms its own disjoint tree
243     /// in the region hierarchy. These fn bodies are themselves
244     /// arranged into a tree. See the "Modeling closures" section of
245     /// the README in infer::region_inference for more
246     /// details.
247     root_id: Option<ast::NodeId>,
248
249     /// the scope that contains any new variables declared
250     var_parent: Option<CodeExtent>,
251
252     /// region parent of expressions etc
253     parent: Option<CodeExtent>,
254 }
255
256 struct RegionResolutionVisitor<'a, 'tcx: 'a> {
257     tcx: TyCtxt<'a, 'tcx, 'tcx>,
258
259     // Generated maps:
260     region_maps: RegionMaps,
261
262     cx: Context,
263
264     /// `terminating_scopes` is a set containing the ids of each
265     /// statement, or conditional/repeating expression. These scopes
266     /// are calling "terminating scopes" because, when attempting to
267     /// find the scope of a temporary, by default we search up the
268     /// enclosing scopes until we encounter the terminating scope. A
269     /// conditional/repeating expression is one which is not
270     /// guaranteed to execute exactly once upon entering the parent
271     /// scope. This could be because the expression only executes
272     /// conditionally, such as the expression `b` in `a && b`, or
273     /// because the expression may execute many times, such as a loop
274     /// body. The reason that we distinguish such expressions is that,
275     /// upon exiting the parent scope, we cannot statically know how
276     /// many times the expression executed, and thus if the expression
277     /// creates temporaries we cannot know statically how many such
278     /// temporaries we would have to cleanup. Therefore we ensure that
279     /// the temporaries never outlast the conditional/repeating
280     /// expression, preventing the need for dynamic checks and/or
281     /// arbitrary amounts of stack space. Terminating scopes end
282     /// up being contained in a DestructionScope that contains the
283     /// destructor's execution.
284     terminating_scopes: NodeSet,
285 }
286
287
288 impl<'tcx> RegionMaps {
289     pub fn new() -> Self {
290         RegionMaps {
291             root_body: None,
292             root_parent: None,
293             scope_map: FxHashMap(),
294             destruction_scopes: FxHashMap(),
295             var_map: NodeMap(),
296             rvalue_scopes: NodeMap(),
297             fn_tree: NodeMap(),
298         }
299     }
300
301     pub fn record_code_extent(&mut self,
302                               child: CodeExtent,
303                               parent: Option<CodeExtent>) {
304         debug!("{:?}.parent = {:?}", child, parent);
305
306         if let Some(p) = parent {
307             let prev = self.scope_map.insert(child, p);
308             assert!(prev.is_none());
309         }
310
311         // record the destruction scopes for later so we can query them
312         if let CodeExtent::DestructionScope(n) = child {
313             self.destruction_scopes.insert(n, child);
314         }
315     }
316
317     pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(CodeExtent, CodeExtent) {
318         for (&child, &parent) in &self.scope_map {
319             e(child, parent)
320         }
321     }
322
323     pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&ast::NodeId, CodeExtent) {
324         for (child, &parent) in self.var_map.iter() {
325             e(child, parent)
326         }
327     }
328
329     pub fn opt_destruction_extent(&self, n: ast::NodeId) -> Option<CodeExtent> {
330         self.destruction_scopes.get(&n).cloned()
331     }
332
333     /// Records that `sub_fn` is defined within `sup_fn`. These ids
334     /// should be the id of the block that is the fn body, which is
335     /// also the root of the region hierarchy for that fn.
336     fn record_fn_parent(&mut self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
337         debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
338         assert!(sub_fn != sup_fn);
339         let previous = self.fn_tree.insert(sub_fn, sup_fn);
340         assert!(previous.is_none());
341     }
342
343     fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
344         loop {
345             if sub_fn == sup_fn { return true; }
346             match self.fn_tree.get(&sub_fn) {
347                 Some(&s) => { sub_fn = s; }
348                 None => { return false; }
349             }
350         }
351     }
352
353     fn record_var_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent) {
354         debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
355         assert!(var != lifetime.node_id());
356         self.var_map.insert(var, lifetime);
357     }
358
359     fn record_rvalue_scope(&mut self, var: ast::NodeId, lifetime: CodeExtent) {
360         debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
361         assert!(var != lifetime.node_id());
362         self.rvalue_scopes.insert(var, lifetime);
363     }
364
365     pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
366         //! Returns the narrowest scope that encloses `id`, if any.
367         self.scope_map.get(&id).cloned()
368     }
369
370     #[allow(dead_code)] // used in cfg
371     pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
372         //! Returns the narrowest scope that encloses `id`, if any.
373         self.opt_encl_scope(id).unwrap()
374     }
375
376     /// Returns the lifetime of the local variable `var_id`
377     pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
378         match self.var_map.get(&var_id) {
379             Some(&r) => r,
380             None => { bug!("no enclosing scope for id {:?}", var_id); }
381         }
382     }
383
384     pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
385         //! Returns the scope when temp created by expr_id will be cleaned up
386
387         // check for a designated rvalue scope
388         if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
389             debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
390             return Some(s);
391         }
392
393         // else, locate the innermost terminating scope
394         // if there's one. Static items, for instance, won't
395         // have an enclosing scope, hence no scope will be
396         // returned.
397         let mut id = CodeExtent::Misc(expr_id);
398
399         while let Some(&p) = self.scope_map.get(&id) {
400             match p {
401                 CodeExtent::DestructionScope(..) => {
402                     debug!("temporary_scope({:?}) = {:?} [enclosing]",
403                            expr_id, id);
404                     return Some(id);
405                 }
406                 _ => id = p
407             }
408         }
409
410         debug!("temporary_scope({:?}) = None", expr_id);
411         return None;
412     }
413
414     pub fn var_region(&self, id: ast::NodeId) -> ty::RegionKind {
415         //! Returns the lifetime of the variable `id`.
416
417         let scope = ty::ReScope(self.var_scope(id));
418         debug!("var_region({:?}) = {:?}", id, scope);
419         scope
420     }
421
422     pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
423                             -> bool {
424         self.is_subscope_of(scope1, scope2) ||
425         self.is_subscope_of(scope2, scope1)
426     }
427
428     /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
429     /// otherwise.
430     pub fn is_subscope_of(&self,
431                           subscope: CodeExtent,
432                           superscope: CodeExtent)
433                           -> bool {
434         let mut s = subscope;
435         debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
436         while superscope != s {
437             match self.opt_encl_scope(s) {
438                 None => {
439                     debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
440                            subscope, superscope, s);
441                     return false;
442                 }
443                 Some(scope) => s = scope
444             }
445         }
446
447         debug!("is_subscope_of({:?}, {:?})=true",
448                subscope, superscope);
449
450         return true;
451     }
452
453     /// Finds the nearest common ancestor (if any) of two scopes.  That is, finds the smallest
454     /// scope which is greater than or equal to both `scope_a` and `scope_b`.
455     pub fn nearest_common_ancestor(&self,
456                                    scope_a: CodeExtent,
457                                    scope_b: CodeExtent)
458                                    -> CodeExtent {
459         if scope_a == scope_b { return scope_a; }
460
461         /// [1] The initial values for `a_buf` and `b_buf` are not used.
462         /// The `ancestors_of` function will return some prefix that
463         /// is re-initialized with new values (or else fallback to a
464         /// heap-allocated vector).
465         let mut a_buf: [CodeExtent; 32] = [scope_a /* [1] */; 32];
466         let mut a_vec: Vec<CodeExtent> = vec![];
467         let mut b_buf: [CodeExtent; 32] = [scope_b /* [1] */; 32];
468         let mut b_vec: Vec<CodeExtent> = vec![];
469         let scope_map = &self.scope_map;
470         let a_ancestors = ancestors_of(scope_map, scope_a, &mut a_buf, &mut a_vec);
471         let b_ancestors = ancestors_of(scope_map, scope_b, &mut b_buf, &mut b_vec);
472         let mut a_index = a_ancestors.len() - 1;
473         let mut b_index = b_ancestors.len() - 1;
474
475         // Here, [ab]_ancestors is a vector going from narrow to broad.
476         // The end of each vector will be the item where the scope is
477         // defined; if there are any common ancestors, then the tails of
478         // the vector will be the same.  So basically we want to walk
479         // backwards from the tail of each vector and find the first point
480         // where they diverge.  If one vector is a suffix of the other,
481         // then the corresponding scope is a superscope of the other.
482
483         if a_ancestors[a_index] != b_ancestors[b_index] {
484             // In this case, the two regions belong to completely
485             // different functions.  Compare those fn for lexical
486             // nesting. The reasoning behind this is subtle.  See the
487             // "Modeling closures" section of the README in
488             // infer::region_inference for more details.
489             let a_root_scope = a_ancestors[a_index];
490             let b_root_scope = a_ancestors[a_index];
491             return match (a_root_scope, b_root_scope) {
492                 (CodeExtent::DestructionScope(a_root_id),
493                  CodeExtent::DestructionScope(b_root_id)) => {
494                     if self.fn_is_enclosed_by(a_root_id, b_root_id) {
495                         // `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
496                         scope_b
497                     } else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
498                         // `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
499                         scope_a
500                     } else {
501                         // neither fn encloses the other
502                         bug!()
503                     }
504                 }
505                 _ => {
506                     // root ids are always Misc right now
507                     bug!()
508                 }
509             };
510         }
511
512         loop {
513             // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
514             // for all indices between a_index and the end of the array
515             if a_index == 0 { return scope_a; }
516             if b_index == 0 { return scope_b; }
517             a_index -= 1;
518             b_index -= 1;
519             if a_ancestors[a_index] != b_ancestors[b_index] {
520                 return a_ancestors[a_index + 1];
521             }
522         }
523
524         fn ancestors_of<'a, 'tcx>(scope_map: &FxHashMap<CodeExtent, CodeExtent>,
525                                   scope: CodeExtent,
526                                   buf: &'a mut [CodeExtent; 32],
527                                   vec: &'a mut Vec<CodeExtent>)
528                                   -> &'a [CodeExtent] {
529             // debug!("ancestors_of(scope={:?})", scope);
530             let mut scope = scope;
531
532             let mut i = 0;
533             while i < 32 {
534                 buf[i] = scope;
535                 match scope_map.get(&scope) {
536                     Some(&superscope) => scope = superscope,
537                     _ => return &buf[..i+1]
538                 }
539                 i += 1;
540             }
541
542             *vec = Vec::with_capacity(64);
543             vec.extend_from_slice(buf);
544             loop {
545                 vec.push(scope);
546                 match scope_map.get(&scope) {
547                     Some(&superscope) => scope = superscope,
548                     _ => return &*vec
549                 }
550             }
551         }
552     }
553
554     /// Assuming that the provided region was defined within this `RegionMaps`,
555     /// returns the outermost `CodeExtent` that the region outlives.
556     pub fn early_free_extent<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
557                                        br: &ty::EarlyBoundRegion)
558                                        -> CodeExtent {
559         let param_owner = tcx.parent_def_id(br.def_id).unwrap();
560
561         let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
562         let body_id = tcx.hir.maybe_body_owned_by(param_owner_id).unwrap_or_else(|| {
563             // The lifetime was defined on node that doesn't own a body,
564             // which in practice can only mean a trait or an impl, that
565             // is the parent of a method, and that is enforced below.
566             assert_eq!(Some(param_owner_id), self.root_parent,
567                        "free_extent: {:?} not recognized by the region maps for {:?}",
568                        param_owner,
569                        self.root_body.map(|body| tcx.hir.body_owner_def_id(body)));
570
571             // The trait/impl lifetime is in scope for the method's body.
572             self.root_body.unwrap()
573         });
574
575         CodeExtent::CallSiteScope(body_id)
576     }
577
578     /// Assuming that the provided region was defined within this `RegionMaps`,
579     /// returns the outermost `CodeExtent` that the region outlives.
580     pub fn free_extent<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
581                                  -> CodeExtent {
582         let param_owner = match fr.bound_region {
583             ty::BoundRegion::BrNamed(def_id, _) => {
584                 tcx.parent_def_id(def_id).unwrap()
585             }
586             _ => fr.scope
587         };
588
589         // Ensure that the named late-bound lifetimes were defined
590         // on the same function that they ended up being freed in.
591         assert_eq!(param_owner, fr.scope);
592
593         let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
594         CodeExtent::CallSiteScope(tcx.hir.body_owned_by(param_owner_id))
595     }
596 }
597
598 /// Records the lifetime of a local variable as `cx.var_parent`
599 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
600                        var_id: ast::NodeId,
601                        _sp: Span) {
602     match visitor.cx.var_parent {
603         None => {
604             // this can happen in extern fn declarations like
605             //
606             // extern fn isalnum(c: c_int) -> c_int
607         }
608         Some(parent_scope) =>
609             visitor.region_maps.record_var_scope(var_id, parent_scope),
610     }
611 }
612
613 fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
614     debug!("resolve_block(blk.id={:?})", blk.id);
615
616     let prev_cx = visitor.cx;
617
618     // We treat the tail expression in the block (if any) somewhat
619     // differently from the statements. The issue has to do with
620     // temporary lifetimes. Consider the following:
621     //
622     //    quux({
623     //        let inner = ... (&bar()) ...;
624     //
625     //        (... (&foo()) ...) // (the tail expression)
626     //    }, other_argument());
627     //
628     // Each of the statements within the block is a terminating
629     // scope, and thus a temporary (e.g. the result of calling
630     // `bar()` in the initalizer expression for `let inner = ...;`)
631     // will be cleaned up immediately after its corresponding
632     // statement (i.e. `let inner = ...;`) executes.
633     //
634     // On the other hand, temporaries associated with evaluating the
635     // tail expression for the block are assigned lifetimes so that
636     // they will be cleaned up as part of the terminating scope
637     // *surrounding* the block expression. Here, the terminating
638     // scope for the block expression is the `quux(..)` call; so
639     // those temporaries will only be cleaned up *after* both
640     // `other_argument()` has run and also the call to `quux(..)`
641     // itself has returned.
642
643     visitor.enter_node_extent_with_dtor(blk.id);
644     visitor.cx.var_parent = visitor.cx.parent;
645
646     {
647         // This block should be kept approximately in sync with
648         // `intravisit::walk_block`. (We manually walk the block, rather
649         // than call `walk_block`, in order to maintain precise
650         // index information.)
651
652         for (i, statement) in blk.stmts.iter().enumerate() {
653             if let hir::StmtDecl(..) = statement.node {
654                 // Each StmtDecl introduces a subscope for bindings
655                 // introduced by the declaration; this subscope covers
656                 // a suffix of the block . Each subscope in a block
657                 // has the previous subscope in the block as a parent,
658                 // except for the first such subscope, which has the
659                 // block itself as a parent.
660                 visitor.enter_code_extent(
661                     CodeExtent::Remainder(BlockRemainder {
662                         block: blk.id,
663                         first_statement_index: i as u32
664                     })
665                 );
666                 visitor.cx.var_parent = visitor.cx.parent;
667             }
668             visitor.visit_stmt(statement)
669         }
670         walk_list!(visitor, visit_expr, &blk.expr);
671     }
672
673     visitor.cx = prev_cx;
674 }
675
676 fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
677     visitor.terminating_scopes.insert(arm.body.id);
678
679     if let Some(ref expr) = arm.guard {
680         visitor.terminating_scopes.insert(expr.id);
681     }
682
683     intravisit::walk_arm(visitor, arm);
684 }
685
686 fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
687     visitor.record_code_extent(CodeExtent::Misc(pat.id));
688
689     // If this is a binding then record the lifetime of that binding.
690     if let PatKind::Binding(..) = pat.node {
691         record_var_lifetime(visitor, pat.id, pat.span);
692     }
693
694     intravisit::walk_pat(visitor, pat);
695 }
696
697 fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
698     let stmt_id = stmt.node.id();
699     debug!("resolve_stmt(stmt.id={:?})", stmt_id);
700
701     // Every statement will clean up the temporaries created during
702     // execution of that statement. Therefore each statement has an
703     // associated destruction scope that represents the extent of the
704     // statement plus its destructors, and thus the extent for which
705     // regions referenced by the destructors need to survive.
706     visitor.terminating_scopes.insert(stmt_id);
707
708     let prev_parent = visitor.cx.parent;
709     visitor.enter_node_extent_with_dtor(stmt_id);
710
711     intravisit::walk_stmt(visitor, stmt);
712
713     visitor.cx.parent = prev_parent;
714 }
715
716 fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
717     debug!("resolve_expr(expr.id={:?})", expr.id);
718
719     let prev_cx = visitor.cx;
720     visitor.enter_node_extent_with_dtor(expr.id);
721
722     {
723         let terminating_scopes = &mut visitor.terminating_scopes;
724         let mut terminating = |id: ast::NodeId| {
725             terminating_scopes.insert(id);
726         };
727         match expr.node {
728             // Conditional or repeating scopes are always terminating
729             // scopes, meaning that temporaries cannot outlive them.
730             // This ensures fixed size stacks.
731
732             hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
733             hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
734                 // For shortcircuiting operators, mark the RHS as a terminating
735                 // scope since it only executes conditionally.
736                 terminating(r.id);
737             }
738
739             hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
740                 terminating(expr.id);
741                 terminating(then.id);
742                 terminating(otherwise.id);
743             }
744
745             hir::ExprIf(ref expr, ref then, None) => {
746                 terminating(expr.id);
747                 terminating(then.id);
748             }
749
750             hir::ExprLoop(ref body, _, _) => {
751                 terminating(body.id);
752             }
753
754             hir::ExprWhile(ref expr, ref body, _) => {
755                 terminating(expr.id);
756                 terminating(body.id);
757             }
758
759             hir::ExprMatch(..) => {
760                 visitor.cx.var_parent = visitor.cx.parent;
761             }
762
763             hir::ExprAssignOp(..) | hir::ExprIndex(..) |
764             hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
765                 // FIXME(#6268) Nested method calls
766                 //
767                 // The lifetimes for a call or method call look as follows:
768                 //
769                 // call.id
770                 // - arg0.id
771                 // - ...
772                 // - argN.id
773                 // - call.callee_id
774                 //
775                 // The idea is that call.callee_id represents *the time when
776                 // the invoked function is actually running* and call.id
777                 // represents *the time to prepare the arguments and make the
778                 // call*.  See the section "Borrows in Calls" borrowck/README.md
779                 // for an extended explanation of why this distinction is
780                 // important.
781                 //
782                 // record_superlifetime(new_cx, expr.callee_id);
783             }
784
785             _ => {}
786         }
787     }
788
789     match expr.node {
790         // Manually recurse over closures, because they are the only
791         // case of nested bodies that share the parent environment.
792         hir::ExprClosure(.., body, _) => {
793             let body = visitor.tcx.hir.body(body);
794             visitor.visit_body(body);
795         }
796
797         _ => intravisit::walk_expr(visitor, expr)
798     }
799
800     visitor.cx = prev_cx;
801 }
802
803 fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
804                            local: &'tcx hir::Local) {
805     debug!("resolve_local(local.id={:?},local.init={:?})",
806            local.id,local.init.is_some());
807
808     // For convenience in trans, associate with the local-id the var
809     // scope that will be used for any bindings declared in this
810     // pattern.
811     let blk_scope = visitor.cx.var_parent;
812     let blk_scope = blk_scope.expect("locals must be within a block");
813     visitor.region_maps.record_var_scope(local.id, blk_scope);
814
815     // As an exception to the normal rules governing temporary
816     // lifetimes, initializers in a let have a temporary lifetime
817     // of the enclosing block. This means that e.g. a program
818     // like the following is legal:
819     //
820     //     let ref x = HashMap::new();
821     //
822     // Because the hash map will be freed in the enclosing block.
823     //
824     // We express the rules more formally based on 3 grammars (defined
825     // fully in the helpers below that implement them):
826     //
827     // 1. `E&`, which matches expressions like `&<rvalue>` that
828     //    own a pointer into the stack.
829     //
830     // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
831     //    y)` that produce ref bindings into the value they are
832     //    matched against or something (at least partially) owned by
833     //    the value they are matched against. (By partially owned,
834     //    I mean that creating a binding into a ref-counted or managed value
835     //    would still count.)
836     //
837     // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
838     //    based on rvalues like `foo().x[2].y`.
839     //
840     // A subexpression `<rvalue>` that appears in a let initializer
841     // `let pat [: ty] = expr` has an extended temporary lifetime if
842     // any of the following conditions are met:
843     //
844     // A. `pat` matches `P&` and `expr` matches `ET`
845     //    (covers cases where `pat` creates ref bindings into an rvalue
846     //     produced by `expr`)
847     // B. `ty` is a borrowed pointer and `expr` matches `ET`
848     //    (covers cases where coercion creates a borrow)
849     // C. `expr` matches `E&`
850     //    (covers cases `expr` borrows an rvalue that is then assigned
851     //     to memory (at least partially) owned by the binding)
852     //
853     // Here are some examples hopefully giving an intuition where each
854     // rule comes into play and why:
855     //
856     // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
857     // would have an extended lifetime, but not `foo()`.
858     //
859     // Rule B. `let x = &foo().x`. The rvalue ``foo()` would have extended
860     // lifetime.
861     //
862     // In some cases, multiple rules may apply (though not to the same
863     // rvalue). For example:
864     //
865     //     let ref x = [&a(), &b()];
866     //
867     // Here, the expression `[...]` has an extended lifetime due to rule
868     // A, but the inner rvalues `a()` and `b()` have an extended lifetime
869     // due to rule C.
870     //
871     // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
872
873     if let Some(ref expr) = local.init {
874         record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope);
875
876         if is_binding_pat(&local.pat) {
877             record_rvalue_scope(visitor, &expr, blk_scope);
878         }
879     }
880
881     intravisit::walk_local(visitor, local);
882
883     /// True if `pat` match the `P&` nonterminal:
884     ///
885     ///     P& = ref X
886     ///        | StructName { ..., P&, ... }
887     ///        | VariantName(..., P&, ...)
888     ///        | [ ..., P&, ... ]
889     ///        | ( ..., P&, ... )
890     ///        | box P&
891     fn is_binding_pat(pat: &hir::Pat) -> bool {
892         match pat.node {
893             PatKind::Binding(hir::BindByRef(_), ..) => true,
894
895             PatKind::Struct(_, ref field_pats, _) => {
896                 field_pats.iter().any(|fp| is_binding_pat(&fp.node.pat))
897             }
898
899             PatKind::Slice(ref pats1, ref pats2, ref pats3) => {
900                 pats1.iter().any(|p| is_binding_pat(&p)) ||
901                 pats2.iter().any(|p| is_binding_pat(&p)) ||
902                 pats3.iter().any(|p| is_binding_pat(&p))
903             }
904
905             PatKind::TupleStruct(_, ref subpats, _) |
906             PatKind::Tuple(ref subpats, _) => {
907                 subpats.iter().any(|p| is_binding_pat(&p))
908             }
909
910             PatKind::Box(ref subpat) => {
911                 is_binding_pat(&subpat)
912             }
913
914             _ => false,
915         }
916     }
917
918     /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
919     ///
920     ///     E& = & ET
921     ///        | StructName { ..., f: E&, ... }
922     ///        | [ ..., E&, ... ]
923     ///        | ( ..., E&, ... )
924     ///        | {...; E&}
925     ///        | box E&
926     ///        | E& as ...
927     ///        | ( E& )
928     fn record_rvalue_scope_if_borrow_expr<'a, 'tcx>(
929         visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
930         expr: &hir::Expr,
931         blk_id: CodeExtent)
932     {
933         match expr.node {
934             hir::ExprAddrOf(_, ref subexpr) => {
935                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id);
936                 record_rvalue_scope(visitor, &subexpr, blk_id);
937             }
938             hir::ExprStruct(_, ref fields, _) => {
939                 for field in fields {
940                     record_rvalue_scope_if_borrow_expr(
941                         visitor, &field.expr, blk_id);
942                 }
943             }
944             hir::ExprArray(ref subexprs) |
945             hir::ExprTup(ref subexprs) => {
946                 for subexpr in subexprs {
947                     record_rvalue_scope_if_borrow_expr(
948                         visitor, &subexpr, blk_id);
949                 }
950             }
951             hir::ExprCast(ref subexpr, _) => {
952                 record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id)
953             }
954             hir::ExprBlock(ref block) => {
955                 if let Some(ref subexpr) = block.expr {
956                     record_rvalue_scope_if_borrow_expr(
957                         visitor, &subexpr, blk_id);
958                 }
959             }
960             _ => {}
961         }
962     }
963
964     /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
965     /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
966     /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
967     /// statement.
968     ///
969     /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
970     /// `<rvalue>` as `blk_id`:
971     ///
972     ///     ET = *ET
973     ///        | ET[...]
974     ///        | ET.f
975     ///        | (ET)
976     ///        | <rvalue>
977     ///
978     /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
979     fn record_rvalue_scope<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>,
980                                      expr: &hir::Expr,
981                                      blk_scope: CodeExtent) {
982         let mut expr = expr;
983         loop {
984             // Note: give all the expressions matching `ET` with the
985             // extended temporary lifetime, not just the innermost rvalue,
986             // because in trans if we must compile e.g. `*rvalue()`
987             // into a temporary, we request the temporary scope of the
988             // outer expression.
989             visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
990
991             match expr.node {
992                 hir::ExprAddrOf(_, ref subexpr) |
993                 hir::ExprUnary(hir::UnDeref, ref subexpr) |
994                 hir::ExprField(ref subexpr, _) |
995                 hir::ExprTupField(ref subexpr, _) |
996                 hir::ExprIndex(ref subexpr, _) => {
997                     expr = &subexpr;
998                 }
999                 _ => {
1000                     return;
1001                 }
1002             }
1003         }
1004     }
1005 }
1006
1007 impl<'a, 'tcx> RegionResolutionVisitor<'a, 'tcx> {
1008     /// Records the current parent (if any) as the parent of `child_scope`.
1009     fn record_code_extent(&mut self, child_scope: CodeExtent) {
1010         let parent = self.cx.parent;
1011         self.region_maps.record_code_extent(child_scope, parent);
1012     }
1013
1014     /// Records the current parent (if any) as the parent of `child_scope`,
1015     /// and sets `child_scope` as the new current parent.
1016     fn enter_code_extent(&mut self, child_scope: CodeExtent) {
1017         self.record_code_extent(child_scope);
1018         self.cx.parent = Some(child_scope);
1019     }
1020
1021     fn enter_node_extent_with_dtor(&mut self, id: ast::NodeId) {
1022         // If node was previously marked as a terminating scope during the
1023         // recursive visit of its parent node in the AST, then we need to
1024         // account for the destruction scope representing the extent of
1025         // the destructors that run immediately after it completes.
1026         if self.terminating_scopes.contains(&id) {
1027             self.enter_code_extent(CodeExtent::DestructionScope(id));
1028         }
1029         self.enter_code_extent(CodeExtent::Misc(id));
1030     }
1031 }
1032
1033 impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> {
1034     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1035         NestedVisitorMap::None
1036     }
1037
1038     fn visit_block(&mut self, b: &'tcx Block) {
1039         resolve_block(self, b);
1040     }
1041
1042     fn visit_body(&mut self, body: &'tcx hir::Body) {
1043         let body_id = body.id();
1044         let owner_id = self.tcx.hir.body_owner(body_id);
1045
1046         debug!("visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
1047                owner_id,
1048                self.tcx.sess.codemap().span_to_string(body.value.span),
1049                body_id,
1050                self.cx.parent);
1051
1052         let outer_cx = self.cx;
1053         let outer_ts = mem::replace(&mut self.terminating_scopes, NodeSet());
1054
1055         // Only functions have an outer terminating (drop) scope,
1056         // while temporaries in constant initializers are 'static.
1057         if let MirSource::Fn(_) = MirSource::from_node(self.tcx, owner_id) {
1058             self.terminating_scopes.insert(body_id.node_id);
1059         }
1060
1061         if let Some(root_id) = self.cx.root_id {
1062             self.region_maps.record_fn_parent(body_id.node_id, root_id);
1063         }
1064         self.cx.root_id = Some(body_id.node_id);
1065
1066         self.enter_code_extent(CodeExtent::CallSiteScope(body_id));
1067         self.enter_code_extent(CodeExtent::ParameterScope(body_id));
1068
1069         // The arguments and `self` are parented to the fn.
1070         self.cx.var_parent = self.cx.parent.take();
1071         for argument in &body.arguments {
1072             self.visit_pat(&argument.pat);
1073         }
1074
1075         // The body of the every fn is a root scope.
1076         self.cx.parent = self.cx.var_parent;
1077         self.visit_expr(&body.value);
1078
1079         // Restore context we had at the start.
1080         self.cx = outer_cx;
1081         self.terminating_scopes = outer_ts;
1082     }
1083
1084     fn visit_arm(&mut self, a: &'tcx Arm) {
1085         resolve_arm(self, a);
1086     }
1087     fn visit_pat(&mut self, p: &'tcx Pat) {
1088         resolve_pat(self, p);
1089     }
1090     fn visit_stmt(&mut self, s: &'tcx Stmt) {
1091         resolve_stmt(self, s);
1092     }
1093     fn visit_expr(&mut self, ex: &'tcx Expr) {
1094         resolve_expr(self, ex);
1095     }
1096     fn visit_local(&mut self, l: &'tcx Local) {
1097         resolve_local(self, l);
1098     }
1099 }
1100
1101 fn region_maps<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
1102     -> Rc<RegionMaps>
1103 {
1104     let closure_base_def_id = tcx.closure_base_def_id(def_id);
1105     if closure_base_def_id != def_id {
1106         return tcx.region_maps(closure_base_def_id);
1107     }
1108
1109     let id = tcx.hir.as_local_node_id(def_id).unwrap();
1110     let maps = if let Some(body) = tcx.hir.maybe_body_owned_by(id) {
1111         let mut visitor = RegionResolutionVisitor {
1112             tcx,
1113             region_maps: RegionMaps::new(),
1114             cx: Context {
1115                 root_id: None,
1116                 parent: None,
1117                 var_parent: None,
1118             },
1119             terminating_scopes: NodeSet(),
1120         };
1121
1122         visitor.region_maps.root_body = Some(body);
1123
1124         // If the item is an associated const or a method,
1125         // record its impl/trait parent, as it can also have
1126         // lifetime parameters free in this body.
1127         match tcx.hir.get(id) {
1128             hir::map::NodeImplItem(_) |
1129             hir::map::NodeTraitItem(_) => {
1130                 visitor.region_maps.root_parent = Some(tcx.hir.get_parent(id));
1131             }
1132             _ => {}
1133         }
1134
1135         visitor.visit_body(tcx.hir.body(body));
1136
1137         visitor.region_maps
1138     } else {
1139         RegionMaps::new()
1140     };
1141
1142     Rc::new(maps)
1143 }
1144
1145 pub fn provide(providers: &mut Providers) {
1146     *providers = Providers {
1147         region_maps,
1148         ..*providers
1149     };
1150 }