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