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