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