-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscope_.d
More file actions
2174 lines (2120 loc) · 69.7 KB
/
scope_.d
File metadata and controls
2174 lines (2120 loc) · 69.7 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;
static if(language==silq){
struct Dependency{
bool isTop;
SetX!Declaration dependencies;
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){
if(decl !in dependencies) return;
dependencies.remove(decl);
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);
}
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)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);
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);
}
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;
}
}
}
import ast.lastuse;
enum Lookup{
consuming,
constant,
probing,
probingWithCapture,
}
abstract class Scope{
abstract @property ErrorHandler handler();
bool allowsLinear(){
return true;
}
final bool canInsert(Id id){
auto decl=symtabLookup(id,false,null);
return !decl||cast(DeadDecl)decl;
}
final bool tryPrepareRedefine(Declaration newDecl,Declaration oldDecl){
if(oldDecl.scope_&&lastUses.canRedefine(oldDecl)){
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)){
if(!tryPrepareRedefine(decl,d))
return false;
//assert(!symtabLookup(decl.name,false,null));
}
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 if(language==silq){
static struct DeclProp{
Identifier[] constBlock;
static if(language==silq){
static struct ComponentReplacement{
IndexExp write;
Id name;
IndexExp read;
}
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_(); }
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 DeclProp[Declaration] props;
DeclProps dup(){ return DeclProps(props.dup); }
void clear(){ props.clear(); }
DeclProp* tryGet(Declaration decl){ return decl in props; }
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){
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;
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(!meaning.isToplevelDeclaration()){
lastUses.pin(meaning,false); // previous last use cannot be used to forget anymore
if(!id.constLookup&&!id.implicitDup)
lastUses.consumption(meaning,id,this); // TODO: ok?
updateDeclProps(meaning).accesses~=id;
}
}
final void recordCapturer(Declaration capturer,Declaration meaning){
if(!meaning.isToplevelDeclaration){
updateDeclProps(meaning).capturers~=capturer;
}
}
private final Identifier isConstHere(Declaration decl){
if(auto r=declProps.tryGet(decl))
if(r.constBlock.length)
return r.constBlock[$-1];
return null;
}
final void blockConst(Declaration decl,Identifier constBlock){
if(!decl.isToplevelDeclaration){
if(auto props=updateDeclProps(decl))
props.constBlock~=constBlock;
}
}
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);
}
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()){
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;
if(auto declProp=declProps.tryGet(decl)){
bool seen=false;
DeadDecl[] failures;
foreach(access;declProp.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?
}
return ok;
}
final bool cancelImplicitDup(Identifier id)in{
assert(!!id.implicitDup);
assert(!!id.meaning);
assert(!id.constLookup);
}do{
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) continue; // nothing to do for recomputable temporaries
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;
}
static struct ConstBlockContext{
private Identifier[][Declaration] constBlock;
private size_t numTrackedTemporaries;
}
final ConstBlockContext saveConst(){
Identifier[][Declaration] constBlock;
foreach(decl,ref prop;declProps.props){
auto r=prop.constBlock;
if(r.length) constBlock[decl]=r;
}
return ConstBlockContext(constBlock,trackedTemporaries.length);
}
private void recordResetConst(Declaration decl,Identifier constBlock,ref Expression parent,bool isStatement,bool inType){
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())
lastUses.constUse(constBlock,parent,isStatement,inType);
}
final bool resetConst(ConstBlockContext context,ref Expression parent,bool isStatement,bool inType){
foreach(decl,ref prop;declProps.props){
auto nconstBlock=context.constBlock.get(decl,null);
if(prop.constBlock != nconstBlock) recordResetConst(decl,prop.constBlock[$-1],parent,isStatement,inType);
prop.constBlock=nconstBlock;
}
foreach(decl,constBlock;context.constBlock){
auto prop=declProps.tryGet(decl);
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];
return success;
}
final bool resetConst(ref Expression parent,bool isStatement,bool inType){
foreach(decl,ref prop;declProps.props){
if(prop.constBlock.length){
recordResetConst(decl,prop.constBlock[$-1],parent,isStatement,inType);
prop.constBlock=[];
}
}
auto success=checkTrackedTemporaries(trackedTemporaries,parent);
trackedTemporaries=[];
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;
}
static struct ComponentReplacementContext{
private DeclProp.ComponentReplacement[][Declaration] componentReplacements;
bool empty(){ return !componentReplacements.length; }
}
final ComponentReplacementContext moveLocalComponentReplacements(){ // TODO: get rid of this
DeclProp.ComponentReplacement[][Declaration] r;
foreach(decl,ref prop;declProps.props){
r[decl]=prop.componentReplacements;
prop.componentReplacements=[];
}
return typeof(return)(r);
}
final void restoreLocalComponentReplacements(ComponentReplacementContext previous){ // TODO: get rid of this
foreach(decl,crepls;previous.componentReplacements)
updateDeclProps(decl).componentReplacements=crepls;
}
}else{
struct DeclProps{ }
struct ConstBlockContext{ }
final DeclProps saveDeclProps(){ return DeclProps.init; }
final void resetDeclProps(DeclProps previous){ }
final Identifier isConst(Declaration decl){ return null; }
final ConstBlockContext saveConst(){ return ConstBlockContext.init; }
final void resetConst(ConstBlockContext previous){ }
final void resetConst(){ }
final void resetComponentReplacement(){ }
}
final ConsumedDecl recordConsumption(Declaration decl,Identifier use){
if(allowMerge) return null;
if(!use) return null;
auto cd=new ConsumedDecl(decl,use);
if(decl.rename){
cd.rename=new Identifier(decl.rename.id);
cd.rename.loc=decl.rename.loc;
}
cd.scope_=decl.scope_;
cd.setSemCompleted();
if(canInsert(cd.name.id))
symtabInsert(cd);
return cd;
}
final Declaration consume(Declaration decl,Identifier use){
if(use&&!decl.isSemError&&!use.isSemError){
if(auto read=isConst(decl)){
foreach(prop;nestedDeclProp(decl)){
foreach(block;prop.constBlock)
block.consumedDuringBorrow=true;
}
recordConstBlockedConsumption(read,use);
}
}
if(rnsymtab.get(decl.getId,null) !is decl) return null;
if(cast(DeadDecl)decl) return null;
Expression type;
return consumeImpl(decl,decl,type,true,use); // TODO: separate splitting and consuming
}
final bool canSplit(Declaration decl)in{
if(!decl.isToplevelDeclaration()&&!decl.isSemError)
assert(decl.scope_&&this.isNestedIn(decl.scope_));
}do{
if(decl.scope_ is this) return true;
if(decl.isToplevelDeclaration()) return false;
if(decl.isConst||decl.typeConstBlocker||isConst(decl)&&!canRecompute(decl)) return false;
return true;
}
final Declaration split(Declaration decl,Identifier use)in{
if(!decl.isToplevelDeclaration()&&!decl.isSemError)
assert(decl.scope_&&this.isNestedIn(decl.scope_),text(decl));
}do{
if(decl.scope_ is this) return decl;
if(!canSplit(decl)) return decl;
Expression type;
auto result=consume(decl,use);
if(!result) return decl;
unconsume(result);
return result;
}
final void unsplit(Declaration decl)in{
assert(this is decl.scope_);
}do{
foreach(split;decl.splitInto){
// assert(split !in split.scope_.lastUses.lastUses,text(split," ",split.scope_.lastUses.lastUses[split]));
split.scope_.unsplit(split);
if(split.scope_.consumedOuter.canFind(decl)){
split.scope_.consumedOuter=split.scope_.consumedOuter.filter!(d=>d!is decl).array; // TODO: make more efficient
}
if(split.scope_.splitVars.canFind(split)){
split.scope_.splitVars=split.scope_.splitVars.filter!(d=>d!is split).array; // TODO: make more efficient
}
if(split.scope_.forgottenVarsOnEntry.canFind(split)){
split.scope_.forgottenVarsOnEntry=split.scope_.forgottenVarsOnEntry.filter!(d=>d!is split).array; // TODO: make more efficient
}
if(split.scope_.forgottenVars.canFind(split)){
split.scope_.forgottenVars=split.scope_.forgottenVars.filter!(d=>d!is split).array; // TODO: make more efficient
}
if(split.scope_.mergedVars.canFind(split)){
split.scope_.mergedVars=split.scope_.mergedVars.filter!(d=>d!is split).array; // TODO: make more efficient
if(split.mergedInto&&split.mergedInto.scope_){
split.mergedInto.scope_.unsplit(split.mergedInto);
split.mergedInto.scope_.consume(split.mergedInto,null);
}
}
split.scope_.consume(split,null);
}
decl.splitInto=[];
}
final void reinsert(Declaration decl){
if(toRemove.canFind(decl))
toRemove=toRemove.filter!(pdecl=>pdecl!is decl).array; // TODO: make more efficient
symtabInsert(decl);
}
final void unconsume(Declaration decl)in{
assert(decl.scope_ is null||decl.scope_ is this||decl.isSemError(),text(decl," ",decl.loc));
}do{
reinsert(decl);
decl.scope_=this;
}
Declaration[] consumedOuter;
Declaration[] splitVars;
final void splitVar(Declaration splitFrom,Declaration splitInto){
if(splitFrom.isSemError())
splitInto.setSemForceError();
assert(splitFrom.scope_ !is splitInto.scope_);
splitFrom.splitInto~=splitInto;
splitInto.splitFrom=splitFrom;
splitVars~=splitInto;
}
final void resetSplits(Declaration decl){
void rec(Declaration cdecl){
foreach(split;cdecl.splitInto){
replaceDecl(split,decl);
rec(split);
}
cdecl.splitInto=[];
}
rec(decl);
}
final void replaceDecl(Declaration splitFrom,Declaration splitInto)in{
assert(splitFrom !is splitInto);
}do{
if(splitFrom.isSemError())
splitInto.setSemForceError();
foreach(scopes;mergedNestedScopes){
foreach(sc;scopes)
sc.replaceDecl(splitFrom,splitInto);
}
if(language==silq){
if(dependencyTracked(splitFrom))
replaceDependencies(splitFrom,splitInto);
declProps.replaceDecl(splitFrom,splitInto);
}
foreach(ref oldDecl;forgottenVarsOnEntry){
if(oldDecl is splitFrom)
oldDecl=splitInto;
}
lastUses.replaceDecl(splitFrom,splitInto);
}
final void updateType(Declaration decl){
if(auto prop=declProps.tryGet(decl)){
foreach(id;prop.accesses){
if(auto ty=id.typeFromMeaning)
id.type=ty;
}
}
}
protected Declaration consumeImpl(Declaration odecl,Declaration ndecl,ref Expression type,bool remove,Identifier use)in{
assert(odecl is ndecl||!remove);
}do{
assert(odecl.scope_ is this&&ndecl.scope_ is this);
if(rnsymtab.get(odecl.getId,null) !is odecl) return null;
if(remove){
symtabRemove(odecl);
if(odecl !is ndecl)
replaceDecl(odecl,ndecl);
static if(language==silq){
if(dependencyTracked(ndecl))
pushDependencies(ndecl,true);
}
recordConsumption(odecl,use);
}else if(odecl !is ndecl){
assert(odecl.name.id == ndecl.name.id);
symtabRemove(odecl);
symtabInsert(ndecl);
replaceDecl(odecl,ndecl);
}
return ndecl;
}
static if(language==silq){
private Declaration[] toRemove;
private TrackedTemporary[] trackedTemporaries;
final void pushUp(ref Dependency dependency,Declaration removed){
if(!dependencyTracked(removed)) return; // TODO: ideally can be removed
dependency.replace(removed,dependencies.dependencies[removed]);
}
final void clearConsumed(){
foreach(removed;toRemove)
removeDependency(removed);
toRemove=[];
}
}
protected final Declaration symtabLookup(Identifier ident,bool rnsym,DeadDecl[]* failures){
return symtabLookup(ident.id,rnsym,failures);
}
protected final Declaration symtabLookup(Id id,bool rnsym,DeadDecl[]* failures){
if(allowMerge) return null;
auto r=rnsym?rnsymtab.get(id,null):symtab.get(id,null);
if(auto dd=cast(DeadDecl)r){
if(failures) *failures~=dd;
r=null;
}
return r;
}
final Declaration peekSymtab(Id name,bool rnsym){
return rnsym?rnsymtab.get(name,null):symtab.get(name,null);
}
final bool isConsumable(Identifier id,Declaration meaning=null)in{
assert(id.isSemError||id.meaning||meaning);
}do{
if(!meaning) meaning=id.meaning;
if(!meaning) return true;
if(meaning.typeConstBlocker) return false;
if(canRecompute(meaning)) return true;
if(isConst(meaning)) return false;
if(meaning.isConst) return false;
return true;
}
final bool checkConsumable(Identifier id,Declaration meaning=null)in{
assert(id.isSemError||id.meaning||meaning);
}do{
if(!meaning) meaning=id.meaning;
if(!meaning) return true;
assert(!!meaning);
if(meaning.isToplevelDeclaration()){
if(!meaning.isSemError()){
error(format("cannot consume top-level %s `%s`",meaning.kind,id), id.loc);
note("declared here",meaning.loc);
id.setSemForceError();
}
return false;
}
if(meaning.typeConstBlocker){
if(!meaning.isSemError()){
error(format("cannot consume `const` %s `%s`",meaning.kind,id), id.loc);
meaning.setSemForceError();
}
import ast.semantic_:typeConstBlockNote;
typeConstBlockNote(meaning,this);
id.setSemForceError();
return false;
}
if(meaning.isConst){
if(!meaning.isSemError()){
error(format("cannot consume `const` %s `%s`",meaning.kind,id), id.loc);
note("declared `const` here", meaning.loc);
meaning.setSemForceError();
}
id.setSemForceError();
return false;
}
if(auto read=isConst(meaning)){
if(canRecompute(meaning))
return true;
if(!meaning.isSemError()){
if(read !is id){
error(format("cannot consume `const` %s `%s`",meaning.kind,id), id.loc);
note(format("%s was made `const` here", meaning.kind), read.loc);
}else{
import ast.semantic_:nonLiftedError;
nonLiftedError(id,this); // TODO: would be better to locate this around the enclosing `const` expression
}
meaning.setSemForceError();
}
id.setSemForceError();
return false;
}
return true;
}
private Declaration postprocessLookup(Identifier id,Declaration meaning,Lookup kind){
//imported!"util.io".writeln("POSTPROCESSING: ",id.loc," ",meaning," ",kind);
static if(language==silq) enum performConsume=true;
else auto performConsume=id.byRef;
if(performConsume){
if(!meaning) return meaning;
if(kind==Lookup.consuming){
bool doConsume=true;
if(doConsume){
if(!checkConsumable(id,meaning))
doConsume=false;
if(doConsume&&meaning.scope_){
assert(!meaning.isConst);
if(auto nmeaning=consume(meaning,id))
meaning=nmeaning;
}
}
}
static if(language==silq)
if(kind==Lookup.constant&&!meaning.isConst&&!meaning.isToplevelDeclaration())
blockConst(meaning,id);
}
if(kind!=Lookup.probing&&meaning){
recordAccess(id,meaning);
}
return meaning;
}
final Declaration lookup(Identifier ident,bool rnsym,bool lookupImports,Lookup kind,DeadDecl[]* failures){
auto meaning=lookupImpl(ident,rnsym,lookupImports,kind,this,failures);
return postprocessLookup(ident,meaning,kind);
}
Declaration lookupImpl(Identifier ident,bool rnsym,bool lookupImports,Lookup kind,Scope origin,DeadDecl[]* failures){
return lookupHereImpl(ident,rnsym,failures);
}
Identifier getRenamed(Identifier cname){
for(;;){ // TODO: quite hacky
auto d=lookup(cname,true,true,Lookup.probing,null);
import ast.semantic_: isBuiltIn;
if(!d&&!isBuiltIn(cname)) break;
auto loc=cname.loc;
cname=new Identifier(cname.id.apos);
cname.loc=loc;
}
return cname;
}
protected final void rename(Declaration decl){
auto cname=decl.rename?decl.rename:decl.name;
decl.rename=getRenamed(cname);
}
final Declaration lookupHere(Identifier ident,bool rnsym,Lookup kind,DeadDecl[]* failures){
auto meaning=lookupHereImpl(ident,rnsym,failures);
return postprocessLookup(ident,meaning,kind);
}
final Declaration lookupHereImpl(Identifier ident,bool rnsym,DeadDecl[]* failures){
auto r=symtabLookup(ident,rnsym,failures);
if(auto fd=cast(FunctionDef)r){
import ast.semantic_:isInDataScope;
if(auto asc=isInDataScope(fd.scope_))
if(fd.name.id==asc.decl.name.id)
r=asc.decl;
}
return r;
}
bool isNestedIn(Scope rhs){ return rhs is this; }
void error(lazy string err, Location loc){handler.error(err,loc);}
void note(lazy string err, Location loc){handler.note(err,loc);}
void message(lazy string msg, Location loc){handler.message(msg,loc);}
final bool close(T)(T loc)if(is(T==Scope)||is(T==ReturnExp)){
import ast.semantic_: unrealizable;
bool errors=false;
static if(language==silq){
foreach(_,d;rnsymtab.dup){
if(cast(DeadDecl)d) continue;
if(d.isSemError()) continue;
if(rnsymtab.get(d.getId,null) !is d) continue;
//if(d.scope_ !is this && !d.isLinear()) continue;
//imported!"util.io".writeln("REMOVING: ",d," ",getDependency(d)," ",canSplit(d)," ",canForget(d)," ",lastUses.canForget(d,true,false)," ",rnsymtab," ",isConst(d)," ",lastUses.lastUses);
if(d.scope_.getFunction() !is getFunction()) continue;
//d=split(d,null);
//assert(d.scope_ is this);
if(auto vd=cast(VarDecl)d) if(!vd.vtype||unrealizable(vd.vtype)) {
d.setSemForceError();
continue;
}
if(!canForgetAppend(loc,d)){
if(!d.isSemError()){
bool done=false;
if(!canSplit(d)){
if(auto read=isConst(d)){
error(format("cannot forget `const` variable `%s`",d), d.loc);
note("variable was made `const` here", read.loc);
errors=true;
done=true;
}else continue; // TODO: catch this early
}
if(!done) done=lastUses.betterUnforgettableError(d,this);
if(!done){
if(cast(Parameter)d) error(format("%s `%s` is not consumed (perhaps return it or annotate it `const`)",d.kind,d.getName),d.loc);
else error(format("%s `%s` is not consumed (perhaps return it)",d.kind,d.getName),d.loc);
errors=true;
done=true;
}
d.setSemForceError();
}
static if(is(typeof(loc):Expression)) loc.setSemForceError();
}else{
Identifier use=null;
if(isConst(d)){
use=new Identifier(d.getName);
use.constLookup=false;
static if(is(T==Scope)) use.loc=d.loc;
else use.loc=loc.loc;
use.sstate=SemState.completed;
}
consume(d,use);
clearConsumed();
}
}
}
return errors;
}