forked from silq-lang/silq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qsim.d
2512 lines (2490 loc) · 84.3 KB
/
qsim.d
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
import std.conv: text, to;
import std.string: split;
import std.algorithm;
import std.array: array;
import std.range: iota, zip, repeat, walkLength;
import std.string: startsWith,join;
import std.typecons: q=tuple,Q=Tuple;
import std.exception: enforce;
import options;
import astopt;
import util.hashtable,util;
import ast.expression,ast.declaration,ast.type;
import ast.lexer,ast.semantic_,ast.reverse,ast.scope_,ast.error;
import util;
import std.random, sample;
import std.complex, std.math;
class LocalizedException: Exception{
Location loc;
Location[] stackTrace;
this(Exception e,Location loc){
super(e.msg,e.file,e.line,e);
this.loc=loc;
}
}
LocalizedException localizedException(Exception e,Location loc){
if(auto r=cast(LocalizedException)e) return r;
return new LocalizedException(e,loc);
}
version=LOCALIZE;
version(LOCALIZE){}else pragma(msg,"NOTE: error messages not formatted");
class QSim{
this(string sourceFile){
this.sourceFile=sourceFile;
}
QState run(FunctionDef def,ErrorHandler err){
if(def.params.length){
err.error("main function with parameters not supported in simulator",def.loc);
return QState.empty();
}
/+DExpr[string] fields;
foreach(i,a;def.params) fields[a.getName]=dVar(a.getName);
DExpr init=dRecord(fields);+/
auto init=QState.unit();
auto interpreter=Interpreter!QState(def,def.body_,init,false);
auto ret=QState.empty();
try{
interpreter.runFun(ret);
}catch(LocalizedException ex){
err.error(ex.msg,ex.loc);
foreach(loc;ex.stackTrace)
err.note("called from here",loc);
return QState.empty();
}
assert(!!def.ftype);
bool isTuple = !!def.ftype.cod.isTupleTy;
return ret;
}
private:
string sourceFile;
}
private alias FormattingOptions=QState.Value.FormattingOptions;
private alias FormattingType=QState.Value.FormattingOptions.FormattingType;
string formatQValue(QState qs,QState.Value value){ // (only makes sense if value contains the full quantum state)
if(value.isClassical()) return value.toStringImpl(FormattingOptions.init);
string r;
foreach(k,v;qs.state){
if(r.length) r~="+";
r~=text("(",v,")·",value.classicalValue(k).toBasisStringImpl());
}
if(!r.length) return "0";
return r;
}
long smallValue(ℤ value){
if(long.min<=value&&value<=long.max) return to!long(value);
enforce(0,"value too large");
assert(0);
}
enum zeroThreshold=1e-15; // TODO: make configurable
bool isToplevelClassical(Expression ty)in{
assert(!!ty);
}do{
return ty.isClassical()||cast(TupleTy)ty||cast(ArrayTy)ty||cast(VectorTy)ty||cast(ContextTy)ty||cast(ProductTy)ty;
}
void hadamardUnitary(alias add,QState)(QState.Value x){
alias C=QState.C;
enforce(x.tag==QState.Value.Tag.bval);
enum norm=C(sqrt(1.0/2.0));
if(!x.bval){ add(x,norm); add(x.eqZ,norm); }
else{ add(x.eqZ,norm); add(x,-norm); }
}
void xUnitary(alias add,QState)(QState.Value x){
alias C=QState.C;
enforce(x.tag==QState.Value.Tag.bval);
add(x.eqZ,C(1.0));
}
void yUnitary(alias add,QState)(QState.Value x){
alias C=QState.C;
enforce(x.tag==QState.Value.Tag.bval);
add(x.eqZ,C(0.0,x.eqZImpl?1.0:-1.0));
}
void zUnitary(alias add,QState)(QState.Value x){
alias C=QState.C;
enforce(x.tag==QState.Value.Tag.bval);
add(x,C(x.eqZImpl?1.0:-1.0));
}
// (string mixin as workaround for DMD compiler bug)
enum rotUnitary(string D)=mixin(X!q{
void r@(D)Unitary(alias add,QState)(QState.Value x,QState.R φ){
alias C=QState.C;
enforce(x.tag==QState.Value.Tag.bval);
add(x,C(cos(0.5*φ),0.0));
@(lowerf(D))Unitary!((k,v)=>add(k,C(0.0,-sin(0.5*φ))*v))(x);
}
});
mixin(rotUnitary!"X");
mixin(rotUnitary!"Y");
mixin(rotUnitary!"Z");
struct QState{
MapX!(Σ,C) state;
Record vars;
QVar[] popFrameCleanup;
static Value dupValue(Value v){
if(!v.type) return Value.init;
auto tt=v.tag;
if(tt==QState.Value.Tag.array_) v.array_=dupValue(v.array_);
if(tt==QState.Value.Tag.record) v.record=dupValue(v.record);
return v;
}
static Value[] dupValue(QState.Value[] r){
r=r.dup;
foreach(ref v;r) v=dupValue(v);
return r;
}
static Record dupValue(Record r){
r=r.dup;
foreach(k,ref v;r) v=dupValue(v);
return r;
}
string toString(){
FormattingOptions opt={type: FormattingType.dump};
string r="/────────\nQUANTUM STATE\n";
Q!(string,Σ.Sortable)[] vk;
foreach(k,v;state)
vk~=q(text("(",v,")·"),k.toSortable());
sort!"a[1]<b[1]"(vk);
if(state.length){
auto maxlen=vk.map!(x=>x[0].displayWidth).reduce!max;
foreach(ref t;vk) t[0]=text(' '.repeat(maxlen-t[0].displayWidth),t[0]);
}
bool first=true;
foreach(t;vk){
if(first){
first=false;
if(state.length>1) r~=" ";
}else r~="\n+";
r~=text(t[0],t[1].toStringImpl(opt));
}
r~="\n\nVARIABLES\n";
alias Mapping=Q!(string,Value);
Mapping[] mappings;
foreach(var,val;vars) mappings~=q(var,val);
bool special(string name){
return name.length&&name[0]=='`';
}
bool compare(Mapping a,Mapping b){
return q(special(a[0]),a[0])<q(special(b[0]),b[0]);
}
sort!compare(mappings);
foreach(i,t;mappings){
if(i&&special(t[0])&&!special(mappings[i-1][0]))
r~="\n";
r~=text(t[0]," ↦ ",t[1].toStringImpl(opt),"\n");
}
r~="────────/";
return r;
}
void dump(){
writeln(toString());
}
QState dup(){
return QState(state.dup,dupValue(vars),popFrameCleanup);
}
void copyNonState(ref QState rhs){
this.tupleof[1..$]=rhs.tupleof[1..$];
}
void add(Σ k,C v){
if(k in state) state[k]+=v;
else state[k]=v;
if(abs(state[k]) <= zeroThreshold) state.remove(k);
}
void updateRelabeling(ref Σ.Ref[Σ.Ref] relabeling,Value to,Value from){
if(!to.type) return;
auto tag=to.tag;
enforce(tag==from.tag);
final switch(tag){
case Value.Tag.array_:
enforce(to.array_.length==from.array_.length);
foreach(i;0..to.array_.length)
updateRelabeling(relabeling,to.array_[i],from.array_[i]);
break;
case Value.Tag.record:
foreach(k,v;to.record)
updateRelabeling(relabeling,v,from.record[k]);
break;
case Value.Tag.quval:
auto tquvar=cast(QVar)to.quval;
auto fquvar=cast(QVar)from.quval;
if(tquvar&&fquvar&&fquvar.ref_!=tquvar.ref_) relabeling[fquvar.ref_]=tquvar.ref_;
break;
case Value.Tag.closure:
/+if(to.closure.context&&from.closure.context)
updateRelabeling(relabeling,*to.closure.context,*from.closure.context);+/
break;
case Value.Tag.fval,Value.Tag.qval,Value.Tag.zval,Value.Tag.uintval,Value.Tag.intval,Value.Tag.bval:
break;
}
}
void opOpAssign(string op:"+")(QState r){
Σ.Ref[Σ.Ref] relabeling;
foreach(k,ref v;r.vars){
if(k in vars) updateRelabeling(relabeling,vars[k],v);
else vars[k]=v;
}
foreach(k,v;r.state){
k.relabel(relabeling);
add(k,v);
}
}
Q!(QState,QState) split(Value cond){
QState then,othw;
then.copyNonState(this);
othw.copyNonState(this);
othw.vars=dupValue(othw.vars);
if(cond.isClassical()){
if(cond.asBoolean) then=this;
else othw=this;
}else{
foreach(k,v;state){
if(cond.classicalValue(k).asBoolean) then.add(k,v);
else othw.add(k,v);
}
}
return q(then,othw);
}
QState map(alias f,bool checkInterference=true,T...)(T args){
QState new_;
new_.copyNonState(this);
foreach(k,v;state){
auto nk=f(k,args);
static if(checkInterference){
enforce(nk !in new_.state,"bad forget"); // TODO: good error reporting, e.g. for forget
new_.state[nk]=v;
}else new_.add(nk,v);
}
return new_;
}
alias R=double;
alias C=Complex!double;
static abstract class QVal{
override string toString(){ return text("_ (",typeid(this),")"); }
abstract Value get(ref Σ);
QVar dup(ref QState state,Value self){
auto nref_=Σ.curRef++;
state.assignTo(nref_,self);
return new QVar(nref_);
}
void forget(ref QState state,Value rhs){ }
void forget(ref QState state){ }
QVal consumeOnRead(){
return this;
}
Value toVar(ref QState state,Value self,bool cleanUp){
auto r=state.makeQVar(self);
if(cleanUp){
auto var=cast(QVar)r.quval;
assert(!!var);
state.popFrameCleanup~=var;
}
return r;
}
void removeVar(ref Σ σ){}
final Value applyUnitary(alias unitary,T...)(ref QState qs,Expression type,T controls){
// TODO: get rid of code duplication
QState nstate;
nstate.copyNonState(qs);
auto ref_=Σ.curRef++; // TODO: reuse reference of x if possible
foreach(k,v;qs.state){
void add(Value nk,C nv){
auto σ=k.dup;
σ.assign(ref_,nk);
removeVar(σ);
nstate.add(σ,nv*v);
}
unitary!(add,QState)(get(k),controls);
}
auto r=makeQuval(type,new QVar(ref_));
qs=nstate;
return r;
}
static Value applyUnitaryToClassical(alias unitary,T...)(ref QState qs,Value value,Expression type,T controls){
// TODO: get rid of code duplication
QState nstate;
nstate.copyNonState(qs);
auto ref_=Σ.curRef++; // TODO: reuse reference of x if possible
foreach(k,v;qs.state){
void add(Value nk,C nv){
auto σ=k.dup;
σ.assign(ref_,nk);
nstate.add(σ,nv*v);
}
unitary!(add,QState)(value,controls);
}
auto r=makeQuval(type,new QVar(ref_));
qs=nstate;
return r;
}
}
static class QConst: QVal{
Value constant;
override string toString(){ return constant.toStringImpl(FormattingOptions.init); }
this(Value constant){ this.constant=constant; }
override Value get(ref Σ){ return constant; }
}
static class QVar: QVal{
Σ.Ref ref_;
bool consumedOnRead=false;
override string toString(){ return text("ref(",ref_,")"); }
this(Σ.Ref ref_){ this.ref_=ref_; }
override Value get(ref Σ s){
if(astopt.allowUnsafeCaptureConst) enforce(ref_ in s.qvars, "dangling reference");
auto r=s.qvars[ref_];
if(consumedOnRead) removeVar(s);
return r;
}
override void removeVar(ref Σ s){
s.qvars.remove(ref_);
}
void assign(ref QState state,Value rhs){
state.assignTo(ref_,rhs);
}
override QVar dup(ref QState state,Value self){
if(consumedOnRead){ consumedOnRead=false; return this; }
return super.dup(state,self);
}
override void forget(ref QState state,Value rhs){
state.forget(ref_,rhs);
}
override void forget(ref QState state){
state.forget(ref_);
}
override QVar consumeOnRead(){
consumedOnRead=true;
return this;
}
override Value toVar(ref QState state,Value self,bool cleanUp){
if(consumedOnRead){
consumedOnRead=false;
if(cleanUp) state.popFrameCleanup~=this;
}
return self;
}
}
static class ConvertQVal: QVal{
Value value;
Expression ntype;
this(Value value,Expression ntype){ this.value=value; this.ntype=ntype.getClassical(); }
override Value get(ref Σ σ){ return value.classicalValue(σ).convertTo(ntype); }
override void removeVar(ref Σ σ){
value.removeVar(σ);
}
override void forget(ref QState state,Value rhs){
value.forget(state,rhs);
}
override void forget(ref QState state){
value.forget(state);
}
}
static class IndexQVal: QVal{
Value value,i;
this(Value value,Value i){ this.value=value; this.i=i; }
override Value get(ref Σ σ){ return value.classicalValue(σ)[i.classicalValue(σ)]; }
}
static class UnOpQVal(string op):QVal{
Value value;
this(Value value){ this.value=value; }
override Value get(ref Σ σ){ return value.classicalValue(σ).opUnary!op; }
}
static class BinOpQVal(string op):QVal{
Value l,r;
this(Value l,Value r){ this.l=l; this.r=r; }
override Value get(ref Σ σ){ return l.classicalValue(σ).opBinary!op(r.classicalValue(σ)); }
}
static class MemberFunctionQVal(string fun,T...):QVal{
Value value;
T args;
this(Value value,T args){ this.value=value; this.args=args; }
override Value get(ref Σ σ){ return mixin(`value.classicalValue(σ).`~fun)(args); }
}
static class FunctionQVal(alias fun,T...):QVal{
Value value;
T args;
this(Value value,T args){ this.value=value; this.args=args; }
override Value get(ref Σ σ){ return fun(value.classicalValue(σ),args); }
}
static class CompareQVal(string op):QVal{
Value l,r;
this(Value l,Value r){ this.l=l; this.r=r; }
override Value get(ref Σ σ){ return l.classicalValue(σ).compare!op(r.classicalValue(σ)); }
}
alias Record=HashMap!(string,Value,(a,b)=>a==b,(a)=>typeid(a).getHash(&a));
struct Closure{
FunctionDef fun;
Value* context;
this(FunctionDef fun,Value* context){
this.fun=fun; this.context=context;
}
hash_t toHash(){ return context?tuplex(fun,*context).toHash():fun.toHash(); }
bool opEquals(Closure rhs){ return fun==rhs.fun && (context is rhs.context || context&&rhs.context&&*context==*rhs.context); }
}
struct Value{
Expression type;
enum Tag{
array_,
record,
closure,
quval,
fval,
qval,
zval,
intval,
uintval,
bval,
}
static Tag getTag(Expression type){
assert(!!type);
if(cast(ArrayTy)type||cast(VectorTy)type||cast(TupleTy)type) return Tag.array_;
if(cast(ContextTy)type) return Tag.record;
if(cast(ProductTy)type) return Tag.closure;
if(!type.isClassical()){
assert(!type.isToplevelClassical());
return Tag.quval;
}
if(type==ℝ(true)) return Tag.fval;
if(type==ℚt(true)) return Tag.qval;
if(type==ℤt(true)) return Tag.zval;
if(type==Bool(true)) return Tag.bval;
if(type==typeTy) return Tag.bval; // TODO: ok?
if(isInt(type)) return Tag.intval;
if(isUint(type)) return Tag.uintval;
enforce(0,text("TODO: representation for type ",type," ",typeid(type)));
assert(0);
}
@property Tag tag(){
return getTag(type);
}
bool isValid(){ return !!type; }
void opAssign(Value rhs){
// TODO: make safe
type=rhs.type;
if(!type) return;
Lswitch:final switch(tag){
import std.traits:EnumMembers;
static foreach(t;EnumMembers!Tag)
case t: mixin(`this.`~text(t)~`=rhs.`~text(t)~`;`); break Lswitch;
}
}
Value dup(ref QState state){
final switch(tag){
static foreach(t;[Tag.fval,Tag.qval,Tag.zval,Tag.intval,Tag.uintval,Tag.bval])
case t: return this;
case Tag.closure:
return state.makeClosure(type,Closure(closure.fun,closure.context?[closure.context.dup(state)].ptr:null));
case Tag.array_: return state.makeArray(type,array_.map!(x=>x.dup(state)).array);
case Tag.record:
Record nrecord;
foreach(k,v;record) nrecord[k]=v.dup(state);
return state.makeRecord(type,nrecord);
case Tag.quval: return state.makeQuval(type,quval.dup(state,this));
}
}
Value toVar(ref QState state,bool cleanUp){
if(isClassical) return this;
final switch(tag){
static foreach(t;[Tag.fval,Tag.qval,Tag.zval,Tag.intval,Tag.uintval,Tag.bval])
case t: assert(0);
case Tag.closure:
return state.makeClosure(type,Closure(closure.fun,closure.context?[closure.context.toVar(state,cleanUp)].ptr:null));
case Tag.array_:
return makeArray(type,array_.map!(v=>v.toVar(state,cleanUp)).array); // TODO: this can be inefficient, avoid
case Tag.record: // TODO: get rid of this
Record nrecord;
foreach(k,v;record) nrecord[k]=v.toVar(state,cleanUp);
return state.makeRecord(type,nrecord);
case Tag.quval: return quval.toVar(state,this,cleanUp);
}
}
bool opEquals(Value rhs){
if(type!=rhs.type) return false;
if(!type) return true;
assert(tag==rhs.tag);
final switch(tag){
import std.traits:EnumMembers;
static foreach(t;EnumMembers!Tag){
case t: return mixin(`this.`~text(t)~`==rhs.`~text(t));
}
}
}
hash_t toHash(){
if(!type) return 0;
final switch(tag){
import std.traits:EnumMembers;
static foreach(t;EnumMembers!Tag)
case t: return tuplex(type,mixin(text(t))).toHash();
}
}
this(this){
if(!type) return;
auto tt=tag;
Lswitch:final switch(tt){
import std.traits:EnumMembers;
static foreach(t;EnumMembers!Tag)
case t: static if(__traits(hasMember,mixin(text(t)),"__postblit")) mixin(`this.`~text(t)~`.__postblit();`);
}
}
void assign(ref QState state,Value rhs){
if(!type){ this=rhs; return; }
if(isClassical()){
if(rhs.isClassical) this=rhs.dup(state);
else this=rhs.toVar(state,false);
return;
}
if(rhs.isClassical()){
Value nrhs;
nrhs.type=type;
nrhs.quval=new QConst(rhs);
return assign(state,nrhs);
}
assert(tag==rhs.tag);
Lswitch: final switch(tag){
static foreach(t;[Tag.fval,Tag.qval,Tag.zval,Tag.intval,Tag.uintval,Tag.bval])
case t: this=rhs; break Lswitch;
case Tag.closure:
closure.fun=rhs.closure.fun;
if(closure.context&&rhs.closure.context)
(*closure.context).assign(state,*rhs.closure.context);
return;
case Tag.array_:
enforce(rhs.tag==Tag.array_);
if(array_.length==rhs.array_.length){
foreach(i;0..array_.length)
array_[i].assign(state,rhs.array_[i]);
}else{
forget(state);
this=rhs.dup(state);
}
return;
case Tag.record:
enforce(rhs.tag==Tag.record);
bool ok=true;
foreach(k,v;rhs.record) if(k !in record) ok=false;
foreach(k,v;record) if(k !in rhs.record) ok=false;
if(ok) foreach(k,v;record) v.assign(state,rhs.record[k]);
else{
forget(state);
this=rhs.dup(state);
}
return;
case Tag.quval:
if(auto quvar=cast(QVar)quval) // TODO: ok?
return quvar.assign(state,rhs);
}
assert(0,text("can't assign to constant ",this," ",rhs));
}
void removeVar(ref Σ σ){
final switch(tag){
static foreach(t;[Tag.fval,Tag.qval,Tag.zval,Tag.intval,Tag.uintval,Tag.bval])
case t: assert(isClassical); return;
case Tag.closure:
if(closure.context) return closure.context.removeVar(σ);
return;
case Tag.array_:
foreach(i,ref x;array_) x.removeVar(σ);
return;
case Tag.record:
foreach(k,v;record) v.removeVar(σ);
return;
case Tag.quval:
return quval.removeVar(σ);
}
}
void forget(ref QState state,Value rhs){
final switch(tag){
static foreach(t;[Tag.fval,Tag.qval,Tag.zval,Tag.intval,Tag.uintval,Tag.bval])
case t: assert(isClassical); return;
case Tag.closure:
enforce(rhs.tag==Tag.closure);
if(closure.context) return closure.context.forget(state,*rhs.closure.context);
return;
case Tag.array_:
assert(rhs.tag==Tag.array_);
enforce(array_.length==rhs.array_.length,"inconsistent array lengths for forget"); // TODO: good error reporting
foreach(i,ref x;array_) x.forget(state,rhs.array_[i]);
return;
case Tag.record:
enforce(rhs.tag==Tag.record);
foreach(k,v;rhs.record) enforce(k in record);
foreach(k,v;record) v.forget(state,rhs.record[k]);
return;
case Tag.quval:
return quval.forget(state,rhs);
}
}
void forget(ref QState state){
// TODO: get rid of code duplication
final switch(tag){
static foreach(t;[Tag.fval,Tag.qval,Tag.zval,Tag.intval,Tag.uintval,Tag.bval])
case t: assert(isClassical); return;
case Tag.closure:
if(closure.context) return closure.context.forget(state);
return;
case Tag.array_:
foreach(i,ref x;array_) x.forget(state);
return;
case Tag.record:
foreach(k,v;record) v.forget(state);
return;
case Tag.quval:
return quval.forget(state);
}
}
Value consumeOnRead(){ // TODO: do this in-place
final switch(tag){
static foreach(t;[Tag.fval,Tag.qval,Tag.zval,Tag.intval,Tag.uintval,Tag.bval])
case t: assert(isClassical); return this;
case Tag.closure:
Closure nclosure=this.closure;
if(nclosure.context) *nclosure.context=(*closure.context).consumeOnRead();
return makeClosure(type,nclosure);
case Tag.array_: return makeArray(type,array_.map!(x=>x.consumeOnRead()).array);
case Tag.record:
Record nrecord;
foreach(k,v;record) nrecord[k]=v.consumeOnRead();
return makeRecord(type,nrecord);
case Tag.quval: return makeQuval(type,quval.consumeOnRead());
}
}
Value applyUnitary(alias unitary,T...)(ref QState qs,Expression type,T controls){
if(this.isClassical()) return QVal.applyUnitaryToClassical!unitary(qs,this,type,controls);
enforce(tag==Tag.quval);
return quval.applyUnitary!unitary(qs,type,controls);
}
union{
Value[] array_;
Record record;
Closure closure;
QVal quval;
R fval;
ℚ qval;
ℤ zval;
BitInt!true intval;
BitInt!false uintval;
bool bval;
ubyte[max(array_.sizeof,record.sizeof,quval.sizeof,fval.sizeof,qval.sizeof,zval.sizeof,bval.sizeof)] bits;
}
bool isClassical(){
final switch(tag){
static foreach(t;[Tag.fval,Tag.qval,Tag.zval,Tag.intval,Tag.uintval,Tag.bval])
case t: return true;
case Tag.closure:
if(closure.context) return (*closure.context).isClassical();
return true;
case Tag.array_: return array_.all!(x=>x.isClassical());
case Tag.record:
foreach(k,v;record) if(!v.isClassical()) return false;
return true;
case Tag.quval: return false;
}
}
bool isToplevelClassical(){
return type.isToplevelClassical();
}
Value convertTo(Expression ntype){
if(ntype==ℕt(true)) ntype=ℤt(true);
if(cast(Identifier)ntype) ntype=type;
// TODO: do this in-place?
auto otag=tag, ntag=getTag(ntype);
if(ntag==tag.quval){
if(isClassical()){
auto constant=convertTo(ntype.getClassical());
return makeQuval(ntype,new QConst(constant));
}else return makeQuval(ntype,new ConvertQVal(this,ntype));
}else if(isClassical()&&type==ntype) return this;
final switch(otag){
case Tag.array_:
if(ntag==Tag.array_){
if(auto tpl=ntype.isTupleTy()){
assert(array_.length==tpl.length);
return makeArray(ntype,iota(array_.length).map!(i=>array_[i].convertTo(tpl[i])).array);
}else if(auto arr=cast(ArrayTy)ntype){
return makeArray(ntype,array_.map!(v=>v.convertTo(arr.next)).array);
}else if(auto vec=cast(VectorTy)ntype){
return makeArray(ntype,array_.map!(v=>v.convertTo(vec.next)).array);
}else assert(0);
}
if(ntag==Tag.intval||ntag==Tag.uintval){
ℤ r=0;
foreach(i,ref v;array_){
assert(v.tag==Tag.bval);
if(v.bval) r+=ℤ(1)<<i;
}
if(ntag==Tag.intval) return makeInt(ntype,BitInt!true(array_.length,r));
return makeUint(ntype,BitInt!false(array_.length,r));
}
break;
case Tag.record:
break;
case Tag.closure:
assert(ntag==Tag.closure);
return makeClosure(ntype,closure);
case Tag.quval:
// can happen when converting from int[n]/uint[n] to array (TODO: store n classically?)
break;
case Tag.fval:
if(ntag==Tag.bval) return neqZ;
if(ntag==Tag.zval||ntag==Tag.qval){
static assert(R.sizeof*8==64);
auto r=fval.toℚ;
if(ntag==Tag.qval) return makeRational(r);
if(ntag==Tag.zval) return makeInteger(.floor(r));
}
if(ntag==Tag.fval) return this;
break;
case Tag.qval:
if(ntag==Tag.bval) return neqZ;
if(ntag==Tag.zval) return makeInteger(.floor(qval));
if(ntag==Tag.qval) return this;
if(ntag==Tag.fval) return makeReal(toReal(qval));
break;
case Tag.zval:
if(ntag==Tag.bval) return neqZ;
if(ntag==Tag.zval) return this;
if(ntag==Tag.qval) return makeRational(ℚ(zval));
if(ntag==Tag.fval) return makeReal(toReal(zval));
break;
case Tag.intval,Tag.uintval:
if(ntag==Tag.bval) return neqZ;
if(ntag==tag){
auto r=this;
r.type=ntype;
return r;
}
if(ntag==Tag.array_){
size_t nbits=0;
ℤ val=0;
if(otag==Tag.intval){
nbits=intval.nbits;
val=intval.val;
}else{
nbits=uintval.nbits;
val=uintval.val;
}
return makeArray(ntype.getClassical(),iota(nbits).map!(i=>makeBool(!!(val&(1<<i)))).array).convertTo(ntype);
}
break;
case Tag.bval:
if(ntag==Tag.bval) return this;
if(ntag==Tag.zval) return makeInteger(ℤ(cast(int)bval));
if(ntag==Tag.qval) return makeRational(ℚ(bval));
if(ntag==Tag.fval) return makeReal(to!R(bval));
}
if(ntag==Tag.bval) return neqZ;
enforce(0,text("TODO: convert ",type," to ",ntype));
assert(0);
}
Value inFrame(){
return this;
}
Value opIndex(ℤ i)in{
assert(tag==Tag.array_||isInt(type)||isUint(type));
}do{
final switch(tag){
case Tag.array_: enforce(0<=i&&i<array_.length,"index out of bounds"); return array_[to!size_t(i)];
case Tag.quval:
assert(isInt(type)||isUint(type));
return makeQuval(Bool(false),new IndexQVal(this,makeInteger(ℤ(i))));
case Tag.uintval:
enforce(0<=i&&i<uintval.nbits,"index out of bounds");
return makeBool((uintval.val&(ℤ(1)<<to!size_t(i)))!=0);
case Tag.intval:
enforce(0<=i,"index out of bounds");
if(i>=size_t.max) return makeBool(false);
return makeBool((intval.val&(ℤ(1)<<to!size_t(i)))!=0);
case Tag.fval,Tag.qval,Tag.zval,Tag.bval: enforce(0,"TODO?"); assert(0);
case Tag.record,Tag.closure: assert(0);
}
}
Value opIndex(Value i){
if(i.isℤ()) return this[i.asℤ()];
if(cast(ArrayTy)i.type||cast(VectorTy)i.type||cast(TupleTy)i.type){
if(cast(TupleTy)type){
auto values=i.array_.map!(v=>this[v]).array;
auto ntype=tupleTy(values.map!(v=>v.type).array);
return makeTuple(ntype,values);
}
auto values=i.array_.map!(v=>this[v]).array;
auto ntype=!values.length?ast.type.unit:values.map!(v=>v.type).fold!joinTypes;
if(cast(ArrayTy)i.type) ntype=arrayTy(ntype);
if(auto vt=cast(VectorTy)i.type) ntype=vectorTy(ntype,vt.num);
return makeArray(arrayTy(ntype),values);
}
final switch(tag){
case Tag.array_:
// TODO: bounds checking
Value build(Value[] array_,size_t offset){ // TODO: this is a hack
if(array_.length==1) return array_[0];
auto cond=i.compare!"<"(makeInteger(ℤ(offset+array_.length/2)));
return ite(cond,build(array_[0..$/2],offset),build(array_[$/2..$],offset+array_.length/2));
}
enforce(array_.length,"array index out of bounds");
return build(array_,0);
case Tag.uintval,Tag.intval,Tag.quval:
assert(isInt(type)||isUint(type));
return makeQuval(Bool(false),new IndexQVal(this,i));
case Tag.fval,Tag.qval,Tag.zval,Tag.bval: enforce(0,"TODO?"); assert(0);
case Tag.record,Tag.closure: assert(0);
}
}
Value opSlice(ℤ l,ℤ r)in{
assert(tag==Tag.array_);
}do{
enforce(r<=array_.length,"slice upper bound exceeds array length");
enforce(l<=r,"slice lower bound exceeds slice upper bound");
return makeArray(type,array_[to!size_t(l)..to!size_t(r)]);
}
Value opSlice(Value l,Value r){
if(l.isℤ()&&r.isℤ()) return this[l.asℤ()..r.asℤ()];
enforce(0,text("TODO: slicing for types ",this.type,", ",l.type," and ",r.type));
assert(0);
}
static Expression unaryType(string op)(Expression t){
static if(op=="-") return minusType(t);
else static if(op=="~") return bitNotType(t);
else static if(op=="!") return handleUnary!notType(t);
else{
enforce(0,text("TODO: '",op,"' for type ",t));
assert(0);
}
}
Value opUnary(string op)(){
auto ntype=unaryType!op(type);
if(!ntype.isToplevelClassical()) return makeQuval(ntype,new UnOpQVal!op(this));
static if(op=="-"||op=="~"){
static if(is(typeof(mixin(op~` fval`))))
if(type==ℝ(true)) return makeReal(mixin(op~` fval`));
static if(is(typeof(mixin(op~` qval`))))
if(type==ℚt(true)) return makeRational(mixin(op~` qval`));
static if(is(typeof(mixin(op~` zval`))))
if(type==ℤt(true))
return makeInteger(mixin(op~` zval`)); // TODO: wraparound
if(isInt(type)) return makeInt(type,mixin(op~` intval`));
if(isUint(type)) return makeUint(type,mixin(op~` uintval`));
if(type==Bool(true)){
static if(op=="~") return makeBool(!bval);
else return makeInteger(mixin(op~` ℤ(cast(int)bval)`));
}
}else static if(op=="!"){
if(type==ℝ(true)) return makeBool(mixin(op~` fval`));
if(type==ℚt(true)) return makeBool(mixin(op~` qval`));
if(type==ℤt(true)) return makeBool(mixin(op~` zval`));
if(type==Bool(true)) return makeBool(mixin(op~` bval`));
}
enforce(0,text("TODO: '",op,"' for type ",this.type));
assert(0);
}
static Expression binaryType(string op)(Expression t1,Expression t2){
static if(op=="+") return arithmeticType!false(t1,t2);
else static if(op=="-") return subtractionType(t1,t2);
else static if(op=="sub") return nSubType(t1,t2);
else static if(op=="*") return arithmeticType!true(t1,t2);
else static if(op=="/") return divisionType(t1,t2);
else static if(op=="div") return iDivType(t1,t2);
else static if(op=="%") return moduloType(t1,t2);
else static if(op=="^^") return powerType(t1,t2);
else static if(op=="|") return arithmeticType!true(t1,t2);
else static if(op=="^") return arithmeticType!true(t1,t2);
else static if(op=="&") return arithmeticType!true(t1,t2);
else static if(op=="~") return t1; // TODO: add function to semantic instead
else static if(op=="<<"||op==">>") return arithmeticType!false(arithmeticType!false(t1,t1),t2); // TODO: add function to semantic instead
else{
enforce(0,text("TODO: '",op,"' for types ",t1," and ",t2));
assert(0);
}
}
Value opBinary(string op)(Value r){
// % does not work for ℚ
// |,& don't work for ℚ, ℝ
// ^^ needs special handling
// ~ needs special handling
auto ntype=binaryType!op(type,r.type);
if(!ntype) ntype=type; // TODO: this is a hack
if(ntype==ℕt(true)) ntype=ℤt(true);
if(!ntype.isToplevelClassical()) return makeQuval(ntype,new BinOpQVal!op(this,r));
assert(!!ntype);
static if(op=="^^"){
auto t1=type,t2=r.type;
if(t1==Bool(true)&&isSubtype(t2,ℕt(true))) return makeBool(asBoolean||!r.asBoolean);
//if(cast(ℂTy)t1||cast(ℂTy)t2) return t1^^t2; // ?
if(util.among(t1,Bool(true),ℕt(true),ℤt(true),ℚt(true))&&isSubtype(t2,ℤt(false))){
auto p=r.asℤ();
if(t1!=ℚt(true)&&p>=0) return makeInteger(pow(asℤ(),p)); // TODO: this is a hack
return makeRational(pow(asℚ(),p));
}
if(type==Bool(true)) return makeBool(asBoolean||r.asBoolean);
if(t1!=ℝ(true)||t2!=ℝ(true))
return convertTo(ℝ(true))^^r.convertTo(ℝ(true));
return makeReal(fval^^r.fval);
}else static if(op=="~"){
enforce(tag==Tag.array_&&r.tag==Tag.array_);
return makeArray(ntype,array_~r.array_);
}else static if(op=="<<"||op==">>"){
if(type==ℤt(true)) return makeInteger(mixin(`zval `~op~` smallValue(r.asℤ())`));
if(type==Bool(true)) return makeInteger(mixin(`ℤ(cast(int)bval) `~op~` smallValue(r.asℤ())`));
if(isInt(type)) return makeInt(type,mixin(`intval `~op~` smallValue(r.asℤ())`));
if(isUint(type)) return makeUint(type,mixin(`uintval `~op~` smallValue(r.asℤ())`));
}else{
if(type!=ntype||r.type!=ntype){
if(type==ntype&&util.among(r.type,Bool(true),ℤt(true))){
static if(op=="%"){
alias abs=util.abs;
if(isInt(type)){
auto rz=abs(r.asℤ);
return makeInt(ntype,BitInt!true(intval.nbits,(intval.val%rz+rz)%rz));
}
if(isUint(type)){
auto rz=abs(r.asℤ);
return makeUint(ntype,BitInt!false(uintval.nbits,uintval.val%rz));
}
}else{
if(isInt(type)) return this.opBinary!op(makeInt(ntype,BitInt!true(intval.nbits,r.asℤ())));
if(isUint(type)) return this.opBinary!op(makeUint(ntype,BitInt!false(uintval.nbits,r.asℤ())));
}
}else if(type==ℤt(true)&&r.type==ntype){
if(isInt(r.type)) return makeInt(ntype,BitInt!true(r.intval.nbits,asℤ())).opBinary!op(r);
if(isUint(r.type)) return makeUint(ntype,BitInt!false(r.uintval.nbits,asℤ())).opBinary!op(r);
// TODO: rat
}
return this.convertTo(ntype).opBinary!op(r.convertTo(ntype));
}
static if(op=="/") enforce(!r.eqZImpl,"division by zero");
static if(op=="%"){ // TODO: make more efficient
if(type==ℝ(true)) return makeReal(((fval%abs(r.fval))+abs(r.fval))%abs(r.fval)); // TODO: make numerically sound
alias abs=util.abs;
alias floor=util.floor;
if(type==ℚt(true)) return makeRational(qval-ℚ(floor(qval/r.qval))*r.qval);
if(type==ℤt(true)) return makeInteger((zval%abs(r.zval)+abs(r.zval))%abs(r.zval));
if(isInt(type)) return makeInt(ntype,(intval%abs(r.intval)+abs(r.intval))%abs(r.intval));
if(isUint(type)) return makeUint(ntype,uintval%r.uintval);
}else{
static if(is(typeof(mixin(`fval `~op~` r.fval`))))
if(type==ℝ(true)) return makeReal(mixin(`fval `~op~` r.fval`));
static if(is(typeof(mixin(`qval `~op~` r.qval`))))
if(type==ℚt(true)) return makeRational(mixin(`qval `~op~` r.qval`));
static if(is(typeof(mixin(`zval `~op~` r.zval`))))
if(type==ℤt(true)) return makeInteger(mixin(`zval `~op~` r.zval`));
static if(is(typeof(mixin(`intval `~op~` r.intval`))))
if(isInt(type)) return makeInt(ntype,mixin(`intval `~op~` r.intval`));
static if(is(typeof(mixin(`uintval `~op~` r.uintval`))))
if(isUint(type)) return makeUint(ntype,mixin(`uintval `~op~` r.uintval`));
}
static if(op=="div"){
enforce(!r.eqZImpl,"division by zero");
final switch(tag){
case Tag.fval: return (this/r).floor();
case Tag.qval: return makeInteger(.floor(qval/r.qval));
case Tag.zval: return makeInteger(floordiv(zval,r.zval));
case Tag.intval: return makeInt(type,BitInt!true(intval.nbits,floordiv(intval.val,r.intval.val)));
case Tag.uintval: return makeUint(ntype,uintval/r.uintval);
case Tag.bval: return makeInteger(ℤ(bval/r.bval));
case Tag.closure,Tag.array_,Tag.record,Tag.quval: break;
}
}
static if(is(typeof((bool a,bool b){ bool c=mixin(`a `~op~` b`); })))
if(type==Bool(true)&&r.type==Bool(true)) return makeBool(mixin(`bval `~op~` r.bval`));
}
enforce(0,text("TODO: '",op,"' for types ",this.type," and ",r.type));