/
mod.rs
1350 lines (1195 loc) · 47.9 KB
/
mod.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.
/*! See doc.rs */
use middle::ty;
use middle::ty::{BoundRegion, FreeRegion, Region, RegionVid, Vid};
use middle::ty::{ReEmpty, ReStatic, ReInfer, ReFree, ReEarlyBound,
ReLateBound};
use middle::ty::{ReScope, ReVar, ReSkolemized, BrFresh};
use middle::typeck::infer::cres;
use middle::typeck::infer::{RegionVariableOrigin, SubregionOrigin, TypeTrace};
use middle::typeck::infer;
use middle::graph;
use middle::graph::{Direction, NodeIndex};
use util::common::indenter;
use util::ppaux::{Repr};
use std::cell::{Cell, RefCell};
use std::uint;
use collections::{HashMap, HashSet};
use syntax::ast;
mod doc;
#[deriving(Eq, TotalEq, Hash)]
pub enum Constraint {
ConstrainVarSubVar(RegionVid, RegionVid),
ConstrainRegSubVar(Region, RegionVid),
ConstrainVarSubReg(RegionVid, Region),
ConstrainRegSubReg(Region, Region),
}
#[deriving(Eq, TotalEq, Hash)]
pub struct TwoRegions {
a: Region,
b: Region,
}
pub enum UndoLogEntry {
Snapshot,
AddVar(RegionVid),
AddConstraint(Constraint),
AddCombination(CombineMapType, TwoRegions)
}
pub enum CombineMapType {
Lub, Glb
}
#[deriving(Clone)]
pub enum RegionResolutionError {
/// `ConcreteFailure(o, a, b)`:
///
/// `o` requires that `a <= b`, but this does not hold
ConcreteFailure(SubregionOrigin, Region, Region),
/// `SubSupConflict(v, sub_origin, sub_r, sup_origin, sup_r)`:
///
/// Could not infer a value for `v` because `sub_r <= v` (due to
/// `sub_origin`) but `v <= sup_r` (due to `sup_origin`) and
/// `sub_r <= sup_r` does not hold.
SubSupConflict(RegionVariableOrigin,
SubregionOrigin, Region,
SubregionOrigin, Region),
/// `SupSupConflict(v, origin1, r1, origin2, r2)`:
///
/// Could not infer a value for `v` because `v <= r1` (due to
/// `origin1`) and `v <= r2` (due to `origin2`) and
/// `r1` and `r2` have no intersection.
SupSupConflict(RegionVariableOrigin,
SubregionOrigin, Region,
SubregionOrigin, Region),
/// For subsets of `ConcreteFailure` and `SubSupConflict`, we can derive
/// more specific errors message by suggesting to the user where they
/// should put a lifetime. In those cases we process and put those errors
/// into `ProcessedErrors` before we do any reporting.
ProcessedErrors(Vec<RegionVariableOrigin>,
Vec<(TypeTrace, ty::type_err)>,
Vec<SameRegions>),
}
/// SameRegions is used to group regions that we think are the same and would
/// like to indicate so to the user.
/// For example, the following function
/// ```
/// struct Foo { bar: int }
/// fn foo2<'a, 'b>(x: &'a Foo) -> &'b int {
/// &x.bar
/// }
/// ```
/// would report an error because we expect 'a and 'b to match, and so we group
/// 'a and 'b together inside a SameRegions struct
#[deriving(Clone)]
pub struct SameRegions {
pub scope_id: ast::NodeId,
pub regions: Vec<BoundRegion>
}
impl SameRegions {
pub fn contains(&self, other: &BoundRegion) -> bool {
self.regions.contains(other)
}
pub fn push(&mut self, other: BoundRegion) {
self.regions.push(other);
}
}
pub type CombineMap = HashMap<TwoRegions, RegionVid>;
pub struct RegionVarBindings<'a> {
tcx: &'a ty::ctxt,
var_origins: RefCell<Vec<RegionVariableOrigin>>,
constraints: RefCell<HashMap<Constraint, SubregionOrigin>>,
lubs: RefCell<CombineMap>,
glbs: RefCell<CombineMap>,
skolemization_count: Cell<uint>,
bound_count: Cell<uint>,
// The undo log records actions that might later be undone.
//
// Note: when the undo_log is empty, we are not actively
// snapshotting. When the `start_snapshot()` method is called, we
// push a Snapshot entry onto the list to indicate that we are now
// actively snapshotting. The reason for this is that otherwise
// we end up adding entries for things like the lower bound on
// a variable and so forth, which can never be rolled back.
undo_log: RefCell<Vec<UndoLogEntry> >,
// This contains the results of inference. It begins as an empty
// option and only acquires a value after inference is complete.
values: RefCell<Option<Vec<VarValue> >>,
}
pub fn RegionVarBindings<'a>(tcx: &'a ty::ctxt) -> RegionVarBindings<'a> {
RegionVarBindings {
tcx: tcx,
var_origins: RefCell::new(Vec::new()),
values: RefCell::new(None),
constraints: RefCell::new(HashMap::new()),
lubs: RefCell::new(HashMap::new()),
glbs: RefCell::new(HashMap::new()),
skolemization_count: Cell::new(0),
bound_count: Cell::new(0),
undo_log: RefCell::new(Vec::new())
}
}
impl<'a> RegionVarBindings<'a> {
pub fn in_snapshot(&self) -> bool {
self.undo_log.borrow().len() > 0
}
pub fn start_snapshot(&self) -> uint {
debug!("RegionVarBindings: start_snapshot()");
if self.in_snapshot() {
self.undo_log.borrow().len()
} else {
self.undo_log.borrow_mut().push(Snapshot);
0
}
}
pub fn commit(&self) {
debug!("RegionVarBindings: commit()");
let mut undo_log = self.undo_log.borrow_mut();
while undo_log.len() > 0 {
undo_log.pop().unwrap();
}
}
pub fn rollback_to(&self, snapshot: uint) {
debug!("RegionVarBindings: rollback_to({})", snapshot);
let mut undo_log = self.undo_log.borrow_mut();
while undo_log.len() > snapshot {
let undo_item = undo_log.pop().unwrap();
debug!("undo_item={:?}", undo_item);
match undo_item {
Snapshot => {}
AddVar(vid) => {
let mut var_origins = self.var_origins.borrow_mut();
assert_eq!(var_origins.len(), vid.to_uint() + 1);
var_origins.pop().unwrap();
}
AddConstraint(ref constraint) => {
self.constraints.borrow_mut().remove(constraint);
}
AddCombination(Glb, ref regions) => {
self.glbs.borrow_mut().remove(regions);
}
AddCombination(Lub, ref regions) => {
self.lubs.borrow_mut().remove(regions);
}
}
}
}
pub fn num_vars(&self) -> uint {
self.var_origins.borrow().len()
}
pub fn new_region_var(&self, origin: RegionVariableOrigin) -> RegionVid {
let id = self.num_vars();
self.var_origins.borrow_mut().push(origin.clone());
let vid = RegionVid { id: id };
if self.in_snapshot() {
self.undo_log.borrow_mut().push(AddVar(vid));
}
debug!("created new region variable {:?} with origin {:?}",
vid, origin.repr(self.tcx));
return vid;
}
pub fn new_skolemized(&self, br: ty::BoundRegion) -> Region {
let sc = self.skolemization_count.get();
self.skolemization_count.set(sc + 1);
ReInfer(ReSkolemized(sc, br))
}
pub fn new_bound(&self, binder_id: ast::NodeId) -> Region {
// Creates a fresh bound variable for use in GLB computations.
// See discussion of GLB computation in the large comment at
// the top of this file for more details.
//
// This computation is potentially wrong in the face of
// rollover. It's conceivable, if unlikely, that one might
// wind up with accidental capture for nested functions in
// that case, if the outer function had bound regions created
// a very long time before and the inner function somehow
// wound up rolling over such that supposedly fresh
// identifiers were in fact shadowed. For now, we just assert
// that there is no rollover -- eventually we should try to be
// robust against this possibility, either by checking the set
// of bound identifiers that appear in a given expression and
// ensure that we generate one that is distinct, or by
// changing the representation of bound regions in a fn
// declaration
let sc = self.bound_count.get();
self.bound_count.set(sc + 1);
if sc >= self.bound_count.get() {
self.tcx.sess.bug("rollover in RegionInference new_bound()");
}
ReLateBound(binder_id, BrFresh(sc))
}
fn values_are_none(&self) -> bool {
self.values.borrow().is_none()
}
pub fn add_constraint(&self,
constraint: Constraint,
origin: SubregionOrigin) {
// cannot add constraints once regions are resolved
assert!(self.values_are_none());
debug!("RegionVarBindings: add_constraint({:?})", constraint);
if self.constraints.borrow_mut().insert(constraint, origin) {
if self.in_snapshot() {
self.undo_log.borrow_mut().push(AddConstraint(constraint));
}
}
}
pub fn make_subregion(&self,
origin: SubregionOrigin,
sub: Region,
sup: Region) {
// cannot add constraints once regions are resolved
assert!(self.values_are_none());
debug!("RegionVarBindings: make_subregion({}, {}) due to {}",
sub.repr(self.tcx),
sup.repr(self.tcx),
origin.repr(self.tcx));
match (sub, sup) {
(ReEarlyBound(..), _) |
(ReLateBound(..), _) |
(_, ReEarlyBound(..)) |
(_, ReLateBound(..)) => {
self.tcx.sess.span_bug(
origin.span(),
format!("cannot relate bound region: {} <= {}",
sub.repr(self.tcx),
sup.repr(self.tcx)));
}
(_, ReStatic) => {
// all regions are subregions of static, so we can ignore this
}
(ReInfer(ReVar(sub_id)), ReInfer(ReVar(sup_id))) => {
self.add_constraint(ConstrainVarSubVar(sub_id, sup_id), origin);
}
(r, ReInfer(ReVar(sup_id))) => {
self.add_constraint(ConstrainRegSubVar(r, sup_id), origin);
}
(ReInfer(ReVar(sub_id)), r) => {
self.add_constraint(ConstrainVarSubReg(sub_id, r), origin);
}
_ => {
self.add_constraint(ConstrainRegSubReg(sub, sup), origin);
}
}
}
pub fn lub_regions(&self,
origin: SubregionOrigin,
a: Region,
b: Region)
-> Region {
// cannot add constraints once regions are resolved
assert!(self.values_are_none());
debug!("RegionVarBindings: lub_regions({:?}, {:?})", a, b);
match (a, b) {
(ReStatic, _) | (_, ReStatic) => {
ReStatic // nothing lives longer than static
}
_ => {
self.combine_vars(
Lub, a, b, origin.clone(),
|this, old_r, new_r|
this.make_subregion(origin.clone(), old_r, new_r))
}
}
}
pub fn glb_regions(&self,
origin: SubregionOrigin,
a: Region,
b: Region)
-> Region {
// cannot add constraints once regions are resolved
assert!(self.values_are_none());
debug!("RegionVarBindings: glb_regions({:?}, {:?})", a, b);
match (a, b) {
(ReStatic, r) | (r, ReStatic) => {
// static lives longer than everything else
r
}
_ => {
self.combine_vars(
Glb, a, b, origin.clone(),
|this, old_r, new_r|
this.make_subregion(origin.clone(), new_r, old_r))
}
}
}
pub fn resolve_var(&self, rid: RegionVid) -> ty::Region {
let v = match *self.values.borrow() {
None => {
self.tcx.sess.span_bug(
self.var_origins.borrow().get(rid.to_uint()).span(),
format!("attempt to resolve region variable before \
values have been computed!"))
}
Some(ref values) => *values.get(rid.to_uint())
};
debug!("RegionVarBindings: resolve_var({:?}={})={:?}",
rid, rid.to_uint(), v);
match v {
Value(r) => r,
NoValue => {
// No constraints, return ty::ReEmpty
ReEmpty
}
ErrorValue => {
// An error that has previously been reported.
ReStatic
}
}
}
fn combine_map<'a>(&'a self, t: CombineMapType)
-> &'a RefCell<CombineMap> {
match t {
Glb => &self.glbs,
Lub => &self.lubs,
}
}
pub fn combine_vars(&self,
t: CombineMapType,
a: Region,
b: Region,
origin: SubregionOrigin,
relate: |this: &RegionVarBindings,
old_r: Region,
new_r: Region|)
-> Region {
let vars = TwoRegions { a: a, b: b };
match self.combine_map(t).borrow().find(&vars) {
Some(&c) => {
return ReInfer(ReVar(c));
}
None => {}
}
let c = self.new_region_var(infer::MiscVariable(origin.span()));
self.combine_map(t).borrow_mut().insert(vars, c);
if self.in_snapshot() {
self.undo_log.borrow_mut().push(AddCombination(t, vars));
}
relate(self, a, ReInfer(ReVar(c)));
relate(self, b, ReInfer(ReVar(c)));
debug!("combine_vars() c={:?}", c);
ReInfer(ReVar(c))
}
pub fn vars_created_since_snapshot(&self, snapshot: uint)
-> Vec<RegionVid> {
self.undo_log.borrow().slice_from(snapshot).iter()
.filter_map(|&elt| match elt {
AddVar(vid) => Some(vid),
_ => None
})
.collect()
}
pub fn tainted(&self, snapshot: uint, r0: Region) -> Vec<Region> {
/*!
* Computes all regions that have been related to `r0` in any
* way since the snapshot `snapshot` was taken---`r0` itself
* will be the first entry. This is used when checking whether
* skolemized regions are being improperly related to other
* regions.
*/
debug!("tainted(snapshot={}, r0={:?})", snapshot, r0);
let _indenter = indenter();
let undo_len = self.undo_log.borrow().len();
// `result_set` acts as a worklist: we explore all outgoing
// edges and add any new regions we find to result_set. This
// is not a terribly efficient implementation.
let mut result_set = vec!(r0);
let mut result_index = 0;
while result_index < result_set.len() {
// nb: can't use uint::range() here because result_set grows
let r = *result_set.get(result_index);
debug!("result_index={}, r={:?}", result_index, r);
let mut undo_index = snapshot;
while undo_index < undo_len {
// nb: can't use uint::range() here as we move result_set
let regs = match self.undo_log.borrow().get(undo_index) {
&AddConstraint(ConstrainVarSubVar(ref a, ref b)) => {
Some((ReInfer(ReVar(*a)),
ReInfer(ReVar(*b))))
}
&AddConstraint(ConstrainRegSubVar(ref a, ref b)) => {
Some((*a, ReInfer(ReVar(*b))))
}
&AddConstraint(ConstrainVarSubReg(ref a, ref b)) => {
Some((ReInfer(ReVar(*a)), *b))
}
&AddConstraint(ConstrainRegSubReg(a, b)) => {
Some((a, b))
}
_ => {
None
}
};
match regs {
None => {}
Some((r1, r2)) => {
result_set =
consider_adding_edge(result_set, r, r1, r2);
result_set =
consider_adding_edge(result_set, r, r2, r1);
}
}
undo_index += 1;
}
result_index += 1;
}
return result_set;
fn consider_adding_edge(result_set: Vec<Region> ,
r: Region,
r1: Region,
r2: Region) -> Vec<Region> {
let mut result_set = result_set;
if r == r1 { // Clearly, this is potentially inefficient.
if !result_set.iter().any(|x| *x == r2) {
result_set.push(r2);
}
}
return result_set;
}
}
/**
This function performs the actual region resolution. It must be
called after all constraints have been added. It performs a
fixed-point iteration to find region values which satisfy all
constraints, assuming such values can be found; if they cannot,
errors are reported.
*/
pub fn resolve_regions(&self) -> Vec<RegionResolutionError> {
debug!("RegionVarBindings: resolve_regions()");
let mut errors = vec!();
let v = self.infer_variable_values(&mut errors);
*self.values.borrow_mut() = Some(v);
errors
}
}
impl<'a> RegionVarBindings<'a> {
fn is_subregion_of(&self, sub: Region, sup: Region) -> bool {
self.tcx.region_maps.is_subregion_of(sub, sup)
}
fn lub_concrete_regions(&self, a: Region, b: Region) -> Region {
match (a, b) {
(ReLateBound(..), _) |
(_, ReLateBound(..)) |
(ReEarlyBound(..), _) |
(_, ReEarlyBound(..)) => {
self.tcx.sess.bug(
format!("cannot relate bound region: LUB({}, {})",
a.repr(self.tcx),
b.repr(self.tcx)));
}
(ReStatic, _) | (_, ReStatic) => {
ReStatic // nothing lives longer than static
}
(ReEmpty, r) | (r, ReEmpty) => {
r // everything lives longer than empty
}
(ReInfer(ReVar(v_id)), _) | (_, ReInfer(ReVar(v_id))) => {
self.tcx.sess.span_bug(
self.var_origins.borrow().get(v_id.to_uint()).span(),
format!("lub_concrete_regions invoked with \
non-concrete regions: {:?}, {:?}", a, b));
}
(f @ ReFree(ref fr), ReScope(s_id)) |
(ReScope(s_id), f @ ReFree(ref fr)) => {
// A "free" region can be interpreted as "some region
// at least as big as the block fr.scope_id". So, we can
// reasonably compare free regions and scopes:
match self.tcx.region_maps.nearest_common_ancestor(fr.scope_id, s_id) {
// if the free region's scope `fr.scope_id` is bigger than
// the scope region `s_id`, then the LUB is the free
// region itself:
Some(r_id) if r_id == fr.scope_id => f,
// otherwise, we don't know what the free region is,
// so we must conservatively say the LUB is static:
_ => ReStatic
}
}
(ReScope(a_id), ReScope(b_id)) => {
// The region corresponding to an outer block is a
// subtype of the region corresponding to an inner
// block.
match self.tcx.region_maps.nearest_common_ancestor(a_id, b_id) {
Some(r_id) => ReScope(r_id),
_ => ReStatic
}
}
(ReFree(ref a_fr), ReFree(ref b_fr)) => {
self.lub_free_regions(a_fr, b_fr)
}
// For these types, we cannot define any additional
// relationship:
(ReInfer(ReSkolemized(..)), _) |
(_, ReInfer(ReSkolemized(..))) => {
if a == b {a} else {ReStatic}
}
}
}
fn lub_free_regions(&self,
a: &FreeRegion,
b: &FreeRegion) -> ty::Region
{
/*!
* Computes a region that encloses both free region arguments.
* Guarantee that if the same two regions are given as argument,
* in any order, a consistent result is returned.
*/
return match a.cmp(b) {
Less => helper(self, a, b),
Greater => helper(self, b, a),
Equal => ty::ReFree(*a)
};
fn helper(this: &RegionVarBindings,
a: &FreeRegion,
b: &FreeRegion) -> ty::Region
{
if this.tcx.region_maps.sub_free_region(*a, *b) {
ty::ReFree(*b)
} else if this.tcx.region_maps.sub_free_region(*b, *a) {
ty::ReFree(*a)
} else {
ty::ReStatic
}
}
}
fn glb_concrete_regions(&self,
a: Region,
b: Region)
-> cres<Region> {
debug!("glb_concrete_regions({:?}, {:?})", a, b);
match (a, b) {
(ReLateBound(..), _) |
(_, ReLateBound(..)) |
(ReEarlyBound(..), _) |
(_, ReEarlyBound(..)) => {
self.tcx.sess.bug(
format!("cannot relate bound region: GLB({}, {})",
a.repr(self.tcx),
b.repr(self.tcx)));
}
(ReStatic, r) | (r, ReStatic) => {
// static lives longer than everything else
Ok(r)
}
(ReEmpty, _) | (_, ReEmpty) => {
// nothing lives shorter than everything else
Ok(ReEmpty)
}
(ReInfer(ReVar(v_id)), _) |
(_, ReInfer(ReVar(v_id))) => {
self.tcx.sess.span_bug(
self.var_origins.borrow().get(v_id.to_uint()).span(),
format!("glb_concrete_regions invoked with \
non-concrete regions: {:?}, {:?}", a, b));
}
(ReFree(ref fr), s @ ReScope(s_id)) |
(s @ ReScope(s_id), ReFree(ref fr)) => {
// Free region is something "at least as big as
// `fr.scope_id`." If we find that the scope `fr.scope_id` is bigger
// than the scope `s_id`, then we can say that the GLB
// is the scope `s_id`. Otherwise, as we do not know
// big the free region is precisely, the GLB is undefined.
match self.tcx.region_maps.nearest_common_ancestor(fr.scope_id, s_id) {
Some(r_id) if r_id == fr.scope_id => Ok(s),
_ => Err(ty::terr_regions_no_overlap(b, a))
}
}
(ReScope(a_id), ReScope(b_id)) => {
self.intersect_scopes(a, b, a_id, b_id)
}
(ReFree(ref a_fr), ReFree(ref b_fr)) => {
self.glb_free_regions(a_fr, b_fr)
}
// For these types, we cannot define any additional
// relationship:
(ReInfer(ReSkolemized(..)), _) |
(_, ReInfer(ReSkolemized(..))) => {
if a == b {
Ok(a)
} else {
Err(ty::terr_regions_no_overlap(b, a))
}
}
}
}
fn glb_free_regions(&self,
a: &FreeRegion,
b: &FreeRegion) -> cres<ty::Region>
{
/*!
* Computes a region that is enclosed by both free region arguments,
* if any. Guarantees that if the same two regions are given as argument,
* in any order, a consistent result is returned.
*/
return match a.cmp(b) {
Less => helper(self, a, b),
Greater => helper(self, b, a),
Equal => Ok(ty::ReFree(*a))
};
fn helper(this: &RegionVarBindings,
a: &FreeRegion,
b: &FreeRegion) -> cres<ty::Region>
{
if this.tcx.region_maps.sub_free_region(*a, *b) {
Ok(ty::ReFree(*a))
} else if this.tcx.region_maps.sub_free_region(*b, *a) {
Ok(ty::ReFree(*b))
} else {
this.intersect_scopes(ty::ReFree(*a), ty::ReFree(*b),
a.scope_id, b.scope_id)
}
}
}
fn intersect_scopes(&self,
region_a: ty::Region,
region_b: ty::Region,
scope_a: ast::NodeId,
scope_b: ast::NodeId) -> cres<Region>
{
// We want to generate the intersection of two
// scopes or two free regions. So, if one of
// these scopes is a subscope of the other, return
// it. Otherwise fail.
debug!("intersect_scopes(scope_a={:?}, scope_b={:?}, region_a={:?}, region_b={:?})",
scope_a, scope_b, region_a, region_b);
match self.tcx.region_maps.nearest_common_ancestor(scope_a, scope_b) {
Some(r_id) if scope_a == r_id => Ok(ReScope(scope_b)),
Some(r_id) if scope_b == r_id => Ok(ReScope(scope_a)),
_ => Err(ty::terr_regions_no_overlap(region_a, region_b))
}
}
}
// ______________________________________________________________________
#[deriving(Eq, Show)]
enum Classification { Expanding, Contracting }
pub enum VarValue { NoValue, Value(Region), ErrorValue }
struct VarData {
classification: Classification,
value: VarValue,
}
struct RegionAndOrigin {
region: Region,
origin: SubregionOrigin,
}
type RegionGraph = graph::Graph<(), Constraint>;
impl<'a> RegionVarBindings<'a> {
fn infer_variable_values(&self,
errors: &mut Vec<RegionResolutionError>)
-> Vec<VarValue> {
let mut var_data = self.construct_var_data();
self.expansion(var_data.as_mut_slice());
self.contraction(var_data.as_mut_slice());
self.collect_concrete_region_errors(&mut *errors);
self.extract_values_and_collect_conflicts(var_data.as_slice(), errors)
}
fn construct_var_data(&self) -> Vec<VarData> {
Vec::from_fn(self.num_vars(), |_| {
VarData {
// All nodes are initially classified as contracting; during
// the expansion phase, we will shift the classification for
// those nodes that have a concrete region predecessor to
// Expanding.
classification: Contracting,
value: NoValue,
}
})
}
fn expansion(&self, var_data: &mut [VarData]) {
self.iterate_until_fixed_point("Expansion", |constraint| {
match *constraint {
ConstrainRegSubVar(a_region, b_vid) => {
let b_data = &mut var_data[b_vid.to_uint()];
self.expand_node(a_region, b_vid, b_data)
}
ConstrainVarSubVar(a_vid, b_vid) => {
match var_data[a_vid.to_uint()].value {
NoValue | ErrorValue => false,
Value(a_region) => {
let b_node = &mut var_data[b_vid.to_uint()];
self.expand_node(a_region, b_vid, b_node)
}
}
}
ConstrainVarSubReg(..) => {
// This is a contraction constraint. Ignore it.
false
}
ConstrainRegSubReg(..) => {
// No region variables involved. Ignore.
false
}
}
})
}
fn expand_node(&self,
a_region: Region,
b_vid: RegionVid,
b_data: &mut VarData)
-> bool {
debug!("expand_node({:?}, {:?} == {:?})",
a_region, b_vid, b_data.value);
b_data.classification = Expanding;
match b_data.value {
NoValue => {
debug!("Setting initial value of {:?} to {:?}", b_vid, a_region);
b_data.value = Value(a_region);
return true;
}
Value(cur_region) => {
let lub = self.lub_concrete_regions(a_region, cur_region);
if lub == cur_region {
return false;
}
debug!("Expanding value of {:?} from {:?} to {:?}",
b_vid, cur_region, lub);
b_data.value = Value(lub);
return true;
}
ErrorValue => {
return false;
}
}
}
fn contraction(&self,
var_data: &mut [VarData]) {
self.iterate_until_fixed_point("Contraction", |constraint| {
match *constraint {
ConstrainRegSubVar(..) => {
// This is an expansion constraint. Ignore.
false
}
ConstrainVarSubVar(a_vid, b_vid) => {
match var_data[b_vid.to_uint()].value {
NoValue | ErrorValue => false,
Value(b_region) => {
let a_data = &mut var_data[a_vid.to_uint()];
self.contract_node(a_vid, a_data, b_region)
}
}
}
ConstrainVarSubReg(a_vid, b_region) => {
let a_data = &mut var_data[a_vid.to_uint()];
self.contract_node(a_vid, a_data, b_region)
}
ConstrainRegSubReg(..) => {
// No region variables involved. Ignore.
false
}
}
})
}
fn contract_node(&self,
a_vid: RegionVid,
a_data: &mut VarData,
b_region: Region)
-> bool {
debug!("contract_node({:?} == {:?}/{:?}, {:?})",
a_vid, a_data.value, a_data.classification, b_region);
return match a_data.value {
NoValue => {
assert_eq!(a_data.classification, Contracting);
a_data.value = Value(b_region);
true // changed
}
ErrorValue => {
false // no change
}
Value(a_region) => {
match a_data.classification {
Expanding => {
check_node(self, a_vid, a_data, a_region, b_region)
}
Contracting => {
adjust_node(self, a_vid, a_data, a_region, b_region)
}
}
}
};
fn check_node(this: &RegionVarBindings,
a_vid: RegionVid,
a_data: &mut VarData,
a_region: Region,
b_region: Region)
-> bool {
if !this.is_subregion_of(a_region, b_region) {
debug!("Setting {:?} to ErrorValue: {:?} not subregion of {:?}",
a_vid, a_region, b_region);
a_data.value = ErrorValue;
}
false
}
fn adjust_node(this: &RegionVarBindings,
a_vid: RegionVid,
a_data: &mut VarData,
a_region: Region,
b_region: Region)
-> bool {
match this.glb_concrete_regions(a_region, b_region) {
Ok(glb) => {
if glb == a_region {
false
} else {
debug!("Contracting value of {:?} from {:?} to {:?}",
a_vid, a_region, glb);
a_data.value = Value(glb);
true
}
}
Err(_) => {
debug!("Setting {:?} to ErrorValue: no glb of {:?}, {:?}",
a_vid, a_region, b_region);
a_data.value = ErrorValue;
false
}
}
}
}
fn collect_concrete_region_errors(
&self,
errors: &mut Vec<RegionResolutionError>)
{
for (constraint, _) in self.constraints.borrow().iter() {
let (sub, sup) = match *constraint {
ConstrainVarSubVar(..) |
ConstrainRegSubVar(..) |
ConstrainVarSubReg(..) => {
continue;
}
ConstrainRegSubReg(sub, sup) => {
(sub, sup)
}
};
if self.is_subregion_of(sub, sup) {
continue;
}
debug!("ConcreteFailure: !(sub <= sup): sub={:?}, sup={:?}",
sub, sup);
let origin = self.constraints.borrow().get_copy(constraint);
errors.push(ConcreteFailure(origin, sub, sup));
}
}
fn extract_values_and_collect_conflicts(
&self,
var_data: &[VarData],
errors: &mut Vec<RegionResolutionError>)
-> Vec<VarValue> {
debug!("extract_values_and_collect_conflicts()");
// This is the best way that I have found to suppress
// duplicate and related errors. Basically we keep a set of
// flags for every node. Whenever an error occurs, we will