-
Notifications
You must be signed in to change notification settings - Fork 7
/
interpret.c
6496 lines (6126 loc) · 215 KB
/
interpret.c
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
// Compiler implementation of the D programming language
// Copyright (c) 1999-2011 by Digital Mars
// All Rights Reserved
// written by Walter Bright
// http://www.digitalmars.com
// License for redistribution is by either the Artistic License
// in artistic.txt, or the GNU General Public License in gnu.txt.
// See the included readme.txt for details.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "rmem.h"
#include "statement.h"
#include "expression.h"
#include "cond.h"
#include "init.h"
#include "staticassert.h"
#include "mtype.h"
#include "scope.h"
#include "declaration.h"
#include "aggregate.h"
#include "id.h"
#include "utf.h"
#include "attrib.h" // for AttribDeclaration
#include "template.h"
TemplateInstance *isSpeculativeFunction(FuncDeclaration *fd);
#define LOG 0
#define LOGASSIGN 0
#define SHOWPERFORMANCE 0
// Maximum allowable recursive function calls in CTFE
#define CTFE_RECURSION_LIMIT 1000
// The values of all CTFE variables.
struct CtfeStack
{
private:
/* The stack. Every declaration we encounter is pushed here,
together with the VarDeclaration, and the previous
stack address of that variable, so that we can restore it
when we leave the stack frame.
Ctfe Stack addresses are just 0-based integers, but we save
them as 'void *' because ArrayBase can only do pointers.
*/
Expressions values; // values on the stack
VarDeclarations vars; // corresponding variables
ArrayBase<void> savedId; // id of the previous state of that var
/* Global constants get saved here after evaluation, so we never
* have to redo them. This saves a lot of time and memory.
*/
Expressions globalValues; // values of global constants
size_t framepointer; // current frame pointer
size_t maxStackPointer; // most stack we've ever used
public:
CtfeStack() : framepointer(0)
{
}
size_t stackPointer()
{
return values.dim;
}
// Largest number of stack positions we've used
size_t maxStackUsage()
{
return maxStackPointer;
}
// return the previous frame
size_t startFrame()
{
size_t oldframe = framepointer;
framepointer = stackPointer();
return oldframe;
}
void endFrame(size_t oldframe)
{
popAll(framepointer);
framepointer = oldframe;
}
Expression *getValue(VarDeclaration *v)
{
if (v->isDataseg() && !v->isCTFE())
{
assert(v->ctfeAdrOnStack >= 0 &&
v->ctfeAdrOnStack < globalValues.dim);
return globalValues.tdata()[v->ctfeAdrOnStack];
}
assert(v->ctfeAdrOnStack >= 0 && v->ctfeAdrOnStack < stackPointer());
return values.tdata()[v->ctfeAdrOnStack];
}
void setValue(VarDeclaration *v, Expression *e)
{
assert(!v->isDataseg() || v->isCTFE());
assert(v->ctfeAdrOnStack >= 0 && v->ctfeAdrOnStack < stackPointer());
values.tdata()[v->ctfeAdrOnStack] = e;
}
void push(VarDeclaration *v)
{
assert(!v->isDataseg() || v->isCTFE());
if (v->ctfeAdrOnStack!= (size_t)-1
&& v->ctfeAdrOnStack >= framepointer)
{ // Already exists in this frame, reuse it.
values.tdata()[v->ctfeAdrOnStack] = NULL;
return;
}
savedId.push((void *)(v->ctfeAdrOnStack));
v->ctfeAdrOnStack = values.dim;
vars.push(v);
values.push(NULL);
}
void pop(VarDeclaration *v)
{
assert(!v->isDataseg() || v->isCTFE());
assert(!(v->storage_class & (STCref | STCout)));
int oldid = v->ctfeAdrOnStack;
v->ctfeAdrOnStack = (size_t)(savedId.tdata()[oldid]);
if (v->ctfeAdrOnStack == values.dim - 1)
{
values.pop();
vars.pop();
savedId.pop();
}
}
void popAll(size_t stackpointer)
{
if (stackPointer() > maxStackPointer)
maxStackPointer = stackPointer();
assert(values.dim >= stackpointer && stackpointer >= 0);
for (size_t i = stackpointer; i < values.dim; ++i)
{
VarDeclaration *v = vars.tdata()[i];
v->ctfeAdrOnStack = (size_t)(savedId.tdata()[i]);
}
values.setDim(stackpointer);
vars.setDim(stackpointer);
savedId.setDim(stackpointer);
}
void saveGlobalConstant(VarDeclaration *v, Expression *e)
{
assert(v->isDataseg() && !v->isCTFE());
v->ctfeAdrOnStack = globalValues.dim;
globalValues.push(e);
}
};
CtfeStack ctfeStack;
struct InterState
{
InterState *caller; // calling function's InterState
FuncDeclaration *fd; // function being interpreted
size_t framepointer; // frame pointer of previous frame
Statement *start; // if !=NULL, start execution at this statement
Statement *gotoTarget; /* target of EXP_GOTO_INTERPRET result; also
* target of labelled EXP_BREAK_INTERPRET or
* EXP_CONTINUE_INTERPRET. (NULL if no label).
*/
Expression *localThis; // value of 'this', or NULL if none
bool awaitingLvalueReturn; // Support for ref return values:
// Any return to this function should return an lvalue.
InterState();
};
InterState::InterState()
{
memset(this, 0, sizeof(InterState));
}
// Global status of the CTFE engine
struct CtfeStatus
{
static int callDepth; // current number of recursive calls
static int stackTraceCallsToSuppress; /* When printing a stack trace,
* suppress this number of calls
*/
static int maxCallDepth; // highest number of recursive calls
static int numArrayAllocs; // Number of allocated arrays
static int numAssignments; // total number of assignments executed
};
int CtfeStatus::callDepth = 0;
int CtfeStatus::stackTraceCallsToSuppress = 0;
int CtfeStatus::maxCallDepth = 0;
int CtfeStatus::numArrayAllocs = 0;
int CtfeStatus::numAssignments = 0;
// CTFE diagnostic information
void printCtfePerformanceStats()
{
#if SHOWPERFORMANCE
printf(" ---- CTFE Performance ----\n");
printf("max call depth = %d\tmax stack = %d\n", CtfeStatus::maxCallDepth, ctfeStack.maxStackUsage());
printf("array allocs = %d\tassignments = %d\n\n", CtfeStatus::numArrayAllocs, CtfeStatus::numAssignments);
#endif
}
Expression * resolveReferences(Expression *e, Expression *thisval);
Expression *getVarExp(Loc loc, InterState *istate, Declaration *d, CtfeGoal goal);
VarDeclaration *findParentVar(Expression *e, Expression *thisval);
bool needToCopyLiteral(Expression *expr);
Expression *copyLiteral(Expression *e);
Expression *paintTypeOntoLiteral(Type *type, Expression *lit);
Expression *findKeyInAA(AssocArrayLiteralExp *ae, Expression *e2);
Expression *evaluateIfBuiltin(InterState *istate, Loc loc,
FuncDeclaration *fd, Expressions *arguments, Expression *pthis);
Expression *scrubReturnValue(Loc loc, Expression *e);
bool isAssocArray(Type *t);
bool isPointer(Type *t);
// CTFE only expressions
#define TOKclassreference ((TOK)(TOKMAX+1))
#define TOKthrownexception ((TOK)(TOKMAX+2))
// Reference to a class, or an interface. We need this when we
// point to a base class (we must record what the type is).
struct ClassReferenceExp : Expression
{
StructLiteralExp *value;
ClassReferenceExp(Loc loc, StructLiteralExp *lit, Type *type) : Expression(loc, TOKclassreference, sizeof(ClassReferenceExp))
{
assert(lit && lit->sd && lit->sd->isClassDeclaration());
this->value = lit;
this->type = type;
}
Expression *interpret(InterState *istate, CtfeGoal goal = ctfeNeedRvalue)
{
//printf("ClassReferenceExp::interpret() %s\n", value->toChars());
return this;
}
char *toChars()
{
return value->toChars();
}
ClassDeclaration *originalClass()
{
return value->sd->isClassDeclaration();
}
// Return index of the field, or -1 if not found
int getFieldIndex(Type *fieldtype, size_t fieldoffset)
{
ClassDeclaration *cd = originalClass();
size_t fieldsSoFar = 0;
for (size_t j = 0; j < value->elements->dim; j++)
{ while (j - fieldsSoFar >= cd->fields.dim)
{ fieldsSoFar += cd->fields.dim;
cd = cd->baseClass;
}
Dsymbol *s = cd->fields.tdata()[j - fieldsSoFar];
VarDeclaration *v2 = s->isVarDeclaration();
if (fieldoffset == v2->offset &&
fieldtype->size() == v2->type->size())
{ return value->elements->dim - fieldsSoFar - cd->fields.dim + (j-fieldsSoFar);
}
}
return -1;
}
// Return index of the field, or -1 if not found
// Same as getFieldIndex, but checks for a direct match with the VarDeclaration
int findFieldIndexByName(VarDeclaration *v)
{
ClassDeclaration *cd = originalClass();
size_t fieldsSoFar = 0;
for (size_t j = 0; j < value->elements->dim; j++)
{ while (j - fieldsSoFar >= cd->fields.dim)
{ fieldsSoFar += cd->fields.dim;
cd = cd->baseClass;
}
Dsymbol *s = cd->fields.tdata()[j - fieldsSoFar];
VarDeclaration *v2 = s->isVarDeclaration();
if (v == v2)
{ return value->elements->dim - fieldsSoFar - cd->fields.dim + (j-fieldsSoFar);
}
}
return -1;
}
};
// Return index of the field, or -1 if not found
// Same as getFieldIndex, but checks for a direct match with the VarDeclaration
int findFieldIndexByName(StructDeclaration *sd, VarDeclaration *v)
{
for (int i = 0; i < sd->fields.dim; ++i)
{
if (sd->fields.tdata()[i] == v)
return i;
}
return -1;
}
// Fake class which holds the thrown exception. Used for implementing exception handling.
struct ThrownExceptionExp : Expression
{
ClassReferenceExp *thrown; // the thing being tossed
ThrownExceptionExp(Loc loc, ClassReferenceExp *victim) : Expression(loc, TOKthrownexception, sizeof(ThrownExceptionExp))
{
this->thrown = victim;
this->type = type;
}
Expression *interpret(InterState *istate, CtfeGoal goal = ctfeNeedRvalue)
{
assert(0); // This should never be interpreted
return this;
}
char *toChars()
{
return (char *)"CTFE ThrownException";
}
// Generate an error message when this exception is not caught
void generateUncaughtError()
{
thrown->error("Uncaught CTFE exception %s(%s)", thrown->type->toChars(),
thrown->value->elements->tdata()[0]->toChars());
/* Also give the line where the throw statement was. We won't have it
* in the case where the ThrowStatement is generated internally
* (eg, in ScopeStatement)
*/
if (loc.filename && !loc.equals(thrown->loc))
errorSupplemental(loc, "thrown from here");
}
};
// True if 'e' is EXP_CANT_INTERPRET, or an exception
bool exceptionOrCantInterpret(Expression *e)
{
if (e == EXP_CANT_INTERPRET) return true;
if (!e || e == EXP_GOTO_INTERPRET || e == EXP_VOID_INTERPRET
|| e == EXP_BREAK_INTERPRET || e == EXP_CONTINUE_INTERPRET)
return false;
return e->op == TOKthrownexception;
}
// Used for debugging only
void showCtfeExpr(Expression *e, int level = 0)
{
for (int i = level; i>0; --i) printf(" ");
Expressions *elements = NULL;
// We need the struct definition to detect block assignment
StructDeclaration *sd = NULL;
ClassDeclaration *cd = NULL;
if (e->op == TOKstructliteral)
{ elements = ((StructLiteralExp *)e)->elements;
sd = ((StructLiteralExp *)e)->sd;
printf("STRUCT type = %s %p:\n", e->type->toChars(),
e);
}
else if (e->op == TOKclassreference)
{ elements = ((ClassReferenceExp *)e)->value->elements;
cd = ((ClassReferenceExp *)e)->originalClass();
printf("CLASS type = %s %p:\n", e->type->toChars(),
((ClassReferenceExp *)e)->value);
}
else if (e->op == TOKarrayliteral)
{
elements = ((ArrayLiteralExp *)e)->elements;
printf("ARRAY LITERAL type=%s %p:\n", e->type->toChars(),
e);
}
else if (e->op == TOKassocarrayliteral)
{
printf("AA LITERAL type=%s %p:\n", e->type->toChars(),
e);
}
else if (e->op == TOKstring)
{
printf("STRING %s %p\n", e->toChars(),
((StringExp *)e)->string);
}
else if (e->op == TOKslice)
{
printf("SLICE %p: %s\n", e, e->toChars());
showCtfeExpr(((SliceExp *)e)->e1, level + 1);
}
else if (e->op == TOKvar)
{
printf("VAR %p %s\n", e, e->toChars());
VarDeclaration *v = ((VarExp *)e)->var->isVarDeclaration();
if (v && v->getValue())
showCtfeExpr(v->getValue(), level + 1);
}
else if (isPointer(e->type))
{
// This is potentially recursive. We mustn't try to print the thing we're pointing to.
if (e->op == TOKindex)
printf("POINTER %p into %p [%s]\n", e, ((IndexExp *)e)->e1, ((IndexExp *)e)->e2->toChars());
else if (e->op == TOKdotvar)
printf("POINTER %p to %p .%s\n", e, ((DotVarExp *)e)->e1, ((DotVarExp *)e)->var->toChars());
else
printf("POINTER %p: %s\n", e, e->toChars());
}
else
printf("VALUE %p: %s\n", e, e->toChars());
if (elements)
{
size_t fieldsSoFar = 0;
for (size_t i = 0; i < elements->dim; i++)
{ Expression *z = NULL;
Dsymbol *s = NULL;
if (i > 15) {
printf("...(total %d elements)\n", elements->dim);
return;
}
if (sd)
{ s = sd->fields.tdata()[i];
z = elements->tdata()[i];
}
else if (cd)
{ while (i - fieldsSoFar >= cd->fields.dim)
{ fieldsSoFar += cd->fields.dim;
cd = cd->baseClass;
for (int j = level; j>0; --j) printf(" ");
printf(" BASE CLASS: %s\n", cd->toChars());
}
s = cd->fields.tdata()[i - fieldsSoFar];
size_t indx = (elements->dim - fieldsSoFar)- cd->fields.dim + i;
assert(indx >= 0);
assert(indx < elements->dim);
z = elements->tdata()[indx];
}
if (!z) {
for (int j = level; j>0; --j) printf(" ");
printf(" void\n");
continue;
}
if (s)
{
VarDeclaration *v = s->isVarDeclaration();
assert(v);
// If it is a void assignment, use the default initializer
if ((v->type->ty != z->type->ty) && v->type->ty == Tsarray)
{
for (int j = level; --j;) printf(" ");
printf(" field: block initalized static array\n");
continue;
}
}
showCtfeExpr(z, level + 1);
}
}
}
/*************************************
* Attempt to interpret a function given the arguments.
* Input:
* istate state for calling function (NULL if none)
* arguments function arguments
* thisarg 'this', if a needThis() function, NULL if not.
*
* Return result expression if successful, EXP_CANT_INTERPRET if not.
*/
Expression *FuncDeclaration::interpret(InterState *istate, Expressions *arguments, Expression *thisarg)
{
#if LOG
printf("\n********\nFuncDeclaration::interpret(istate = %p) %s\n", istate, toChars());
#endif
if (semanticRun == PASSsemantic3)
return EXP_CANT_INTERPRET;
if (semanticRun < PASSsemantic3 && scope)
{
/* Forward reference - we need to run semantic3 on this function.
* If errors are gagged, and it's not part of a speculative
* template instance, we need to temporarily ungag errors.
*/
int olderrors = global.errors;
int oldgag = global.gag;
TemplateInstance *spec = isSpeculativeFunction(this);
if (global.gag && !spec)
global.gag = 0;
semantic3(scope);
global.gag = oldgag; // regag errors
// If it is a speculatively-instantiated template, and errors occur,
// we need to mark the template as having errors.
if (spec && global.errors != olderrors)
spec->errors = global.errors - olderrors;
if (olderrors != global.errors) // if errors compiling this function
return EXP_CANT_INTERPRET;
}
if (semanticRun < PASSsemantic3done)
return EXP_CANT_INTERPRET;
Type *tb = type->toBasetype();
assert(tb->ty == Tfunction);
TypeFunction *tf = (TypeFunction *)tb;
Type *tret = tf->next->toBasetype();
if (tf->varargs && arguments &&
((parameters && arguments->dim != parameters->dim) || (!parameters && arguments->dim)))
{
error("C-style variadic functions are not yet implemented in CTFE");
return EXP_CANT_INTERPRET;
}
// Nested functions always inherit the 'this' pointer from the parent,
// except for delegates. (Note that the 'this' pointer may be null).
// Func literals report isNested() even if they are in global scope,
// so we need to check that the parent is a function.
if (isNested() && toParent2()->isFuncDeclaration() && !thisarg && istate)
thisarg = istate->localThis;
InterState istatex;
istatex.caller = istate;
istatex.fd = this;
istatex.localThis = thisarg;
istatex.framepointer = ctfeStack.startFrame();
Expressions vsave; // place to save previous parameter values
size_t dim = 0;
if (needThis() && !thisarg)
{ // error, no this. Prevent segfault.
error("need 'this' to access member %s", toChars());
return EXP_CANT_INTERPRET;
}
if (thisarg && !istate)
{ // Check that 'this' aleady has a value
if (thisarg->interpret(istate) == EXP_CANT_INTERPRET)
return EXP_CANT_INTERPRET;
}
static int evaluatingArgs = 0;
if (arguments)
{
dim = arguments->dim;
assert(!dim || (parameters && (parameters->dim == dim)));
vsave.setDim(dim);
/* Evaluate all the arguments to the function,
* store the results in eargs[]
*/
Expressions eargs;
eargs.setDim(dim);
for (size_t i = 0; i < dim; i++)
{ Expression *earg = arguments->tdata()[i];
Parameter *arg = Parameter::getNth(tf->parameters, i);
if (arg->storageClass & (STCout | STCref))
{
if (!istate && (arg->storageClass & STCout))
{ // initializing an out parameter involves writing to it.
earg->error("global %s cannot be passed as an 'out' parameter at compile time", earg->toChars());
return EXP_CANT_INTERPRET;
}
// Convert all reference arguments into lvalue references
++evaluatingArgs;
earg = earg->interpret(istate, ctfeNeedLvalueRef);
--evaluatingArgs;
if (earg == EXP_CANT_INTERPRET)
return earg;
}
else if (arg->storageClass & STClazy)
{
}
else
{ /* Value parameters
*/
Type *ta = arg->type->toBasetype();
if (ta->ty == Tsarray && earg->op == TOKaddress)
{
/* Static arrays are passed by a simple pointer.
* Skip past this to get at the actual arg.
*/
earg = ((AddrExp *)earg)->e1;
}
++evaluatingArgs;
earg = earg->interpret(istate);
--evaluatingArgs;
if (earg == EXP_CANT_INTERPRET)
return earg;
}
if (earg->op == TOKthrownexception)
{
if (istate)
return earg;
((ThrownExceptionExp *)earg)->generateUncaughtError();
return EXP_CANT_INTERPRET;
}
eargs.tdata()[i] = earg;
}
for (size_t i = 0; i < dim; i++)
{ Expression *earg = eargs.tdata()[i];
Parameter *arg = Parameter::getNth(tf->parameters, i);
VarDeclaration *v = parameters->tdata()[i];
#if LOG
printf("arg[%d] = %s\n", i, earg->toChars());
#endif
if (arg->storageClass & (STCout | STCref) && earg->op == TOKvar)
{
VarExp *ve = (VarExp *)earg;
VarDeclaration *v2 = ve->var->isVarDeclaration();
if (!v2)
{
error("cannot interpret %s as a ref parameter", ve->toChars());
return EXP_CANT_INTERPRET;
}
/* The push() isn't a variable we'll use, it's just a place
* to save the old value of v.
* Note that v might be v2! So we need to save v2's index
* before pushing.
*/
size_t oldadr = v2->ctfeAdrOnStack;
ctfeStack.push(v);
v->ctfeAdrOnStack = oldadr;
assert(v2->hasValue());
}
else
{ // Value parameters and non-trivial references
ctfeStack.push(v);
v->setValueWithoutChecking(earg);
}
#if LOG || LOGASSIGN
printf("interpreted arg[%d] = %s\n", i, earg->toChars());
showCtfeExpr(earg);
#endif
}
}
if (vresult)
ctfeStack.push(vresult);
// Enter the function
++CtfeStatus::callDepth;
if (CtfeStatus::callDepth > CtfeStatus::maxCallDepth)
CtfeStatus::maxCallDepth = CtfeStatus::callDepth;
Expression *e = NULL;
while (1)
{
if (CtfeStatus::callDepth > CTFE_RECURSION_LIMIT)
{ // This is a compiler error. It must not be suppressed.
global.gag = 0;
error("CTFE recursion limit exceeded");
e = EXP_CANT_INTERPRET;
break;
}
e = fbody->interpret(&istatex);
if (e == EXP_CANT_INTERPRET)
{
#if LOG
printf("function body failed to interpret\n");
#endif
}
/* This is how we deal with a recursive statement AST
* that has arbitrary goto statements in it.
* Bubble up a 'result' which is the target of the goto
* statement, then go recursively down the AST looking
* for that statement, then execute starting there.
*/
if (e == EXP_GOTO_INTERPRET)
{
istatex.start = istatex.gotoTarget; // set starting statement
istatex.gotoTarget = NULL;
}
else
break;
}
assert(e != EXP_CONTINUE_INTERPRET && e != EXP_BREAK_INTERPRET);
// Leave the function
--CtfeStatus::callDepth;
ctfeStack.endFrame(istatex.framepointer);
// If fell off the end of a void function, return void
if (!e && type->toBasetype()->nextOf()->ty == Tvoid)
return EXP_VOID_INTERPRET;
// If it generated an exception, return it
if (exceptionOrCantInterpret(e))
{
if (istate || e == EXP_CANT_INTERPRET)
return e;
((ThrownExceptionExp *)e)->generateUncaughtError();
return EXP_CANT_INTERPRET;
}
if (!istate && !evaluatingArgs)
{
e = scrubReturnValue(loc, e);
}
return e;
}
/******************************** Statement ***************************/
#define START() \
if (istate->start) \
{ if (istate->start != this) \
return NULL; \
istate->start = NULL; \
}
/***********************************
* Interpret the statement.
* Returns:
* NULL continue to next statement
* EXP_CANT_INTERPRET cannot interpret statement at compile time
* !NULL expression from return statement, or thrown exception
*/
Expression *Statement::interpret(InterState *istate)
{
#if LOG
printf("Statement::interpret()\n");
#endif
START()
error("Statement %s cannot be interpreted at compile time", this->toChars());
return EXP_CANT_INTERPRET;
}
Expression *ExpStatement::interpret(InterState *istate)
{
#if LOG
printf("ExpStatement::interpret(%s)\n", exp ? exp->toChars() : "");
#endif
START()
if (exp)
{
Expression *e = exp->interpret(istate, ctfeNeedNothing);
if (e == EXP_CANT_INTERPRET)
{
//printf("-ExpStatement::interpret(): %p\n", e);
return EXP_CANT_INTERPRET;
}
if (e && e!= EXP_VOID_INTERPRET && e->op == TOKthrownexception)
return e;
}
return NULL;
}
Expression *CompoundStatement::interpret(InterState *istate)
{ Expression *e = NULL;
#if LOG
printf("CompoundStatement::interpret()\n");
#endif
if (istate->start == this)
istate->start = NULL;
if (statements)
{
for (size_t i = 0; i < statements->dim; i++)
{ Statement *s = statements->tdata()[i];
if (s)
{
e = s->interpret(istate);
if (e)
break;
}
}
}
#if LOG
printf("-CompoundStatement::interpret() %p\n", e);
#endif
return e;
}
Expression *UnrolledLoopStatement::interpret(InterState *istate)
{ Expression *e = NULL;
#if LOG
printf("UnrolledLoopStatement::interpret()\n");
#endif
if (istate->start == this)
istate->start = NULL;
if (statements)
{
for (size_t i = 0; i < statements->dim; i++)
{ Statement *s = statements->tdata()[i];
e = s->interpret(istate);
if (e == EXP_CANT_INTERPRET)
break;
if (e == EXP_CONTINUE_INTERPRET)
{
if (istate->gotoTarget && istate->gotoTarget != this)
break; // continue at higher level
istate->gotoTarget = NULL;
e = NULL;
continue;
}
if (e == EXP_BREAK_INTERPRET)
{
if (!istate->gotoTarget || istate->gotoTarget == this)
{
istate->gotoTarget = NULL;
e = NULL;
} // else break at a higher level
break;
}
if (e)
break;
}
}
return e;
}
// For CTFE only. Returns true if 'e' is TRUE or a non-null pointer.
int isTrueBool(Expression *e)
{
return e->isBool(TRUE) || ((e->type->ty == Tpointer || e->type->ty == Tclass)
&& e->op != TOKnull);
}
Expression *IfStatement::interpret(InterState *istate)
{
#if LOG
printf("IfStatement::interpret(%s)\n", condition->toChars());
#endif
if (istate->start == this)
istate->start = NULL;
if (istate->start)
{
Expression *e = NULL;
if (ifbody)
e = ifbody->interpret(istate);
if (exceptionOrCantInterpret(e))
return e;
if (istate->start && elsebody)
e = elsebody->interpret(istate);
return e;
}
Expression *e = condition->interpret(istate);
assert(e);
//if (e == EXP_CANT_INTERPRET) printf("cannot interpret\n");
if (e != EXP_CANT_INTERPRET && (e && e->op != TOKthrownexception))
{
if (isTrueBool(e))
e = ifbody ? ifbody->interpret(istate) : NULL;
else if (e->isBool(FALSE))
e = elsebody ? elsebody->interpret(istate) : NULL;
else
{
e = EXP_CANT_INTERPRET;
}
}
return e;
}
Expression *ScopeStatement::interpret(InterState *istate)
{
#if LOG
printf("ScopeStatement::interpret()\n");
#endif
if (istate->start == this)
istate->start = NULL;
return statement ? statement->interpret(istate) : NULL;
}
Expression *resolveSlice(Expression *e)
{
if ( ((SliceExp *)e)->e1->op == TOKnull)
return ((SliceExp *)e)->e1;
return Slice(e->type, ((SliceExp *)e)->e1,
((SliceExp *)e)->lwr, ((SliceExp *)e)->upr);
}
/* Determine the array length, without interpreting it.
* e must be an array literal, or a slice
* It's very wasteful to resolve the slice when we only
* need the length.
*/
uinteger_t resolveArrayLength(Expression *e)
{
if (e->op == TOKnull)
return 0;
if (e->op == TOKslice)
{ uinteger_t ilo = ((SliceExp *)e)->lwr->toInteger();
uinteger_t iup = ((SliceExp *)e)->upr->toInteger();
return iup - ilo;
}
if (e->op == TOKstring)
{ return ((StringExp *)e)->len;
}
if (e->op == TOKarrayliteral)
{ ArrayLiteralExp *ale = (ArrayLiteralExp *)e;
return ale->elements ? ale->elements->dim : 0;
}
if (e->op == TOKassocarrayliteral)
{ AssocArrayLiteralExp *ale = (AssocArrayLiteralExp *)e;
return ale->keys->dim;
}
assert(0);
return 0;
}
// As Equal, but resolves slices before comparing
Expression *ctfeEqual(enum TOK op, Type *type, Expression *e1, Expression *e2)
{
if (e1->op == TOKslice)
e1 = resolveSlice(e1);
if (e2->op == TOKslice)
e2 = resolveSlice(e2);
return Equal(op, type, e1, e2);
}
Expression *ctfeCat(Type *type, Expression *e1, Expression *e2)
{
Loc loc = e1->loc;
Type *t1 = e1->type->toBasetype();
Type *t2 = e2->type->toBasetype();
Expression *e;
if (e2->op == TOKstring && e1->op == TOKarrayliteral &&
t1->nextOf()->isintegral())
{
// [chars] ~ string => string (only valid for CTFE)
StringExp *es1 = (StringExp *)e2;
ArrayLiteralExp *es2 = (ArrayLiteralExp *)e1;
size_t len = es1->len + es2->elements->dim;
int sz = es1->sz;
void *s = mem.malloc((len + 1) * sz);
memcpy((char *)s + sz * es2->elements->dim, es1->string, es1->len * sz);
for (size_t i = 0; i < es2->elements->dim; i++)
{ Expression *es2e = es2->elements->tdata()[i];
if (es2e->op != TOKint64)
return EXP_CANT_INTERPRET;
dinteger_t v = es2e->toInteger();
memcpy((unsigned char *)s + i * sz, &v, sz);
}
// Add terminating 0
memset((unsigned char *)s + len * sz, 0, sz);
StringExp *es = new StringExp(loc, s, len);
es->sz = sz;
es->committed = 0;
es->type = type;
e = es;
return e;
}
else if (e1->op == TOKstring && e2->op == TOKarrayliteral &&
t2->nextOf()->isintegral())
{
// string ~ [chars] => string (only valid for CTFE)
// Concatenate the strings
StringExp *es1 = (StringExp *)e1;
ArrayLiteralExp *es2 = (ArrayLiteralExp *)e2;
size_t len = es1->len + es2->elements->dim;
int sz = es1->sz;
void *s = mem.malloc((len + 1) * sz);
memcpy(s, es1->string, es1->len * sz);
for (size_t i = 0; i < es2->elements->dim; i++)
{ Expression *es2e = es2->elements->tdata()[i];
if (es2e->op != TOKint64)
return EXP_CANT_INTERPRET;
dinteger_t v = es2e->toInteger();
memcpy((unsigned char *)s + (es1->len + i) * sz, &v, sz);
}
// Add terminating 0
memset((unsigned char *)s + len * sz, 0, sz);
StringExp *es = new StringExp(loc, s, len);
es->sz = sz;
es->committed = 0; //es1->committed;
es->type = type;
e = es;
return e;
}
return Cat(type, e1, e2);
}
void scrubArray(Loc loc, Expressions *elems);
/* All results destined for use outside of CTFE need to have their CTFE-specific
* features removed.
* In particular, all slices must be resolved.
*/
Expression *scrubReturnValue(Loc loc, Expression *e)
{
if (e->op == TOKclassreference)
{
error(loc, "%s class literals cannot be returned from CTFE", ((ClassReferenceExp*)e)->originalClass()->toChars());
return EXP_CANT_INTERPRET;
}
if (e->op == TOKslice)
{
e = resolveSlice(e);
}
if (e->op == TOKstructliteral)
{
StructLiteralExp *se = (StructLiteralExp *)e;
se->ownedByCtfe = false;
scrubArray(loc, se->elements);
}
if (e->op == TOKstring)
{