-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinterpret.d
6478 lines (6062 loc) · 198 KB
/
interpret.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
// Written in the D programming language
// Author: Timon Gehr
// License: http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0
import lexer, expression, semantic, scope_, type;
import util;
import std.string;
import std.conv: to;
import std.typecons : q=tuple, Q=Tuple;
import std.algorithm : max;
private template NotYetImplemented(T){
static if(is(T _==BinaryExp!S,TokenType S) || is(T==ABinaryExp) || is(T==AssignExp))
enum NotYetImplemented = false;
else static if(is(T _==UnaryExp!S,TokenType S)||is(T _==PostfixExp!S,TokenType S))
enum NotYetImplemented = false;
else enum NotYetImplemented = !is(T==Expression) && !is(T==ExpTuple) && !is(T:Type) && !is(T:Symbol) && !is(T==FieldExp) && !is(T:LiteralExp) && !is(T==CastExp) && !is(T==ArrayLiteralExp) && !is(T==IndexExp) && !is(T==SliceExp) && !is(T==TernaryExp) && !is(T==CallExp) && !is(T==UFCSCallExp) && !is(T==MixinExp) && !is(T==IsExp) && !is(T==AssertExp) && !is(T==LengthExp) && !is(T==PtrExp) && !is(T==DollarExp) && !is(T==CurrentExp) && !is(T==ThisExp) && !is(T==SuperExp) && !is(T==TemporaryExp) && !is(T==TmpVarExp) && !is(T==StructConsExp) && !is(T==NewExp);
}
enum IntFCEplg = mixin(X!q{needRetry = false; @(SemRet);});
template IntFCChldNoEplg(string s){
enum IntFCChldNoEplg = {
string r;
auto ss=s.split(",");
foreach(t; ss){
r~=mixin(X!q{
@(t)._interpretFunctionCalls(sc);
mixin(PropRetry!q{@(t)});
});
}
return r~PropErr!s;
}();
}
template IntFCChld(string s){
enum IntFCChld=IntFCChldNoEplg!s~IntFCEplg;
}
// should never be interpreted:
mixin template Interpret(T) if(is(T==MixinExp) || is(T==IsExp)){
override bool checkInterpret(Scope sc){assert(0);}
override void interpret(Scope sc){assert(0);}
override void _interpretFunctionCalls(Scope sc){assert(0);}
}
mixin template Interpret(T) if(is(T:Expression) && NotYetImplemented!T){
override void interpret(Scope sc){
assert(sc, "expression "~toString()~" was assumed to be interpretable");
sc.error(format("expression '%s' is not interpretable at compile time yet %s",toString(),typeid(this)),loc);
mixin(ErrEplg);
}
}
mixin template Interpret(T) if(is(T==Expression)){
final void prepareInterpret(){
weakenAccessCheck(AccessCheck.ctfe);
}
final void prepareLazyConditionalSemantic(){
static struct ApplyLazyConditionalSemantic{
void perform(BinaryExp!(Tok!"||") self){ self.lazyConditionalSemantic = true; }
void perform(BinaryExp!(Tok!"&&") self){ self.lazyConditionalSemantic = true; }
}
runAnalysis!ApplyLazyConditionalSemantic(this);
}
// scope may be null if it is evident that the expression can be interpreted
bool checkInterpret(Scope sc)in{assert(sstate == SemState.completed);}body{
assert(sc, loc.rep);
sc.error(format("%s '%s' is not interpretable at compile time",kind,loc.rep),loc);
mixin(SetErr!q{});
return false;
}
static int numint = 0;
void interpret(Scope sc)in{
assert(sstate == SemState.completed);
}body{
if(rewrite) return;
void fixupLocations(Expression r){
r.loc=loc;
r.type=type;
//pragma(msg, __traits(allMembers,ArrayLiteralExp)); // TODO: report bug
if(auto tl = isArrayLiteralExp()){
if(auto rl = r.isArrayLiteralExp())
copyLocations(rl,tl);
}
}
//assert(!numint);
if(isAConstant()) return;
if(!checkInterpret(sc)) mixin(ErrEplg);
_interpretFunctionCalls(sc);
auto x = this;
mixin(Rewrite!q{x});
fixupLocations(x);
if(this is x) mixin(SemCheck);
else mixin(SemProp!q{x});
auto r = x.interpretV().toExpr();
r.dontConstFold();
if(this is r) mixin(SemCheck);
fixupLocations(r);
assert(!isConstant() || !needRetry); // TODO: file bug, so that this can be 'out'
rewrite = null;
if(this !is r) mixin(RewEplg!q{r});
}
Variant interpretV()in{assert(sstate == SemState.completed, to!string(this));}body{
//return Variant.error(format("expression '%s' is not interpretable at compile time"),loc.rep);
return Variant("TODO: cannot interpret "~to!string(this)~" yet",Type.get!string());
//return Variant.init_;
}
final Expression cloneConstant()in{assert(!!isConstant()||isArrayLiteralExp());}body{
auto r = interpretV().toExpr();
r.type = type;
if(isArrayLiteralExp()){
assert(cast(LiteralExp)r);
r = (cast(LiteralExp)cast(void*)r).toArrayLiteral();
}
return r;
}
// for interpret.d internal use only, protection system cannot express this.
void _interpretFunctionCalls(Scope sc){}
}
// TODO: investigate the void[][] = [[[2]]]; case some more
void copyLocations(ArrayLiteralExp r, ArrayLiteralExp a){
assert(r.lit.length == a.lit.length);
foreach(i,x;a.lit){
r.lit[i].loc = x.loc;
if(auto rl = r.lit[i].isArrayLiteralExp()){
if(auto al = x.isArrayLiteralExp()){
copyLocations(rl, al);
}
}
}
}
mixin template Interpret(T) if(is(T==CastExp)){
override bool checkInterpret(Scope sc){
if(e.sstate != SemState.completed) return true;
bool sanityCheck(){
auto t1=e.type.getHeadUnqual(), t2=type.getHeadUnqual();
auto cvt1=t1, cvt2=t2;
if(auto e1=t1.isEnumTy()) cvt1=e1.decl.base;
if(auto e2=t2.isEnumTy()) cvt2=e2.decl.base;
assert(cvt1&&cvt2);
// TODO: comprehensive treatment of unique expressions
if(e.isUnique()) cvt1=t1.getUnqual(), cvt2=t2.getUnqual();
if(cvt1.equals(cvt2)) return true;
auto impld = cvt1.implicitlyConvertsTo(cvt2);
assert(!impld.dependee); // analysis has already determined this
if(impld.value||cvt1.isBasicType()&&cvt2.isBasicType()) return true;
auto t1u=t1.getUnqual();
if(t1u is Type.get!(void[])() && t2.isDynArrTy()||
t1u is Type.get!(void*)() && t2.isPointerTy())
return true;
auto le=e.isLiteralExp();
auto el = type.getElementType();
if(el&&le&&le.isPolyString()&&el.getHeadUnqual() !is Type.get!void())
return !!type.getHeadUnqual().isSomeString();
return false;
}
if(!sanityCheck()){
sc.error(format("cannot interpret cast from '%s' to '%s' at compile time",e.type,type),loc);
return false;
}
return e.checkInterpret(sc);
}
override Variant interpretV(){
auto le=e.isLiteralExp(); // polysemous string literals might be cast
auto el = type.getElementType();
if(el&&le&&le.isPolyString()&&el.getHeadUnqual() !is Type.get!void()){
auto vle=e.interpretV();
auto typeu = type.getHeadUnqual();
if(typeu.isSomeString()) return vle.convertTo(type);
// TODO: allocation ok?
Variant[] r = new Variant[vle.length];
foreach(i,ref x;r) x = vle[i].convertTo(el);
return Variant(r,r,type);
}else return e.interpretV().convertTo(type);
}
override void _interpretFunctionCalls(Scope sc){
mixin(IntFCChldNoEplg!q{e});
if(!invokedSemantic){
sstate=SemState.begin;
needRetry=false;
semantic(sc);
}
if(needRetry){ sstate=SemState.completed; return; }
invokedSemantic=true;
mixin(IntChld!q{e});
auto t1u=e.type.getUnqual(), t2=type.getHeadUnqual();
if(t1u is Type.get!(void[])() && t2.isDynArrTy()||
t1u is Type.get!(void*)() && t2.isPointerTy()){
auto cnt=e.interpretV().getContainer();
auto ty2=t2.isDynArrTy()?t2.getElementType():t2.isPointerTy().ty;
auto t1=null;
if(cnt.length){
auto ty1=cnt[0].getType();
mixin(RefConvertsTo!q{bool c; ty1, ty2, 0});
if(!c){
sc.error(format("cannot interpret cast from '%s' aliasing a '%s' to '%s' at compile time", e.type,t2.isDynArrTy()?ty1.getDynArr():ty1.getPointer(),type), loc); // TODO: 'an'
mixin(ErrEplg);
}
}
}
mixin(IntFCEplg);
}
private:
bool invokedSemantic=false;
}
mixin template Interpret(T) if(is(T==Type)){
override bool checkInterpret(Scope sc){return true;}
override void interpret(Scope sc){return this;}
}mixin template Interpret(T) if(!is(T==Type) && is(T:Type)){}
mixin template Interpret(T) if(is(T==Symbol)){
override bool checkInterpret(Scope sc){
if(meaning.sstate == SemState.error) return false;
if(isConstant()) return true;
return super.checkInterpret(sc);
}
override Variant interpretV(){
if(auto vd = meaning.isVarDecl()){
assert(meaning.sstate == SemState.completed);
assert(vd.init_, text(this," ",loc));
return vd.init_.interpretV();
}
assert(0);
}
override void _interpretFunctionCalls(Scope sc){
makeStrong(); // TODO: maybe not optimal
return semantic(scope_);
}
}mixin template Interpret(T) if(is(T==Identifier)||is(T==ModuleIdentifier)){}
mixin template Interpret(T) if(is(T==FieldExp)){
override bool checkInterpret(Scope sc){
// more or less duplicated above
if(!e2.meaning.isVarDecl()){
sc.error("cannot interpret member function at compile time",loc); // TODO: allow?
return false;
}
if(e2.meaning.sstate == SemState.error) return false;
if(e2.isConstant()) return true;
auto this_=e1.extractThis();
return this_&&this_.checkInterpret(sc);
}
override Variant interpretV(){
if(e2.isConstant()) return e2.interpretV();
auto value=e1.interpretV();
auto aggr=value.get!(Variant[VarDecl])();
// TODO: handle the case when the variable decl does not occur
assert(cast(VarDecl)e2.meaning);
return aggr[cast(VarDecl)cast(void*)e2.meaning];
}
override void _interpretFunctionCalls(Scope sc){
mixin(IntFCChld!q{e1});
}
}
mixin template Interpret(T) if(is(T==BinaryExp!(Tok!"."))){ } // (workaround for DMD bug)
mixin template Interpret(T) if(is(T==LengthExp)||is(T==PtrExp)){
override bool checkInterpret(Scope sc){
return e.checkInterpret(sc);
}
override Variant interpretV(){
static if(is(T==LengthExp)) return Variant(e.interpretV().length, type);
else return e.interpretV().ptr;
}
override void _interpretFunctionCalls(Scope sc){
mixin(IntFCChld!q{e});
}
}
mixin template Interpret(T) if(is(T==DollarExp)){
override bool checkInterpret(Scope sc){ return true; }
ulong ivalue = 0xDEAD_BEEF__DEAD_BEEF;
override Variant interpretV(){ return Variant(ivalue, Type.get!Size_t()); }
static void resolveValue(Expression[] e, ulong value){
static struct DollarResolve{
ulong value;
void perform(DollarExp self){ self.ivalue = value; }
// crosstalk between const-folding and bytecode
// interpretation. see CTFEInterpret!DollarExp
// for the rest of the implementation
// TODO: this could be done by rewriting dollar exp
// instead of saving a value in the existing exp
void perform(Symbol self){
if(self.isFunctionLiteral)
if(auto fd=self.meaning.isFunctionDef)
runAnalysis!DollarResolve(fd, value);
}
}
foreach(x;e) runAnalysis!DollarResolve(x, value);
}
}
mixin template Interpret(T) if(is(T==CurrentExp)||is(T==ThisExp)||is(T==SuperExp)){}
mixin template Interpret(T) if(is(T==LiteralExp)){
private template getTokOccupied(T){
enum vocc = to!string(getOccupied!T);
static if(vocc == "wstr") enum occ = "str";
else static if(vocc == "dstr") enum occ = "str";
else static if(vocc == "fli80") enum occ = "flt80";
else enum occ = vocc;
enum getTokOccupied = occ;
}
private Variant value;
this(Token lit){ // TODO: suitable contract
this.lit=lit;
if(lit.type==Tok!"true") lit.int64=1;
else if(lit.type==Tok!"false") lit.int64=0;
swtch:switch(lit.type){
foreach(x; ToTuple!literals){
static if(x!="null"){
alias typeof(mixin(x)) U;
enum occ = getTokOccupied!U;
static if(x=="``w"||x=="``d"){
case Tok!x: value=Variant(to!U(mixin(`lit.`~occ)),Type.get!U()); break swtch;
}else static if(x==".0fi"||x==".0i"||x==".0Li"){
case Tok!x: value=Variant(cast(U)(mixin(`lit.`~occ)*1i),Type.get!U()); break swtch;
}else{
case Tok!x: value=Variant(cast(U)mixin(`lit.`~occ),Type.get!U()); break swtch;
}
}else{
// TODO: DMD allows Variant(null). Why?
case Tok!x: value=Variant(null,Type.get!(typeof(null))()); break swtch;
}
}
default: assert(0, to!string(lit.type));
}
}
this(Variant value){ this.value = value; }
static LiteralExp create(alias New=New,T)(T val){//workaround for long standing bug
auto le = New!LiteralExp(Variant(val));
le.semantic(null);
assert(!le.rewrite);
return le;
}
override bool checkInterpret(Scope sc){ return true; }
override void interpret(Scope sc){ }
override Variant interpretV(){ return value; }
final ArrayLiteralExp toArrayLiteral()in{
assert(!!type.getElementType());
assert(!type.isSomeString());
}body{
auto arr=value.get!(Variant[])();
// TODO: allocation ok?
Expression[] lit = new Expression[arr.length];
foreach(i,ref x;lit){
x = arr[i].toExpr();
if(x.type.getElementType()&&!x.type.isSomeString())
if(auto le=x.isLiteralExp()){
x=le.toArrayLiteral();
continue;
}
}
// TODO: this sometimes leaves implicit casts from typeof([]) in the AST...
auto r=New!ArrayLiteralExp(lit);
r.loc=loc;
r.type=type;
r.semantic(null); // TODO: ok?
assert(!r.rewrite);
return r;
}
}
mixin template Interpret(T) if(is(T==ArrayLiteralExp)){
override bool checkInterpret(Scope sc){
// TODO: this is a kludge
foreach(x; lit) if(auto ce=x.isCommaExp()) if(ce.e1.isTmpVarExp()) return true;
bool ok = true;
foreach(x; lit) if(!x.checkInterpret(sc)) ok=false;
if(litLeftover && !litLeftover.checkInterpret(sc)) ok=false;
return ok;
}
override Variant interpretV(){
// TODO: this GC allocation is probably justified
Variant[] res = new Variant[lit.length];
foreach(i, ref x; res) x = lit[i].interpretV();
return Variant(res,res,type);
}
override void _interpretFunctionCalls(Scope sc){
// TODO: this is a kludge
foreach(x; lit)
if(auto ce=x.isCommaExp())
if(auto tmpv=ce.e1.isTmpVarExp())
return callWrapper(sc,tmpv.ctfeCallWrapper,null);
foreach(ref x; lit){
x._interpretFunctionCalls(sc);
mixin(PropRetry!q{x});
}
if(litLeftover){
litLeftover._interpretFunctionCalls(sc);
mixin(SemProp!q{litLeftover});
}
mixin(PropErr!q{lit});
mixin(IntFCEplg);
}
}
mixin template Interpret(T) if(is(T==IndexExp)){
override bool checkInterpret(Scope sc){
assert(a.length<=1);
return e.checkInterpret(sc)&(!a.length||a[0].checkInterpret(sc))
&(!aLeftover||aLeftover.checkInterpret(sc));
}
override Variant interpretV(){
if(a.length==0) return e.interpretV();
assert(a.length==1);
if(e.type.getUnqual() is Type.get!(void[])())
return Variant(null, Type.get!void());
auto lit = e.interpretV();
auto ind = a[0].interpretV();
return lit[ind];
}
override void _interpretFunctionCalls(Scope sc){
e._interpretFunctionCalls(sc);
if(e.sstate == SemState.completed){
e.interpret(sc);
mixin(Rewrite!q{e});
}
if(ascope.dollar){
mixin(SemProp!q{e});
auto len = e.interpretV().length;
DollarExp.resolveValue(a, len);
if(aLeftover) DollarExp.resolveValue((&aLeftover)[0..1], len);
}
if(a.length){
assert(a.length==1);
a[0]._interpretFunctionCalls(sc);
}
if(aLeftover){
aLeftover._interpretFunctionCalls(sc);
mixin(SemProp!q{aLeftover});
}
if(a.length) mixin(SemProp!q{a[0]});
mixin(SemProp!q{e});
if(a.length==1){
auto len = e.interpretV().length;
a[0].interpret(sc);
mixin(SemProp!q{a[0]});
if(a[0].interpretV().get!ulong()>=len){
sc.error(format("array index %s is out of bounds [0%s..%d%s)",
a[0].toString(), Size_t.suffix, len, Size_t.suffix), a[0].loc);
mixin(ErrEplg);
}
}
mixin(IntFCEplg);
}
}
mixin template Interpret(T) if(is(T==SliceExp)){
override bool checkInterpret(Scope sc){
return e.checkInterpret(sc) & l.checkInterpret(sc) & r.checkInterpret(sc);
}
override Variant interpretV(){
auto lit=e.interpretV();
return lit[l.interpretV()..r.interpretV()];
}
override void _interpretFunctionCalls(Scope sc){
e._interpretFunctionCalls(sc);
if(ascope.dollar){
mixin(SemProp!q{e});
auto len = e.interpretV().length;
Expression[2] e = [l,r];
DollarExp.resolveValue(e[], len);
}
l._interpretFunctionCalls(sc);
r._interpretFunctionCalls(sc);
mixin(SemProp!q{l,r});
if(e.sstate == SemState.completed){
e.interpret(sc);
mixin(Rewrite!q{e});
}
l.interpret(sc);
r.interpret(sc);
mixin(SemProp!q{e,l,r});
auto len = e.interpretV().length;
auto a = l.interpretV().get!ulong();
auto b = r.interpretV().get!ulong();
if(a>len || b>len){
sc.error(format("slice indices [%s..%s] are out of bounds [0%s..%d%s]",
l.toString(),r.toString(),Size_t.suffix,len,Size_t.suffix),
l.loc.to(r.loc));
mixin(ErrEplg);
}
if(a>b){
sc.error("lower slice index exceeds upper slice index",l.loc.to(r.loc));
mixin(ErrEplg);
}
mixin(IntFCEplg);
}
}
mixin template Interpret(T) if(is(T==AssertExp)){
override bool checkInterpret(Scope sc){
foreach(x; a) if(auto ce=x.isCommaExp()) if(ce.e1.isTmpVarExp()) return true;
return a[0].checkInterpret(sc) & (!aLeftover||aLeftover.checkInterpret(sc));
}
override Variant interpretV(){return Variant(null,Type.get!void());}
override void _interpretFunctionCalls(Scope sc){
// TODO: this is a kludge
foreach(x; a)
if(auto ce=x.isCommaExp())
if(auto tmpv=ce.e1.isTmpVarExp())
return callWrapper(sc,tmpv.ctfeCallWrapper,null);
a[0]._interpretFunctionCalls(sc);
mixin(PropRetry!q{a[0]});
if(a.length>1){
a[1]._interpretFunctionCalls(sc);
mixin(PropRetry!q{a[1]});
}
mixin(PropErr!q{a});
auto cond = a[0].interpretV();
if(aLeftover){
aLeftover._interpretFunctionCalls(sc);
mixin(SemProp!q{aLeftover});
}
if(!cond){
if(a.length<2||!a[1].checkInterpret(sc)){
if(a[0].loc.rep=="false"||a[0].loc.rep=="0")
// don't state the obvious:
sc.error("assertion failure", loc);
else sc.error(format("assertion failure: %s is false",a[0].loc.rep), loc);
}else{
auto expr = a[1];
sc.error(expr.interpretV().get!string(), loc);
}
mixin(ErrEplg);
}
mixin(IntFCEplg);
}
}
mixin template Interpret(T) if(is(T _==UnaryExp!S,TokenType S)){
static if(is(T _==UnaryExp!S,TokenType S)):
static if(S==Tok!"&"||S==Tok!"*"){
// TODO: some operations may be handled more efficiently than invoking byte code
// compilation by doing direct computation.
override bool checkInterpret(Scope sc){
return e.checkInterpret(sc);
}
override void _interpretFunctionCalls(Scope sc){
callWrapper(sc,ctfeCallWrapper,null);
}
private:
FunctionDef ctfeCallWrapper;
}else static if(S!=Tok!"++"&&S!=Tok!"--"):
override bool checkInterpret(Scope sc){ return e.checkInterpret(sc); }
override Variant interpretV(){
return e.interpretV().opUnary!(TokChars!S)();
}
override void _interpretFunctionCalls(Scope sc){mixin(IntFCChld!q{e});}
}
mixin template Interpret(T) if(is(T _==PostfixExp!S,TokenType S)){}
mixin template Interpret(T) if(is(T==ExpTuple)){
override bool checkInterpret(Scope sc){
bool r=true;
if(isConstant()) return r;
foreach(x;exprs) r&=x.checkInterpret(sc);
return r;
}
override Variant interpretV(){
auto vals=new Variant[](exprs.length);
foreach(i,x;exprs) vals[i]=exprs[i].interpretV();
assert(!!cast(TypeTuple)type);
return Variant(vals, cast(TypeTuple)cast(void*)type);
}
}
mixin template Interpret(T) if(is(T==ABinaryExp)||is(T==AssignExp)){}
mixin template Interpret(T) if(is(T _==BinaryExp!S, TokenType S) && !is(T==BinaryExp!(Tok!"."))){
static if(is(T _==BinaryExp!S, TokenType S)):
static if(!isAssignOp(S)):
override bool checkInterpret(Scope sc){
static if(S==Tok!",") if(e1.isTmpVarExp()) return true;
return e1.checkInterpret(sc)&e2.checkInterpret(sc);
}
override Variant interpretV(){
// first two conditions are a workaround for a segfault in DMD
static if(S==Tok!"is"){
return Variant(!e1.interpretV().opBinary!"!is"(e2.interpretV),Type.get!bool());
}else static if(S==Tok!"in"){
return Variant(!e1.interpretV().opBinary!"!in"(e2.interpretV),Type.get!bool());
}else static if(S==Tok!","){
return e2.interpretV();
}else static if(isRelationalOp(S)||isArithmeticOp(S)||isBitwiseOp(S)||isShiftOp(S)||isLogicalOp(S))
return e1.interpretV().opBinary!(TokChars!S)(e2.interpretV());
else static if(S==Tok!"~"){
// TODO: this might be optimized. this gc allocates
// TODO: get rid of bulky string special casing code
if(auto ety = e1.type.getElementType()){
if(ety.getUnqual().equals(e2.type.getUnqual())){
Variant rhs = e2.interpretV();
if(ety is Type.get!(immutable(char))())
rhs = Variant(""c~rhs.get!char(),type);
else if(ety is Type.get!(immutable(wchar))())
rhs = Variant(""w~rhs.get!wchar(),type);
else if(ety is Type.get!(immutable(dchar))())
rhs = Variant(""d~rhs.get!dchar(),type);
else{ auto r=[rhs];rhs = Variant(r,r,ety.getDynArr()); }
return e1.interpretV().opBinary!"~"(rhs);
}
}
if(auto ety = e2.type.getElementType()){
if(e1.type.getUnqual().equals(ety.getUnqual())){
auto lhs = e1.interpretV();
if(ety is Type.get!(immutable(char))())
lhs = Variant(""c~lhs.get!char(),type);
else if(ety is Type.get!(immutable(wchar))())
lhs = Variant(""w~lhs.get!wchar(),type);
else if(ety is Type.get!(immutable(dchar))())
lhs = Variant(""d~lhs.get!dchar(),type);
else{ auto l=[lhs];lhs = Variant(l,l,ety.getDynArr()); }
return lhs.opBinary!"~"(e2.interpretV());
}
}
return e1.interpretV().opBinary!"~"(e2.interpretV());
}else return super.interpretV();
}
override void _interpretFunctionCalls(Scope sc){
static if(S==Tok!","){
if(auto tve=e1.isTmpVarExp())
callWrapper(sc,tve.ctfeCallWrapper,null);
else mixin(IntFCChld!q{e1,e2});
}else static if(S==Tok!"/"){
mixin(IntFCChldNoEplg!q{e1,e2});
if(type.isIntegral() && e2.interpretV() == Variant(0,type)){
sc.error("divide by zero",loc);
mixin(ErrEplg);
}
mixin(IntFCEplg);
}/+else static if(S==Tok!"is"||S==Tok!"!is"){
mixin(IntFCChldNoEplg!q{e1,e2});
assert(e1.type is e2.type);
// TODO: allow comparing values against 'null' or '[]'
sc.error("cannot interpret '"~TokChars!S~"' expression during compile time", loc);
mixin(ErrEplg);
}+/else static if(S==Tok!"&&"||S==Tok!"||"){
mixin(IntFCChldNoEplg!q{e1});
assert(e1.type is Type.get!bool());
if(cast(bool)e1.interpretV()^(S==Tok!"&&")){mixin(RewEplg!q{e1});}
mixin(IntFCChld!q{e2});
}else mixin(IntFCChld!q{e1,e2});
}
}
mixin template Interpret(T) if(is(T==TernaryExp)){
override bool checkInterpret(Scope sc){
return e1.checkInterpret(sc)&e2.checkInterpret(sc)&e3.checkInterpret(sc);
}
override Variant interpretV(){
auto r = e1.interpretV();
assert(r.getType() is Type.get!bool(), to!string(r.getType()));
return r ? e2.interpretV() : e3.interpretV();
}
override void _interpretFunctionCalls(Scope sc){mixin(IntFCChld!q{e1,e2,e3});}
}
mixin template Interpret(T) if(is(T==TemporaryExp)){}
mixin template Interpret(T) if(is(T==TmpVarExp)){
override bool checkInterpret(Scope sc){
assert(!!tmpVarDecl.init_);
return true; // be optimistic
}
override Variant interpretV(){ return Variant(null, Type.get!void()); }
override void _interpretFunctionCalls(Scope sc){
assert(!!tmpVarDecl.init_);
mixin(IntFCChld!q{tmpVarDecl.init_});
}
FunctionDef ctfeCallWrapper;
}
mixin template Interpret(T) if(is(T==StructConsExp)||is(T==NewExp)){
override bool checkInterpret(Scope sc){
return true; // be optimistic
}
override void _interpretFunctionCalls(Scope sc){
// TODO: all StructConsExp's making it until here do not call a constructor,
// because those initialize temporary variables, which invoke the interpreter instead
// use this fact to avoid invoking the byte code interpreter
callWrapper(sc,ctfeCallWrapper,consCall?consCall.e:null);
}
private:
FunctionDef ctfeCallWrapper;
}
mixin template Interpret(T) if(is(T==CallExp)){
//private Variant val;
override bool checkInterpret(Scope sc){
return true; // be optimistic
}
override void _interpretFunctionCalls(Scope sc){
callWrapper(sc,ctfeCallWrapper,e);
}
//sc.error(format("cannot interpret function call '%s' at compile time",toString()),loc);
// mixin(ErrEplg);
private:
FunctionDef ctfeCallWrapper;
}
mixin template Interpret(T) if(is(T==UFCSCallExp)){ }
class CTFERetryException: Exception{Node node;this(Node n){super("");node = n;}}
class UnwindException: Exception{Location loc; this(Location loc){this.loc=loc;super("");}}
class SilentUnwindException: Exception{this(){super("");}}
void dependentCTFE(T)(Dependent!T node){
if(node.dependee){
if(node.dependee.node.needRetry){
throw new CTFERetryException(node.dependee.node);
}else{
assert(node.dependee.node.sstate == SemState.error);
throw new UnwindException(node.dependee.node.loc);
}
}
}
// bytecode interpreter for functions
import expression, declaration, statement;
enum Instruction : uint{
hlt,
hltstr,
nop,
// flow control
jmp, // jump to (constant) location of argument
jz, // jump if zero
jnz, // jump if non-zero
call, // function call
ret, // return from function
// stack control
push, // push 1
pop, // pop 1
push2, // push 2
pop2, // pop 2
popn, // pop n
pushp, // push 1 from constant stack location
popp, // pop and store 1 to constant stack location
pushp2, // push 2s to consecutive constant stack locations
popp2, // pop and store 2 to consecutive constant stack locations
pushpn, // pop and store to n consecutive constant stack locations
poppn, // pop and store n to consecutive constant stack locations
pushr, // pop 1 and push stack location given by value
popr, // pop 2 and store higher to stack location given by lower
pushr2, // pop 1 and push 2 consecutive stack locations given by value
popr2, // pop 3, store 2 higher to stack location given by lowest
pushrn, // pop 1 and push n consecutive stack locations given by value
poprn, // pop n+1, store n higher to stack location given by lowest
poprkv, // like popr, but keep value on stack (dup-rot-popr)
poprkr, // like popr, but keep stack reference on stack
poprkv2, // like popr2, but keep value on stack
poprkr2, // like popr2, but keep stack reference on stack
poprkvn, // like poprn, but keep value on stack
poprkrn, // like poprn, but keep stack reference on stack
pushcn, // push n consecutive heap stack locations given by top
popcn, // pop n consecutive heap stack locations given by top
popckvn, // like popcn, but keep value on stack
popckrn, // like popcn, but keep heap stack location on stack
pushccn, // ltop: n, top: number of heap stacks to traverse
popccn, // ltop: n, top: number of heap stacks to traverse
popcckvn, // like popccn, but keep value
popcckrn, // like popccn, but keep location (and number of heap stacks)
ptrfc, // create pointer to context
ptrfcc, // create pointer to enclosing context
pushcontext, // push address of an enclosing context on the stack
swap, // swap topmost values
swap2, // swap topmost value pairs
swapn, // swap topmost n-tuples
dup, // push top of stack
dup2, // duplicate the 2 topmost stack entries
dupn, // duplicate the n topmost stack entries
rot, // rotate the 3 topmost entries by moving top 2 entries down
rot2, // rotate the 3 topmost pairs of 2
rot221, // rotate the 2 topmost pairs of 2 and the following entry
alloca, // pop 1 and reserve stack space
allocc, // create a context of fixed size and push to stack
// temporaries
tmppush, // pop 1 and push to temporary stack
tmppop, // pop 2 and push to temporary stack
// type conversion
int2bool, // pop 1, convert to bool and push 1
real2bool, // pop 2, interpret as real convert to bool and push 1
uint2real, // pop 1, convert to real, push 2
real2uint, // pop 2, convert to ulong push 1
int2real, // pop 1, interpret as signed, convert to real, push 2
real2int, // pop 2, convert to long, interpret as ulong, push 1
float2real, // pop 1, interpret as float, convert to real, push 2
real2float, // pop 2, convert to float, push 1
double2real, // pop 1, interpret as double, convert to real, push 2
real2double, // pop 2, convert to double, push 1
trunc, // truncate top to given number of bits
truncs, // truncate top to given number of bits, sign extend
// arithmetics
negi, // negate top of stack
noti, // ~ top of stack
notb, // ! top of stack
// integer
addi, // add 2 ulongs
subi, // subtract top from ltop
muli, // multiply 2 ulongs
divi, // divide ltop by top unsigned
divsi, // divide ltop by top signed
modi, // ltop%top unsigned
modsi, // ltop%top signed
// float
addf,
subf,
mulf,
divf,
modf,
// double
addd,
subd,
muld,
divd,
modd,
// real
addr,
subr,
mulr,
divr,
modr,
// shifts
shl32, // logic shift left, shamt below 32
shr32, // logic shift right, shamt below 32
sar32, // shift arithmetic right, shamt below 32
shl64, // logic shift left, shamt below 64
shr64, // logic shift right, shamt below 64
sar64, // shift arithmetic right, shamt below 64
// bitwise ops
or,
xor,
and,
// comparison
cmpei, // compare for equality
cmpli, // signed <
cmpbi, // unsigned <
cmplei, // signed <=
cmpbei, // unsigned <=
cmpnei, // compare for inequality
cmpgi, // signed >
cmpai, // unsigned >
cmpgei, // signed >=
cmpaei, // unsigned >=
// float
cmpisf,
cmpef,
cmplf,
cmplef,
cmpnef,
cmpgf,
cmpgef,
// double
cmpisd,
cmped,
cmpld,
cmpled,
cmpned,
cmpgd,
cmpged,
// real
cmpisr,
cmper,
cmplr,
cmpler,
cmpner,
cmpgr,
cmpger,
// array operations
ptra, // get pointer field
lengtha, // get length field
setlengtha, // set length field
newarray, // creates an array, stack top is length
makearray, // pop values from the stack and turn them into an array
appenda,
concata,
// arrays of simple types
loada, // stack top is the index
loadak, // like loada, but keep array and index on stack
storea,
storeakr,
storeakv,
slicea,
// array of arrays (not actually required anymore, but instruction size is smaller)
loadaa,
loadaak,
storeaa,
storeaakr,
storeaakv,
// pointers
loadap, // generate a pointer to an array location
ptrtoa,
addp, // add an integer to a pointer
cmpep,
cmpbp,
cmpbep,
cmpnep,
cmpap,
cmpaep,
// fields
loadf, // args: off, len, pop pointer and load field
loadfkr,
storef, // args: off, len, pop data and pointer and store to field
storefkr,
storefkv,
ptrf,
// casts from void[] and void*
castfromvarr,
castfromvptr,
// virtual methods
fetchvtbl, // if there already is a vtbl, use it (if the child does have it as well)
fetchoverride, // there is no vtbl, always determine overrides dynamically
// partially analyzed functions
analyzeandfail,
// error handling table
errtbl,
}
private enum isize = Instruction.sizeof;
size_t numArgs(Instruction inst){
alias Instruction I;
enum TBD = -1;
static int[] args =
[// flow control
I.hlt: 0, I.hltstr: 0,
I.jmp: 1, I.jz: 1, I.jnz: 1, I.call: 1, I.ret: 0,
// stack control
I.push: 1, I.pop: 0, I.popn: 1, I.pushp: 1, I.popp: 1,
I.push2: 2, I.pop2: 0, I.pushp2: 1, I.popp2: 1, I.pushpn: 2, I.poppn: 2,
I.pushcn: 1, I.popcn: 1, I.popckvn: 1, I.popckrn: 1,
I.pushccn: 1, I.popccn: 1, I.popcckvn: 1, I.popcckrn: 1,
I.ptrfc: 1, I.ptrfcc: 1, I.pushcontext: 1,
I.pushr: 0, I.popr: 0, I.pushr2: 0, I.popr2: 0, I.pushrn: 1, I.poprn: 1,
I.poprkv: 0, I.poprkr: 0, I.poprkv2: 0, I.poprkr2: 0, I.poprkvn: 1, I.poprkrn: 1,
I.swap: 0, I.swap2: 0, I.swapn: 1, I.dup: 0, I.dup2: 0, I.dupn: 1,
I.rot: 0, I.rot2: 0, I.rot221: 0,
I.alloca: 0, I.allocc: 1,
// temporaries
I.tmppush: 0, I.tmppop: 0,
// type conversion
I.int2bool: 0, I.real2bool: 0,
I.uint2real: 0, I.real2uint: 0,
I.int2real: 0, I.real2int: 0,
I.float2real: 0, I.real2float: 0,
I.double2real:0, I.real2double:0,
I.trunc: 1, I.truncs: 1,
// arithmetics
I.negi: 0, I.noti: 0, I.addi: 0, I.subi: 0,I.muli: 0,
I.divi: 0, I.divsi: 0, I.modi: 0, I.modsi: 0,
I.addf: 0, I.subf: 0, I.mulf: 0, I.divf: 0,
I.addd: 0, I.subd: 0, I.muld: 0, I.divd: 0,
I.addr: 0, I.subr: 0, I.mulr: 0, I.divr: 0,
I.shl32: 0, I.shr32: 0, I.sar32: 0, I.shl64: 0, I.shr64: 0, I.sar64: 0,
// comparison