]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/region.rs
Auto merge of #21488 - aturon:os-str, 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, 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::visit::{Visitor, FnKind};
30
31 /// CodeExtent represents a statically-describable extent that can be
32 /// used to bound the lifetime/region for values.
33 ///
34 /// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
35 /// placate the same deriving in `ty::FreeRegion`, but we may want to
36 /// actually attach a more meaningful ordering to scopes than the one
37 /// generated via deriving here.
38 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
39            RustcDecodable, Show, Copy)]
40 pub enum CodeExtent {
41     Misc(ast::NodeId)
42 }
43
44 impl CodeExtent {
45     /// Creates a scope that represents the dynamic extent associated
46     /// with `node_id`.
47     pub fn from_node_id(node_id: ast::NodeId) -> CodeExtent {
48         CodeExtent::Misc(node_id)
49     }
50
51     /// Returns a node id associated with this scope.
52     ///
53     /// NB: likely to be replaced as API is refined; e.g. pnkfelix
54     /// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
55     pub fn node_id(&self) -> ast::NodeId {
56         match *self {
57             CodeExtent::Misc(node_id) => node_id,
58         }
59     }
60
61     /// Maps this scope to a potentially new one according to the
62     /// NodeId transformer `f_id`.
63     pub fn map_id<F>(&self, f_id: F) -> CodeExtent where
64         F: FnOnce(ast::NodeId) -> ast::NodeId,
65     {
66         match *self {
67             CodeExtent::Misc(node_id) => CodeExtent::Misc(f_id(node_id)),
68         }
69     }
70 }
71
72 /// The region maps encode information about region relationships.
73 ///
74 /// - `scope_map` maps from a scope id to the enclosing scope id; this is
75 ///   usually corresponding to the lexical nesting, though in the case of
76 ///   closures the parent scope is the innermost conditional expression or repeating
77 ///   block
78 ///
79 /// - `var_map` maps from a variable or binding id to the block in which
80 ///   that variable is declared.
81 ///
82 /// - `free_region_map` maps from a free region `a` to a list of free
83 ///   regions `bs` such that `a <= b for all b in bs`
84 ///   - the free region map is populated during type check as we check
85 ///     each function. See the function `relate_free_regions` for
86 ///     more information.
87 ///
88 /// - `rvalue_scopes` includes entries for those expressions whose cleanup
89 ///   scope is larger than the default. The map goes from the expression
90 ///   id to the cleanup scope id. For rvalues not present in this table,
91 ///   the appropriate cleanup scope is the innermost enclosing statement,
92 ///   conditional expression, or repeating block (see `terminating_scopes`).
93 ///
94 /// - `terminating_scopes` is a set containing the ids of each statement,
95 ///   or conditional/repeating expression. These scopes are calling "terminating
96 ///   scopes" because, when attempting to find the scope of a temporary, by
97 ///   default we search up the enclosing scopes until we encounter the
98 ///   terminating scope. A conditional/repeating
99 ///   expression is one which is not guaranteed to execute exactly once
100 ///   upon entering the parent scope. This could be because the expression
101 ///   only executes conditionally, such as the expression `b` in `a && b`,
102 ///   or because the expression may execute many times, such as a loop
103 ///   body. The reason that we distinguish such expressions is that, upon
104 ///   exiting the parent scope, we cannot statically know how many times
105 ///   the expression executed, and thus if the expression creates
106 ///   temporaries we cannot know statically how many such temporaries we
107 ///   would have to cleanup. Therefore we ensure that the temporaries never
108 ///   outlast the conditional/repeating expression, preventing the need
109 ///   for dynamic checks and/or arbitrary amounts of stack space.
110 pub struct RegionMaps {
111     scope_map: RefCell<FnvHashMap<CodeExtent, CodeExtent>>,
112     var_map: RefCell<NodeMap<CodeExtent>>,
113     free_region_map: RefCell<FnvHashMap<FreeRegion, Vec<FreeRegion>>>,
114     rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
115     terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
116 }
117
118 #[derive(Copy)]
119 pub struct Context {
120     var_parent: Option<ast::NodeId>,
121
122     // Innermost enclosing expression
123     parent: Option<ast::NodeId>,
124 }
125
126 struct RegionResolutionVisitor<'a> {
127     sess: &'a Session,
128
129     // Generated maps:
130     region_maps: &'a RegionMaps,
131
132     cx: Context
133 }
134
135
136 impl RegionMaps {
137     pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) {
138         match self.free_region_map.borrow_mut().get_mut(&sub) {
139             Some(sups) => {
140                 if !sups.iter().any(|x| x == &sup) {
141                     sups.push(sup);
142                 }
143                 return;
144             }
145             None => {}
146         }
147
148         debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup);
149         self.free_region_map.borrow_mut().insert(sub, vec!(sup));
150     }
151
152     pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
153         debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
154         assert!(sub != sup);
155         self.scope_map.borrow_mut().insert(sub, sup);
156     }
157
158     pub fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
159         debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
160         assert!(var != lifetime.node_id());
161         self.var_map.borrow_mut().insert(var, lifetime);
162     }
163
164     pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
165         debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
166         assert!(var != lifetime.node_id());
167         self.rvalue_scopes.borrow_mut().insert(var, lifetime);
168     }
169
170     /// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
171     /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
172     /// scope.
173     pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
174         debug!("record_terminating_scope(scope_id={:?})", scope_id);
175         self.terminating_scopes.borrow_mut().insert(scope_id);
176     }
177
178     pub fn opt_encl_scope(&self, id: CodeExtent) -> Option<CodeExtent> {
179         //! Returns the narrowest scope that encloses `id`, if any.
180         self.scope_map.borrow().get(&id).map(|x| *x)
181     }
182
183     #[allow(dead_code)] // used in middle::cfg
184     pub fn encl_scope(&self, id: CodeExtent) -> CodeExtent {
185         //! Returns the narrowest scope that encloses `id`, if any.
186         match self.scope_map.borrow().get(&id) {
187             Some(&r) => r,
188             None => { panic!("no enclosing scope for id {:?}", id); }
189         }
190     }
191
192     /// Returns the lifetime of the local variable `var_id`
193     pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent {
194         match self.var_map.borrow().get(&var_id) {
195             Some(&r) => r,
196             None => { panic!("no enclosing scope for id {:?}", var_id); }
197         }
198     }
199
200     pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option<CodeExtent> {
201         //! Returns the scope when temp created by expr_id will be cleaned up
202
203         // check for a designated rvalue scope
204         match self.rvalue_scopes.borrow().get(&expr_id) {
205             Some(&s) => {
206                 debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
207                 return Some(s);
208             }
209             None => { }
210         }
211
212         // else, locate the innermost terminating scope
213         // if there's one. Static items, for instance, won't
214         // have an enclosing scope, hence no scope will be
215         // returned.
216         let mut id = match self.opt_encl_scope(CodeExtent::from_node_id(expr_id)) {
217             Some(i) => i,
218             None => { return None; }
219         };
220
221         while !self.terminating_scopes.borrow().contains(&id) {
222             match self.opt_encl_scope(id) {
223                 Some(p) => {
224                     id = p;
225                 }
226                 None => {
227                     debug!("temporary_scope({:?}) = None", expr_id);
228                     return None;
229                 }
230             }
231         }
232         debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id);
233         return Some(id);
234     }
235
236     pub fn var_region(&self, id: ast::NodeId) -> ty::Region {
237         //! Returns the lifetime of the variable `id`.
238
239         let scope = ty::ReScope(self.var_scope(id));
240         debug!("var_region({:?}) = {:?}", id, scope);
241         scope
242     }
243
244     pub fn scopes_intersect(&self, scope1: CodeExtent, scope2: CodeExtent)
245                             -> bool {
246         self.is_subscope_of(scope1, scope2) ||
247         self.is_subscope_of(scope2, scope1)
248     }
249
250     /// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
251     /// otherwise.
252     pub fn is_subscope_of(&self,
253                           subscope: CodeExtent,
254                           superscope: CodeExtent)
255                           -> bool {
256         let mut s = subscope;
257         while superscope != s {
258             match self.scope_map.borrow().get(&s) {
259                 None => {
260                     debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
261                            subscope, superscope, s);
262
263                     return false;
264                 }
265                 Some(&scope) => s = scope
266             }
267         }
268
269         debug!("is_subscope_of({:?}, {:?})=true",
270                subscope, superscope);
271
272         return true;
273     }
274
275     /// Determines whether two free regions have a subregion relationship
276     /// by walking the graph encoded in `free_region_map`.  Note that
277     /// it is possible that `sub != sup` and `sub <= sup` and `sup <= sub`
278     /// (that is, the user can give two different names to the same lifetime).
279     pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool {
280         can_reach(&*self.free_region_map.borrow(), sub, sup)
281     }
282
283     /// Determines whether one region is a subregion of another.  This is intended to run *after
284     /// inference* and sadly the logic is somewhat duplicated with the code in infer.rs.
285     pub fn is_subregion_of(&self,
286                            sub_region: ty::Region,
287                            super_region: ty::Region)
288                            -> bool {
289         debug!("is_subregion_of(sub_region={:?}, super_region={:?})",
290                sub_region, super_region);
291
292         sub_region == super_region || {
293             match (sub_region, super_region) {
294                 (ty::ReEmpty, _) |
295                 (_, ty::ReStatic) => {
296                     true
297                 }
298
299                 (ty::ReScope(sub_scope), ty::ReScope(super_scope)) => {
300                     self.is_subscope_of(sub_scope, super_scope)
301                 }
302
303                 (ty::ReScope(sub_scope), ty::ReFree(ref fr)) => {
304                     self.is_subscope_of(sub_scope, fr.scope)
305                 }
306
307                 (ty::ReFree(sub_fr), ty::ReFree(super_fr)) => {
308                     self.sub_free_region(sub_fr, super_fr)
309                 }
310
311                 (ty::ReEarlyBound(param_id_a, param_space_a, index_a, _),
312                  ty::ReEarlyBound(param_id_b, param_space_b, index_b, _)) => {
313                     // This case is used only to make sure that explicitly-
314                     // specified `Self` types match the real self type in
315                     // implementations.
316                     param_id_a == param_id_b &&
317                         param_space_a == param_space_b &&
318                         index_a == index_b
319                 }
320
321                 _ => {
322                     false
323                 }
324             }
325         }
326     }
327
328     /// Finds the nearest common ancestor (if any) of two scopes.  That is, finds the smallest
329     /// scope which is greater than or equal to both `scope_a` and `scope_b`.
330     pub fn nearest_common_ancestor(&self,
331                                    scope_a: CodeExtent,
332                                    scope_b: CodeExtent)
333                                    -> Option<CodeExtent> {
334         if scope_a == scope_b { return Some(scope_a); }
335
336         let a_ancestors = ancestors_of(self, scope_a);
337         let b_ancestors = ancestors_of(self, scope_b);
338         let mut a_index = a_ancestors.len() - 1u;
339         let mut b_index = b_ancestors.len() - 1u;
340
341         // Here, ~[ab]_ancestors is a vector going from narrow to broad.
342         // The end of each vector will be the item where the scope is
343         // defined; if there are any common ancestors, then the tails of
344         // the vector will be the same.  So basically we want to walk
345         // backwards from the tail of each vector and find the first point
346         // where they diverge.  If one vector is a suffix of the other,
347         // then the corresponding scope is a superscope of the other.
348
349         if a_ancestors[a_index] != b_ancestors[b_index] {
350             return None;
351         }
352
353         loop {
354             // Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
355             // for all indices between a_index and the end of the array
356             if a_index == 0u { return Some(scope_a); }
357             if b_index == 0u { return Some(scope_b); }
358             a_index -= 1u;
359             b_index -= 1u;
360             if a_ancestors[a_index] != b_ancestors[b_index] {
361                 return Some(a_ancestors[a_index + 1]);
362             }
363         }
364
365         fn ancestors_of(this: &RegionMaps, scope: CodeExtent)
366             -> Vec<CodeExtent> {
367             // debug!("ancestors_of(scope={:?})", scope);
368             let mut result = vec!(scope);
369             let mut scope = scope;
370             loop {
371                 match this.scope_map.borrow().get(&scope) {
372                     None => return result,
373                     Some(&superscope) => {
374                         result.push(superscope);
375                         scope = superscope;
376                     }
377                 }
378                 // debug!("ancestors_of_loop(scope={:?})", scope);
379             }
380         }
381     }
382 }
383
384 /// Records the current parent (if any) as the parent of `child_id`.
385 fn record_superlifetime(visitor: &mut RegionResolutionVisitor,
386                         child_id: ast::NodeId,
387                         _sp: Span) {
388     match visitor.cx.parent {
389         Some(parent_id) => {
390             let child_scope = CodeExtent::from_node_id(child_id);
391             let parent_scope = CodeExtent::from_node_id(parent_id);
392             visitor.region_maps.record_encl_scope(child_scope, parent_scope);
393         }
394         None => {}
395     }
396 }
397
398 /// Records the lifetime of a local variable as `cx.var_parent`
399 fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
400                        var_id: ast::NodeId,
401                        _sp: Span) {
402     match visitor.cx.var_parent {
403         Some(parent_id) => {
404             let parent_scope = CodeExtent::from_node_id(parent_id);
405             visitor.region_maps.record_var_scope(var_id, parent_scope);
406         }
407         None => {
408             // this can happen in extern fn declarations like
409             //
410             // extern fn isalnum(c: c_int) -> c_int
411         }
412     }
413 }
414
415 fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
416     debug!("resolve_block(blk.id={:?})", blk.id);
417
418     // Record the parent of this block.
419     record_superlifetime(visitor, blk.id, blk.span);
420
421     // We treat the tail expression in the block (if any) somewhat
422     // differently from the statements. The issue has to do with
423     // temporary lifetimes. If the user writes:
424     //
425     //   {
426     //     ... (&foo()) ...
427     //   }
428     //
429
430     let prev_cx = visitor.cx;
431     visitor.cx = Context {var_parent: Some(blk.id), parent: Some(blk.id)};
432     visit::walk_block(visitor, blk);
433     visitor.cx = prev_cx;
434 }
435
436 fn resolve_arm(visitor: &mut RegionResolutionVisitor, arm: &ast::Arm) {
437     let arm_body_scope = CodeExtent::from_node_id(arm.body.id);
438     visitor.region_maps.mark_as_terminating_scope(arm_body_scope);
439
440     match arm.guard {
441         Some(ref expr) => {
442             let guard_scope = CodeExtent::from_node_id(expr.id);
443             visitor.region_maps.mark_as_terminating_scope(guard_scope);
444         }
445         None => { }
446     }
447
448     visit::walk_arm(visitor, arm);
449 }
450
451 fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) {
452     record_superlifetime(visitor, pat.id, pat.span);
453
454     // If this is a binding (or maybe a binding, I'm too lazy to check
455     // the def map) then record the lifetime of that binding.
456     match pat.node {
457         ast::PatIdent(..) => {
458             record_var_lifetime(visitor, pat.id, pat.span);
459         }
460         _ => { }
461     }
462
463     visit::walk_pat(visitor, pat);
464 }
465
466 fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) {
467     let stmt_id = stmt_id(stmt);
468     debug!("resolve_stmt(stmt.id={:?})", stmt_id);
469
470     let stmt_scope = CodeExtent::from_node_id(stmt_id);
471     visitor.region_maps.mark_as_terminating_scope(stmt_scope);
472     record_superlifetime(visitor, stmt_id, stmt.span);
473
474     let prev_parent = visitor.cx.parent;
475     visitor.cx.parent = Some(stmt_id);
476     visit::walk_stmt(visitor, stmt);
477     visitor.cx.parent = prev_parent;
478 }
479
480 fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) {
481     debug!("resolve_expr(expr.id={:?})", expr.id);
482
483     record_superlifetime(visitor, expr.id, expr.span);
484
485     let prev_cx = visitor.cx;
486     visitor.cx.parent = Some(expr.id);
487
488     {
489         let region_maps = &mut visitor.region_maps;
490         let terminating = |&: id| {
491             let scope = CodeExtent::from_node_id(id);
492             region_maps.mark_as_terminating_scope(scope)
493         };
494         match expr.node {
495             // Conditional or repeating scopes are always terminating
496             // scopes, meaning that temporaries cannot outlive them.
497             // This ensures fixed size stacks.
498
499             ast::ExprBinary(codemap::Spanned { node: ast::BiAnd, .. }, _, ref r) |
500             ast::ExprBinary(codemap::Spanned { node: ast::BiOr, .. }, _, ref r) => {
501                 // For shortcircuiting operators, mark the RHS as a terminating
502                 // scope since it only executes conditionally.
503                 terminating(r.id);
504             }
505
506             ast::ExprIf(_, ref then, Some(ref otherwise)) => {
507                 terminating(then.id);
508                 terminating(otherwise.id);
509             }
510
511             ast::ExprIf(ref expr, ref then, None) => {
512                 terminating(expr.id);
513                 terminating(then.id);
514             }
515
516             ast::ExprLoop(ref body, _) => {
517                 terminating(body.id);
518             }
519
520             ast::ExprWhile(ref expr, ref body, _) => {
521                 terminating(expr.id);
522                 terminating(body.id);
523             }
524
525             ast::ExprForLoop(ref _pat, ref _head, ref body, _) => {
526                 terminating(body.id);
527
528                 // The variable parent of everything inside (most importantly, the
529                 // pattern) is the body.
530                 visitor.cx.var_parent = Some(body.id);
531             }
532
533             ast::ExprMatch(..) => {
534                 visitor.cx.var_parent = Some(expr.id);
535             }
536
537             ast::ExprAssignOp(..) | ast::ExprIndex(..) |
538             ast::ExprUnary(..) | ast::ExprCall(..) | ast::ExprMethodCall(..) => {
539                 // FIXME(#6268) Nested method calls
540                 //
541                 // The lifetimes for a call or method call look as follows:
542                 //
543                 // call.id
544                 // - arg0.id
545                 // - ...
546                 // - argN.id
547                 // - call.callee_id
548                 //
549                 // The idea is that call.callee_id represents *the time when
550                 // the invoked function is actually running* and call.id
551                 // represents *the time to prepare the arguments and make the
552                 // call*.  See the section "Borrows in Calls" borrowck/doc.rs
553                 // for an extended explanation of why this distinction is
554                 // important.
555                 //
556                 // record_superlifetime(new_cx, expr.callee_id);
557             }
558
559             _ => {}
560         }
561     }
562
563     visit::walk_expr(visitor, expr);
564     visitor.cx = prev_cx;
565 }
566
567 fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) {
568     debug!("resolve_local(local.id={:?},local.init={:?})",
569            local.id,local.init.is_some());
570
571     let blk_id = match visitor.cx.var_parent {
572         Some(id) => id,
573         None => {
574             visitor.sess.span_bug(
575                 local.span,
576                 "local without enclosing block");
577         }
578     };
579
580     // For convenience in trans, associate with the local-id the var
581     // scope that will be used for any bindings declared in this
582     // pattern.
583     let blk_scope = CodeExtent::from_node_id(blk_id);
584     visitor.region_maps.record_var_scope(local.id, blk_scope);
585
586     // As an exception to the normal rules governing temporary
587     // lifetimes, initializers in a let have a temporary lifetime
588     // of the enclosing block. This means that e.g. a program
589     // like the following is legal:
590     //
591     //     let ref x = HashMap::new();
592     //
593     // Because the hash map will be freed in the enclosing block.
594     //
595     // We express the rules more formally based on 3 grammars (defined
596     // fully in the helpers below that implement them):
597     //
598     // 1. `E&`, which matches expressions like `&<rvalue>` that
599     //    own a pointer into the stack.
600     //
601     // 2. `P&`, which matches patterns like `ref x` or `(ref x, ref
602     //    y)` that produce ref bindings into the value they are
603     //    matched against or something (at least partially) owned by
604     //    the value they are matched against. (By partially owned,
605     //    I mean that creating a binding into a ref-counted or managed value
606     //    would still count.)
607     //
608     // 3. `ET`, which matches both rvalues like `foo()` as well as lvalues
609     //    based on rvalues like `foo().x[2].y`.
610     //
611     // A subexpression `<rvalue>` that appears in a let initializer
612     // `let pat [: ty] = expr` has an extended temporary lifetime if
613     // any of the following conditions are met:
614     //
615     // A. `pat` matches `P&` and `expr` matches `ET`
616     //    (covers cases where `pat` creates ref bindings into an rvalue
617     //     produced by `expr`)
618     // B. `ty` is a borrowed pointer and `expr` matches `ET`
619     //    (covers cases where coercion creates a borrow)
620     // C. `expr` matches `E&`
621     //    (covers cases `expr` borrows an rvalue that is then assigned
622     //     to memory (at least partially) owned by the binding)
623     //
624     // Here are some examples hopefully giving an intuition where each
625     // rule comes into play and why:
626     //
627     // Rule A. `let (ref x, ref y) = (foo().x, 44)`. The rvalue `(22, 44)`
628     // would have an extended lifetime, but not `foo()`.
629     //
630     // Rule B. `let x: &[...] = [foo().x]`. The rvalue `[foo().x]`
631     // would have an extended lifetime, but not `foo()`.
632     //
633     // Rule C. `let x = &foo().x`. The rvalue ``foo()` would have extended
634     // lifetime.
635     //
636     // In some cases, multiple rules may apply (though not to the same
637     // rvalue). For example:
638     //
639     //     let ref x = [&a(), &b()];
640     //
641     // Here, the expression `[...]` has an extended lifetime due to rule
642     // A, but the inner rvalues `a()` and `b()` have an extended lifetime
643     // due to rule C.
644     //
645     // FIXME(#6308) -- Note that `[]` patterns work more smoothly post-DST.
646
647     match local.init {
648         Some(ref expr) => {
649             record_rvalue_scope_if_borrow_expr(visitor, &**expr, blk_scope);
650
651             let is_borrow =
652                 if let Some(ref ty) = local.ty { is_borrowed_ty(&**ty) } else { false };
653
654             if is_binding_pat(&*local.pat) || is_borrow {
655                 record_rvalue_scope(visitor, &**expr, blk_scope);
656             }
657         }
658
659         None => { }
660     }
661
662     visit::walk_local(visitor, local);
663
664     /// True if `pat` match the `P&` nonterminal:
665     ///
666     ///     P& = ref X
667     ///        | StructName { ..., P&, ... }
668     ///        | VariantName(..., P&, ...)
669     ///        | [ ..., P&, ... ]
670     ///        | ( ..., P&, ... )
671     ///        | box P&
672     fn is_binding_pat(pat: &ast::Pat) -> bool {
673         match pat.node {
674             ast::PatIdent(ast::BindByRef(_), _, _) => true,
675
676             ast::PatStruct(_, ref field_pats, _) => {
677                 field_pats.iter().any(|fp| is_binding_pat(&*fp.node.pat))
678             }
679
680             ast::PatVec(ref pats1, ref pats2, ref pats3) => {
681                 pats1.iter().any(|p| is_binding_pat(&**p)) ||
682                 pats2.iter().any(|p| is_binding_pat(&**p)) ||
683                 pats3.iter().any(|p| is_binding_pat(&**p))
684             }
685
686             ast::PatEnum(_, Some(ref subpats)) |
687             ast::PatTup(ref subpats) => {
688                 subpats.iter().any(|p| is_binding_pat(&**p))
689             }
690
691             ast::PatBox(ref subpat) => {
692                 is_binding_pat(&**subpat)
693             }
694
695             _ => false,
696         }
697     }
698
699     /// True if `ty` is a borrowed pointer type like `&int` or `&[...]`.
700     fn is_borrowed_ty(ty: &ast::Ty) -> bool {
701         match ty.node {
702             ast::TyRptr(..) => true,
703             _ => false
704         }
705     }
706
707     /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate:
708     ///
709     ///     E& = & ET
710     ///        | StructName { ..., f: E&, ... }
711     ///        | [ ..., E&, ... ]
712     ///        | ( ..., E&, ... )
713     ///        | {...; E&}
714     ///        | box E&
715     ///        | E& as ...
716     ///        | ( E& )
717     fn record_rvalue_scope_if_borrow_expr(visitor: &mut RegionResolutionVisitor,
718                                           expr: &ast::Expr,
719                                           blk_id: CodeExtent) {
720         match expr.node {
721             ast::ExprAddrOf(_, ref subexpr) => {
722                 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
723                 record_rvalue_scope(visitor, &**subexpr, blk_id);
724             }
725             ast::ExprStruct(_, ref fields, _) => {
726                 for field in fields.iter() {
727                     record_rvalue_scope_if_borrow_expr(
728                         visitor, &*field.expr, blk_id);
729                 }
730             }
731             ast::ExprVec(ref subexprs) |
732             ast::ExprTup(ref subexprs) => {
733                 for subexpr in subexprs.iter() {
734                     record_rvalue_scope_if_borrow_expr(
735                         visitor, &**subexpr, blk_id);
736                 }
737             }
738             ast::ExprUnary(ast::UnUniq, ref subexpr) => {
739                 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id);
740             }
741             ast::ExprCast(ref subexpr, _) |
742             ast::ExprParen(ref subexpr) => {
743                 record_rvalue_scope_if_borrow_expr(visitor, &**subexpr, blk_id)
744             }
745             ast::ExprBlock(ref block) => {
746                 match block.expr {
747                     Some(ref subexpr) => {
748                         record_rvalue_scope_if_borrow_expr(
749                             visitor, &**subexpr, blk_id);
750                     }
751                     None => { }
752                 }
753             }
754             _ => {
755             }
756         }
757     }
758
759     /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by
760     /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that
761     /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let`
762     /// statement.
763     ///
764     /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching
765     /// `<rvalue>` as `blk_id`:
766     ///
767     ///     ET = *ET
768     ///        | ET[...]
769     ///        | ET.f
770     ///        | (ET)
771     ///        | <rvalue>
772     ///
773     /// Note: ET is intended to match "rvalues or lvalues based on rvalues".
774     fn record_rvalue_scope<'a>(visitor: &mut RegionResolutionVisitor,
775                                expr: &'a ast::Expr,
776                                blk_scope: CodeExtent) {
777         let mut expr = expr;
778         loop {
779             // Note: give all the expressions matching `ET` with the
780             // extended temporary lifetime, not just the innermost rvalue,
781             // because in trans if we must compile e.g. `*rvalue()`
782             // into a temporary, we request the temporary scope of the
783             // outer expression.
784             visitor.region_maps.record_rvalue_scope(expr.id, blk_scope);
785
786             match expr.node {
787                 ast::ExprAddrOf(_, ref subexpr) |
788                 ast::ExprUnary(ast::UnDeref, ref subexpr) |
789                 ast::ExprField(ref subexpr, _) |
790                 ast::ExprTupField(ref subexpr, _) |
791                 ast::ExprIndex(ref subexpr, _) |
792                 ast::ExprParen(ref subexpr) => {
793                     expr = &**subexpr;
794                 }
795                 _ => {
796                     return;
797                 }
798             }
799         }
800     }
801 }
802
803 fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
804     // Items create a new outer block scope as far as we're concerned.
805     let prev_cx = visitor.cx;
806     visitor.cx = Context {var_parent: None, parent: None};
807     visit::walk_item(visitor, item);
808     visitor.cx = prev_cx;
809 }
810
811 fn resolve_fn(visitor: &mut RegionResolutionVisitor,
812               fk: FnKind,
813               decl: &ast::FnDecl,
814               body: &ast::Block,
815               sp: Span,
816               id: ast::NodeId) {
817     debug!("region::resolve_fn(id={:?}, \
818                                span={:?}, \
819                                body.id={:?}, \
820                                cx.parent={:?})",
821            id,
822            visitor.sess.codemap().span_to_string(sp),
823            body.id,
824            visitor.cx.parent);
825
826     let body_scope = CodeExtent::from_node_id(body.id);
827     visitor.region_maps.mark_as_terminating_scope(body_scope);
828
829     let outer_cx = visitor.cx;
830
831     // The arguments and `self` are parented to the body of the fn.
832     visitor.cx = Context { parent: Some(body.id),
833                            var_parent: Some(body.id) };
834     visit::walk_fn_decl(visitor, decl);
835
836     // The body of the fn itself is either a root scope (top-level fn)
837     // or it continues with the inherited scope (closures).
838     match fk {
839         visit::FkItemFn(..) | visit::FkMethod(..) => {
840             visitor.cx = Context { parent: None, var_parent: None };
841             visitor.visit_block(body);
842             visitor.cx = outer_cx;
843         }
844         visit::FkFnBlock(..) => {
845             // FIXME(#3696) -- at present we are place the closure body
846             // within the region hierarchy exactly where it appears lexically.
847             // This is wrong because the closure may live longer
848             // than the enclosing expression. We should probably fix this,
849             // but the correct fix is a bit subtle, and I am also not sure
850             // that the present approach is unsound -- it may not permit
851             // any illegal programs. See issue for more details.
852             visitor.cx = outer_cx;
853             visitor.visit_block(body);
854         }
855     }
856 }
857
858 impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
859
860     fn visit_block(&mut self, b: &Block) {
861         resolve_block(self, b);
862     }
863
864     fn visit_item(&mut self, i: &Item) {
865         resolve_item(self, i);
866     }
867
868     fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
869                 b: &'v Block, s: Span, n: NodeId) {
870         resolve_fn(self, fk, fd, b, s, n);
871     }
872     fn visit_arm(&mut self, a: &Arm) {
873         resolve_arm(self, a);
874     }
875     fn visit_pat(&mut self, p: &Pat) {
876         resolve_pat(self, p);
877     }
878     fn visit_stmt(&mut self, s: &Stmt) {
879         resolve_stmt(self, s);
880     }
881     fn visit_expr(&mut self, ex: &Expr) {
882         resolve_expr(self, ex);
883     }
884     fn visit_local(&mut self, l: &Local) {
885         resolve_local(self, l);
886     }
887 }
888
889 pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
890     let maps = RegionMaps {
891         scope_map: RefCell::new(FnvHashMap()),
892         var_map: RefCell::new(NodeMap()),
893         free_region_map: RefCell::new(FnvHashMap()),
894         rvalue_scopes: RefCell::new(NodeMap()),
895         terminating_scopes: RefCell::new(FnvHashSet()),
896     };
897     {
898         let mut visitor = RegionResolutionVisitor {
899             sess: sess,
900             region_maps: &maps,
901             cx: Context { parent: None, var_parent: None }
902         };
903         visit::walk_crate(&mut visitor, krate);
904     }
905     return maps;
906 }
907
908 pub fn resolve_inlined_item(sess: &Session,
909                             region_maps: &RegionMaps,
910                             item: &ast::InlinedItem) {
911     let mut visitor = RegionResolutionVisitor {
912         sess: sess,
913         region_maps: region_maps,
914         cx: Context { parent: None, var_parent: None }
915     };
916     visit::walk_inlined_item(&mut visitor, item);
917 }