Repository navigation
Expand file tree
/
Copy pathscope_.d
More file actions
3717 lines (3652 loc) · 146 KB
/
Copy pathscope_.d
File metadata and controls
3717 lines (3652 loc) · 146 KB
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
// Written in the D programming language
// License: http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0
module ast.scope_;
import astopt;
import std.format, std.conv, std.range, std.algorithm;
import util.tuple:Q=Tuple,q=tuple;
import ast.lexer, ast.expression, ast.declaration, ast.type, ast.error;
import util, util.hashtable: HashMap;
struct Dependency{
bool isTop;
SetX!Declaration dependencies;
Declaration lostVar; // (if `isTop`: a consumed value it depended on, if known)
Identifier lostAt; // (where `lostVar` was consumed)
void joinWith(Dependency rhs){
if(isTop) return;
if(rhs.isTop){
this=rhs;
return;
}
foreach(x;rhs.dependencies)
dependencies.insert(x);
}
void remove(Declaration decl){
dependencies.remove(decl);
}
void replace(Declaration decl, Dependency rhs, Identifier consumedAt=null){
if(decl !in dependencies) return;
dependencies.remove(decl);
if(rhs.isTop&&!rhs.lostVar&&consumedAt){
rhs.lostVar=decl;
rhs.lostAt=consumedAt;
}
joinWith(rhs);
}
void replace(Declaration decl,Declaration ndecl){
if(decl in dependencies){
dependencies.remove(decl);
dependencies.insert(ndecl);
}
}
Dependency dup(){
return Dependency(isTop, dependencies.dup, lostVar, lostAt);
}
private Q!(bool,SetX!Id) getIds(){
SetX!Id result;
foreach(decl;dependencies){
auto id=decl.getId;
if(id==Id()) continue;
assert(id !in result);
result.insert(id);
}
return q(isTop,result);
}
bool matches(Dependency rhs){ // TODO: make faster?
auto ids=getIds,rids=rhs.getIds;
return ids==rids;
}
}
struct Dependencies{
HashMap!(Declaration,Dependency,(a,b)=>a is b,(a)=>a.toHash()) dependencies;
void joinWith(Dependencies rhs){
foreach(k,ref v;dependencies){
if(k in rhs.dependencies){
v.joinWith(rhs.dependencies[k]);
if(k in v.dependencies)
v=Dependency(true); // TODO: get rid of this
}
}
}
void pushUp(Declaration removed, bool keep, Identifier consumedAt=null)in{
assert(removed in dependencies,text(removed," ",removed.loc," ",dependencies));
}do{
Dependency x=dependencies[removed];
if(!keep) dependencies.remove(removed);
foreach(k,ref v;dependencies){
v.replace(removed, x, consumedAt);
if(k in v.dependencies)
v=Dependency(true); // TODO: get rid of this
}
}
void replace(Declaration decl,Declaration ndecl)in{
assert(decl in dependencies,text(decl.loc," ",dependencies));
assert(ndecl !in dependencies,text(ndecl.loc," ",dependencies));
}do{
foreach(k,ref v;dependencies) v.replace(decl,ndecl);
dependencies[ndecl]=dependencies[decl];
dependencies.remove(decl);
}
void merge(Declaration decl,Declaration ndecl)in{ // (`ndecl` is another version of the variable of `decl`)
assert(decl in dependencies&&ndecl in dependencies);
}do{
auto dep=dependencies[decl];
dependencies.remove(decl);
foreach(k,ref v;dependencies) v.replace(decl,ndecl);
dependencies[ndecl].joinWith(dep);
foreach(k,ref v;dependencies)
if(k in v.dependencies)
v=Dependency(true); // TODO: get rid of this
}
void substitute(Declaration decl,Dependency dep){ // substitute `decl` by `dep` inside all tracked sets (`decl` itself has no entry)
foreach(k,ref v;dependencies){
v.replace(decl,dep);
if(k in v.dependencies)
v=Dependency(true); // TODO: get rid of this
}
}
Dependencies dup(){
typeof(Dependencies.dependencies) result;
foreach(k,ref v;dependencies)
result[k]=v.dup;
return Dependencies(result);
}
bool canForget(Declaration decl)in{
assert(decl in dependencies||decl.isSemError(),text(decl," ",dependencies));
}do{
if(decl !in dependencies) return true;
return !dependencies[decl].isTop;
}
void clear(){
dependencies.clear();
}
private HashMap!(Id,typeof(Dependency.getIds()),(a,b)=>a is b,(a)=>a.toHash) getIds(){
typeof(return) result;
foreach(decl,ref dependency;dependencies){
auto id=decl.getId;
if(id==Id()) continue;
assert(id !in result,text(decl," ",dependencies," ",result));
result[id]=dependency.getIds();
}
return result;
}
bool matches(Dependencies rhs){ // TODO: make faster?
auto ids=getIds,rids=rhs.getIds;
return ids==rids;
}
}
struct DummyWitnessContext{
MapX!(Declaration,Declaration) dummies; // candidate -> dummy placeholder
MapX!(Declaration,Declaration) results; // candidates witnessed so far
MapSX!(Declaration,Dependency) consumedDeps; // dependency each decl had when it was consumed while this context was active
SetX!Id[] nestedLoopCarried; // the loop-carried candidates of each nested quantum loop analyzed while this context was active
Dependency[] reconstructed; // dependencies of quantum guards whose inputs change while borrowed, and of variables that recomputed temporaries depend on (see `noteImplicitDupCancelled`)
size_t order; // (of the implicit duplications and the recomputed temporaries below)
MapX!(Identifier,size_t) dupOrder; // implicit duplications
Q!(size_t,SetX!Id)[] recomputed; // variables that temporaries forgotten by recomputation depend on
}
import ast.lastuse;
enum Lookup{
consuming,
constant,
probing,
probingWithCapture,
}
abstract class Scope{
final TopScope getTopScope(){
for(Scope sc=this;sc;){
if(auto ts=cast(TopScope)sc) return ts;
auto nsc=cast(NestedScope)sc;
if(!nsc) return null;
sc=nsc.parent;
}
return null;
}
abstract @property ErrorHandler handler();
import ast.looplowering:LoopContinuation;
LoopContinuation loopContinuation; // loop lowering: code after a loop that the lowering may absorb
int droppedCodeAnalysis; // loop lowering: the code after a loop that the lowering drops is being analyzed, without lowering its loops (see `unreachableSemantic`)
bool allowsLinear(){
return true;
}
Scope parentScope(){
return null;
}
@property bool inferenceMode(){
return false;
}
final bool canInsert(Id id){
auto decl=symtabLookup(id,false,null);
return !decl||cast(DeadDecl)decl;
}
static if(language==silq) final bool checkCaptureRedefinition(Declaration decl){
auto fd=getFunction();
if(!fd||!decl.name||!fd.fscope_||cast(Parameter)decl) return true;
if(Id.s!"silq-loop" in fd.attributes||Id.s!"silq-join" in fd.attributes) return true;
bool inBody(Identifier id){
return fd.body_&&fd.body_.blscope_&&id.scope_&&id.scope_.isNestedIn(fd.body_.blscope_);
}
foreach(capture,allIds;fd.captures){
if(!capture.name||capture.name.id!=decl.name.id) continue;
auto ids=allIds.filter!inBody.array;
if(!ids.length) continue;
if(fd.isConsumedCapture(capture)) continue;
import ast.semantic_:typeForDecl;
auto type=typeForDecl(capture);
if(type&&type.isClassical()&&ids.any!(id=>!id.constLookup)&&!capture.isConst()){ // (a `const` variable is not consumed by a capture)
fd.consumingCaptures.insert(decl.name.id);
fd.captureReanalysis=true;
for(auto efd=fd.scope_.getFunction();efd&&capture.scope_&&!capture.scope_.isNestedIn(efd.fscope_);efd=efd.scope_.getFunction()){
efd.consumingCaptures.insert(decl.name.id);
efd.captureReanalysis=true;
}
return true;
}
if(!decl.isSemError()){
error(format("redefinition of captured variable \"%s\"",decl.name),decl.name.loc);
note("captured here",ids[0].loc);
decl.setSemError();
}
return false;
}
return true;
}
final bool tryPrepareRedefine(Declaration newDecl,Declaration oldDecl){
static if(language==silq) if(blockedRedefinitionError(newDecl,oldDecl)) return false;
if(oldDecl.scope_&&lastUses.canRedefine(oldDecl)){
static if(language==silq) if(consumesOutsideType(oldDecl,letTypeBoundary())){ // (the previous version is forgotten)
if(!oldDecl.isSemError()&&!newDecl.isSemError()) error(format("cannot consume `%s` in a type",oldDecl.name),newDecl.name.loc);
newDecl.setSemError();
return false;
}
lastUses.forget(oldDecl,true);
return true;
}
if(!oldDecl.isSemError()&&!newDecl.isSemError()) redefinitionError(newDecl, oldDecl);
newDecl.setSemError();
return false;
}
final void redefinitionError(Declaration decl, Declaration prev) in{
assert(decl&&prev);
assert(!cast(DeadDecl)decl&&!cast(DeadDecl)prev);
}do{
error(format("redefinition of \"%s\"",decl.name), decl.name.loc);
note("previous definition was here",prev.name.loc);
decl.setSemError();
}
bool insert(Declaration decl,bool force=false)in{assert(!decl.scope_);}do{
if(auto d=symtabLookup(decl.name,false,null)){
static if(language==silq) if(isConstLocal(d)&&!d.isSemError()){
if(!decl.isSemError()){
error(format("redefinition of `const` variable \"%s\"",decl.name),decl.name.loc);
note("previous definition was here",d.name.loc);
}
decl.setSemError();
return false;
}
if(!tryPrepareRedefine(decl,d))
return false;
//assert(!symtabLookup(decl.name,false,null));
}else static if(language==silq){
for(Scope sc=this;sc;sc=cast(FunctionScope)sc?null:sc.parentScope()){
auto d=sc.peekSymtab(decl.name.id,false);
if(!d) continue;
if(auto dd=cast(DeadDecl)d)
if(dd.reportRedefinition(decl,this))
return false;
break;
}
if(!checkCaptureRedefinition(decl)) return false;
}
rename(decl);
symtabInsert(decl);
decl.scope_=this;
return true;
}
void symtabInsert(Declaration decl)in{
assert(!toRemove.canFind(decl));
assert(!!decl);
assert(decl.getId !in rnsymtab||cast(DeadDecl)rnsymtab[decl.getId]);
}do{
if(decl.name.id !in symtab||cast(DeadDecl)symtab[decl.name.id])
symtab[decl.name.id]=decl;
rnsymtab[decl.getId]=decl;
}
void symtabRemove(Declaration decl)in{
assert(!!decl);
assert(rnsymtab.get(decl.getId,null) is decl);
}do{
if(symtab.get(decl.name.id,null) is decl)
symtab.remove(decl.name.id);
rnsymtab.remove(decl.getId);
}
static struct DeclProp{
Identifier[] constBlock;
static struct ComponentReplacement{
IndexExp write; // null for temporary conversion
Id name;
IndexExp read;
IndexExp constRead;
IndexExp convertedWrite;
IndexExp location(){ return write?write:convertedWrite; }
bool blocksAggregate(){ return !write&&convertedWrite; }
}
ComponentReplacement[] componentReplacements;
void nameIndex(IndexExp index,Id name){
auto r=ComponentReplacement(index,name,IndexExp.init);
if(index.isSemError()) swap(r.write,r.read);
componentReplacements~=r;
}
/+private+/ Identifier[] accesses;
/+private+/ Declaration[] capturers;
static DeclProp default_(){
return DeclProp.init;
}
DeclProp dup(){
return DeclProp(constBlock,componentReplacements.dup,accesses.dup,capturers.dup);
}
DeclProp move(){
auto r=DeclProp(constBlock,componentReplacements,accesses,capturers);
this=typeof(this).init;
return r;
}
DeclProp inherit(){ return default_(); }
enum inheritIsDefault=true; // set to false if inherit becomes nontrivial
DeclProp merged()in{
//assert(!constBlock);
assert(!componentReplacements.length);
}do{
constBlock=[]; // TODO: ok?
return this;
}
void merge(DeclProp nested)in{
//assert(!nested.constBlock);
assert(!nested.componentReplacements.length);
}do{
accesses~=nested.accesses;
capturers~=nested.capturers;
}
void replaceDecl(Declaration splitFrom,Declaration splitInto){
foreach(id;accesses){ // TODO: avoid considering the same access multiple times in different scopes
// foreach(id,decl;declProps.accesses.map!(x=>x)) hangs the compiler
//imported!"util.io".writeln("ADJUSTING: ",id.loc," ",id.meaning is splitFrom," ",id.meaning is splitInto);
id.meaning=splitInto;
//if(id.scope_) id.scope_.lastUses.replaceDecl(splitFrom,splitInto);
}
foreach(capturer;capturers){
void doIt(T)(T capturer){
if(splitFrom !in capturer.captures) return;
capturer.captures[splitInto]=capturer.captures[splitFrom];
capturer.captures.remove(splitFrom);
foreach(ref oldDecl;capturer.capturedDecls){
if(oldDecl is splitFrom){
oldDecl=splitInto;
break;
}
}
foreach(id;capturer.captures[splitInto])
id.meaning=splitInto;
}
if(auto fd=cast(FunctionDef)capturer) doIt(fd);
else if(auto dat=cast(DatDecl)capturer) doIt(dat);
else assert(0,text(typeid(capturer)));
}
}
}
static struct DeclProps{
private MapSX!(Declaration,DeclProp) props;
DeclProps dup(){ return DeclProps(props.dup); }
void clear(){ props.clear(); }
DeclProp* tryGet(Declaration decl){ return props.getPtr(decl); }
ref DeclProp set(Declaration decl,DeclProp prop){
return props[decl]=prop;
}
void remove(Declaration decl){
props.remove(decl);
}
void merge(ref DeclProps nested){
foreach(decl,ref prop;nested.props){
if(decl !in props) props[decl]=prop.merged();
else props[decl].merge(prop);
}
}
void replaceDecl(Declaration splitFrom,Declaration splitInto){
if(auto declProp=tryGet(splitFrom)){
declProp.replaceDecl(splitFrom,splitInto);
props[splitInto]=declProp.move();
props.remove(splitFrom);
}
}
void moveComponentReplacements(Declaration prev,Declaration new_){
if(auto prevProp=tryGet(prev)){
if(new_ !in props) set(new_,DeclProp.default_());
auto newProp=tryGet(new_);
assert(newProp&&!newProp.componentReplacements.length);
newProp.componentReplacements=prevProp.componentReplacements;
prevProp.componentReplacements=[];
}
}
}
final DeclProps saveDeclProps(){ return declProps.dup; }
final void resetDeclProps(DeclProps previous){ declProps=previous; }
final void mergeDeclProps(ref DeclProps nested,ComponentConstBlock[] nestedComponentConstBlocks){
foreach(decl,ref prop;nested.props){
if(!prop.constBlock.length) continue;
if(!decl.scope_||!this.isNestedIn(decl.scope_)) continue;
foreach(read;prop.constBlock){
Expression.CopyArgs cargs={preserveSemantic: true};
auto nread=read.copy(cargs);
nread.scope_=this;
blockConst(decl,nread);
recordAccess(nread,decl);
foreach(ccb;nestedComponentConstBlocks)
if(ccb.read is read)
componentConstBlocks~=ComponentConstBlock(decl,ccb.component,nread);
}
prop.constBlock=[];
}
declProps.merge(nested);
}
final int nestedDeclProps(scope int delegate(ref DeclProps) dg){
if(auto r=dg(declProps)) return r;
return outerDeclProps(dg);
}
int outerDeclProps(scope int delegate(ref DeclProps) dg){
return 0;
}
final nestedDeclProp(Declaration decl){
static struct NestedDeclProps{
Scope sc;
Declaration decl;
int opApply(scope int delegate(ref DeclProp) dg){
foreach(ref props;&sc.nestedDeclProps){
if(auto prop=props.tryGet(decl)){
if(auto r=dg(*prop))
return r;
}
}
return 0;
}
}
return NestedDeclProps(this,decl);
}
// DMD/LDC bug: if this function returns ref DeclProp,
// memory corruption occurs
final DeclProp* updateDeclProps(Declaration decl){
if(auto r=declProps.tryGet(decl)) return r;
static if(!DeclProp.inheritIsDefault){
foreach(ref prop;nestedDeclProp(decl)){
return &declProps.set(decl,prop.inherit);
}
}
return &declProps.set(decl,DeclProp.default_());
}
final void recordAccess(Identifier id,Declaration meaning){
if(id.typeofSuppressedCapture) return;
if(!meaning.isToplevelDeclaration()&&!meaning.isAggregateMember()){
lastUses.pin(meaning,false); // previous last use cannot be used to forget anymore
static if(language==silq) pinTypeMentions(meaning); // (as are the variables that its type mentions)
if(!id.constLookup&&!id.implicitDup)
lastUses.consumption(meaning,id,this); // TODO: ok?
updateDeclProps(meaning).accesses~=id;
}
}
static if(language==silq)
final void pinTypeMentions(Declaration meaning){ // (the variables that the type of `meaning` mentions are live where it is used)
import ast.semantic_: typeForDeclNoAnalyze;
if(auto type=typeForDeclNoAnalyze(meaning)) pinMentions(type);
}
static if(language==silq)
final void pinMentions(Expression type){ // (the variables that `type` mentions are live here, also through the values of type variables, e.g., `n` for `x:a` after `a:=𝔹^n`, see `unfoldTypeVariables`)
void pin(Expression t){
foreach(fid;t.freeIdentifiers)
if(fid.meaning&&!fid.meaning.isToplevelDeclaration()&&!fid.meaning.isAggregateMember()) lastUses.pin(getSplit(fid.meaning),false);
}
pin(type);
auto unfolded=unfoldTypeVariables(type);
if(unfolded !is type) pin(unfolded);
}
final void recordCapturer(Declaration capturer,Declaration meaning){
if(!meaning.isToplevelDeclaration){
updateDeclProps(meaning).capturers~=capturer;
}
}
final void recordCapturers(Expression type){ // (the closures in a type whose uses are recorded as accesses: their captures are renamed with the uses, e.g., to later splits)
foreach(se;type.subexpressions){
FunctionDef fd;
if(auto le=cast(LambdaExp)se) fd=le.fd;
else fd=cast(FunctionDef)se;
if(!fd) continue;
foreach(decl;fd.capturedDecls) recordCapturer(fd,decl);
if(fd.body_) recordCapturers(fd.body_);
}
}
private final Identifier isConstHere(Declaration decl){
if(auto r=declProps.tryGet(decl))
if(r.constBlock.length)
return r.constBlock[$-1];
return null;
}
final void registerConstCapture(Declaration decl,Location loc,Expression type){
if(decl.isToplevelDeclaration()||decl.isPinned()) return;
if(!type||type.isClassical()) return; // TODO: why needed?
if(auto prev=isConstHere(decl)) if(prev.meaning is decl&&prev.loc==loc) return;
auto cid=new Identifier(decl.getId);
cid.loc=loc;
cid.scope_=this;
cid.meaning=decl;
cid.type=type;
cid.constLookup=true;
cid.setSemCompleted();
blockConst(decl,cid);
recordAccess(cid,decl); // (renamed with the other accesses, e.g., to a split of `decl`, as for the const blocks of `mergeDeclProps`)
}
final void blockConst(Declaration decl,Identifier constBlock){
if(!decl.isToplevelDeclaration){
if(auto props=updateDeclProps(decl))
props.constBlock~=constBlock;
}
}
static struct ComponentConstBlock{
Declaration decl;
IndexExp component;
Identifier read;
}
private ComponentConstBlock[] componentConstBlocks;
final void recordComponentConstBlock(Declaration decl,Identifier read,IndexExp component)in{
assert(decl&&!decl.isToplevelDeclaration);
assert(!!read);
assert(!!component);
}do{
if(auto props=declProps.tryGet(decl))
if(props.constBlock.length&&props.constBlock[$-1] is read)
componentConstBlocks~=ComponentConstBlock(decl,component,read);
}
int outerComponentConstBlocks(scope int delegate(ComponentConstBlock) dg){
return 0;
}
final int nestedComponentConstBlocks(scope int delegate(ComponentConstBlock) dg){
foreach(ccb;componentConstBlocks)
if(auto r=dg(ccb)) return r;
return outerComponentConstBlocks(dg);
}
final bool isComponentConstBlock(Identifier read){
bool result=false;
nestedComponentConstBlocks((ComponentConstBlock ccb){
if(ccb.read is read) result=true;
return result;
});
return result;
}
final bool hasNonComponentConstBlock(Declaration decl){
for(auto d=decl;d;d=d.splitFrom)
foreach(ref prop;nestedDeclProp(d))
foreach(read;prop.constBlock)
if(!isComponentConstBlock(read)) return true;
return false;
}
final bool componentConstBlocksAllow(Declaration decl,IndexExp write,Location loc){
import ast.semantic_:guaranteedDisjointComponents,InType;
bool any=false,result=true;
for(auto d=decl;d;d=d.splitFrom)
foreach(ref prop;nestedDeclProp(d)){
foreach(read;prop.constBlock){
any=true;
bool component=false;
nestedComponentConstBlocks((ComponentConstBlock ccb){
if(ccb.read !is read) return 0;
component=true;
if(!guaranteedDisjointComponents(ccb.component,write,loc,this,InType.no))
result=false;
return 1;
});
if(!component||!result) return false;
}
}
return any&&result;
}
final bool componentConstBlockRedefined(ConstBlockContext context){
foreach(ccb;componentConstBlocks[context.numComponentConstBlocks..$])
if(peekSymtab(ccb.decl.getId,true) !is ccb.decl)
return true;
return false;
}
final bool componentConstBlockConsumedDuringBorrow(ConstBlockContext context){
foreach(ccb;componentConstBlocks[context.numComponentConstBlocks..$])
if(peekSymtab(ccb.decl.getId,true) !is ccb.decl&&ccb.read.consumedDuringBorrow)
return true;
return false;
}
static struct TrackedTemporary{
Expression expr;
Dependency dep;
Identifier read; // for recordConstBlockedConsumption
TrackedTemporary dup(){
return TrackedTemporary(expr,dep.dup);
}
}
final bool trackTemporary(Expression expr){
//imported!"util.io".writeln("TRACKING: ",expr," ",expr.loc);
import ast.semantic_:getDependency;
auto implicitDup=expr.implicitDup;
expr.implicitDup=false;
auto dep=getDependency(expr,this);
expr.implicitDup=implicitDup;
if(dep.isTop) return false;
trackedTemporaries~=TrackedTemporary(expr,dep);
if(auto id=cast(Identifier)expr){
if(id.implicitDup&&id.meaning) {
recordImplicitDup(id);
}
}
return true;
}
void pinLastUse(Declaration decl){
lastUses.pin(decl,true);
}
private struct TypeConstBlockEntry{
Declaration decl;
}
private TypeConstBlockEntry[] typeConstBlockLog;
private static void releaseTypeConstBlockEntry(TypeConstBlockEntry entry){
auto decl=entry.decl;
assert(decl.typeConstBlockDepth>0);
if(--decl.typeConstBlockDepth==0) decl.typeConstBlocker=null;
}
final void recordTypeConstBlock(Declaration decl)in{
assert(!!decl);
}do{
typeConstBlockLog~=TypeConstBlockEntry(decl);
decl.typeConstBlockDepth++;
}
final size_t saveTypeConstBlocks(){
return typeConstBlockLog.length;
}
final void releaseTypeConstBlocks(size_t save,bool doRelease)in{
assert(save<=typeConstBlockLog.length);
}do{
foreach_reverse(i;save..typeConstBlockLog.length){
auto entry=typeConstBlockLog[i];
if(doRelease) releaseTypeConstBlockEntry(entry);
}
typeConstBlockLog.length=save;
}
final void filterTypeConstBlocks(size_t save,Expression type)in{
assert(save<=typeConstBlockLog.length);
}do{
filterTypeConstBlocks(save,(Declaration decl){
if(!type) return false;
foreach(id;type.freeIdentifiers){
if(id.meaning&&id.meaning.canonicalSource is decl.canonicalSource)
return true;
}
return false;
});
}
final void filterTypeConstBlocks(size_t save,bool delegate(Declaration) keep)in{
assert(save<=typeConstBlockLog.length);
}do{
size_t j=save;
foreach(i;save..typeConstBlockLog.length){
auto entry=typeConstBlockLog[i];
if(keep(entry.decl)) typeConstBlockLog[j++]=entry;
else releaseTypeConstBlockEntry(entry);
}
typeConstBlockLog.length=j;
}
final void recordConstBlockedConsumption(Identifier read,Identifier use)in{
assert(read.meaning&&read is isConst(read.meaning));
assert(read.scope_);
}do{
if(read.meaning.isSemError()) return;
import ast.semantic_:getDependency;
auto dep=getDependency(read,read.scope_); // can already be top, will cause an error later
read.scope_.trackedTemporaries~=TrackedTemporary(use,dep,read);
}
final void recordImplicitDup(Identifier id)in{
assert(!!id);
assert(id.implicitDup);
assert(!id.constLookup);
assert(!!id.meaning);
assert(id.scope_ is this);
}do{
if(!id.meaning.isToplevelDeclaration()&&!id.typeofSuppressedCapture){
if(isConsumable(id)) lastUses.implicitDup(id);
}
}
final bool checkImplicitDupCancel(Identifier id)in{
assert(id&&id.meaning);
}do{
return checkDeclarationCancel(id.meaning,id);
}
final bool checkDeclarationCancel(Declaration decl,Identifier use)in{
assert(!!decl);
}do{
if(use&&use.isSemError()) return false;
bool ok=true;
Identifier[] accesses; // TODO: use ranges?
if(auto declProp=declProps.tryGet(decl)) accesses=declProp.accesses;
if(use&&use.scope_ !is this) // (all accesses here are after `use`, also those of versions split from `decl` in nested scopes)
foreach(d,ref prop;declProps.props) if(d !is decl&&d.isDerivedFrom(decl)) accesses~=prop.accesses;
if(accesses.length){
bool seen=false;
DeadDecl[] failures;
foreach(access;accesses){
if((!use||use.scope_!is this||seen)&&access !is use){
if(ok&&use){
if(auto cd=recordConsumption(decl,use))
failures~=cd;
}
ok=false;
if(use) use.setSemForceError();
decl.setSemForceError();
access.setSemForceError();
import ast.semantic_:undefinedIdentifierError;
undefinedIdentifierError(access,failures,this);
}
if(use&&access is use) seen=true;
}
// TODO: can we have `use.sstate != SemState.error` here?
}
static if(language==silq) if(ok&&use&&use.scope_ is this) ok=checkDeclarationCancelOuter(decl,use);
return ok;
}
static if(language==silq)
private bool checkDeclarationCancelOuter(Declaration decl,Identifier use){ // (accesses after the enclosing branches were analyzed before the cancellation)
bool ok=true;
DeadDecl[] failures;
void reportLater(Identifier access,Scope sc){
if(ok) if(auto cd=recordConsumption(decl,use)) failures~=cd;
ok=false;
use.setSemForceError();
decl.setSemForceError();
access.setSemForceError();
import ast.semantic_:undefinedIdentifierError;
undefinedIdentifierError(access,failures,sc);
}
static Declaration origin(Declaration d){ while(d.splitFrom) d=d.splitFrom; return d; }
void visitActive(Scope sc){ // (accesses in nested scopes after the use that are still being analyzed)
foreach(nsc;sc.activeNestedScopes){
foreach(d,ref nprop;nsc.declProps.props){
if(origin(d) !is origin(decl)) continue;
foreach(access;nprop.accesses) if(!access.isSemError()) reportLater(access,nsc);
}
visitActive(nsc);
}
}
for(auto inner=cast(NestedScope)this;inner;inner=cast(NestedScope)inner.parent){
auto outer=inner.parent;
if(!outer||outer.getFunction() !is getFunction()) break;
if(!outer.activeNestedScopes.canFind(inner)) visitActive(outer);
DeclProp* prop=null;
for(auto d=decl;d&&!prop;d=d.splitFrom) prop=outer.declProps.tryGet(d);
if(!prop) continue;
auto siblings=inner.getSiblingScopes();
bool seen=false;
foreach(access;prop.accesses){
if(access is use){
seen=true;
continue;
}
if(!seen||!access.scope_||access.scope_.isNestedIn(inner)) continue;
if(siblings.any!(sib=>sib !is inner&&access.scope_.isNestedIn(sib))) continue; // (on another path)
reportLater(access,outer);
}
}
return ok;
}
final bool cancelImplicitDup(Identifier id)in{
assert(!!id.implicitDup);
assert(!!id.meaning);
assert(!id.constLookup);
}do{
if(id.typeofSuppressedCapture) return true;
bool ok=true;
if(!checkConsumable(id)){
ok=false;
id.setSemForceError();
id.meaning.setSemForceError();
}
lastUses.cancelImplicitDup(id.meaning); // TOOD: what if this fails?
return ok;
}
final void pushTrackedTemporaryDependencies(Declaration decl){
foreach(ref tt;trackedTemporaries){
if(tt.dep.isTop) continue;
this.pushUp(tt.dep,decl);
if(!tt.dep.isTop) continue;
if(auto id=cast(Identifier)tt.expr){
if(!tt.read){
if(id.implicitDup&&id.meaning){ // implicit dup no longer recomputable
if(!cancelImplicitDup(id)){
decl.setSemForceError();
}
}
}
}
}
}
final bool checkTrackedTemporaries(TrackedTemporary[] trackedTemporaries,Expression parent){
//imported!"util.io".writeln("CHECKING TEMPORARIES: ",trackedTemporaries," ",parent);
bool success=true;
foreach(ref tt;trackedTemporaries){
if(!tt.dep.isTop){ // nothing to do for recomputable temporaries
if(!cast(Identifier)tt.expr) noteRecomputedTemporary(tt.dep);
continue;
}
if(auto id=cast(Identifier)tt.expr){
if(tt.read){ // non-recomputable const-blocked consumption
if(id.meaning&&(!id.constLookup&&!id.implicitDup)){
success=false;
assert(tt.read.meaning);
blockConst(tt.read.meaning,tt.read); // TODO: why needed?
if(tt.read.scope_.checkConsumable(id,tt.read.meaning))
assert(tt.read.meaning.isSemError);
id.setSemForceError();
id.meaning.setSemForceError();
parent.setSemForceError();
}
}
}
}
foreach(ref tt;trackedTemporaries){
//imported!"util.io".writeln("CHECKING TRACKED TEMPORARY: ",tt);
if(!tt.dep.isTop) continue;
if(auto id=cast(Identifier)tt.expr){
if(id.isSemError()) parent.setSemForceError();
continue;
}
success=false;
import ast.semantic_:nonLiftedError;
nonLiftedError(tt.expr,this);
tt.expr.setSemError();
parent.setSemForceError();
}
return success;
}
final Identifier isConst(Declaration decl){
foreach(ref prop;nestedDeclProp(decl)){
auto r=prop.constBlock;
if(r.length) return r[$-1];
}
return null;
}
final void inheritConstBlocks(Declaration prev,Declaration new_){ // new_ replaces prev, so it inherits prev's active const blocks
foreach(ref props;&nestedDeclProps){
bool done=false;
for(auto d=prev;d&&!done;d=d.splitFrom)
if(auto prop=props.tryGet(d))
if(prop.constBlock.length){
if(!props.tryGet(new_)) props.set(new_,DeclProp.default_());
props.tryGet(new_).constBlock~=prop.constBlock;
done=true;
}
}
}
static struct ConstBlockContext{
private MapX!(Declaration,Identifier[]) constBlock;
private size_t numTrackedTemporaries;
private size_t numComponentConstBlocks;
}
final ConstBlockContext saveConst(){
MapX!(Declaration,Identifier[]) constBlock;
foreach(decl,ref prop;declProps.props){
auto r=prop.constBlock;
if(r.length) constBlock[decl]=r;
}
return ConstBlockContext(constBlock,trackedTemporaries.length,componentConstBlocks.length);
}
private void recordResetConst(Declaration decl,Identifier constBlock,ref Expression parent,bool isStatement,bool inType)in{
assert(decl&&constBlock);
}do{
if(constBlock is parent&&!(!constBlock.type||constBlock.type.isClassical())) return; // TODO: would be nice if we would not need this, can happen e.g. in consumeArray
if(auto lu=lastUses.get(decl,true)){
if(lu.isConsumption()){
if(constBlock.meaning){
if(dependencyTracked(constBlock.meaning)&&!getDependency(constBlock.meaning).isTop){ // TODO: make this condition unnecessary?
if(lu.kind==LastUse.Kind.consumption){
lastUses.synthesizedForget(constBlock.meaning,null,this,parent);
}
}
}
return;
}
if(lu.kind==LastUse.Kind.implicitDup) return;
}
if(constBlock.scope_&&constBlock.meaning&&!constBlock.meaning.isToplevelDeclaration()){
if(constBlock.meaning.isSemError()&&!constBlock.scope_.dependencyTracked(constBlock.meaning)) return; // (replaced after an error)
lastUses.constUse(constBlock,parent,isStatement,inType);
}
}
final bool resetConst(ConstBlockContext context,ref Expression parent,bool isStatement,bool inType){
Identifier[] lookupSnapshot(Declaration decl){
for(auto d=decl; d; d=d.splitFrom){
if(auto r=context.constBlock.get(d,null)) return r;
}
return null;
}
Declaration lookupCurrent(Declaration decl){
if(declProps.tryGet(decl)) return decl;
foreach(d,ref prop;declProps.props){
for(auto s=d.splitFrom; s; s=s.splitFrom){
if(s is decl) return d;
}
}
return null;
}
foreach(decl,ref prop;declProps.props){
auto nconstBlock=lookupSnapshot(decl);
if(prop.constBlock.length&&prop.constBlock!=nconstBlock){
auto reads=prop.constBlock;
recordOuterConstReads(decl,reads.filter!(read=>!nconstBlock.canFind(read)));
prop.constBlock=nconstBlock; // (the forget after the last use follows the reads that end here, e.g., both in `t⊕t`)
recordResetConst(decl,reads[$-1],parent,isStatement,inType);
}
prop.constBlock=nconstBlock;
}
foreach(decl,constBlock;context.constBlock){
auto current=lookupCurrent(decl);
if(!current) continue; // declaration was consumed/removed entirely
auto prop=declProps.tryGet(current);
assert(prop&&prop.constBlock==constBlock,text(prop is null," ",prop?prop.constBlock:null," ",constBlock));
}
auto success=checkTrackedTemporaries(trackedTemporaries[context.numTrackedTemporaries..$],parent);
trackedTemporaries=trackedTemporaries[0..context.numTrackedTemporaries];
componentConstBlocks=componentConstBlocks[0..context.numComponentConstBlocks];
return success;
}
static struct OuterConstRead{
Declaration decl;
Identifier read;
IndexExp component;
}
OuterConstRead[]* outerConstReads=null; // (const reads of outer variables that are reset, e.g., within a `let` expression in a `const` position)
private void recordOuterConstReads(R)(Declaration decl,R reads){
if(!outerConstReads||decl.scope_&&decl.scope_.isNestedIn(this)&&!decl.splitFrom) return;
foreach(read;reads){
IndexExp component=null;
foreach(ccb;componentConstBlocks) if(ccb.read is read) component=ccb.component;
*outerConstReads~=OuterConstRead(decl,read,component);
}
}
final bool resetConst(ref Expression parent,bool isStatement,bool inType){
foreach(decl,ref prop;declProps.props){
if(prop.constBlock.length){
auto reads=prop.constBlock;
recordOuterConstReads(decl,reads);
prop.constBlock=[];
recordResetConst(decl,reads[$-1],parent,isStatement,inType);
}
}
auto success=checkTrackedTemporaries(trackedTemporaries,parent);
trackedTemporaries=[];
componentConstBlocks=[];
return success;
}
final void resetLocalComponentReplacements(){
foreach(decl,ref prop;declProps.props)
prop.componentReplacements=[];
}
final DeclProp.ComponentReplacement[] localComponentReplacements(){
typeof(return) r;
foreach(decl,ref prop;declProps.props)
r~=prop.componentReplacements;
return r;
}
final DeclProp.ComponentReplacement[][] localComponentReplacementsByDecl(){
Declaration[] decls;
typeof(return) r;
foreach(decl,ref prop;declProps.props){
if(!prop.componentReplacements.length) continue;
decls~=decl;
r~=prop.componentReplacements;
}
sort!"a[0].getName<b[0].getName"(zip(decls,r));
return r;
}
DeclProp.ComponentReplacement*[] allComponentReplacements(){ // TODO: get rid of this?
typeof(return) r=[];
foreach(ref props;&nestedDeclProps)
foreach(decl,ref prop;props.props)
r~=iota(prop.componentReplacements.length).map!(i=>&prop.componentReplacements[i]).array;
return r;
}
final DeclProp.ComponentReplacement*[] componentReplacements(Declaration decl){ // TODO: get rid of this?
typeof(return) r=[];
foreach(ref prop;nestedDeclProp(decl))
r~=iota(prop.componentReplacements.length).map!(i=>&prop.componentReplacements[i]).array;
return r;
}
// the component replacements of the versions of the aggregate that `decl` derives from, which also apply to it (through
// splits, merges, promotions and writes of other components, e.g., to `x` after `x[2]:=X(x[2]);` in the body of
// `with{ t:=x[1]; }do{ … }`), with the versions they are registered for
final Q!(Declaration,DeclProp.ComponentReplacement*)[] versionComponentReplacements(Declaration decl){
typeof(return) r=[];
Declaration[] visited;
void add(Declaration version_){
for(auto d=version_;d;d=d.splitFrom){ // (the replacements may move to a split, see `DeclProps.replaceDecl`)
if(visited.canFind(d)) continue;
visited~=d;