Skip to content

Commit d528aa9

Browse files
committedApr 1, 2015
Auto merge of #23109 - nikomatsakis:closure-region-hierarchy, r=pnkfelix
Adjust internal treatment of the region hierarchy around closures. Work towards #3696. r? @pnkfelix
2 parents 8943653 + f15813d commit d528aa9

File tree

4 files changed

+218
-197
lines changed

4 files changed

+218
-197
lines changed
 

‎src/librustc/middle/infer/region_inference/README.md

+55-108
Original file line numberDiff line numberDiff line change
@@ -249,114 +249,61 @@ there is a reference created whose lifetime does not enclose
249249
the borrow expression, we must issue sufficient restrictions to ensure
250250
that the pointee remains valid.
251251

252-
## Adding closures
253-
254-
The other significant complication to the region hierarchy is
255-
closures. I will describe here how closures should work, though some
256-
of the work to implement this model is ongoing at the time of this
257-
writing.
258-
259-
The body of closures are type-checked along with the function that
260-
creates them. However, unlike other expressions that appear within the
261-
function body, it is not entirely obvious when a closure body executes
262-
with respect to the other expressions. This is because the closure
263-
body will execute whenever the closure is called; however, we can
264-
never know precisely when the closure will be called, especially
265-
without some sort of alias analysis.
266-
267-
However, we can place some sort of limits on when the closure
268-
executes. In particular, the type of every closure `fn:'r K` includes
269-
a region bound `'r`. This bound indicates the maximum lifetime of that
270-
closure; once we exit that region, the closure cannot be called
271-
anymore. Therefore, we say that the lifetime of the closure body is a
272-
sublifetime of the closure bound, but the closure body itself is unordered
273-
with respect to other parts of the code.
274-
275-
For example, consider the following fragment of code:
276-
277-
'a: {
278-
let closure: fn:'a() = || 'b: {
279-
'c: ...
280-
};
281-
'd: ...
282-
}
283-
284-
Here we have four lifetimes, `'a`, `'b`, `'c`, and `'d`. The closure
285-
`closure` is bounded by the lifetime `'a`. The lifetime `'b` is the
286-
lifetime of the closure body, and `'c` is some statement within the
287-
closure body. Finally, `'d` is a statement within the outer block that
288-
created the closure.
289-
290-
We can say that the closure body `'b` is a sublifetime of `'a` due to
291-
the closure bound. By the usual lexical scoping conventions, the
292-
statement `'c` is clearly a sublifetime of `'b`, and `'d` is a
293-
sublifetime of `'d`. However, there is no ordering between `'c` and
294-
`'d` per se (this kind of ordering between statements is actually only
295-
an issue for dataflow; passes like the borrow checker must assume that
296-
closures could execute at any time from the moment they are created
297-
until they go out of scope).
298-
299-
### Complications due to closure bound inference
300-
301-
There is only one problem with the above model: in general, we do not
302-
actually *know* the closure bounds during region inference! In fact,
303-
closure bounds are almost always region variables! This is very tricky
304-
because the inference system implicitly assumes that we can do things
305-
like compute the LUB of two scoped lifetimes without needing to know
306-
the values of any variables.
307-
308-
Here is an example to illustrate the problem:
309-
310-
fn identify<T>(x: T) -> T { x }
311-
312-
fn foo() { // 'foo is the function body
313-
'a: {
314-
let closure = identity(|| 'b: {
315-
'c: ...
316-
});
317-
'd: closure();
318-
}
319-
'e: ...;
320-
}
321-
322-
In this example, the closure bound is not explicit. At compile time,
323-
we will create a region variable (let's call it `V0`) to represent the
324-
closure bound.
325-
326-
The primary difficulty arises during the constraint propagation phase.
327-
Imagine there is some variable with incoming edges from `'c` and `'d`.
328-
This means that the value of the variable must be `LUB('c,
329-
'd)`. However, without knowing what the closure bound `V0` is, we
330-
can't compute the LUB of `'c` and `'d`! Any we don't know the closure
331-
bound until inference is done.
332-
333-
The solution is to rely on the fixed point nature of inference.
334-
Basically, when we must compute `LUB('c, 'd)`, we just use the current
335-
value for `V0` as the closure's bound. If `V0`'s binding should
336-
change, then we will do another round of inference, and the result of
337-
`LUB('c, 'd)` will change.
338-
339-
One minor implication of this is that the graph does not in fact track
340-
the full set of dependencies between edges. We cannot easily know
341-
whether the result of a LUB computation will change, since there may
342-
be indirect dependencies on other variables that are not reflected on
343-
the graph. Therefore, we must *always* iterate over all edges when
344-
doing the fixed point calculation, not just those adjacent to nodes
345-
whose values have changed.
346-
347-
Were it not for this requirement, we could in fact avoid fixed-point
348-
iteration altogether. In that universe, we could instead first
349-
identify and remove strongly connected components (SCC) in the graph.
350-
Note that such components must consist solely of region variables; all
351-
of these variables can effectively be unified into a single variable.
352-
Once SCCs are removed, we are left with a DAG. At this point, we
353-
could walk the DAG in topological order once to compute the expanding
354-
nodes, and again in reverse topological order to compute the
355-
contracting nodes. However, as I said, this does not work given the
356-
current treatment of closure bounds, but perhaps in the future we can
357-
address this problem somehow and make region inference somewhat more
358-
efficient. Note that this is solely a matter of performance, not
359-
expressiveness.
252+
## Modeling closures
253+
254+
Integrating closures properly into the model is a bit of
255+
work-in-progress. In an ideal world, we would model closures as
256+
closely as possible after their desugared equivalents. That is, a
257+
closure type would be modeled as a struct, and the region hierarchy of
258+
different closure bodies would be completely distinct from all other
259+
fns. We are generally moving in that direction but there are
260+
complications in terms of the implementation.
261+
262+
In practice what we currently do is somewhat different. The basis for
263+
the current approach is the observation that the only time that
264+
regions from distinct fn bodies interact with one another is through
265+
an upvar or the type of a fn parameter (since closures live in the fn
266+
body namespace, they can in fact have fn parameters whose types
267+
include regions from the surrounding fn body). For these cases, there
268+
are separate mechanisms which ensure that the regions that appear in
269+
upvars/parameters outlive the dynamic extent of each call to the
270+
closure:
271+
272+
1. Types must outlive the region of any expression where they are used.
273+
For a closure type `C` to outlive a region `'r`, that implies that the
274+
types of all its upvars must outlive `'r`.
275+
2. Parameters must outlive the region of any fn that they are passed to.
276+
277+
Therefore, we can -- sort of -- assume that any region from an
278+
enclosing fns is larger than any region from one of its enclosed
279+
fn. And that is precisely what we do: when building the region
280+
hierarchy, each region lives in its own distinct subtree, but if we
281+
are asked to compute the `LUB(r1, r2)` of two regions, and those
282+
regions are in disjoint subtrees, we compare the lexical nesting of
283+
the two regions.
284+
285+
*Ideas for improving the situation:* (FIXME #3696) The correctness
286+
argument here is subtle and a bit hand-wavy. The ideal, as stated
287+
earlier, would be to model things in such a way that it corresponds
288+
more closely to the desugared code. The best approach for doing this
289+
is a bit unclear: it may in fact be possible to *actually* desugar
290+
before we start, but I don't think so. The main option that I've been
291+
thinking through is imposing a "view shift" as we enter the fn body,
292+
so that regions appearing in the types of fn parameters and upvars are
293+
translated from being regions in the outer fn into free region
294+
parameters, just as they would be if we applied the desugaring. The
295+
challenge here is that type inference may not have fully run, so the
296+
types may not be fully known: we could probably do this translation
297+
lazilly, as type variables are instantiated. We would also have to
298+
apply a kind of inverse translation to the return value. This would be
299+
a good idea anyway, as right now it is possible for free regions
300+
instantiated within the closure to leak into the parent: this
301+
currently leads to type errors, since those regions cannot outlive any
302+
expressions within the parent hierarchy. Much like the current
303+
handling of closures, there are no known cases where this leads to a
304+
type-checking accepting incorrect code (though it sometimes rejects
305+
what might be considered correct code; see rust-lang/rust#22557), but
306+
it still doesn't feel like the right approach.
360307

361308
### Skolemization
362309

‎src/librustc/middle/infer/region_inference/mod.rs

+18-15
Original file line numberDiff line numberDiff line change
@@ -760,26 +760,25 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> {
760760
// at least as big as the block fr.scope_id". So, we can
761761
// reasonably compare free regions and scopes:
762762
let fr_scope = fr.scope.to_code_extent();
763-
match self.tcx.region_maps.nearest_common_ancestor(fr_scope, s_id) {
763+
let r_id = self.tcx.region_maps.nearest_common_ancestor(fr_scope, s_id);
764+
765+
if r_id == fr_scope {
764766
// if the free region's scope `fr.scope_id` is bigger than
765767
// the scope region `s_id`, then the LUB is the free
766768
// region itself:
767-
Some(r_id) if r_id == fr_scope => f,
768-
769+
f
770+
} else {
769771
// otherwise, we don't know what the free region is,
770772
// so we must conservatively say the LUB is static:
771-
_ => ReStatic
773+
ReStatic
772774
}
773775
}
774776

775777
(ReScope(a_id), ReScope(b_id)) => {
776778
// The region corresponding to an outer block is a
777779
// subtype of the region corresponding to an inner
778780
// block.
779-
match self.tcx.region_maps.nearest_common_ancestor(a_id, b_id) {
780-
Some(r_id) => ReScope(r_id),
781-
_ => ReStatic
782-
}
781+
ReScope(self.tcx.region_maps.nearest_common_ancestor(a_id, b_id))
783782
}
784783

785784
(ReFree(ref a_fr), ReFree(ref b_fr)) => {
@@ -866,9 +865,10 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> {
866865
// is the scope `s_id`. Otherwise, as we do not know
867866
// big the free region is precisely, the GLB is undefined.
868867
let fr_scope = fr.scope.to_code_extent();
869-
match self.tcx.region_maps.nearest_common_ancestor(fr_scope, s_id) {
870-
Some(r_id) if r_id == fr_scope => Ok(s),
871-
_ => Err(ty::terr_regions_no_overlap(b, a))
868+
if self.tcx.region_maps.nearest_common_ancestor(fr_scope, s_id) == fr_scope {
869+
Ok(s)
870+
} else {
871+
Err(ty::terr_regions_no_overlap(b, a))
872872
}
873873
}
874874

@@ -934,10 +934,13 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> {
934934
// it. Otherwise fail.
935935
debug!("intersect_scopes(scope_a={:?}, scope_b={:?}, region_a={:?}, region_b={:?})",
936936
scope_a, scope_b, region_a, region_b);
937-
match self.tcx.region_maps.nearest_common_ancestor(scope_a, scope_b) {
938-
Some(r_id) if scope_a == r_id => Ok(ReScope(scope_b)),
939-
Some(r_id) if scope_b == r_id => Ok(ReScope(scope_a)),
940-
_ => Err(ty::terr_regions_no_overlap(region_a, region_b))
937+
let r_id = self.tcx.region_maps.nearest_common_ancestor(scope_a, scope_b);
938+
if r_id == scope_a {
939+
Ok(ReScope(scope_b))
940+
} else if r_id == scope_b {
941+
Ok(ReScope(scope_a))
942+
} else {
943+
Err(ty::terr_regions_no_overlap(region_a, region_b))
941944
}
942945
}
943946
}

‎src/librustc/middle/region.rs

+144-74
Original file line numberDiff line numberDiff line change
@@ -206,50 +206,66 @@ impl CodeExtent {
206206
}
207207

208208
/// The region maps encode information about region relationships.
209-
///
210-
/// - `scope_map` maps from a scope id to the enclosing scope id; this is
211-
/// usually corresponding to the lexical nesting, though in the case of
212-
/// closures the parent scope is the innermost conditional expression or repeating
213-
/// block. (Note that the enclosing scope id for the block
214-
/// associated with a closure is the closure itself.)
215-
///
216-
/// - `var_map` maps from a variable or binding id to the block in which
217-
/// that variable is declared.
218-
///
219-
/// - `free_region_map` maps from a free region `a` to a list of free
220-
/// regions `bs` such that `a <= b for all b in bs`
221-
/// - the free region map is populated during type check as we check
222-
/// each function. See the function `relate_free_regions` for
223-
/// more information.
224-
///
225-
/// - `rvalue_scopes` includes entries for those expressions whose cleanup
226-
/// scope is larger than the default. The map goes from the expression
227-
/// id to the cleanup scope id. For rvalues not present in this table,
228-
/// the appropriate cleanup scope is the innermost enclosing statement,
229-
/// conditional expression, or repeating block (see `terminating_scopes`).
230-
///
231-
/// - `terminating_scopes` is a set containing the ids of each statement,
232-
/// or conditional/repeating expression. These scopes are calling "terminating
233-
/// scopes" because, when attempting to find the scope of a temporary, by
234-
/// default we search up the enclosing scopes until we encounter the
235-
/// terminating scope. A conditional/repeating
236-
/// expression is one which is not guaranteed to execute exactly once
237-
/// upon entering the parent scope. This could be because the expression
238-
/// only executes conditionally, such as the expression `b` in `a && b`,
239-
/// or because the expression may execute many times, such as a loop
240-
/// body. The reason that we distinguish such expressions is that, upon
241-
/// exiting the parent scope, we cannot statically know how many times
242-
/// the expression executed, and thus if the expression creates
243-
/// temporaries we cannot know statically how many such temporaries we
244-
/// would have to cleanup. Therefore we ensure that the temporaries never
245-
/// outlast the conditional/repeating expression, preventing the need
246-
/// for dynamic checks and/or arbitrary amounts of stack space.
247209
pub struct RegionMaps {
210+
/// `scope_map` maps from a scope id to the enclosing scope id;
211+
/// this is usually corresponding to the lexical nesting, though
212+
/// in the case of closures the parent scope is the innermost
213+
/// conditional expression or repeating block. (Note that the
214+
/// enclosing scope id for the block associated with a closure is
215+
/// the closure itself.)
248216
scope_map: RefCell<FnvHashMap<CodeExtent, CodeExtent>>,
217+
218+
/// `var_map` maps from a variable or binding id to the block in
219+
/// which that variable is declared.
249220
var_map: RefCell<NodeMap<CodeExtent>>,
221+
222+
/// `free_region_map` maps from a free region `a` to a list of
223+
/// free regions `bs` such that `a <= b for all b in bs`
224+
///
225+
/// NB. the free region map is populated during type check as we
226+
/// check each function. See the function `relate_free_regions`
227+
/// for more information.
250228
free_region_map: RefCell<FnvHashMap<FreeRegion, Vec<FreeRegion>>>,
229+
230+
/// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
231+
/// larger than the default. The map goes from the expression id
232+
/// to the cleanup scope id. For rvalues not present in this
233+
/// table, the appropriate cleanup scope is the innermost
234+
/// enclosing statement, conditional expression, or repeating
235+
/// block (see `terminating_scopes`).
251236
rvalue_scopes: RefCell<NodeMap<CodeExtent>>,
237+
238+
/// `terminating_scopes` is a set containing the ids of each
239+
/// statement, or conditional/repeating expression. These scopes
240+
/// are calling "terminating scopes" because, when attempting to
241+
/// find the scope of a temporary, by default we search up the
242+
/// enclosing scopes until we encounter the terminating scope. A
243+
/// conditional/repeating expression is one which is not
244+
/// guaranteed to execute exactly once upon entering the parent
245+
/// scope. This could be because the expression only executes
246+
/// conditionally, such as the expression `b` in `a && b`, or
247+
/// because the expression may execute many times, such as a loop
248+
/// body. The reason that we distinguish such expressions is that,
249+
/// upon exiting the parent scope, we cannot statically know how
250+
/// many times the expression executed, and thus if the expression
251+
/// creates temporaries we cannot know statically how many such
252+
/// temporaries we would have to cleanup. Therefore we ensure that
253+
/// the temporaries never outlast the conditional/repeating
254+
/// expression, preventing the need for dynamic checks and/or
255+
/// arbitrary amounts of stack space.
252256
terminating_scopes: RefCell<FnvHashSet<CodeExtent>>,
257+
258+
/// Encodes the hierarchy of fn bodies. Every fn body (including
259+
/// closures) forms its own distinct region hierarchy, rooted in
260+
/// the block that is the fn body. This map points from the id of
261+
/// that root block to the id of the root block for the enclosing
262+
/// fn, if any. Thus the map structures the fn bodies into a
263+
/// hierarchy based on their lexical mapping. This is used to
264+
/// handle the relationships between regions in a fn and in a
265+
/// closure defined by that fn. See the "Modeling closures"
266+
/// section of the README in middle::infer::region_inference for
267+
/// more details.
268+
fn_tree: RefCell<NodeMap<ast::NodeId>>,
253269
}
254270

255271
/// Carries the node id for the innermost block or match expression,
@@ -320,6 +336,14 @@ impl InnermostEnclosingExpr {
320336

321337
#[derive(Debug, Copy)]
322338
pub struct Context {
339+
/// the root of the current region tree. This is typically the id
340+
/// of the innermost fn body. Each fn forms its own disjoint tree
341+
/// in the region hierarchy. These fn bodies are themselves
342+
/// arranged into a tree. See the "Modeling closures" section of
343+
/// the README in middle::infer::region_inference for more
344+
/// details.
345+
root_id: Option<ast::NodeId>,
346+
323347
/// the scope that contains any new variables declared
324348
var_parent: InnermostDeclaringBlock,
325349

@@ -381,19 +405,40 @@ impl RegionMaps {
381405
self.free_region_map.borrow_mut().insert(sub, vec!(sup));
382406
}
383407

408+
/// Records that `sub_fn` is defined within `sup_fn`. These ids
409+
/// should be the id of the block that is the fn body, which is
410+
/// also the root of the region hierarchy for that fn.
411+
fn record_fn_parent(&self, sub_fn: ast::NodeId, sup_fn: ast::NodeId) {
412+
debug!("record_fn_parent(sub_fn={:?}, sup_fn={:?})", sub_fn, sup_fn);
413+
assert!(sub_fn != sup_fn);
414+
let previous = self.fn_tree.borrow_mut().insert(sub_fn, sup_fn);
415+
assert!(previous.is_none());
416+
}
417+
418+
fn fn_is_enclosed_by(&self, mut sub_fn: ast::NodeId, sup_fn: ast::NodeId) -> bool {
419+
let fn_tree = self.fn_tree.borrow();
420+
loop {
421+
if sub_fn == sup_fn { return true; }
422+
match fn_tree.get(&sub_fn) {
423+
Some(&s) => { sub_fn = s; }
424+
None => { return false; }
425+
}
426+
}
427+
}
428+
384429
pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) {
385430
debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup);
386431
assert!(sub != sup);
387432
self.scope_map.borrow_mut().insert(sub, sup);
388433
}
389434

390-
pub fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
435+
fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
391436
debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
392437
assert!(var != lifetime.node_id());
393438
self.var_map.borrow_mut().insert(var, lifetime);
394439
}
395440

396-
pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
441+
fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) {
397442
debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
398443
assert!(var != lifetime.node_id());
399444
self.rvalue_scopes.borrow_mut().insert(var, lifetime);
@@ -402,7 +447,7 @@ impl RegionMaps {
402447
/// Records that a scope is a TERMINATING SCOPE. Whenever we create automatic temporaries --
403448
/// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating
404449
/// scope.
405-
pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
450+
fn mark_as_terminating_scope(&self, scope_id: CodeExtent) {
406451
debug!("record_terminating_scope(scope_id={:?})", scope_id);
407452
self.terminating_scopes.borrow_mut().insert(scope_id);
408453
}
@@ -562,15 +607,15 @@ impl RegionMaps {
562607
pub fn nearest_common_ancestor(&self,
563608
scope_a: CodeExtent,
564609
scope_b: CodeExtent)
565-
-> Option<CodeExtent> {
566-
if scope_a == scope_b { return Some(scope_a); }
610+
-> CodeExtent {
611+
if scope_a == scope_b { return scope_a; }
567612

568613
let a_ancestors = ancestors_of(self, scope_a);
569614
let b_ancestors = ancestors_of(self, scope_b);
570615
let mut a_index = a_ancestors.len() - 1;
571616
let mut b_index = b_ancestors.len() - 1;
572617

573-
// Here, ~[ab]_ancestors is a vector going from narrow to broad.
618+
// Here, [ab]_ancestors is a vector going from narrow to broad.
574619
// The end of each vector will be the item where the scope is
575620
// defined; if there are any common ancestors, then the tails of
576621
// the vector will be the same. So basically we want to walk
@@ -579,23 +624,47 @@ impl RegionMaps {
579624
// then the corresponding scope is a superscope of the other.
580625

581626
if a_ancestors[a_index] != b_ancestors[b_index] {
582-
return None;
627+
// In this case, the two regions belong to completely
628+
// different functions. Compare those fn for lexical
629+
// nesting. The reasoning behind this is subtle. See the
630+
// "Modeling closures" section of the README in
631+
// middle::infer::region_inference for more details.
632+
let a_root_scope = a_ancestors[a_index];
633+
let b_root_scope = a_ancestors[a_index];
634+
return match (a_root_scope, b_root_scope) {
635+
(CodeExtent::DestructionScope(a_root_id),
636+
CodeExtent::DestructionScope(b_root_id)) => {
637+
if self.fn_is_enclosed_by(a_root_id, b_root_id) {
638+
// `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
639+
scope_b
640+
} else if self.fn_is_enclosed_by(b_root_id, a_root_id) {
641+
// `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
642+
scope_a
643+
} else {
644+
// neither fn encloses the other
645+
unreachable!()
646+
}
647+
}
648+
_ => {
649+
// root ids are always Misc right now
650+
unreachable!()
651+
}
652+
};
583653
}
584654

585655
loop {
586656
// Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
587657
// for all indices between a_index and the end of the array
588-
if a_index == 0 { return Some(scope_a); }
589-
if b_index == 0 { return Some(scope_b); }
658+
if a_index == 0 { return scope_a; }
659+
if b_index == 0 { return scope_b; }
590660
a_index -= 1;
591661
b_index -= 1;
592662
if a_ancestors[a_index] != b_ancestors[b_index] {
593-
return Some(a_ancestors[a_index + 1]);
663+
return a_ancestors[a_index + 1];
594664
}
595665
}
596666

597-
fn ancestors_of(this: &RegionMaps, scope: CodeExtent)
598-
-> Vec<CodeExtent> {
667+
fn ancestors_of(this: &RegionMaps, scope: CodeExtent) -> Vec<CodeExtent> {
599668
// debug!("ancestors_of(scope={:?})", scope);
600669
let mut result = vec!(scope);
601670
let mut scope = scope;
@@ -645,6 +714,7 @@ fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
645714
let prev_cx = visitor.cx;
646715

647716
let blk_scope = CodeExtent::Misc(blk.id);
717+
648718
// If block was previously marked as a terminating scope during
649719
// the recursive visit of its parent node in the AST, then we need
650720
// to account for the destruction scope representing the extent of
@@ -684,6 +754,7 @@ fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
684754
// itself has returned.
685755

686756
visitor.cx = Context {
757+
root_id: prev_cx.root_id,
687758
var_parent: InnermostDeclaringBlock::Block(blk.id),
688759
parent: InnermostEnclosingExpr::Some(blk.id),
689760
};
@@ -710,6 +781,7 @@ fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) {
710781
record_superlifetime(
711782
visitor, declaring.to_code_extent(), statement.span);
712783
visitor.cx = Context {
784+
root_id: prev_cx.root_id,
713785
var_parent: InnermostDeclaringBlock::Statement(declaring),
714786
parent: InnermostEnclosingExpr::Statement(declaring),
715787
};
@@ -1103,6 +1175,7 @@ fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
11031175
// Items create a new outer block scope as far as we're concerned.
11041176
let prev_cx = visitor.cx;
11051177
visitor.cx = Context {
1178+
root_id: None,
11061179
var_parent: InnermostDeclaringBlock::None,
11071180
parent: InnermostEnclosingExpr::None
11081181
};
@@ -1111,7 +1184,7 @@ fn resolve_item(visitor: &mut RegionResolutionVisitor, item: &ast::Item) {
11111184
}
11121185

11131186
fn resolve_fn(visitor: &mut RegionResolutionVisitor,
1114-
fk: FnKind,
1187+
_: FnKind,
11151188
decl: &ast::FnDecl,
11161189
body: &ast::Block,
11171190
sp: Span,
@@ -1127,42 +1200,36 @@ fn resolve_fn(visitor: &mut RegionResolutionVisitor,
11271200

11281201
let body_scope = CodeExtent::from_node_id(body.id);
11291202
visitor.region_maps.mark_as_terminating_scope(body_scope);
1203+
11301204
let dtor_scope = CodeExtent::DestructionScope(body.id);
11311205
visitor.region_maps.record_encl_scope(body_scope, dtor_scope);
1206+
11321207
record_superlifetime(visitor, dtor_scope, body.span);
11331208

1209+
if let Some(root_id) = visitor.cx.root_id {
1210+
visitor.region_maps.record_fn_parent(body.id, root_id);
1211+
}
1212+
11341213
let outer_cx = visitor.cx;
11351214

11361215
// The arguments and `self` are parented to the body of the fn.
11371216
visitor.cx = Context {
1217+
root_id: Some(body.id),
11381218
parent: InnermostEnclosingExpr::Some(body.id),
11391219
var_parent: InnermostDeclaringBlock::Block(body.id)
11401220
};
11411221
visit::walk_fn_decl(visitor, decl);
11421222

1143-
// The body of the fn itself is either a root scope (top-level fn)
1144-
// or it continues with the inherited scope (closures).
1145-
match fk {
1146-
visit::FkItemFn(..) | visit::FkMethod(..) => {
1147-
visitor.cx = Context {
1148-
parent: InnermostEnclosingExpr::None,
1149-
var_parent: InnermostDeclaringBlock::None
1150-
};
1151-
visitor.visit_block(body);
1152-
visitor.cx = outer_cx;
1153-
}
1154-
visit::FkFnBlock(..) => {
1155-
// FIXME(#3696) -- at present we are place the closure body
1156-
// within the region hierarchy exactly where it appears lexically.
1157-
// This is wrong because the closure may live longer
1158-
// than the enclosing expression. We should probably fix this,
1159-
// but the correct fix is a bit subtle, and I am also not sure
1160-
// that the present approach is unsound -- it may not permit
1161-
// any illegal programs. See issue for more details.
1162-
visitor.cx = outer_cx;
1163-
visitor.visit_block(body);
1164-
}
1165-
}
1223+
// The body of the every fn is a root scope.
1224+
visitor.cx = Context {
1225+
root_id: Some(body.id),
1226+
parent: InnermostEnclosingExpr::None,
1227+
var_parent: InnermostDeclaringBlock::None
1228+
};
1229+
visitor.visit_block(body);
1230+
1231+
// Restore context we had at the start.
1232+
visitor.cx = outer_cx;
11661233
}
11671234

11681235
impl<'a, 'v> Visitor<'v> for RegionResolutionVisitor<'a> {
@@ -1203,12 +1270,14 @@ pub fn resolve_crate(sess: &Session, krate: &ast::Crate) -> RegionMaps {
12031270
free_region_map: RefCell::new(FnvHashMap()),
12041271
rvalue_scopes: RefCell::new(NodeMap()),
12051272
terminating_scopes: RefCell::new(FnvHashSet()),
1273+
fn_tree: RefCell::new(NodeMap()),
12061274
};
12071275
{
12081276
let mut visitor = RegionResolutionVisitor {
12091277
sess: sess,
12101278
region_maps: &maps,
12111279
cx: Context {
1280+
root_id: None,
12121281
parent: InnermostEnclosingExpr::None,
12131282
var_parent: InnermostDeclaringBlock::None,
12141283
}
@@ -1225,6 +1294,7 @@ pub fn resolve_inlined_item(sess: &Session,
12251294
sess: sess,
12261295
region_maps: region_maps,
12271296
cx: Context {
1297+
root_id: None,
12281298
parent: InnermostEnclosingExpr::None,
12291299
var_parent: InnermostDeclaringBlock::None
12301300
}

‎src/librustc_driver/test.rs

+1
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,7 @@ fn lub_free_free() {
588588
fn lub_returning_scope() {
589589
test_env(EMPTY_SOURCE_STR,
590590
errors(&["cannot infer an appropriate lifetime"]), |env| {
591+
env.create_simple_region_hierarchy();
591592
let t_rptr_scope10 = env.t_rptr_scope(10);
592593
let t_rptr_scope11 = env.t_rptr_scope(11);
593594

0 commit comments

Comments
 (0)
Please sign in to comment.