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