-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
region.rs
1435 lines (1272 loc) · 56.1 KB
/
region.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This file builds up the `ScopeTree`, which describes
//! the parent links in the region hierarchy.
//!
//! Most of the documentation on regions can be found in
//! `middle/infer/region_constraints/README.md`
use ich::{StableHashingContext, NodeIdHashingMode};
use util::nodemap::{FxHashMap, FxHashSet};
use ty;
use std::fmt;
use std::mem;
use std::rc::Rc;
use syntax::codemap;
use syntax::ast;
use syntax_pos::{Span, DUMMY_SP};
use ty::TyCtxt;
use ty::maps::Providers;
use hir;
use hir::def_id::DefId;
use hir::intravisit::{self, Visitor, NestedVisitorMap};
use hir::{Block, Arm, Pat, PatKind, Stmt, Expr, Local};
use rustc_data_structures::indexed_vec::Idx;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher,
StableHasherResult};
/// Scope represents a statically-describable scope that can be
/// used to bound the lifetime/region for values.
///
/// `Node(node_id)`: Any AST node that has any scope at all has the
/// `Node(node_id)` scope. Other variants represent special cases not
/// immediately derivable from the abstract syntax tree structure.
///
/// `DestructionScope(node_id)` represents the scope of destructors
/// implicitly-attached to `node_id` that run immediately after the
/// expression for `node_id` itself. Not every AST node carries a
/// `DestructionScope`, but those that are `terminating_scopes` do;
/// see discussion with `ScopeTree`.
///
/// `Remainder(BlockRemainder { block, statement_index })` represents
/// the scope of user code running immediately after the initializer
/// expression for the indexed statement, until the end of the block.
///
/// So: the following code can be broken down into the scopes beneath:
///
/// ```text
/// let a = f().g( 'b: { let x = d(); let y = d(); x.h(y) } ) ;
///
/// +-+ (D12.)
/// +-+ (D11.)
/// +---------+ (R10.)
/// +-+ (D9.)
/// +----------+ (M8.)
/// +----------------------+ (R7.)
/// +-+ (D6.)
/// +----------+ (M5.)
/// +-----------------------------------+ (M4.)
/// +--------------------------------------------------+ (M3.)
/// +--+ (M2.)
/// +-----------------------------------------------------------+ (M1.)
///
/// (M1.): Node scope of the whole `let a = ...;` statement.
/// (M2.): Node scope of the `f()` expression.
/// (M3.): Node scope of the `f().g(..)` expression.
/// (M4.): Node scope of the block labeled `'b:`.
/// (M5.): Node scope of the `let x = d();` statement
/// (D6.): DestructionScope for temporaries created during M5.
/// (R7.): Remainder scope for block `'b:`, stmt 0 (let x = ...).
/// (M8.): Node scope of the `let y = d();` statement.
/// (D9.): DestructionScope for temporaries created during M8.
/// (R10.): Remainder scope for block `'b:`, stmt 1 (let y = ...).
/// (D11.): DestructionScope for temporaries and bindings from block `'b:`.
/// (D12.): DestructionScope for temporaries created during M1 (e.g. f()).
/// ```
///
/// Note that while the above picture shows the destruction scopes
/// as following their corresponding node scopes, in the internal
/// data structures of the compiler the destruction scopes are
/// represented as enclosing parents. This is sound because we use the
/// enclosing parent relationship just to ensure that referenced
/// values live long enough; phrased another way, the starting point
/// of each range is not really the important thing in the above
/// picture, but rather the ending point.
///
/// FIXME (pnkfelix): This currently derives `PartialOrd` and `Ord` to
/// placate the same deriving in `ty::FreeRegion`, but we may want to
/// actually attach a more meaningful ordering to scopes than the one
/// generated via deriving here.
///
/// Scope is a bit-packed to save space - if `code` is SCOPE_DATA_REMAINDER_MAX
/// or less, it is a `ScopeData::Remainder`, otherwise it is a type specified
/// by the bitpacking.
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy, RustcEncodable, RustcDecodable)]
pub struct Scope {
pub(crate) id: hir::ItemLocalId,
pub(crate) code: u32
}
const SCOPE_DATA_NODE: u32 = !0;
const SCOPE_DATA_CALLSITE: u32 = !1;
const SCOPE_DATA_ARGUMENTS: u32 = !2;
const SCOPE_DATA_DESTRUCTION: u32 = !3;
const SCOPE_DATA_REMAINDER_MAX: u32 = !4;
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, RustcEncodable, RustcDecodable)]
pub enum ScopeData {
Node(hir::ItemLocalId),
// Scope of the call-site for a function or closure
// (outlives the arguments as well as the body).
CallSite(hir::ItemLocalId),
// Scope of arguments passed to a function or closure
// (they outlive its body).
Arguments(hir::ItemLocalId),
// Scope of destructors for temporaries of node-id.
Destruction(hir::ItemLocalId),
// Scope following a `let id = expr;` binding in a block.
Remainder(BlockRemainder)
}
/// Represents a subscope of `block` for a binding that is introduced
/// by `block.stmts[first_statement_index]`. Such subscopes represent
/// a suffix of the block. Note that each subscope does not include
/// the initializer expression, if any, for the statement indexed by
/// `first_statement_index`.
///
/// For example, given `{ let (a, b) = EXPR_1; let c = EXPR_2; ... }`:
///
/// * the subscope with `first_statement_index == 0` is scope of both
/// `a` and `b`; it does not include EXPR_1, but does include
/// everything after that first `let`. (If you want a scope that
/// includes EXPR_1 as well, then do not use `Scope::Remainder`,
/// but instead another `Scope` that encompasses the whole block,
/// e.g. `Scope::Node`.
///
/// * the subscope with `first_statement_index == 1` is scope of `c`,
/// and thus does not include EXPR_2, but covers the `...`.
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, RustcEncodable,
RustcDecodable, Debug, Copy)]
pub struct BlockRemainder {
pub block: hir::ItemLocalId,
pub first_statement_index: FirstStatementIndex,
}
newtype_index!(FirstStatementIndex
{
pub idx
MAX = SCOPE_DATA_REMAINDER_MAX
});
impl From<ScopeData> for Scope {
#[inline]
fn from(scope_data: ScopeData) -> Self {
let (id, code) = match scope_data {
ScopeData::Node(id) => (id, SCOPE_DATA_NODE),
ScopeData::CallSite(id) => (id, SCOPE_DATA_CALLSITE),
ScopeData::Arguments(id) => (id, SCOPE_DATA_ARGUMENTS),
ScopeData::Destruction(id) => (id, SCOPE_DATA_DESTRUCTION),
ScopeData::Remainder(r) => (r.block, r.first_statement_index.index() as u32)
};
Self { id, code }
}
}
impl fmt::Debug for Scope {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.data(), formatter)
}
}
#[allow(non_snake_case)]
impl Scope {
#[inline]
pub fn data(self) -> ScopeData {
match self.code {
SCOPE_DATA_NODE => ScopeData::Node(self.id),
SCOPE_DATA_CALLSITE => ScopeData::CallSite(self.id),
SCOPE_DATA_ARGUMENTS => ScopeData::Arguments(self.id),
SCOPE_DATA_DESTRUCTION => ScopeData::Destruction(self.id),
idx => ScopeData::Remainder(BlockRemainder {
block: self.id,
first_statement_index: FirstStatementIndex::new(idx as usize)
})
}
}
#[inline]
pub fn Node(id: hir::ItemLocalId) -> Self {
Self::from(ScopeData::Node(id))
}
#[inline]
pub fn CallSite(id: hir::ItemLocalId) -> Self {
Self::from(ScopeData::CallSite(id))
}
#[inline]
pub fn Arguments(id: hir::ItemLocalId) -> Self {
Self::from(ScopeData::Arguments(id))
}
#[inline]
pub fn Destruction(id: hir::ItemLocalId) -> Self {
Self::from(ScopeData::Destruction(id))
}
#[inline]
pub fn Remainder(r: BlockRemainder) -> Self {
Self::from(ScopeData::Remainder(r))
}
}
impl Scope {
/// Returns a item-local id associated with this scope.
///
/// NB: likely to be replaced as API is refined; e.g. pnkfelix
/// anticipates `fn entry_node_id` and `fn each_exit_node_id`.
pub fn item_local_id(&self) -> hir::ItemLocalId {
self.id
}
pub fn node_id(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> ast::NodeId {
match scope_tree.root_body {
Some(hir_id) => {
tcx.hir.hir_to_node_id(hir::HirId {
owner: hir_id.owner,
local_id: self.item_local_id()
})
}
None => ast::DUMMY_NODE_ID
}
}
/// Returns the span of this Scope. Note that in general the
/// returned span may not correspond to the span of any node id in
/// the AST.
pub fn span(&self, tcx: TyCtxt, scope_tree: &ScopeTree) -> Span {
let node_id = self.node_id(tcx, scope_tree);
if node_id == ast::DUMMY_NODE_ID {
return DUMMY_SP;
}
let span = tcx.hir.span(node_id);
if let ScopeData::Remainder(r) = self.data() {
if let hir::map::NodeBlock(ref blk) = tcx.hir.get(node_id) {
// Want span for scope starting after the
// indexed statement and ending at end of
// `blk`; reuse span of `blk` and shift `lo`
// forward to end of indexed statement.
//
// (This is the special case aluded to in the
// doc-comment for this method)
let stmt_span = blk.stmts[r.first_statement_index.index()].span;
// To avoid issues with macro-generated spans, the span
// of the statement must be nested in that of the block.
if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() {
return Span::new(stmt_span.lo(), span.hi(), span.ctxt());
}
}
}
span
}
}
/// The region scope tree encodes information about region relationships.
#[derive(Default, Debug)]
pub struct ScopeTree {
/// If not empty, this body is the root of this region hierarchy.
root_body: Option<hir::HirId>,
/// The parent of the root body owner, if the latter is an
/// an associated const or method, as impls/traits can also
/// have lifetime parameters free in this body.
root_parent: Option<ast::NodeId>,
/// `parent_map` maps from a scope id to the enclosing scope id;
/// this is usually corresponding to the lexical nesting, though
/// in the case of closures the parent scope is the innermost
/// conditional expression or repeating block. (Note that the
/// enclosing scope id for the block associated with a closure is
/// the closure itself.)
parent_map: FxHashMap<Scope, Scope>,
/// `var_map` maps from a variable or binding id to the block in
/// which that variable is declared.
var_map: FxHashMap<hir::ItemLocalId, Scope>,
/// maps from a node-id to the associated destruction scope (if any)
destruction_scopes: FxHashMap<hir::ItemLocalId, Scope>,
/// `rvalue_scopes` includes entries for those expressions whose cleanup scope is
/// larger than the default. The map goes from the expression id
/// to the cleanup scope id. For rvalues not present in this
/// table, the appropriate cleanup scope is the innermost
/// enclosing statement, conditional expression, or repeating
/// block (see `terminating_scopes`).
/// In constants, None is used to indicate that certain expressions
/// escape into 'static and should have no local cleanup scope.
rvalue_scopes: FxHashMap<hir::ItemLocalId, Option<Scope>>,
/// Encodes the hierarchy of fn bodies. Every fn body (including
/// closures) forms its own distinct region hierarchy, rooted in
/// the block that is the fn body. This map points from the id of
/// that root block to the id of the root block for the enclosing
/// fn, if any. Thus the map structures the fn bodies into a
/// hierarchy based on their lexical mapping. This is used to
/// handle the relationships between regions in a fn and in a
/// closure defined by that fn. See the "Modeling closures"
/// section of the README in infer::region_constraints for
/// more details.
closure_tree: FxHashMap<hir::ItemLocalId, hir::ItemLocalId>,
/// If there are any `yield` nested within a scope, this map
/// stores the `Span` of the last one and its index in the
/// postorder of the Visitor traversal on the HIR.
///
/// HIR Visitor postorder indexes might seem like a peculiar
/// thing to care about. but it turns out that HIR bindings
/// and the temporary results of HIR expressions are never
/// storage-live at the end of HIR nodes with postorder indexes
/// lower than theirs, and therefore don't need to be suspended
/// at yield-points at these indexes.
///
/// For an example, suppose we have some code such as:
/// ```rust,ignore (example)
/// foo(f(), yield y, bar(g()))
/// ```
///
/// With the HIR tree (calls numbered for expository purposes)
/// ```
/// Call#0(foo, [Call#1(f), Yield(y), Call#2(bar, Call#3(g))])
/// ```
///
/// Obviously, the result of `f()` was created before the yield
/// (and therefore needs to be kept valid over the yield) while
/// the result of `g()` occurs after the yield (and therefore
/// doesn't). If we want to infer that, we can look at the
/// postorder traversal:
/// ```
/// `foo` `f` Call#1 `y` Yield `bar` `g` Call#3 Call#2 Call#0
/// ```
///
/// In which we can easily see that `Call#1` occurs before the yield,
/// and `Call#3` after it.
///
/// To see that this method works, consider:
///
/// Let `D` be our binding/temporary and `U` be our other HIR node, with
/// `HIR-postorder(U) < HIR-postorder(D)` (in our example, U would be
/// the yield and D would be one of the calls). Let's show that
/// `D` is storage-dead at `U`.
///
/// Remember that storage-live/storage-dead refers to the state of
/// the *storage*, and does not consider moves/drop flags.
///
/// Then:
/// 1. From the ordering guarantee of HIR visitors (see
/// `rustc::hir::intravisit`), `D` does not dominate `U`.
/// 2. Therefore, `D` is *potentially* storage-dead at `U` (because
/// we might visit `U` without ever getting to `D`).
/// 3. However, we guarantee that at each HIR point, each
/// binding/temporary is always either always storage-live
/// or always storage-dead. This is what is being guaranteed
/// by `terminating_scopes` including all blocks where the
/// count of executions is not guaranteed.
/// 4. By `2.` and `3.`, `D` is *statically* storage-dead at `U`,
/// QED.
///
/// I don't think this property relies on `3.` in an essential way - it
/// is probably still correct even if we have "unrestricted" terminating
/// scopes. However, why use the complicated proof when a simple one
/// works?
///
/// A subtle thing: `box` expressions, such as `box (&x, yield 2, &y)`. It
/// might seem that a `box` expression creates a `Box<T>` temporary
/// when it *starts* executing, at `HIR-preorder(BOX-EXPR)`. That might
/// be true in the MIR desugaring, but it is not important in the semantics.
///
/// The reason is that semantically, until the `box` expression returns,
/// the values are still owned by their containing expressions. So
/// we'll see that `&x`.
yield_in_scope: FxHashMap<Scope, (Span, usize)>,
/// The number of visit_expr and visit_pat calls done in the body.
/// Used to sanity check visit_expr/visit_pat call count when
/// calculating generator interiors.
body_expr_count: FxHashMap<hir::BodyId, usize>,
}
#[derive(Debug, Copy, Clone)]
pub struct Context {
/// the root of the current region tree. This is typically the id
/// of the innermost fn body. Each fn forms its own disjoint tree
/// in the region hierarchy. These fn bodies are themselves
/// arranged into a tree. See the "Modeling closures" section of
/// the README in infer::region_constraints for more
/// details.
root_id: Option<hir::ItemLocalId>,
/// the scope that contains any new variables declared
var_parent: Option<Scope>,
/// region parent of expressions etc
parent: Option<Scope>,
}
struct RegionResolutionVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
// The number of expressions and patterns visited in the current body
expr_and_pat_count: usize,
// Generated scope tree:
scope_tree: ScopeTree,
cx: Context,
/// `terminating_scopes` is a set containing the ids of each
/// statement, or conditional/repeating expression. These scopes
/// are calling "terminating scopes" because, when attempting to
/// find the scope of a temporary, by default we search up the
/// enclosing scopes until we encounter the terminating scope. A
/// conditional/repeating expression is one which is not
/// guaranteed to execute exactly once upon entering the parent
/// scope. This could be because the expression only executes
/// conditionally, such as the expression `b` in `a && b`, or
/// because the expression may execute many times, such as a loop
/// body. The reason that we distinguish such expressions is that,
/// upon exiting the parent scope, we cannot statically know how
/// many times the expression executed, and thus if the expression
/// creates temporaries we cannot know statically how many such
/// temporaries we would have to cleanup. Therefore we ensure that
/// the temporaries never outlast the conditional/repeating
/// expression, preventing the need for dynamic checks and/or
/// arbitrary amounts of stack space. Terminating scopes end
/// up being contained in a DestructionScope that contains the
/// destructor's execution.
terminating_scopes: FxHashSet<hir::ItemLocalId>,
}
impl<'tcx> ScopeTree {
pub fn record_scope_parent(&mut self, child: Scope, parent: Option<Scope>) {
debug!("{:?}.parent = {:?}", child, parent);
if let Some(p) = parent {
let prev = self.parent_map.insert(child, p);
assert!(prev.is_none());
}
// record the destruction scopes for later so we can query them
if let ScopeData::Destruction(n) = child.data() {
self.destruction_scopes.insert(n, child);
}
}
pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(Scope, Scope) {
for (&child, &parent) in &self.parent_map {
e(child, parent)
}
}
pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&hir::ItemLocalId, Scope) {
for (child, &parent) in self.var_map.iter() {
e(child, parent)
}
}
pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option<Scope> {
self.destruction_scopes.get(&n).cloned()
}
/// Records that `sub_closure` is defined within `sup_closure`. These ids
/// should be the id of the block that is the fn body, which is
/// also the root of the region hierarchy for that fn.
fn record_closure_parent(&mut self,
sub_closure: hir::ItemLocalId,
sup_closure: hir::ItemLocalId) {
debug!("record_closure_parent(sub_closure={:?}, sup_closure={:?})",
sub_closure, sup_closure);
assert!(sub_closure != sup_closure);
let previous = self.closure_tree.insert(sub_closure, sup_closure);
assert!(previous.is_none());
}
fn closure_is_enclosed_by(&self,
mut sub_closure: hir::ItemLocalId,
sup_closure: hir::ItemLocalId) -> bool {
loop {
if sub_closure == sup_closure { return true; }
match self.closure_tree.get(&sub_closure) {
Some(&s) => { sub_closure = s; }
None => { return false; }
}
}
}
fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) {
debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime);
assert!(var != lifetime.item_local_id());
self.var_map.insert(var, lifetime);
}
fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option<Scope>) {
debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime);
if let Some(lifetime) = lifetime {
assert!(var != lifetime.item_local_id());
}
self.rvalue_scopes.insert(var, lifetime);
}
pub fn opt_encl_scope(&self, id: Scope) -> Option<Scope> {
//! Returns the narrowest scope that encloses `id`, if any.
self.parent_map.get(&id).cloned()
}
#[allow(dead_code)] // used in cfg
pub fn encl_scope(&self, id: Scope) -> Scope {
//! Returns the narrowest scope that encloses `id`, if any.
self.opt_encl_scope(id).unwrap()
}
/// Returns the lifetime of the local variable `var_id`
pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
match self.var_map.get(&var_id) {
Some(&r) => r,
None => { bug!("no enclosing scope for id {:?}", var_id); }
}
}
pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
//! Returns the scope when temp created by expr_id will be cleaned up
// check for a designated rvalue scope
if let Some(&s) = self.rvalue_scopes.get(&expr_id) {
debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s);
return s;
}
// else, locate the innermost terminating scope
// if there's one. Static items, for instance, won't
// have an enclosing scope, hence no scope will be
// returned.
let mut id = Scope::Node(expr_id);
while let Some(&p) = self.parent_map.get(&id) {
match p.data() {
ScopeData::Destruction(..) => {
debug!("temporary_scope({:?}) = {:?} [enclosing]",
expr_id, id);
return Some(id);
}
_ => id = p
}
}
debug!("temporary_scope({:?}) = None", expr_id);
return None;
}
pub fn var_region(&self, id: hir::ItemLocalId) -> ty::RegionKind {
//! Returns the lifetime of the variable `id`.
let scope = ty::ReScope(self.var_scope(id));
debug!("var_region({:?}) = {:?}", id, scope);
scope
}
pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope)
-> bool {
self.is_subscope_of(scope1, scope2) ||
self.is_subscope_of(scope2, scope1)
}
/// Returns true if `subscope` is equal to or is lexically nested inside `superscope` and false
/// otherwise.
pub fn is_subscope_of(&self,
subscope: Scope,
superscope: Scope)
-> bool {
let mut s = subscope;
debug!("is_subscope_of({:?}, {:?})", subscope, superscope);
while superscope != s {
match self.opt_encl_scope(s) {
None => {
debug!("is_subscope_of({:?}, {:?}, s={:?})=false",
subscope, superscope, s);
return false;
}
Some(scope) => s = scope
}
}
debug!("is_subscope_of({:?}, {:?})=true",
subscope, superscope);
return true;
}
/// Finds the nearest common ancestor (if any) of two scopes. That is, finds the smallest
/// scope which is greater than or equal to both `scope_a` and `scope_b`.
pub fn nearest_common_ancestor(&self,
scope_a: Scope,
scope_b: Scope)
-> Scope {
if scope_a == scope_b { return scope_a; }
// [1] The initial values for `a_buf` and `b_buf` are not used.
// The `ancestors_of` function will return some prefix that
// is re-initialized with new values (or else fallback to a
// heap-allocated vector).
let mut a_buf: [Scope; 32] = [scope_a /* [1] */; 32];
let mut a_vec: Vec<Scope> = vec![];
let mut b_buf: [Scope; 32] = [scope_b /* [1] */; 32];
let mut b_vec: Vec<Scope> = vec![];
let parent_map = &self.parent_map;
let a_ancestors = ancestors_of(parent_map, scope_a, &mut a_buf, &mut a_vec);
let b_ancestors = ancestors_of(parent_map, scope_b, &mut b_buf, &mut b_vec);
let mut a_index = a_ancestors.len() - 1;
let mut b_index = b_ancestors.len() - 1;
// Here, [ab]_ancestors is a vector going from narrow to broad.
// The end of each vector will be the item where the scope is
// defined; if there are any common ancestors, then the tails of
// the vector will be the same. So basically we want to walk
// backwards from the tail of each vector and find the first point
// where they diverge. If one vector is a suffix of the other,
// then the corresponding scope is a superscope of the other.
if a_ancestors[a_index] != b_ancestors[b_index] {
// In this case, the two regions belong to completely
// different functions. Compare those fn for lexical
// nesting. The reasoning behind this is subtle. See the
// "Modeling closures" section of the README in
// infer::region_constraints for more details.
let a_root_scope = a_ancestors[a_index];
let b_root_scope = a_ancestors[a_index];
return match (a_root_scope.data(), b_root_scope.data()) {
(ScopeData::Destruction(a_root_id),
ScopeData::Destruction(b_root_id)) => {
if self.closure_is_enclosed_by(a_root_id, b_root_id) {
// `a` is enclosed by `b`, hence `b` is the ancestor of everything in `a`
scope_b
} else if self.closure_is_enclosed_by(b_root_id, a_root_id) {
// `b` is enclosed by `a`, hence `a` is the ancestor of everything in `b`
scope_a
} else {
// neither fn encloses the other
bug!()
}
}
_ => {
// root ids are always Node right now
bug!()
}
};
}
loop {
// Loop invariant: a_ancestors[a_index] == b_ancestors[b_index]
// for all indices between a_index and the end of the array
if a_index == 0 { return scope_a; }
if b_index == 0 { return scope_b; }
a_index -= 1;
b_index -= 1;
if a_ancestors[a_index] != b_ancestors[b_index] {
return a_ancestors[a_index + 1];
}
}
fn ancestors_of<'a, 'tcx>(parent_map: &FxHashMap<Scope, Scope>,
scope: Scope,
buf: &'a mut [Scope; 32],
vec: &'a mut Vec<Scope>)
-> &'a [Scope] {
// debug!("ancestors_of(scope={:?})", scope);
let mut scope = scope;
let mut i = 0;
while i < 32 {
buf[i] = scope;
match parent_map.get(&scope) {
Some(&superscope) => scope = superscope,
_ => return &buf[..i+1]
}
i += 1;
}
*vec = Vec::with_capacity(64);
vec.extend_from_slice(buf);
loop {
vec.push(scope);
match parent_map.get(&scope) {
Some(&superscope) => scope = superscope,
_ => return &*vec
}
}
}
}
/// Assuming that the provided region was defined within this `ScopeTree`,
/// returns the outermost `Scope` that the region outlives.
pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
br: &ty::EarlyBoundRegion)
-> Scope {
let param_owner = tcx.parent_def_id(br.def_id).unwrap();
let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
let scope = tcx.hir.maybe_body_owned_by(param_owner_id).map(|body_id| {
tcx.hir.body(body_id).value.hir_id.local_id
}).unwrap_or_else(|| {
// The lifetime was defined on node that doesn't own a body,
// which in practice can only mean a trait or an impl, that
// is the parent of a method, and that is enforced below.
assert_eq!(Some(param_owner_id), self.root_parent,
"free_scope: {:?} not recognized by the \
region scope tree for {:?} / {:?}",
param_owner,
self.root_parent.map(|id| tcx.hir.local_def_id(id)),
self.root_body.map(|hir_id| DefId::local(hir_id.owner)));
// The trait/impl lifetime is in scope for the method's body.
self.root_body.unwrap().local_id
});
Scope::CallSite(scope)
}
/// Assuming that the provided region was defined within this `ScopeTree`,
/// returns the outermost `Scope` that the region outlives.
pub fn free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, fr: &ty::FreeRegion)
-> Scope {
let param_owner = match fr.bound_region {
ty::BoundRegion::BrNamed(def_id, _) => {
tcx.parent_def_id(def_id).unwrap()
}
_ => fr.scope
};
// Ensure that the named late-bound lifetimes were defined
// on the same function that they ended up being freed in.
assert_eq!(param_owner, fr.scope);
let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
let body_id = tcx.hir.body_owned_by(param_owner_id);
Scope::CallSite(tcx.hir.body(body_id).value.hir_id.local_id)
}
/// Checks whether the given scope contains a `yield`. If so,
/// returns `Some((span, expr_count))` with the span of a yield we found and
/// the number of expressions appearing before the `yield` in the body.
pub fn yield_in_scope(&self, scope: Scope) -> Option<(Span, usize)> {
self.yield_in_scope.get(&scope).cloned()
}
/// Gives the number of expressions visited in a body.
/// Used to sanity check visit_expr call count when
/// calculating generator interiors.
pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> {
self.body_expr_count.get(&body_id).map(|r| *r)
}
}
/// Records the lifetime of a local variable as `cx.var_parent`
fn record_var_lifetime(visitor: &mut RegionResolutionVisitor,
var_id: hir::ItemLocalId,
_sp: Span) {
match visitor.cx.var_parent {
None => {
// this can happen in extern fn declarations like
//
// extern fn isalnum(c: c_int) -> c_int
}
Some(parent_scope) =>
visitor.scope_tree.record_var_scope(var_id, parent_scope),
}
}
fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: &'tcx hir::Block) {
debug!("resolve_block(blk.id={:?})", blk.id);
let prev_cx = visitor.cx;
// We treat the tail expression in the block (if any) somewhat
// differently from the statements. The issue has to do with
// temporary lifetimes. Consider the following:
//
// quux({
// let inner = ... (&bar()) ...;
//
// (... (&foo()) ...) // (the tail expression)
// }, other_argument());
//
// Each of the statements within the block is a terminating
// scope, and thus a temporary (e.g. the result of calling
// `bar()` in the initalizer expression for `let inner = ...;`)
// will be cleaned up immediately after its corresponding
// statement (i.e. `let inner = ...;`) executes.
//
// On the other hand, temporaries associated with evaluating the
// tail expression for the block are assigned lifetimes so that
// they will be cleaned up as part of the terminating scope
// *surrounding* the block expression. Here, the terminating
// scope for the block expression is the `quux(..)` call; so
// those temporaries will only be cleaned up *after* both
// `other_argument()` has run and also the call to `quux(..)`
// itself has returned.
visitor.enter_node_scope_with_dtor(blk.hir_id.local_id);
visitor.cx.var_parent = visitor.cx.parent;
{
// This block should be kept approximately in sync with
// `intravisit::walk_block`. (We manually walk the block, rather
// than call `walk_block`, in order to maintain precise
// index information.)
for (i, statement) in blk.stmts.iter().enumerate() {
if let hir::StmtDecl(..) = statement.node {
// Each StmtDecl introduces a subscope for bindings
// introduced by the declaration; this subscope covers
// a suffix of the block . Each subscope in a block
// has the previous subscope in the block as a parent,
// except for the first such subscope, which has the
// block itself as a parent.
visitor.enter_scope(
Scope::Remainder(BlockRemainder {
block: blk.hir_id.local_id,
first_statement_index: FirstStatementIndex::new(i)
})
);
visitor.cx.var_parent = visitor.cx.parent;
}
visitor.visit_stmt(statement)
}
walk_list!(visitor, visit_expr, &blk.expr);
}
visitor.cx = prev_cx;
}
fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
if let Some(ref expr) = arm.guard {
visitor.terminating_scopes.insert(expr.hir_id.local_id);
}
intravisit::walk_arm(visitor, arm);
}
fn resolve_pat<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, pat: &'tcx hir::Pat) {
visitor.record_child_scope(Scope::Node(pat.hir_id.local_id));
// If this is a binding then record the lifetime of that binding.
if let PatKind::Binding(..) = pat.node {
record_var_lifetime(visitor, pat.hir_id.local_id, pat.span);
}
intravisit::walk_pat(visitor, pat);
visitor.expr_and_pat_count += 1;
}
fn resolve_stmt<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
let stmt_id = visitor.tcx.hir.node_to_hir_id(stmt.node.id()).local_id;
debug!("resolve_stmt(stmt.id={:?})", stmt_id);
// Every statement will clean up the temporaries created during
// execution of that statement. Therefore each statement has an
// associated destruction scope that represents the scope of the
// statement plus its destructors, and thus the scope for which
// regions referenced by the destructors need to survive.
visitor.terminating_scopes.insert(stmt_id);
let prev_parent = visitor.cx.parent;
visitor.enter_node_scope_with_dtor(stmt_id);
intravisit::walk_stmt(visitor, stmt);
visitor.cx.parent = prev_parent;
}
fn resolve_expr<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, expr: &'tcx hir::Expr) {
debug!("resolve_expr(expr.id={:?})", expr.id);
let prev_cx = visitor.cx;
visitor.enter_node_scope_with_dtor(expr.hir_id.local_id);
{
let terminating_scopes = &mut visitor.terminating_scopes;
let mut terminating = |id: hir::ItemLocalId| {
terminating_scopes.insert(id);
};
match expr.node {
// Conditional or repeating scopes are always terminating
// scopes, meaning that temporaries cannot outlive them.
// This ensures fixed size stacks.
hir::ExprBinary(codemap::Spanned { node: hir::BiAnd, .. }, _, ref r) |
hir::ExprBinary(codemap::Spanned { node: hir::BiOr, .. }, _, ref r) => {
// For shortcircuiting operators, mark the RHS as a terminating
// scope since it only executes conditionally.
terminating(r.hir_id.local_id);
}
hir::ExprIf(ref expr, ref then, Some(ref otherwise)) => {
terminating(expr.hir_id.local_id);
terminating(then.hir_id.local_id);
terminating(otherwise.hir_id.local_id);
}
hir::ExprIf(ref expr, ref then, None) => {
terminating(expr.hir_id.local_id);
terminating(then.hir_id.local_id);
}
hir::ExprLoop(ref body, _, _) => {
terminating(body.hir_id.local_id);
}
hir::ExprWhile(ref expr, ref body, _) => {
terminating(expr.hir_id.local_id);
terminating(body.hir_id.local_id);
}
hir::ExprMatch(..) => {
visitor.cx.var_parent = visitor.cx.parent;
}
hir::ExprAssignOp(..) | hir::ExprIndex(..) |
hir::ExprUnary(..) | hir::ExprCall(..) | hir::ExprMethodCall(..) => {
// FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls
//
// The lifetimes for a call or method call look as follows:
//
// call.id
// - arg0.id
// - ...
// - argN.id
// - call.callee_id
//
// The idea is that call.callee_id represents *the time when
// the invoked function is actually running* and call.id
// represents *the time to prepare the arguments and make the
// call*. See the section "Borrows in Calls" borrowck/README.md
// for an extended explanation of why this distinction is
// important.
//
// record_superlifetime(new_cx, expr.callee_id);
}
_ => {}
}
}
match expr.node {
// Manually recurse over closures, because they are the only
// case of nested bodies that share the parent environment.
hir::ExprClosure(.., body, _, _) => {
let body = visitor.tcx.hir.body(body);
visitor.visit_body(body);
}
_ => intravisit::walk_expr(visitor, expr)
}
visitor.expr_and_pat_count += 1;
if let hir::ExprYield(..) = expr.node {
// Mark this expr's scope and all parent scopes as containing `yield`.
let mut scope = Scope::Node(expr.hir_id.local_id);
loop {
visitor.scope_tree.yield_in_scope.insert(scope,
(expr.span, visitor.expr_and_pat_count));
// Keep traversing up while we can.
match visitor.scope_tree.parent_map.get(&scope) {
// Don't cross from closure bodies to their parent.
Some(&superscope) => match superscope.data() {
ScopeData::CallSite(_) => break,
_ => scope = superscope
},
None => break
}