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