Repository navigation
Expand file tree
/
Copy pathreverse.d
More file actions
4528 lines (4477 loc) · 237 KB
/
Copy pathreverse.d
File metadata and controls
4528 lines (4477 loc) · 237 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 ast.callfailure: explainArgumentCount;
import ast.conversion: typeExplicitConversion;
import util.tuple:Q=Tuple,q=tuple;
import util: SetX;
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;
}
bool isForgettableCallLhs(CallExp ce){
if(auto ft=cast(FunTy)ce.e.type){
bool base=ft.isSquare==ce.isSquare&&ft.annotation>=Annotation.qfree&&(ft.nargs||isEmptyTuple(ce.arg));
static if(language==silq) return base&&(ft.isConstForReverse.all||isClassicalExp(ce));
else return base&&ft.isConstForReverse.all;
}
return false;
}
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 knownLength(fwd,ignoreType);
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&&id.meaning.isConst) // (a copy is analyzed again)
return false;
}else return false;
}
return cast(Identifier)e||cast(IndexExp)e||cast(SliceExp)e;
}
if(auto tpl=cast(TupleExp)olhs){
if(noImplicitDup){
static bool writesBack(Expression e){
auto id=cast(Identifier)unwrap(e);
return id&&id.meaning;
}
if(tpl.e.any!writesBack) return false;
}
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;
static if(language==silq){
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]));
}
if(auto tae=cast(TypeAnnotationExp)olhs){
if(tae.annotationType==TypeAnnotationType.coercion&&cast(CallExp)tae.e
&&validDefLhs!flags(tae.e,sc,unchecked,noImplicitDup))
return true;
}
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,bool defer=false,Id[2][] old=null,NeedOld* needOld=null)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,defer);
static if(language==silq&&(flags&LowerDefineFlags.reverseMode)) if(auto fwd=le.isForward(true)){ // (`let{ x:=e; forget(…); } in x`: recomputes the forgotten variables, then reverses `e`, see `resolveForgets`)
Expression[] r;
auto tpl=new TupleExp([]);
tpl.type=unit;
tpl.loc=loc;
foreach_reverse(t;le.s.s[1..$]) foreach_reverse(u;uncomputed(t)) r~=lowerDefine!flags(u,tpl,loc,sc,unchecked,noImplicitDup,defer);
r~=lowerDefine!flags(fwd,orhs,loc,sc,unchecked,noImplicitDup,defer,old,needOld);
auto res=new CompoundExp(r);
res.loc=loc;
return res;
}
}
if(auto le=cast(LetExp)orhs){
if(auto fwd=le.isForward(false))
return lowerDefine!flags(olhs,fwd,loc,sc,unchecked,noImplicitDup,defer);
}
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) return nlhs;
static if(language==silq) nlhs=reevaluationCopy(olhs); // (see `embeddedForgets`)
else nlhs=olhs.copy();
if(noImplicitDup){ // TODO: this is a hack
void removeImplicitDup(Expression e,Expression o,bool inCall){ // (`o`: the original of `e`)
if(cast(Identifier)e)
if(!inCall||!o.type||!o.type.isClassical()) // (a classical argument of a reversed call is an input of the reversal, it is checked)
e.implicitDup=false;
if(auto tae=cast(TypeAnnotationExp)e){
removeImplicitDup(tae.e,(cast(TypeAnnotationExp)o).e,inCall);
}else if(auto tpl=cast(TupleExp)e){
foreach(i,ne;tpl.e)
removeImplicitDup(ne,(cast(TupleExp)o).e[i],inCall);
}else if(auto let=cast(LetExp)e){
if(auto fwd=let.isForward(false))
if(auto ofwd=(cast(LetExp)o).isForward(false))
removeImplicitDup(fwd,ofwd,inCall);
}else if(auto ce=cast(CallExp)e){
removeImplicitDup(ce.arg,(cast(CallExp)o).arg,true);
}
}
removeImplicitDup(nlhs,olhs,false);
}
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(language==silq&&reverseMode) if(auto le=cast(LambdaExp)olhs){ // (uncomputes the copies of the quantum values that it captures, as for a local function)
auto captureAnnotation=le.fd.ftype?le.fd.ftype.captureAnnotation:le.fd.getCaptureAnnotation();
if(captureAnnotation==CaptureAnnotation.const_) return res=new ForgetExp(rhs,olhs.copy());
}
static if(reverseMode){
if(!noImplicitDup&&cast(Identifier)olhs&&olhs.type&&olhs.type.isClassical()){
lhs.implicitDup=true;
(cast(Identifier)lhs).moved=false; // (the classical value is checked, it remains available)
}
}
static if(language==silq){
if(auto le=cast(LetExp)olhs){
if(!le.isForward(true)){
static if(reverseMode) if(recomputable(le)) return res=new ForgetExp(rhs,lhs); // (e.g., for a conditional in it whose branches forget its locals)
return res=lowerLetDefine(le,rhs,loc,sc,old,needOld);
}
}
}
static if(language==silq&&reverseMode){
auto bare=olhs;
for(auto tae=cast(TypeAnnotationExp)bare;tae;tae=cast(TypeAnnotationExp)bare) bare=tae.e;
bool lowered=cast(LetExp)bare||cast(IteExp)bare&&olhs.isSemCompleted(); // (a `let` expression, as above, or an analyzed conditional, also with type annotations: their blocks may forget variables that the reversal recomputes, see below)
}else enum lowered=false;
if(defer&&!cast(ForgetExp)olhs&&!lowered){
static if(language==silq) return res=new DefineExp(reevaluationCopy(olhs),rhs); // (keeps implicit duplications of analyzed statements)
else return res=new DefineExp(olhs.copy(),rhs); // (keeps implicit duplications of analyzed statements)
}
bool classicalReverse=false;
static if(language==silq&&!(flags&LowerDefineFlags.reverseMode)) classicalReverse=isClassicalReverseCall(olhs,orhs);
if(!classicalReverse&&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){
static if(language==silq) auto newLhs=new TupleExp((cast(VectorExp)reevaluationCopy(vec)).e);
else 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)=>temporaryIdentifier(orhs.loc)).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(cast(Identifier)olhs?isLiftedBuiltIn(olhs):isLiftedBuiltIn(lhs)){
static if(createFresh){ // (`dup(e):=x` forgets `x` with the value of `e`, which the forget only reads, e.g., `forget(x=v[0])` for an implicit duplication of a component in a branch of a `with` transformation: a copy would remain)
for(auto e=lhs;;){
e.implicitDup=false;
auto tae=cast(TypeAnnotationExp)e;
if(!tae) break;
e=tae.e;
}
}
return forget();
}
static if(reverseMode) if(auto fe=cast(FieldExp)olhs) if(fe.type&&fe.type.isClassical()) return forget(); // (e.g., the reversal of `t:=f(x).length`, which checks the value)
if(auto ce=cast(CallExp)olhs){
if(isForgettableCallLhs(ce))
return forget();
}
if(auto tae=cast(TypeAnnotationExp)olhs){
if(auto ce=cast(CallExp)tae.e) if(tae.type&&ce.type&&!typeExplicitConversion(tae.type,ce.type,TypeAnnotationType.coercion)){ // (only the reversed call classicalizes: moved non-entry arguments are defined through temporaries)
Expression[] unpacks;
Expression entry(Expression arg){
if(cast(Identifier)arg||cast(IndexExp)arg||cast(SliceExp)arg) return arg;
auto tmp=new Identifier(freshName);
tmp.loc=arg.loc;
auto use=tmp.copy();
use.moved=true;
unpacks~=lowerDefine!flags(arg,use,loc,sc,unchecked,noImplicitDup);
return tmp;
}
Expression nce=ce;
auto ft=cast(FunTy)ce.e.type, tpl=cast(TupleExp)ce.arg;
if(ft&&ft.isSquare==ce.isSquare){
Expression narg=ce.arg;
if(!ft.isConstForReverse.any) narg=entry(ce.arg);
else if(tpl&&!ft.isConstForReverse.all&&tpl.length==ft.nargs){
narg=new TupleExp(iota(tpl.length).map!(i=>ft.isConstForReverse[i]?tpl.e[i]:entry(tpl.e[i])).array);
narg.loc=tpl.loc;
}
if(unpacks.length){
nce=new CallExp(ce.e,narg,ce.isSquare,ce.isClassical_);
nce.loc=ce.loc;
}
}
auto def=lowerDefine!flags(nce,orhs,loc,sc,unchecked,noImplicitDup);
if(!unpacks.length) return def;
return res=new CompoundExp([def]~unpacks);
}
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,defer,old,needOld);
}else return lowerDefine!flags(tae.e,orhs,loc,sc,unchecked,noImplicitDup,defer,old,needOld);
}
}
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,defer,old,needOld);
}
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&&(noImplicitDup||!ue1.implicitDup),valid2=cast(Identifier)ue2&&(noImplicitDup||!ue2.implicitDup); // (consistent with `validDefLhs`)
if(!valid1){
auto tmpe1=new Identifier(freshName);
tmpe1.loc=ce.e1.loc;
auto use1=tmpe1.copy();
use1.moved=true;
stmts~=lowerDefine!flags(ne1,use1,loc,sc,unchecked,noImplicitDup);
ne1=tmpe1.copy();
ne1.loc=ce.e1.loc;
}
if(!valid2){
auto tmpe2=new Identifier(freshName);
tmpe2.loc=ce.e2.loc;
auto use2=tmpe2.copy();
use2.moved=true;
stmts~=lowerDefine!flags(ne2,use2,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;
auto tae1=new TypeAnnotationExp(ne1,ty1,TypeAnnotationType.coercion);
tae1.fromElaboration=true;
ne1=tae1;
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;
auto tae2=new TypeAnnotationExp(ne2,ty2,TypeAnnotationType.coercion);
tae2.fromElaboration=true;
ne2=tae2;
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,reevaluationCopy(fe.val),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,defer);
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);
explainAnnotation(sc,ce.e,Annotation.mfree);
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{
explainArgumentCount(ce,ft,tpl.length,sc);
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);
}
static if(language==silq)
if(auto vfe=cast(VectorForExp)olhs){
static Expression dupVariableUses(Expression e,SetX!Id names,Scope sc){ // TODO: this is a hack
Expression dupWrap(Expression e){
auto ce=new CallExp(getDup(e.loc,sc),e,false,false);
ce.loc=e.loc;
return ce;
}
Expression rec(Expression e,out bool known){
known=false;
if(!e) return e;
Expression recWrap(Expression e){
bool k;
auto r=rec(e,k);
return k?dupWrap(r):r;
}
if(auto id=cast(Identifier)e){
known=!!(id.id in names);
return e;
}
if(cast(LiteralExp)e){
known=true;
return e;
}
if(auto tpl=cast(TupleExp)e){
auto ks=new bool[](tpl.e.length);
foreach(i,ref x;tpl.e) x=rec(x,ks[i]);
if(tpl.e.length&&ks.all){ known=true; return e; }
foreach(i,ref x;tpl.e) if(ks[i]) x=dupWrap(x);
return e;
}
if(auto vec=cast(VectorExp)e){
auto ks=new bool[](vec.e.length);
foreach(i,ref x;vec.e) x=rec(x,ks[i]);
if(vec.e.length&&ks.all){ known=true; return e; }
foreach(i,ref x;vec.e) if(ks[i]) x=dupWrap(x);
return e;
}
if(auto ce=cast(CallExp)e){
ce.e=recWrap(ce.e);
if(!ce.isSquare){
if(auto tpl=cast(TupleExp)ce.arg){
foreach(ref x;tpl.e) x=recWrap(x);
}else ce.arg=recWrap(ce.arg);
}
return e;
}
if(auto tae=cast(TypeAnnotationExp)e){
tae.e=rec(tae.e,known);
return e;
}
if(auto idx=cast(IndexExp)e){
bool ke,ka;
idx.e=rec(idx.e,ke);
idx.a=rec(idx.a,ka);
known=ke&&ka;
if(!known&&ke) idx.e=dupWrap(idx.e);
return e;
}
if(auto sl=cast(SliceExp)e){
bool ke;
sl.e=rec(sl.e,ke);
known=ke;
return e;
}
if(auto ue=cast(AUnaryExp)e){
ue.e=rec(ue.e,known);
return e;
}
if(auto be=cast(ABinaryExp)e){
bool k1,k2;
be.e1=rec(be.e1,k1);
be.e2=rec(be.e2,k2);
known=k1&&k2;
if(!known){
if(k1) be.e1=dupWrap(be.e1);
if(k2) be.e2=dupWrap(be.e2);
}
return e;
}
if(auto nvfe=cast(VectorForExp)e){
bool shadowed=nvfe.fe.var&&nvfe.fe.var.id in names;
if(nvfe.fe.pattern) nvfe.fe.pattern.freeVarsImpl((id){ if(id.id in names) shadowed=true; return 0; });
if(auto nrange=nvfe.fe.aggr.isRange){
nrange.left=recWrap(nrange.left);
if(nrange.step) nrange.step=recWrap(nrange.step);
nrange.right=recWrap(nrange.right);
}else if(auto ncnt=nvfe.fe.aggr.isContainer())
ncnt.e=recWrap(ncnt.e);
if(!shadowed){
bool kb;
nvfe.fe.bdy.s[0]=rec(nvfe.fe.bdy.s[0],kb);
}
return e;
}
return e;
}
bool k;
auto r=rec(e,k);
return k?dupWrap(r):r;
}
if(auto range=vfe.fe.aggr.isRange){
auto restId=new Identifier(freshName());
restId.loc=orhs.loc;
auto restDef=new DefineExp(restId,rhs);
restDef.loc=loc;
auto xId=new Identifier(freshName());
xId.loc=vfe.fe.bdy.s[0].loc;
auto xTpl=new TupleExp([cast(Expression)xId]);
xTpl.loc=xId.loc;
auto peelLhs=new CatExp(xTpl,restId.copy());
peelLhs.loc=xId.loc;
auto restUse=restId.copy();
restUse.moved=true;
auto peel=new DefineExp(peelLhs,restUse);
peel.loc=xId.loc;
auto bodyLhs=vfe.fe.bdy.s[0].copy();
SetX!Id loopVarNames;
if(vfe.fe.var) loopVarNames[vfe.fe.var.id]=[];
if(vfe.fe.pattern) vfe.fe.pattern.freeVarsImpl((id){ loopVarNames[id.id]=[]; return 0; });
bodyLhs=dupVariableUses(bodyLhs,loopVarNames,sc);
auto xUse=xId.copy();
xUse.moved=true;
auto bodyDef=new DefineExp(bodyLhs,xUse);
bodyDef.loc=bodyLhs.loc;
auto lbdy=new CompoundExp([cast(Expression)peel,bodyDef]);
lbdy.loc=vfe.fe.bdy.loc;
auto nrange=ForRange(range.leftExclusive,range.left.copy(),range.step?range.step.copy():null,range.rightExclusive,range.right.copy());
auto nvar=vfe.fe.var?vfe.fe.var.copy():null;
auto npat=vfe.fe.pattern?vfe.fe.pattern.copy():null;
auto nfe=new ForExp(nvar,npat,ForAggregate(nrange),lbdy);
nfe.loc=vfe.fe.loc;
auto unit=new TupleExp([]);
unit.loc=loc;
auto restFin=restId.copy();
restFin.moved=true;
auto fin=new DefineExp(unit,restFin);
fin.loc=loc;
return res=new CompoundExp([restDef,cast(Expression)nfe,fin]);
}else if(auto cnt=vfe.fe.aggr.isContainer()){
auto yid=new Identifier(freshName());
yid.loc=orhs.loc;
auto bodyLhs=vfe.fe.bdy.s[0].copy();
auto yuse=yid.copy();
yuse.loc=orhs.loc;
yuse.moved=true;
auto inner=new DefineExp(bodyLhs,yuse);
inner.loc=vfe.fe.bdy.s[0].loc;
Expression result;
if(vfe.fe.pattern) result=vfe.fe.pattern.copy();
else{
assert(!!vfe.fe.var);
result=vfe.fe.var.copy();
}
result.loc=vfe.fe.pattern?vfe.fe.pattern.loc:vfe.fe.var.loc;
auto lstm=new CompoundExp([cast(Expression)inner]);
lstm.loc=inner.loc;
auto letExp=new LetExp(lstm,result);
letExp.loc=inner.loc;
auto nbdy=new CompoundExp([cast(Expression)letExp]);
nbdy.loc=vfe.fe.bdy.loc;
auto nfe=new ForExp(yid,null,ForAggregate(ForContainer(rhs)),nbdy);
nfe.loc=vfe.fe.loc;
auto nvfe=new VectorForExp(nfe);
nvfe.loc=loc;
return lowerDefine!flags(cnt.e,nvfe,loc,sc,unchecked,noImplicitDup);
}else{
sc.error("aggregate not supported in vector comprehension on definition left-hand side",vfe.fe.aggr.loc);
return error();
}
}
if(auto we=cast(WildcardExp)olhs){
auto tmp=temporaryIdentifier(orhs.loc);
auto de=new DefineExp(tmp,rhs);
de.loc=rhs.loc;
auto fe=new ForgetExp(tmp.copy(),null);
fe.loc=loc;