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