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