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