-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreverse.d
More file actions
1304 lines (1281 loc) · 41.5 KB
/
reverse.d
File metadata and controls
1304 lines (1281 loc) · 41.5 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.reverse;
import astopt;
import std.conv,std.format,std.algorithm,std.range,std.exception;
import ast.lexer,ast.scope_,ast.expression,ast.type,ast.declaration,ast.semantic_,ast.error,util;
import util.tuple:Q=Tuple,q=tuple;
bool isEmptyTupleTy(Expression ty){
return isSubtype(ty,unit)&&isSubtype(unit,ty); // TODO: improve?
}
Expression constantExp(size_t l){
Token tok;
tok.type=Tok!"0";
tok.str=to!string(l);
auto r=new LiteralExp(tok);
r.type=l<=1?Bool(true):ℕt(true);
r.setSemCompleted();
return r;
}
static if(language==silq)
Identifier getDup(Location loc,Scope isc){
return getPreludeSymbol("dup",loc,isc);
}
bool isClassicalExp(Expression e){
static if(language==silq) return e.type&&e.subexpressions.all!(x=>!x.type||x.type.isClassical())&&e.isQfree()&&!e.consumes;
else return true;
}
enum LowerDefineFlags{
none=0,
createFresh=1,
reverseMode=2,
}
Expression knownLength(Expression e,bool ignoreType){ // TODO: version that returns bool
Expression res;
scope(exit) if(res) res.loc=e.loc;
if(auto let=cast(LetExp)e) if(auto fwd=let.isForward(false)) return fwd;
if(auto vec=cast(VectorExp)e) return res=constantExp(vec.e.length);
if(auto tpl=cast(TupleExp)e) return res=constantExp(tpl.e.length);
if(auto cat=cast(CatExp)e){
auto a=cat.e1.knownLength(ignoreType);
auto b=cat.e2.knownLength(ignoreType);
if(a&&b){
res=new AddExp(a,b);
propErr(a,res);
propErr(b,res);
if(a.type&&b.type){
res.type=arithmeticType!false(a.type,b.type);
if(!res.type) res.setSemError();
}
if(res.type&&a.isSemCompleted()&&b.isSemCompleted())
res.setSemCompleted();
return res;
}
}
if(auto tae=cast(TypeAnnotationExp)e){
Expression knownLengthType(Expression t){
if(auto une=cast(UNotExp)t)
return knownLengthType(une.e);
if(auto vec=cast(VectorTy)t)
return vec.num;
if(auto tt=t.isTupleTy())
return res=constantExp(tt.length);
if(auto pow=cast(PowExp)t)
return pow.e2;
if(auto ty=cast(TypeofExp)t){
if(auto sl=cast(SliceExp)ty.e){
res=new NSubExp(sl.r,sl.l);
propErr(sl.r,res);
propErr(sl.l,res);
if(sl.r.type&&sl.l.type){
res.type=nSubType(sl.r,sl.l);
if(!res.type) res.setSemError();
}
if(res.type&&sl.r.isSemCompleted()&&sl.l.isSemCompleted())
res.setSemCompleted();
return res;
}
}
return null;
}
if(auto l=knownLengthType(tae.t))
return l;
return knownLength(tae.e,ignoreType);
}
if(!ignoreType&&e.type){
if(auto vec=cast(VectorTy)e.type)
return vec.num;
if(auto tt=e.type.isTupleTy())
return res=constantExp(tt.length);
}
return null;
}
bool isEmptyTuple(Expression e){
auto tpl=cast(TupleExp)e;
return tpl&&tpl.length==0;
}
bool validDefLhs(LowerDefineFlags flags)(Expression olhs,Scope sc,bool unchecked,bool noImplicitDup){
bool validDefEntry(Expression e){
if(e.implicitDup){
if(noImplicitDup){
if(auto id=cast(Identifier)olhs)
if(id.meaning.isConst)
return false;
}else return false;
}
return cast(Identifier)e||cast(IndexExp)e||cast(SliceExp)e;
}
if(auto tpl=cast(TupleExp)olhs) return tpl.e.all!validDefEntry;
if(auto cat=cast(CatExp)olhs) return validDefEntry(unwrap(cat.e1))&&validDefEntry(unwrap(cat.e2))
&&(knownLength(cat.e1,true)||knownLength(cat.e2,true));
if(auto ce=cast(CallExp)olhs){
static if(language==silq){
if(isPrimitiveCall(ce))
return false;
if(isBuiltInCall(cast(CallExp)unwrap(ce.e)))
return false;
}
auto f=ce.e, ft=cast(ProductTy)f.type;
if(!ft) return false;
if(ce.isSquare!=ft.isSquare) return false;
if(ce.checkReverse&&!unchecked){
auto r=reverseCallRewriter(ft,ce.loc);
if(r.movedType.hasClassicalComponent()){
return false;
}
}
// if(!equal(ft.isConst,ft.isConstForReverse)) return false; // TODO: can we completely rewrite away isConstForReverse?
if((ft.nargs||isEmptyTuple(ce.arg))&&iota(ft.nargs).all!(i=>ft.isConstForReverse[i])){
auto tpl=cast(TupleExp)ce.arg;
auto tt=ft.dom.isTupleTy;
return !tpl||tt&&tpl.length==tt.length;
}
if(iota(ft.nargs).all!(i=>!ft.isConstForReverse[i]))
return validDefEntry(ce.arg);
assert(ft.isTuple);
auto tpl=cast(TupleExp)ce.arg;
if(!tpl||ft.nargs!=tpl.length) return false;
return iota(ft.nargs).all!(i=>ft.isConstForReverse[i]||validDefEntry(tpl.e[i]));
}
return validDefEntry(olhs);
}
static if(language==silq)
ReverseCallRewriter reverseCallRewriter(FunTy ft_,Location loc){
auto r=ReverseCallRewriter(ft_,loc);
with(r){
constTuple=constIndices.walkLength!=1||movedIndices.empty&&ft.isTuple;
movedTuple=movedIndices.walkLength!=1||constIndices.empty&&ft.isTuple;
constType=constTuple?tupleTy(constIndices.map!(i=>ft.argTy(i)).array):ft.argTy(constIndices.front);
movedType=movedTuple?tupleTy(movedIndices.map!(i=>ft.argTy(i)).array):ft.argTy(movedIndices.front);
returnType=ft.cod;
returnTuple=isEmptyTupleTy(returnType);
return r;
}
}
struct ReverseCallRewriter{
static if(language==silq):
ProductTy ft;
Location loc;
bool constTuple,movedTuple,returnTuple;
Expression constType,movedType,returnType;
@property constIndices()return scope{ return iota(ft.nargs).filter!(i=>ft.isConstForReverse[i]); }
@property movedIndices()return scope{ return iota(ft.nargs).filter!(i=>!ft.isConstForReverse[i]); }
@property bool constLast(){
static bool constLastImpl(FunTy ft){
return ft.nargs&&!ft.isConstForReverse[0]&&ft.isConstForReverse[$-1];
}
if(ft.isSquare){
if(auto ft2=cast(FunTy)ft.cod){
return constLastImpl(ft2);
}else return false;
}
return constLastImpl(ft);
}
@property bool innerNeeded(){
return !(equal(ft.isConst,ft.isConstForReverse)&&equal(constIndices,only(0))&&equal(movedIndices,only(1))&&ft.annotation==Annotation.mfree);
}
Q!(Expression,Expression) reorderArguments(TupleExp tpl)in{
assert(ft.isTuple&&ft.nargs==tpl.length);
}do{
auto loc=tpl.loc;
auto constArgs=constIndices.map!(i=>tpl.e[i]);
auto movedArgs=movedIndices.map!(i=>tpl.e[i]);
Expression constArg,movedArg;
if(constTuple){
constArg=new TupleExp(constArgs.array);
constArg.loc=loc;
}else constArg=constArgs.front;
if(movedTuple){
movedArg=new TupleExp(movedArgs.array);
movedArg.loc=loc;
}else movedArg=movedArgs.front;
return q(constArg,movedArg);
}
Expression wrapInner(Expression f){
auto loc=this.loc;
auto names=only(freshName,freshName);
auto params=makeParams(only(true,false),names,only(constType,movedType),loc);
Expression unpackExp=null;
Expression[] movedArgs;
Expression[] constArgs;
if(constTuple){
constArgs=makeIndexLookups(names[0],iota(constIndices.walkLength),loc);
}else{
auto id=new Identifier(names[0]);
id.loc=loc;
constArgs=[id];
}
if(movedTuple){
auto unpackNames=movedIndices.map!((i)=>Id.intern("`arg_"~(ft.names[i]?ft.names[i].str:text(i))));
auto unpackLhs=new TupleExp(makeIdentifiers(unpackNames,loc));
unpackLhs.loc=loc;
auto unpackRhs=new Identifier(names[1]);
unpackRhs.loc=loc;
if(!movedIndices.empty){ // TODO: get rid of this branch
unpackExp=new BinaryExp!(Tok!":=")(unpackLhs,unpackRhs);
unpackExp.loc=loc;
movedArgs=makeIdentifiers(unpackNames,loc);
}else{
// TODO: remove this once classical move semantics is implemented
unpackExp=new ForgetExp(unpackRhs,unpackLhs);
unpackExp.loc=loc;
movedArgs=[];
}
}else movedArgs=makeIdentifiers(only(names[1]),loc);
auto nargs=new Expression[](ft.nargs);
foreach(i,carg;zip(constIndices,constArgs)){
assert(!nargs[i]);
nargs[i]=carg;
}
foreach(i,marg;zip(movedIndices,movedArgs)){
assert(!nargs[i]);
nargs[i]=marg;
}
assert(nargs.all!(x=>!!x));
Expression narg;
bool isTuple=(constArgs.length!=0||movedTuple)&&(movedArgs.length!=0||constTuple);
if(isTuple){
narg=new TupleExp(nargs);
narg.loc=loc;
}else{
assert(nargs.length==1);
narg=nargs[0];
}
auto ce1=new CallExp(f.copy,narg,ft.isSquare,false);
ce1.loc=loc;
Expression ret=new ReturnExp(ce1);
ret.loc=loc;
auto body_=new CompoundExp((unpackExp?[unpackExp]:[])~[ret]);
body_.loc=loc;
auto le=makeLambda(params,true,false,ft.annotation,body_,loc);
return le;
}
@property bool outerNeeded(bool simplify=true){
return simplify&&(constTuple||returnTuple)||ft.isSquare||constLast;
}
Expression wrapOuter(Expression rev,bool simplify){
if(!outerNeeded(simplify)) return rev;
auto loc=this.loc;
if(simplify&&(constTuple||returnTuple)){
auto isConst=(bool[]).init;
auto names=(Id[]).init;
auto types=(Expression[]).init;
void add(bool isConst_)(){
static if(isConst_){
alias isTuple=constTuple;
alias type=constType;
alias indices=constIndices;
}else{
alias isTuple=returnTuple;
alias type=returnType;
}
if(isTuple){
if(auto tpl=type.isTupleTy()){
static if(isConst_){
foreach(i,j;enumerate(indices)){
isConst~=isConst_;
names~=Id.intern("`arg_"~(ft.names[j]?ft.names[j].str:text(j)));
types~=tpl[i];
}
}else{
foreach(i;0..tpl.length){
isConst~=isConst_;
names~=freshName();
types~=tpl[i];
}
}
return;
}
}
isConst~=isConst_;
static if(isConst_){
auto j=constIndices.front;
names~=Id.intern("`arg_"~(ft.names[j]?ft.names[j].str:text(j)));
}else names~=freshName();
types~=type;
}
if(constLast){
add!false();
add!true();
}else{
add!true();
add!false();
}
auto nparams=makeParams(isConst,names,types,loc);
auto constArgs=makeIdentifiers(iota(isConst.length).filter!(i=>isConst[i]).map!(i=>names[i]),loc);
auto constArg=constTuple?new TupleExp(constArgs):constArgs.front;
constArg.loc=loc;
auto movedArgs=makeIdentifiers(iota(isConst.length).filter!(i=>!isConst[i]).map!(i=>names[i]),loc);
auto movedArg=returnTuple?new TupleExp(movedArgs):movedArgs.front;
auto nnarg=new TupleExp([constArg,movedArg]);
nnarg.loc=loc;
auto ce2=new CallExp(rev,nnarg,false,false);
ce2.loc=loc;
auto body2=makeLambdaBody(ce2,loc);
bool isTuple=(constArgs.length!=0||returnTuple)&&(movedArgs.length!=0||constTuple);
auto le2=makeLambda(nparams,isTuple,ft.isSquare,ft.annotation,body2,loc);
return le2;
}else{
auto names=only(freshName,freshName);
auto nparams=constLast ? makeParams(only(true,false).retro,names.retro,only(constType,returnType).retro,loc)
: makeParams(only(true,false),names,only(constType,returnType),loc);
auto nnargs=makeIdentifiers(names,loc);
auto nnarg=new TupleExp(nnargs);
nnarg.loc=loc;
auto ce2=new CallExp(rev,nnarg,false,false);
ce2.loc=loc;
auto body2=makeLambdaBody(ce2,loc);
auto le2=makeLambda(nparams,true,ft.isSquare,ft.annotation,body2,loc);
return le2;
}
}
}
Expression lowerDefine(LowerDefineFlags flags)(Expression olhs,Expression orhs,Location loc,Scope sc,bool unchecked,bool noImplicitDup)in{
assert(loc.line);
}do{
if(auto le=cast(LetExp)olhs){
if(auto fwd=le.isForward(false))
return lowerDefine!flags(fwd,orhs,loc,sc,unchecked,noImplicitDup);
}
if(auto le=cast(LetExp)orhs){
if(auto fwd=le.isForward(false))
return lowerDefine!flags(olhs,fwd,loc,sc,unchecked,noImplicitDup);
}
enum createFresh=!!(flags&LowerDefineFlags.createFresh); // TODO: can we get rid of this?
enum reverseMode=!!(flags&LowerDefineFlags.reverseMode);
Expression res;
scope(success) if(res){ res.loc=loc; }
static if(createFresh) Expression nlhs;
Expression lhs(){ // TODO: solve better
static if(createFresh){
if(!nlhs) nlhs=olhs.copy();
if(noImplicitDup){ // TODO: this is a hack
void removeImplicitDup(Expression e){
e.implicitDup=false;
if(auto tae=cast(TypeAnnotationExp)e)
removeImplicitDup(tae.e);
else if(auto tpl=cast(TupleExp)e)
foreach(ne;tpl.e)
removeImplicitDup(ne);
else if(auto let=cast(LetExp)e)
if(auto fwd=let.isForward(false))
removeImplicitDup(fwd);
}
removeImplicitDup(nlhs);
}
return nlhs;
}else return olhs;
}
static if(createFresh) Expression nrhs;
Expression rhs(){ // TODO: solve better
static if(createFresh){
if(!nrhs) nrhs=orhs.copy();
return nrhs;
}else return orhs;
}
Expression error(){
res=new DefineExp(lhs,rhs);
res.setSemError();
return res;
}
static if(reverseMode){
if(cast(Identifier)olhs&&olhs.type&&olhs.type.isClassical())
lhs.implicitDup=true;
}
if(validDefLhs!flags(olhs,sc,unchecked,noImplicitDup)){
if(auto tpl=cast(TupleExp)olhs) if(!tpl.e.length&&(cast(CallExp)orhs||cast(ForgetExp)orhs)) return rhs;
if(auto ce=cast(CallExp)lhs) ce.checkReverse&=!unchecked;
return res=new DefineExp(lhs,rhs);
}
Expression forget(){ return res=new ForgetExp(rhs,lhs); }
if(auto vec=cast(VectorExp)olhs){
auto newLhs=new TupleExp(vec.copy().e);
newLhs.loc=olhs.loc;
auto newRhs=orhs;
if(auto aty=cast(ArrayTy)orhs.type){
auto tty=tupleTy(aty.next.repeat(vec.e.length).array); // TODO: use vectorTy?
newRhs=new TypeAnnotationExp(orhs,tty,TypeAnnotationType.coercion);
newRhs.type=tty;
newRhs.loc=orhs.loc;
}
return lowerDefine!flags(newLhs,newRhs,loc,sc,unchecked,noImplicitDup);
}
if(auto tpll=cast(TupleExp)olhs){
auto tplr=new TupleExp(iota(tpll.e.length).map!(delegate Expression(i){ auto id=new Identifier(freshName); id.loc=orhs.loc; return id; }).array);
tplr.loc=orhs.loc;
auto d1=lowerDefine!(flags&~LowerDefineFlags.createFresh)(tplr,rhs,loc,sc,unchecked,noImplicitDup);
enforce(tpll.e.length==tplr.e.length);
Expression[] es;
foreach_reverse(i;0..tpll.e.length){
es~=lowerDefine!flags(tpll.e[i],moveExp(tplr.e[i]),loc,sc,unchecked,noImplicitDup); // TODO: evaluation order of rhs okay?
}
if(es.any!(x=>!x)) return null;
auto d2=new CompoundExp(es);
d2.loc=loc;
return res=new CompoundExp([d1,d2]);
}
if(isLiftedBuiltIn(olhs)) return forget();
if(auto ce=cast(CallExp)olhs){
if(auto ft=cast(FunTy)ce.e.type){
if(ft.isSquare==ce.isSquare&&ft.annotation>=Annotation.qfree&&(ft.nargs||isEmptyTuple(ce.arg))&&ft.isConstForReverse.all)
return forget();
}
}
if(auto tae=cast(TypeAnnotationExp)olhs){
static if(reverseMode){
if(olhs.type){
if(!orhs.type||orhs.type!=tae.e.type){
auto newRhs=new TypeAnnotationExp(rhs,tae.e.type,TypeAnnotationType.coercion);
newRhs.loc=orhs.loc;
return lowerDefine!flags(tae.e,newRhs,loc,sc,unchecked,noImplicitDup);
}else return lowerDefine!flags(tae.e,orhs,loc,sc,unchecked,noImplicitDup);
}
}
Expression newRhs;
if(tae.annotationType==TypeAnnotationType.coercion&&tae.e.type){
newRhs=new TypeAnnotationExp(orhs,tae.e.type,tae.annotationType);
}else{
// TOOD: only do this if lhs is variable
newRhs=new TypeAnnotationExp(orhs,tae.t,tae.annotationType);
}
newRhs.loc=orhs.loc;
return lowerDefine!flags(tae.e,newRhs,loc,sc,unchecked,noImplicitDup);
}
if(auto ce=cast(CatExp)olhs){
//scope(exit) imported!"util.io".writeln(olhs," := ",orhs," → ",res);
auto l1=knownLength(ce.e1,false),l2=knownLength(ce.e2,false);
if(!l1&&!l2){
sc.error("concatenation of arrays of unknown length not supported as definition left-hand side",ce.loc);
return error();
}
if(l1) l1=l1.copy();
if(l2) l2=l2.copy();
auto known1=knownLength(ce.e1,true),known2=knownLength(ce.e2,true);
Expression[] stmts=[];
auto ne1=ce.e1,ne2=ce.e2;
auto ue1=unwrap(ne1),ue2=unwrap(ne2);
auto valid1=cast(Identifier)ue1,valid2=cast(Identifier)ue2;
if(!valid1){
auto tmpe1=new Identifier(freshName);
tmpe1.loc=ce.e1.loc;
stmts~=lowerDefine!flags(ne1,tmpe1,loc,sc,unchecked,noImplicitDup);
ne1=tmpe1.copy();
ne1.loc=ce.e1.loc;
}
if(!valid2){
auto tmpe2=new Identifier(freshName);
tmpe2.loc=ce.e2.loc;
stmts~=lowerDefine!flags(ne2,tmpe2,loc,sc,unchecked,noImplicitDup);
ne2=tmpe2.copy();
ne2.loc=ce.e2.loc;
}
assert(l1||l2);
if(!(known1&&valid1)&&l1){
static if(reverseMode) ne1=unwrap(ne1); // TODO: ok?
auto w1=new WildcardExp();
w1.loc=ce.e1.loc;
auto ty1=new PowExp(w1,l1);
ty1.loc=ce.e1.loc;
ne1=new TypeAnnotationExp(ne1,ty1,TypeAnnotationType.coercion);
ne1.loc=ce.e1.loc;
}
if(!(known2&&valid2)&&l2){
static if(reverseMode) ne2=unwrap(ne2); // TODO: ok?
auto w2=new WildcardExp();
w2.loc=ce.e2.loc;
auto ty2=new PowExp(w2,l2);
ty2.loc=ce.e2.loc;
ne2=new TypeAnnotationExp(ne2,ty2,TypeAnnotationType.coercion);
ne2.loc=ce.e2.loc;
}
auto nce=new CatExp(ne1,ne2);
nce.loc=ce.loc;
auto d=lowerDefine!flags(nce,orhs,loc,sc,unchecked,noImplicitDup);
return res=new CompoundExp([d]~stmts);
}
if(auto fe=cast(ForgetExp)olhs){
if(!fe.val){
if(fe.var.type&&fe.var.type.isClassical()){
return res=new CompoundExp([]); // TODO: this is a hack
}
sc.error("reversal of implicit forget not supported",fe.loc);
return error();
}
auto tpl=cast(TupleExp)rhs;
enforce(!tpl||tpl.length==0);
static if(language==silq){
auto dup=getDup(fe.val.loc,sc);
Expression nval=new CallExp(dup,fe.val.copy(),false,false);
}else{
Expression nval=fe.val.copy();
}
nval.type=fe.val.type;
nval.loc=fe.val.loc;
if(nval.type!=fe.var.type){
nval=new TypeAnnotationExp(nval,fe.var.type,TypeAnnotationType.coercion);
nval.type=fe.var.type;
nval.loc=fe.val.loc;
}
auto def=lowerDefine!(flags&~LowerDefineFlags.reverseMode)(fe.var,nval,loc,sc,unchecked,noImplicitDup);
auto arhs=rhs;
if(orhs.type!=unit){
arhs=new TypeAnnotationExp(arhs,unit,TypeAnnotationType.annotation);
arhs.type=unit;
arhs.loc=orhs.loc;
}
if(!tpl) return res=new CompoundExp([arhs,def]);
return def;
}
static if(language==silq)
if(string prim=isPrimitiveCall(olhs)) {
auto oce=cast(CallExp)olhs;
assert(!!oce);
Expression newlhs, newrhs;
switch(prim) {
case null:
break;
case "dup":
//dup(arg) := orhs
//forget(orhs=arg);
auto ce=cast(CallExp)lhs;
assert(!!ce);
return new ForgetExp(rhs, ce.arg);
case "H", "X", "Y", "Z":
//gate(arg) := orhs
//arg := gate(orhs)
newlhs=oce.arg;
newrhs=new CallExp(oce.e, orhs, false, false);
newrhs.loc=olhs.loc;
break;
case "P":
//P(arg) := orhs
//orhs; P(-arg)
auto ce=cast(CallExp)lhs;
assert(!!ce);
auto negated=new UMinusExp(ce.arg);
negated.loc=olhs.loc;
auto reversed=new CallExp(ce.e, negated, false, false);
reversed.loc=olhs.loc;
//return new CompoundExp([orhs, reversed]);
return reversed;
case "rZ":
//rZ(arg[0], arg[1]) := orhs
//orhs; rZ(-args[0], args[1])
auto ce=cast(CallExp)lhs;
assert(!!ce);
auto argt = cast(TupleExp)ce.arg;
if(!argt) {
// TODO unpack?
sc.error(format("cannot reverse primitive `%s`",prim),oce.e.loc);
return error();
}
auto args = argt.e;
assert(args.length==2);
auto negated=new UMinusExp(args[0]);
negated.loc=olhs.loc;
auto reversed=new CallExp(ce.e, new TupleExp([negated, args[1]]), false, false);
reversed.loc=olhs.loc;
//return new CompoundExp([orhs, reversed]);
return reversed;
case "rX","rY":
//rX(args[0], args[1]) := orhs
//args[1] := rX(-args[0], orhs)
auto argt = cast(TupleExp)oce.arg;
if(!argt) {
// TODO unpack?
sc.error(format("cannot reverse primitive `%s`",prim),oce.e.loc);
return error();
}
auto args = argt.e;
assert(args.length==2);
newlhs=args[1];
auto negated=new UMinusExp(args[0]);
negated.loc=olhs.loc;
newrhs=new CallExp(oce.e, new TupleExp([negated, orhs]), false, false);
newrhs.loc=olhs.loc;
break; // DMD bug: does not detect if this is missing
default:
sc.error(format("cannot reverse primitive `%s`",prim),oce.e.loc);
return error();
}
return lowerDefine!flags(newlhs,newrhs,loc,sc,unchecked,noImplicitDup);
}
static if(language==silq)
if(auto ce=cast(CallExp)olhs){
if(!ce.e.type){
ce.e=expressionSemantic(ce.e,expSemContext(sc,ConstResult.yes,InType.no));
}
auto ft=cast(FunTy)ce.e.type;
assert(!!ce);
if(!ft) {
sc.error("call to non-function not supported as definition left-hand side", ce.e.loc);
return error();
}
bool needWrapper=false;
if(ft.isSquare&&!ce.isSquare){
if(auto ft2=cast(FunTy)ft.cod){
ft=ft2;
needWrapper=true;
}else{
sc.error("implicit function call not supported as definition left-hand side",ce.loc); // TODO?
return error();
}
}
if(!unchecked&&!needWrapper&&ft.annotation<Annotation.mfree){
sc.error("reversed function must be `mfree`",ce.e.loc);
return error();
}
if(!unchecked&&!needWrapper&&!ft.isClassical){
sc.error("quantum function call not supported as definition left-hand side",ce.loc); // TODO: support within reversed functions
return error();
}
auto f=ce.e;
auto r=reverseCallRewriter(ft,f.loc);
if(!unchecked&&!needWrapper&&r.movedType.hasClassicalComponent()){
sc.error("reversed function cannot have classical components in `moved` arguments", f.loc);
return error();
}
Expression newlhs;
Expression newarg;
if(ft.isConstForReverse.all!(x=>x==ft.isConstForReverse[0])){
if(!ft.isConstForReverse.any){
if(cast(TupleExp)ce.arg){
auto tmp=new Identifier(freshName);
newlhs=new CallExp(ce.e,tmp,ce.isSquare,ce.isClassical_);
newlhs.loc=loc;
auto def=lowerDefine!flags(newlhs,rhs,loc,sc,unchecked,noImplicitDup);
auto argUnpack=lowerDefine!flags(ce.arg,tmp,loc,sc,unchecked,noImplicitDup);
return res=new CompoundExp([def,argUnpack]);
}else{
newlhs=ce.arg;
auto constArg=new TupleExp([]);
constArg.loc=orhs.loc;
newarg=new TupleExp([constArg,orhs]);
newarg.loc=orhs.loc;
}
}else{
newlhs=new TupleExp([]);
newlhs.loc=ce.arg.loc;
newarg=new TupleExp([ce.arg,orhs]);
newarg.loc=ce.arg.loc.to(orhs.loc);
}
}else if(auto tpl=cast(TupleExp)ce.arg){
assert(ft.isTuple);
if(ft.nargs==tpl.length){
auto constMovedArgs=r.reorderArguments(tpl); // note: this changes order of assertion failures. ok?
newlhs=constMovedArgs[1];
newarg=new TupleExp([constMovedArgs[0],orhs]);
newarg.loc=constMovedArgs[0].loc.to(orhs.loc);
}else{
sc.error(format("wrong number of arguments to reversed function call (%s instead of %s)",tpl.length,ft.nargs),ce.loc);
return error();
}
}else{
sc.error("cannot match single tuple to function with mixed `const` and consumed parameters",ce.loc);
return error();
}
auto checked=!unchecked;
enum simplify=false, outerWanted=false;
auto rev=getReverse(ce.e.loc,sc,Annotation.mfree,outerWanted);
auto reversed=tryReverse(rev,ce.e,false,false,sc,checked,simplify);
if(ce.e.isSemError()) return error();
if(!reversed){
auto ce2=new CallExp(rev,ce.e,false,false);
ce2.loc=ce.e.loc;
ce2.checkReverse=checked;
reversed=ce2;
}
auto newrhs=new CallExp(reversed,newarg,ce.isSquare,ce.isClassical_);
newrhs.loc=newarg.loc;
return lowerDefine!flags(newlhs,newrhs,loc,sc,unchecked,noImplicitDup);
}
if(auto we=cast(WildcardExp)olhs){
auto tmp=new Identifier(freshName);
tmp.loc=orhs.loc;
auto de=new DefineExp(tmp,rhs);
de.loc=rhs.loc;
auto fe=new ForgetExp(tmp.copy(),null);
fe.loc=loc;
return res=new CompoundExp([de,fe]);
}
if(auto ite=cast(IteExp)olhs){
if(ite.then.s.length==1&&ite.othw&&ite.othw.s.length==1){
auto tmp=new Identifier(freshName());
tmp.loc=orhs.loc;
auto d1=lowerDefine!flags(tmp,orhs,orhs.loc,sc,unchecked,noImplicitDup);
auto thenlhs=ite.then.s[0];
auto othwlhs=ite.othw.s[0];
auto dthen=lowerDefine!(flags|LowerDefineFlags.createFresh)(thenlhs,tmp,thenlhs.loc,sc,unchecked,noImplicitDup);
auto dothw=lowerDefine!(flags|LowerDefineFlags.createFresh)(othwlhs,tmp,othwlhs.loc,sc,unchecked,noImplicitDup);
auto cond=createFresh?ite.cond.copy():ite.cond;
auto blthen=cast(CompoundExp)dthen;
if(!blthen) blthen=new CompoundExp([dthen]);
auto blothw=cast(CompoundExp)dothw;
if(!blothw) blothw=new CompoundExp([dothw]);
auto nite=new IteExp(cond,blthen,blothw);
nite.loc=ite.loc;
return res=new CompoundExp([d1,nite]);
}
}
sc.error("not supported as definition left-hand side",olhs.loc);
return error();
}
// rev(x:=y;) ⇒ y:=x;
// rev(x:=H(y);) ⇒ H(y):=x; ⇒ y:=reverse(H)(x);
// rev(x:=dup(y);) ⇒ dup(y):=x; ⇒ ():=reverse(dup)(x,y) ⇒ ():=forget(x=dup(y));
// rev(x:=CNOT(a,b);) ⇒ CNOT(a,b):=x; ⇒ a:=reverse(CNOT)(x,b);
Expression lowerDefine(LowerDefineFlags flags)(DefineExp e,Scope sc,bool unchecked,bool noImplicitDup){
if(e.isSemError()) return e;
if(validDefLhs!flags(e.e1,sc,unchecked,noImplicitDup)) return null;
return lowerDefine!flags(e.e1,e.e2,e.loc,sc,unchecked,noImplicitDup);
}
private bool copyAttr(Id name) {
switch(name.str) {
case "artificial":
case "inline":
return true;
default:
return false;
}
}
static if(language==silq)
FunctionDef reverseFunction(FunctionDef fd)in{
assert(fd.scope_&&fd.ftype&&fd.ftype.captureAnnotation==CaptureAnnotation.const_&&fd.ftype.annotation>=Annotation.mfree);
}do{
enum flags=LowerDefineFlags.createFresh|LowerDefineFlags.reverseMode;
enum unchecked=true; // TODO: ok?
enum noImplicitDup=false;
if(fd.reversed) return fd.reversed;
auto sc=fd.scope_, ft=fd.ftype;
auto asc=sc;
foreach(meaning;fd.capturedDecls){ // TODO: this is a bit hacky
if(meaning&&meaning.scope_&&meaning.scope_.canInsert(meaning.name.id)){
auto scope_=meaning.scope_;
meaning.scope_=null;
meaning.rename=null;
scope_.clearConsumed(); // TODO: get rid of this
if(!scope_.insert(meaning,true))
fd.setSemError();
}
}
/+if(fd.name){
auto scope_=fd.scope_; // TODO: this is a bit hacky
if(scope_.canInsert(fd.name.id)){
fd.scope_=null;
fd.rename=null;
if(!scope_.insert(fd,true))
fd.setSemError();
}
}+/
auto r=reverseCallRewriter(fd.ftype,fd.loc);
// enforce(!argTypes.any!(t=>t.hasClassicalComponent()),"reversed function cannot have classical components in consumed arguments"); // lack of classical components may not be statically known at the point of function definition due to generic parameters
auto fbody_=fd.body_;
if(!fbody_){
if(isPrimitive(fd)){
if(fd.name){
auto id=new Identifier(fd.name.id);
id.loc=fd.loc;
id.meaning=fd;
id.type=fd.ftype;
id.sstate=SemState.completed;
auto ids=fd.params.map!(delegate Expression(p){
auto id=new Identifier(p.name.id);
id.constLookup=p.isConst;
id.meaning=p;
id.type=p.vtype;
id.sstate=SemState.completed;
id.loc=p.loc;
return id;
}).array;
Expression arg;
if(fd.isTuple){
arg=new TupleExp(ids);
arg.loc=fd.loc;
arg.type=tupleTy(ids.map!(id=>id.type).array);
arg.sstate=SemState.completed;
}else{
assert(ids.length==1);
arg=ids[0];
}
auto ce=new CallExp(id,arg,fd.isSquare,false);
ce.loc=fd.loc;
ce.type=fd.ftype.tryApply(arg,fd.isSquare);
ce.sstate=SemState.completed;
auto ret=new ReturnExp(ce);
ret.loc=fd.loc;
ret.type=bottom;
ret.sstate=SemState.completed;
auto cmp=new CompoundExp([ret]);
cmp.loc=fd.loc;
cmp.type=bottom;
fbody_=cmp;
}else{
sc.error("cannot reverse nested function",fd.loc);
enforce(0,text("errors while reversing function"));
}
}else{
sc.error("cannot reverse function without body",fd.loc);
enforce(0,text("errors while reversing function"));
}
}
bool simplify=r.innerNeeded;
ReturnExp getRet(CompoundExp bdy){
if(!bdy||!bdy.s.length) return null;
if(auto ret=cast(ReturnExp)bdy.s[$-1]) return ret;
if(auto ce=cast(CompoundExp)bdy.s[$-1]) return getRet(ce);
return null;
}
auto ret=getRet(fbody_);
if(!ret){
sc.error("reversing early returns not supported yet",fd.loc);
enforce(0,text("errors while reversing function"));
}
Id cpname,rpname;
bool retDefReplaced=false;
if(auto id=cast(Identifier)ret.e){
if(!id.implicitDup&&validDefLhs!flags(id,sc,unchecked,noImplicitDup)){
retDefReplaced=true;
rpname=(id.meaning&&id.meaning.name?id.meaning.name:id).id;
}
}
if(!retDefReplaced) rpname=freshName();
Expression dom, cod;
bool isTuple;
bool[] isConst;
Id[] pnames;
Expression constUnpack=null;
if(simplify&&r.constIndices.empty){
dom=r.returnType;
cod=r.movedType;
isTuple=false;
isConst=[false];
pnames=[rpname];
}else if(simplify&&isEmptyTupleTy(r.returnType)){
dom=r.constType;
cod=r.movedType;
isTuple=r.constTuple;
isConst=r.constIndices.map!(_=>true).array;
pnames=r.constIndices.map!(i=>fd.params[i].name.id).array;
}else{
dom=tupleTy(r.constLast?[r.returnType,r.constType]:[r.constType,r.returnType]);
cod=r.movedType;
isTuple=true;
isConst=r.constLast?[false,true]:[true,false];
auto cids=r.constIndices.map!((i){
auto name=fd.params[i].name.name;
Expression id=new Identifier(name);
id.loc=fd.params[i].loc;
return id;
}).array;
assert(r.constTuple||cids.length==1);
if(r.constTuple){
cpname=freshName();
auto clhs=new TupleExp(cids);
auto cloc=cids.length?cids[0].loc.to(cids[$-1].loc):fd.loc;
clhs.loc=cloc;
auto crhs=new Identifier(cpname);
crhs.loc=cloc;
constUnpack=new DefineExp(clhs,crhs);
// TODO: unpacked variables will not be const declarations, maybe conflicts with implicit dup?
}else{
assert(cids.length==1);
auto id=cast(Identifier)cids[0];
assert(!!id);
cpname=id.id;
}
pnames=r.constLast?[rpname,cpname]:[cpname,rpname];
}
assert(pnames.length==isConst.length);
auto params=iota(pnames.length).map!((i){
auto pname=new Identifier(pnames[i]);
pname.loc=fd.loc;
Expression type;
if(!isTuple){
assert(i==0);
type=dom;
}else{
auto tt=dom.isTupleTy;
assert(!!tt&&tt.length==pnames.length);
type=tt[i];
}
auto param=new Parameter(isConst[i],pname,type);
param.loc=pname.loc;
return param;
}).array;
Expression retRhs;
if(simplify&&isEmptyTupleTy(r.returnType)) retRhs=new TupleExp([]);
else retRhs=new Identifier(rpname);
retRhs.loc=ret.loc;
retRhs.type=r.returnType;
retRhs.loc=ret.loc;
auto body_=new CompoundExp([]);
body_.loc=fbody_.loc;
auto result=new FunctionDef(null,params,isTuple,cod,body_);
foreach(name, val; fd.attributes) {
if(copyAttr(name)) result.attributes[name] = val;
}
result.isSquare=fd.isSquare;
result.annotation=fd.annotation;
result.scope_=sc;
result=cast(FunctionDef)presemantic(result,sc);
assert(!!result);
if(fd.annotation>=Annotation.qfree && r.movedIndices.empty){
Expression argExp;
if(isEmptyTupleTy(r.constType)) argExp=new TupleExp([]);
else if(cpname){ // TODO: would probably be better to not create the temporary at all in this case
argExp=new Identifier(cpname);
}else{
argExp=isTuple?new TupleExp(fd.params.map!(p=>cast(Expression)p.name.copy()).array):fd.params[0].name.copy();
}
Expression call=null;
argExp.loc=fd.loc; // TODO: use precise parameter locations
argExp.type=r.constType;
auto nfd=fd.copy();
auto fun=new LambdaExp(nfd);
fun.loc=fd.loc;
call=new CallExp(fun,argExp,fd.isSquare,false);
call.loc=fd.loc;
auto fe=New!ForgetExp(retRhs,call);
fe.loc=fd.loc;
body_.s=[fe];
}else{
bool retDefNecessary=!(isEmptyTupleTy(r.returnType)&&cast(TupleExp)ret.e||retDefReplaced);
auto retDef=retDefNecessary?lowerDefine!flags(ret.e,retRhs,ret.loc,result.fscope_,unchecked,noImplicitDup):null;
auto movedNames=r.movedIndices.map!(i=>fd.params[i].name.name).array;
Expression[] movedTypes;
if(r.movedTuple){
auto tt=r.movedType.isTupleTy();
assert(!!tt);
movedTypes=iota(tt.length).map!(i=>tt[i]).array;
}else movedTypes=[r.movedType];
auto makeMoved(size_t i){
Expression r;
if(isEmptyTupleTy(movedTypes[i])) r=new TupleExp([]); // TODO: use last-use analysis instead
else r=new Identifier(movedNames[i]);
r.loc=ret.loc;
r.type=movedTypes[i];
return r;
}
auto argExp=r.movedTuple?new TupleExp(iota(movedTypes.length).map!makeMoved.array):makeMoved(0);
argExp.loc=fd.loc; // TODO: use precise parameter locations
argExp=new TypeAnnotationExp(argExp,cod,TypeAnnotationType.coercion);
argExp.loc=fd.loc; // TODO: use precise parameter locations
Expression argRet=new ReturnExp(argExp);
argRet.loc=argExp.loc;
body_.s=mergeCompound((constUnpack?[constUnpack]:[])~reverseStatements(fbody_.s[0..$-1],retDef?[retDef]:[],fd.fscope_,unchecked,noImplicitDup))~[argRet];
}
static if(__traits(hasMember,astopt,"dumpReverse")) if(astopt.dumpReverse){
import util.io:stderr;
stderr.writeln(fd);
stderr.writeln("-reverse→");
stderr.writeln(result);
}
result=functionDefSemantic(result,sc);
if(result.sstate==SemState.passive) result.setSemCompleted(); // TODO: ok?
enforce(result.isSemCompleted(),text("semantic errors while reversing function"));
if(equal(fd.ftype.isConst,only(true,false))) result.reversed=fd; // TODO: fix condition
fd.reversed=result;
return result;
}
enum ComputationClass{
bottom,
classical,
quantum,