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