/
dinterpret.d
7130 lines (6552 loc) · 236 KB
/
dinterpret.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
/**
* Compiler implementation of the
* $(LINK2 http://www.dlang.org, D programming language).
*
* Copyright: Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/dinterpret.d, _dinterpret.d)
* Documentation: https://dlang.org/phobos/dmd_dinterpret.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dinterpret.d
*/
module dmd.dinterpret;
import core.stdc.stdio;
import core.stdc.string;
import dmd.apply;
import dmd.arraytypes;
import dmd.attrib;
import dmd.builtin;
import dmd.constfold;
import dmd.ctfeexpr;
import dmd.dclass;
import dmd.declaration;
import dmd.dstruct;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.dtemplate;
import dmd.errors;
import dmd.expression;
import dmd.expressionsem;
import dmd.func;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.init;
import dmd.initsem;
import dmd.mtype;
import dmd.root.array;
import dmd.root.rootobject;
import dmd.statement;
import dmd.tokens;
import dmd.utf;
import dmd.visitor;
/*************************************
* Entry point for CTFE.
* A compile-time result is required. Give an error if not possible.
*
* `e` must be semantically valid expression. In other words, it should not
* contain any `ErrorExp`s in it. But, CTFE interpretation will cross over
* functions and may invoke a function that contains `ErrorStatement` in its body.
* If that, the "CTFE failed because of previous errors" error is raised.
*/
public extern (C++) Expression ctfeInterpret(Expression e)
{
if (e.op == TOK.error)
return e;
assert(e.type); // https://issues.dlang.org/show_bug.cgi?id=14642
//assert(e.type.ty != Terror); // FIXME
if (e.type.ty == Terror)
return new ErrorExp();
// This code is outside a function, but still needs to be compiled
// (there are compiler-generated temporary variables such as __dollar).
// However, this will only be run once and can then be discarded.
auto ctfeCodeGlobal = CompiledCtfeFunction(null);
ctfeCodeGlobal.callingloc = e.loc;
ctfeCodeGlobal.onExpression(e);
Expression result = interpret(e, null);
if (!CTFEExp.isCantExp(result))
result = scrubReturnValue(e.loc, result);
if (CTFEExp.isCantExp(result))
result = new ErrorExp();
return result;
}
/* Run CTFE on the expression, but allow the expression to be a TypeExp
* or a tuple containing a TypeExp. (This is required by pragma(msg)).
*/
public extern (C++) Expression ctfeInterpretForPragmaMsg(Expression e)
{
if (e.op == TOK.error || e.op == TOK.type)
return e;
// It's also OK for it to be a function declaration (happens only with
// __traits(getOverloads))
if (e.op == TOK.variable && (cast(VarExp)e).var.isFuncDeclaration())
{
return e;
}
if (e.op != TOK.tuple)
return e.ctfeInterpret();
// Tuples need to be treated separately, since they are
// allowed to contain a TypeExp in this case.
TupleExp tup = cast(TupleExp)e;
Expressions* expsx = null;
for (size_t i = 0; i < tup.exps.dim; ++i)
{
Expression g = (*tup.exps)[i];
Expression h = g;
h = ctfeInterpretForPragmaMsg(g);
if (h != g)
{
if (!expsx)
{
expsx = new Expressions();
expsx.setDim(tup.exps.dim);
for (size_t j = 0; j < tup.exps.dim; j++)
(*expsx)[j] = (*tup.exps)[j];
}
(*expsx)[i] = h;
}
}
if (expsx)
{
auto te = new TupleExp(e.loc, expsx);
expandTuples(te.exps);
te.type = new TypeTuple(te.exps);
return te;
}
return e;
}
public extern (C++) Expression getValue(VarDeclaration vd)
{
return ctfeStack.getValue(vd);
}
// CTFE diagnostic information
public extern (C++) void printCtfePerformanceStats()
{
debug (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);
}
}
/*********
* Typesafe PIMPL idiom so we can keep CompiledCtfeFunction private.
*/
struct CompiledCtfeFunctionPimpl
{
private CompiledCtfeFunction* pimpl;
private alias pimpl this;
}
/* ================================================ Implementation ======================================= */
private:
enum CtfeGoal : int
{
ctfeNeedRvalue, // Must return an Rvalue (== CTFE value)
ctfeNeedLvalue, // Must return an Lvalue (== CTFE reference)
ctfeNeedNothing, // The return value is not required
}
alias ctfeNeedRvalue = CtfeGoal.ctfeNeedRvalue;
alias ctfeNeedLvalue = CtfeGoal.ctfeNeedLvalue;
alias ctfeNeedNothing = CtfeGoal.ctfeNeedNothing;
//debug = LOG;
//debug = LOGASSIGN;
//debug = LOGCOMPILE;
//debug = SHOWPERFORMANCE;
// Maximum allowable recursive function calls in CTFE
enum 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.
* Note that when a function is forward referenced, the interpreter must
* run semantic3, and that may start CTFE again with a NULL istate. Thus
* the stack might not be empty when CTFE begins.
*
* Ctfe Stack addresses are just 0-based integers, but we save
* them as 'void *' because Array can only do pointers.
*/
Expressions values; // values on the stack
VarDeclarations vars; // corresponding variables
Array!(void*) savedId; // id of the previous state of that var
Array!(void*) frames; // all previous frame pointers
Expressions savedThis; // all previous values of localThis
/* 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
Expression localThis; // value of 'this', or NULL if none
public:
extern (C++) size_t stackPointer()
{
return values.dim;
}
// The current value of 'this', or NULL if none
extern (C++) Expression getThis()
{
return localThis;
}
// Largest number of stack positions we've used
extern (C++) size_t maxStackUsage()
{
return maxStackPointer;
}
// Start a new stack frame, using the provided 'this'.
extern (C++) void startFrame(Expression thisexp)
{
frames.push(cast(void*)cast(size_t)framepointer);
savedThis.push(localThis);
framepointer = stackPointer();
localThis = thisexp;
}
extern (C++) void endFrame()
{
size_t oldframe = cast(size_t)frames[frames.dim - 1];
localThis = savedThis[savedThis.dim - 1];
popAll(framepointer);
framepointer = oldframe;
frames.setDim(frames.dim - 1);
savedThis.setDim(savedThis.dim - 1);
}
extern (C++) bool isInCurrentFrame(VarDeclaration v)
{
if (v.isDataseg() && !v.isCTFE())
return false; // It's a global
return v.ctfeAdrOnStack >= framepointer;
}
extern (C++) Expression getValue(VarDeclaration v)
{
if ((v.isDataseg() || v.storage_class & STC.manifest) && !v.isCTFE())
{
assert(v.ctfeAdrOnStack >= 0 && v.ctfeAdrOnStack < globalValues.dim);
return globalValues[v.ctfeAdrOnStack];
}
assert(v.ctfeAdrOnStack >= 0 && v.ctfeAdrOnStack < stackPointer());
return values[v.ctfeAdrOnStack];
}
extern (C++) void setValue(VarDeclaration v, Expression e)
{
assert(!v.isDataseg() || v.isCTFE());
assert(v.ctfeAdrOnStack >= 0 && v.ctfeAdrOnStack < stackPointer());
values[v.ctfeAdrOnStack] = e;
}
extern (C++) void push(VarDeclaration v)
{
assert(!v.isDataseg() || v.isCTFE());
if (v.ctfeAdrOnStack != cast(size_t)-1 && v.ctfeAdrOnStack >= framepointer)
{
// Already exists in this frame, reuse it.
values[v.ctfeAdrOnStack] = null;
return;
}
savedId.push(cast(void*)cast(size_t)v.ctfeAdrOnStack);
v.ctfeAdrOnStack = cast(int)values.dim;
vars.push(v);
values.push(null);
}
extern (C++) void pop(VarDeclaration v)
{
assert(!v.isDataseg() || v.isCTFE());
assert(!(v.storage_class & (STC.ref_ | STC.out_)));
int oldid = v.ctfeAdrOnStack;
v.ctfeAdrOnStack = cast(int)cast(size_t)savedId[oldid];
if (v.ctfeAdrOnStack == values.dim - 1)
{
values.pop();
vars.pop();
savedId.pop();
}
}
extern (C++) void popAll(size_t stackpointer)
{
if (stackPointer() > maxStackPointer)
maxStackPointer = stackPointer();
assert(values.dim >= stackpointer);
for (size_t i = stackpointer; i < values.dim; ++i)
{
VarDeclaration v = vars[i];
v.ctfeAdrOnStack = cast(int)cast(size_t)savedId[i];
}
values.setDim(stackpointer);
vars.setDim(stackpointer);
savedId.setDim(stackpointer);
}
extern (C++) void saveGlobalConstant(VarDeclaration v, Expression e)
{
assert(v._init && (v.isConst() || v.isImmutable() || v.storage_class & STC.manifest) && !v.isCTFE());
v.ctfeAdrOnStack = cast(int)globalValues.dim;
globalValues.push(e);
}
}
private struct InterState
{
InterState* caller; // calling function's InterState
FuncDeclaration fd; // function being interpreted
Statement start; // if !=NULL, start execution at this statement
/* target of CTFEExp result; also
* target of labelled CTFEExp or
* CTFEExp. (null if no label).
*/
Statement gotoTarget;
}
extern (C++) __gshared CtfeStack ctfeStack;
/***********************************************************
* CTFE-object code for a single function
*
* Currently only counts the number of local variables in the function
*/
struct CompiledCtfeFunction
{
FuncDeclaration func; // Function being compiled, NULL if global scope
int numVars; // Number of variables declared in this function
Loc callingloc;
extern (D) this(FuncDeclaration f)
{
func = f;
}
extern (C++) void onDeclaration(VarDeclaration v)
{
//printf("%s CTFE declare %s\n", v.loc.toChars(), v.toChars());
++numVars;
}
extern (C++) void onExpression(Expression e)
{
extern (C++) final class VarWalker : StoppableVisitor
{
alias visit = super.visit;
public:
CompiledCtfeFunction* ccf;
extern (D) this(CompiledCtfeFunction* ccf)
{
this.ccf = ccf;
}
override void visit(Expression e)
{
}
override void visit(ErrorExp e)
{
// Currently there's a front-end bug: silent errors
// can occur inside delegate literals inside is(typeof()).
// Suppress the check in this case.
if (global.gag && ccf.func)
{
stop = 1;
return;
}
.error(e.loc, "CTFE internal error: ErrorExp in `%s`\n", ccf.func ? ccf.func.loc.toChars() : ccf.callingloc.toChars());
assert(0);
}
override void visit(DeclarationExp e)
{
VarDeclaration v = e.declaration.isVarDeclaration();
if (!v)
return;
TupleDeclaration td = v.toAlias().isTupleDeclaration();
if (td)
{
if (!td.objects)
return;
for (size_t i = 0; i < td.objects.dim; ++i)
{
RootObject o = td.objects.tdata()[i];
Expression ex = isExpression(o);
DsymbolExp s = (ex && ex.op == TOK.dSymbol) ? cast(DsymbolExp)ex : null;
assert(s);
VarDeclaration v2 = s.s.isVarDeclaration();
assert(v2);
if (!v2.isDataseg() || v2.isCTFE())
ccf.onDeclaration(v2);
}
}
else if (!(v.isDataseg() || v.storage_class & STC.manifest) || v.isCTFE())
ccf.onDeclaration(v);
Dsymbol s = v.toAlias();
if (s == v && !v.isStatic() && v._init)
{
ExpInitializer ie = v._init.isExpInitializer();
if (ie)
ccf.onExpression(ie.exp);
}
}
override void visit(IndexExp e)
{
if (e.lengthVar)
ccf.onDeclaration(e.lengthVar);
}
override void visit(SliceExp e)
{
if (e.lengthVar)
ccf.onDeclaration(e.lengthVar);
}
}
scope VarWalker v = new VarWalker(&this);
walkPostorder(e, v);
}
}
private extern (C++) final class CtfeCompiler : SemanticTimeTransitiveVisitor
{
alias visit = SemanticTimeTransitiveVisitor.visit;
public:
CompiledCtfeFunction* ccf;
extern (D) this(CompiledCtfeFunction* ccf)
{
this.ccf = ccf;
}
override void visit(Statement s)
{
debug (LOGCOMPILE)
{
printf("%s Statement::ctfeCompile %s\n", s.loc.toChars(), s.toChars());
}
assert(0);
}
override void visit(ExpStatement s)
{
debug (LOGCOMPILE)
{
printf("%s ExpStatement::ctfeCompile\n", s.loc.toChars());
}
if (s.exp)
ccf.onExpression(s.exp);
}
override void visit(IfStatement s)
{
debug (LOGCOMPILE)
{
printf("%s IfStatement::ctfeCompile\n", s.loc.toChars());
}
ccf.onExpression(s.condition);
if (s.ifbody)
ctfeCompile(s.ifbody);
if (s.elsebody)
ctfeCompile(s.elsebody);
}
override void visit(OnScopeStatement s)
{
debug (LOGCOMPILE)
{
printf("%s OnScopeStatement::ctfeCompile\n", s.loc.toChars());
}
// rewritten to try/catch/finally
assert(0);
}
override void visit(DoStatement s)
{
debug (LOGCOMPILE)
{
printf("%s DoStatement::ctfeCompile\n", s.loc.toChars());
}
ccf.onExpression(s.condition);
if (s._body)
ctfeCompile(s._body);
}
override void visit(WhileStatement s)
{
debug (LOGCOMPILE)
{
printf("%s WhileStatement::ctfeCompile\n", s.loc.toChars());
}
// rewritten to ForStatement
assert(0);
}
override void visit(ForStatement s)
{
debug (LOGCOMPILE)
{
printf("%s ForStatement::ctfeCompile\n", s.loc.toChars());
}
if (s._init)
ctfeCompile(s._init);
if (s.condition)
ccf.onExpression(s.condition);
if (s.increment)
ccf.onExpression(s.increment);
if (s._body)
ctfeCompile(s._body);
}
override void visit(ForeachStatement s)
{
debug (LOGCOMPILE)
{
printf("%s ForeachStatement::ctfeCompile\n", s.loc.toChars());
}
// rewritten for ForStatement
assert(0);
}
override void visit(SwitchStatement s)
{
debug (LOGCOMPILE)
{
printf("%s SwitchStatement::ctfeCompile\n", s.loc.toChars());
}
ccf.onExpression(s.condition);
// Note that the body contains the the Case and Default
// statements, so we only need to compile the expressions
for (size_t i = 0; i < s.cases.dim; i++)
{
ccf.onExpression((*s.cases)[i].exp);
}
if (s._body)
ctfeCompile(s._body);
}
override void visit(CaseStatement s)
{
debug (LOGCOMPILE)
{
printf("%s CaseStatement::ctfeCompile\n", s.loc.toChars());
}
if (s.statement)
ctfeCompile(s.statement);
}
override void visit(GotoDefaultStatement s)
{
debug (LOGCOMPILE)
{
printf("%s GotoDefaultStatement::ctfeCompile\n", s.loc.toChars());
}
}
override void visit(GotoCaseStatement s)
{
debug (LOGCOMPILE)
{
printf("%s GotoCaseStatement::ctfeCompile\n", s.loc.toChars());
}
}
override void visit(SwitchErrorStatement s)
{
debug (LOGCOMPILE)
{
printf("%s SwitchErrorStatement::ctfeCompile\n", s.loc.toChars());
}
}
override void visit(ReturnStatement s)
{
debug (LOGCOMPILE)
{
printf("%s ReturnStatement::ctfeCompile\n", s.loc.toChars());
}
if (s.exp)
ccf.onExpression(s.exp);
}
override void visit(BreakStatement s)
{
debug (LOGCOMPILE)
{
printf("%s BreakStatement::ctfeCompile\n", s.loc.toChars());
}
}
override void visit(ContinueStatement s)
{
debug (LOGCOMPILE)
{
printf("%s ContinueStatement::ctfeCompile\n", s.loc.toChars());
}
}
override void visit(WithStatement s)
{
debug (LOGCOMPILE)
{
printf("%s WithStatement::ctfeCompile\n", s.loc.toChars());
}
// If it is with(Enum) {...}, just execute the body.
if (s.exp.op == TOK.scope_ || s.exp.op == TOK.type)
{
}
else
{
ccf.onDeclaration(s.wthis);
ccf.onExpression(s.exp);
}
if (s._body)
ctfeCompile(s._body);
}
override void visit(TryCatchStatement s)
{
debug (LOGCOMPILE)
{
printf("%s TryCatchStatement::ctfeCompile\n", s.loc.toChars());
}
if (s._body)
ctfeCompile(s._body);
for (size_t i = 0; i < s.catches.dim; i++)
{
Catch ca = (*s.catches)[i];
if (ca.var)
ccf.onDeclaration(ca.var);
if (ca.handler)
ctfeCompile(ca.handler);
}
}
override void visit(ThrowStatement s)
{
debug (LOGCOMPILE)
{
printf("%s ThrowStatement::ctfeCompile\n", s.loc.toChars());
}
ccf.onExpression(s.exp);
}
override void visit(GotoStatement s)
{
debug (LOGCOMPILE)
{
printf("%s GotoStatement::ctfeCompile\n", s.loc.toChars());
}
}
override void visit(ImportStatement s)
{
debug (LOGCOMPILE)
{
printf("%s ImportStatement::ctfeCompile\n", s.loc.toChars());
}
// Contains no variables or executable code
}
override void visit(ForeachRangeStatement s)
{
debug (LOGCOMPILE)
{
printf("%s ForeachRangeStatement::ctfeCompile\n", s.loc.toChars());
}
// rewritten for ForStatement
assert(0);
}
override void visit(AsmStatement s)
{
debug (LOGCOMPILE)
{
printf("%s AsmStatement::ctfeCompile\n", s.loc.toChars());
}
// we can't compile asm statements
}
void ctfeCompile(Statement s)
{
s.accept(this);
}
}
/*************************************
* Compile this function for CTFE.
* At present, this merely allocates variables.
*/
private void ctfeCompile(FuncDeclaration fd)
{
debug (LOGCOMPILE)
{
printf("\n%s FuncDeclaration::ctfeCompile %s\n", fd.loc.toChars(), fd.toChars());
}
assert(!fd.ctfeCode);
assert(!fd.semantic3Errors);
assert(fd.semanticRun == PASS.semantic3done);
fd.ctfeCode = new CompiledCtfeFunction(fd);
if (fd.parameters)
{
Type tb = fd.type.toBasetype();
assert(tb.ty == Tfunction);
for (size_t i = 0; i < fd.parameters.dim; i++)
{
VarDeclaration v = (*fd.parameters)[i];
fd.ctfeCode.onDeclaration(v);
}
}
if (fd.vresult)
fd.ctfeCode.onDeclaration(fd.vresult);
scope CtfeCompiler v = new CtfeCompiler(fd.ctfeCode);
v.ctfeCompile(fd.fbody);
}
/*************************************
* 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, TOK.cantExpression if not,
* or CTFEExp if function returned void.
*/
private Expression interpretFunction(FuncDeclaration fd, InterState* istate, Expressions* arguments, Expression thisarg)
{
debug (LOG)
{
printf("\n********\n%s FuncDeclaration::interpret(istate = %p) %s\n", fd.loc.toChars(), istate, fd.toChars());
}
if (fd.semanticRun == PASS.semantic3)
{
fd.error("circular dependency. Functions cannot be interpreted while being compiled");
return CTFEExp.cantexp;
}
if (!fd.functionSemantic3())
return CTFEExp.cantexp;
if (fd.semanticRun < PASS.semantic3done)
return CTFEExp.cantexp;
// CTFE-compile the function
if (!fd.ctfeCode)
ctfeCompile(fd);
Type tb = fd.type.toBasetype();
assert(tb.ty == Tfunction);
TypeFunction tf = cast(TypeFunction)tb;
if (tf.varargs && arguments && ((fd.parameters && arguments.dim != fd.parameters.dim) || (!fd.parameters && arguments.dim)))
{
fd.error("C-style variadic functions are not yet implemented in CTFE");
return CTFEExp.cantexp;
}
// 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 (fd.isNested() && fd.toParent2().isFuncDeclaration() && !thisarg && istate)
thisarg = ctfeStack.getThis();
if (fd.needThis() && !thisarg)
{
// error, no this. Prevent segfault.
// Here should be unreachable by the strict 'this' check in front-end.
fd.error("need `this` to access member `%s`", fd.toChars());
return CTFEExp.cantexp;
}
// Place to hold all the arguments to the function while
// we are evaluating them.
Expressions eargs;
size_t dim = arguments ? arguments.dim : 0;
assert((fd.parameters ? fd.parameters.dim : 0) == dim);
/* Evaluate all the arguments to the function,
* store the results in eargs[]
*/
eargs.setDim(dim);
for (size_t i = 0; i < dim; i++)
{
Expression earg = (*arguments)[i];
Parameter fparam = Parameter.getNth(tf.parameters, i);
if (fparam.storageClass & (STC.out_ | STC.ref_))
{
if (!istate && (fparam.storageClass & STC.out_))
{
// 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 CTFEExp.cantexp;
}
// Convert all reference arguments into lvalue references
earg = interpret(earg, istate, ctfeNeedLvalue);
if (CTFEExp.isCantExp(earg))
return earg;
}
else if (fparam.storageClass & STC.lazy_)
{
}
else
{
/* Value parameters
*/
Type ta = fparam.type.toBasetype();
if (ta.ty == Tsarray && earg.op == TOK.address)
{
/* Static arrays are passed by a simple pointer.
* Skip past this to get at the actual arg.
*/
earg = (cast(AddrExp)earg).e1;
}
earg = interpret(earg, istate);
if (CTFEExp.isCantExp(earg))
return earg;
/* Struct literals are passed by value, but we don't need to
* copy them if they are passed as const
*/
if (earg.op == TOK.structLiteral && !(fparam.storageClass & (STC.const_ | STC.immutable_)))
earg = copyLiteral(earg).copy();
}
if (earg.op == TOK.thrownException)
{
if (istate)
return earg;
(cast(ThrownExceptionExp)earg).generateUncaughtError();
return CTFEExp.cantexp;
}
eargs[i] = earg;
}
// Now that we've evaluated all the arguments, we can start the frame
// (this is the moment when the 'call' actually takes place).
InterState istatex;
istatex.caller = istate;
istatex.fd = fd;
ctfeStack.startFrame(thisarg);
if (fd.vthis && thisarg)
{
ctfeStack.push(fd.vthis);
setValue(fd.vthis, thisarg);
}
for (size_t i = 0; i < dim; i++)
{
Expression earg = eargs[i];
Parameter fparam = Parameter.getNth(tf.parameters, i);
VarDeclaration v = (*fd.parameters)[i];
debug (LOG)
{
printf("arg[%d] = %s\n", i, earg.toChars());
}
ctfeStack.push(v);
if ((fparam.storageClass & (STC.out_ | STC.ref_)) && earg.op == TOK.variable && (cast(VarExp)earg).var.toParent2() == fd)
{
VarDeclaration vx = (cast(VarExp)earg).var.isVarDeclaration();
if (!vx)
{
fd.error("cannot interpret `%s` as a `ref` parameter", earg.toChars());
return CTFEExp.cantexp;
}
/* vx is a variable that is declared in fd.
* It means that fd is recursively called. e.g.
*
* void fd(int n, ref int v = dummy) {
* int vx;
* if (n == 1) fd(2, vx);
* }
* fd(1);
*
* The old value of vx on the stack in fd(1)
* should be saved at the start of fd(2, vx) call.
*/
int oldadr = vx.ctfeAdrOnStack;
ctfeStack.push(vx);
assert(!hasValue(vx)); // vx is made uninitialized
// https://issues.dlang.org/show_bug.cgi?id=14299
// v.ctfeAdrOnStack should be saved already
// in the stack before the overwrite.
v.ctfeAdrOnStack = oldadr;
assert(hasValue(v)); // ref parameter v should refer existing value.
}
else
{
// Value parameters and non-trivial references
setValueWithoutChecking(v, earg);
}
debug (LOG)
{
printf("interpreted arg[%d] = %s\n", i, earg.toChars());
showCtfeExpr(earg);
}
debug (LOGASSIGN)
{
printf("interpreted arg[%d] = %s\n", i, earg.toChars());
showCtfeExpr(earg);
}
}
if (fd.vresult)
ctfeStack.push(fd.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;
fd.error("CTFE recursion limit exceeded");
e = CTFEExp.cantexp;
break;
}
e = interpret(fd.fbody, &istatex);
if (CTFEExp.isCantExp(e))
{
debug (LOG)
{
printf("function body failed to interpret\n");
}
}
if (istatex.start)
{
fd.error("CTFE internal error: failed to resume at statement `%s`", istatex.start.toChars());
return CTFEExp.cantexp;
}
/* 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 (CTFEExp.isGotoExp(e))
{
istatex.start = istatex.gotoTarget; // set starting statement
istatex.gotoTarget = null;
}
else
{
assert(!e || (e.op != TOK.continue_ && e.op != TOK.break_));
break;
}
}
// If fell off the end of a void function, return void
if (!e && tf.next.ty == Tvoid)
e = CTFEExp.voidexp;
if (tf.isref && e.op == TOK.variable && (cast(VarExp)e).var == fd.vthis)
e = thisarg;
assert(e !is null);
// Leave the function
--CtfeStatus.callDepth;
ctfeStack.endFrame();
// If it generated an uncaught exception, report error.
if (!istate && e.op == TOK.thrownException)
{
(cast(ThrownExceptionExp)e).generateUncaughtError();
e = CTFEExp.cantexp;
}