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