Debian Codegraph @

gcc/d/dmd/dinterpret.d

raw
1 /**
2 * The entry point for CTFE.
3 *
4 * Specification: ($LINK2 https://dlang.org/spec/function.html#interpretation, Compile Time Function Execution (CTFE))
5 *
6 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
7 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
8 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/dinterpret.d, _dinterpret.d)
10 * Documentation: https://dlang.org/phobos/dmd_dinterpret.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/dinterpret.d
12 */
13
14 module dmd.dinterpret;
15
16 import core.stdc.stdio;
17 import core.stdc.stdlib;
18 import core.stdc.string;
19 import dmd.arraytypes;
20 import dmd.astenums;
21 import dmd.attrib;
22 import dmd.builtin;
23 import dmd.constfold;
24 import dmd.ctfeexpr;
25 import dmd.dcast;
26 import dmd.dclass;
27 import dmd.declaration;
28 import dmd.dstruct;
29 import dmd.dsymbol;
30 import dmd.dsymbolsem;
31 import dmd.dtemplate;
32 import dmd.errors;
33 import dmd.expression;
34 import dmd.expressionsem;
35 import dmd.func;
36 import dmd.funcsem;
37 import dmd.globals;
38 import dmd.hdrgen;
39 import dmd.id;
40 import dmd.identifier;
41 import dmd.init;
42 import dmd.initsem;
43 import dmd.location;
44 import dmd.mtype;
45 import dmd.root.rmem;
46 import dmd.root.array;
47 import dmd.root.ctfloat;
48 import dmd.root.region;
49 import dmd.rootobject;
50 import dmd.root.utf;
51 import dmd.statement;
52 import dmd.tokens;
53 import dmd.typesem : mutableOf, equivalent, pointerTo, sarrayOf, arrayOf, size;
54 import dmd.utils : arrayCastBigEndian;
55 import dmd.visitor;
56
57 /*************************************
58 * Entry point for CTFE.
59 * A compile-time result is required. Give an error if not possible.
60 *
61 * `e` must be semantically valid expression. In other words, it should not
62 * contain any `ErrorExp`s in it. But, CTFE interpretation will cross over
63 * functions and may invoke a function that contains `ErrorStatement` in its body.
64 * If that, the "CTFE failed because of previous errors" error is raised.
65 */
66 public Expression ctfeInterpret(Expression e)
67 {
68 switch (e.op)
69 {
70 case EXP.int64:
71 case EXP.float64:
72 case EXP.complex80:
73 case EXP.null_:
74 case EXP.void_:
75 case EXP.string_:
76 case EXP.this_:
77 case EXP.super_:
78 case EXP.type:
79 case EXP.typeid_:
80 case EXP.template_: // non-eponymous template/instance
81 case EXP.scope_: // ditto
82 case EXP.dotTemplateDeclaration: // ditto, e.e1 doesn't matter here
83 case EXP.dotTemplateInstance: // ditto
84 case EXP.dot: // ditto
85 if (e.type.ty == Terror)
86 return ErrorExp.get();
87 goto case EXP.error;
88
89 case EXP.error:
90 return e;
91
92 default:
93 break;
94 }
95
96 assert(e.type); // https://issues.dlang.org/show_bug.cgi?id=14642
97 //assert(e.type.ty != Terror); // FIXME
98 if (e.type.ty == Terror)
99 return ErrorExp.get();
100
101 auto rgnpos = ctfeGlobals.region.savePos();
102
103 import dmd.timetrace;
104 timeTraceBeginEvent(TimeTraceEventType.ctfe);
105 scope (exit) timeTraceEndEvent(TimeTraceEventType.ctfe, e);
106
107 Expression result = interpret(e, null);
108
109 // Report an error if the expression contained a `ThrowException` and
110 // hence generated an uncaught exception
111 if (auto tee = result.isThrownExceptionExp())
112 {
113 tee.generateUncaughtError();
114 result = CTFEExp.cantexp;
115 }
116 else
117 result = copyRegionExp(result);
118
119 if (!CTFEExp.isCantExp(result))
120 result = scrubReturnValue(e.loc, result);
121 if (CTFEExp.isCantExp(result))
122 result = ErrorExp.get();
123
124 ctfeGlobals.region.release(rgnpos);
125
126 return result;
127 }
128
129 /* Run CTFE on the expression, but allow the expression to be a TypeExp
130 * or a tuple containing a TypeExp. (This is required by pragma(msg)).
131 */
132 public Expression ctfeInterpretForPragmaMsg(Expression e)
133 {
134 if (e.op == EXP.error || e.op == EXP.type)
135 return e;
136
137 // It's also OK for it to be a function declaration (happens only with
138 // __traits(getOverloads))
139 if (auto ve = e.isVarExp())
140 if (ve.var.isFuncDeclaration())
141 {
142 return e;
143 }
144
145 auto tup = e.isTupleExp();
146 if (!tup)
147 return e.ctfeInterpret();
148
149 // Tuples need to be treated separately, since they are
150 // allowed to contain a TypeExp in this case.
151
152 Expressions* expsx = null;
153 foreach (i, g; *tup.exps)
154 {
155 auto h = ctfeInterpretForPragmaMsg(g);
156 if (h != g)
157 {
158 if (!expsx)
159 {
160 expsx = tup.exps.copy();
161 }
162 (*expsx)[i] = h;
163 }
164 }
165 if (expsx)
166 {
167 auto te = new TupleExp(e.loc, expsx);
168 expandTuples(te.exps);
169 te.type = new TypeTuple(te.exps);
170 return te;
171 }
172 return e;
173 }
174
175 public Expression getValue(VarDeclaration vd)
176 {
177 return ctfeGlobals.stack.getValue(vd);
178 }
179
180 /*************************************************
181 * Allocate an Expression in the ctfe region.
182 * Params:
183 * T = type of Expression to allocate
184 * args = arguments to Expression's constructor
185 * Returns:
186 * allocated Expression
187 */
188 T ctfeEmplaceExp(T : Expression, Args...)(Args args)
189 {
190 if (mem.isGCEnabled)
191 return new T(args);
192 auto p = ctfeGlobals.region.malloc(__traits(classInstanceSize, T));
193 emplaceExp!T(p, args);
194 return cast(T)p;
195 }
196
197 // CTFE diagnostic information
198 public extern (C++) void printCtfePerformanceStats()
199 {
200 debug (SHOWPERFORMANCE)
201 {
202 printf(" ---- CTFE Performance ----\n");
203 printf("max call depth = %d\tmax stack = %d\n", ctfeGlobals.maxCallDepth, ctfeGlobals.stack.maxStackUsage());
204 printf("array allocs = %d\tassignments = %d\n\n", ctfeGlobals.numArrayAllocs, ctfeGlobals.numAssignments);
205 }
206 }
207
208 /**************************
209 */
210
211 void incArrayAllocs()
212 {
213 ++ctfeGlobals.numArrayAllocs;
214 }
215
216 /* ================================================ Implementation ======================================= */
217
218 private:
219
220 /***************
221 * Collect together globals used by CTFE
222 */
223 struct CtfeGlobals
224 {
225 Region region;
226
227 CtfeStack stack;
228
229 int callDepth = 0; // current number of recursive calls
230
231 // When printing a stack trace, suppress this number of calls
232 int stackTraceCallsToSuppress = 0;
233
234 int maxCallDepth = 0; // highest number of recursive calls
235 int numArrayAllocs = 0; // Number of allocated arrays
236 int numAssignments = 0; // total number of assignments executed
237 }
238
239 __gshared CtfeGlobals ctfeGlobals;
240
241 enum CTFEGoal : int
242 {
243 RValue, /// Must return an Rvalue (== CTFE value)
244 LValue, /// Must return an Lvalue (== CTFE reference)
245 Nothing, /// The return value is not required
246 }
247
248 //debug = LOG;
249 //debug = LOGASSIGN;
250 //debug = LOGCOMPILE;
251 //debug = SHOWPERFORMANCE;
252
253 // Maximum allowable recursive function calls in CTFE
254 enum CTFE_RECURSION_LIMIT = 1000;
255
256 /**
257 The values of all CTFE variables
258 */
259 struct CtfeStack
260 {
261 private:
262 /* The stack. Every declaration we encounter is pushed here,
263 * together with the VarDeclaration, and the previous
264 * stack address of that variable, so that we can restore it
265 * when we leave the stack frame.
266 * Note that when a function is forward referenced, the interpreter must
267 * run semantic3, and that may start CTFE again with a NULL istate. Thus
268 * the stack might not be empty when CTFE begins.
269 *
270 * Ctfe Stack addresses are just 0-based integers, but we save
271 * them as 'void *' because Array can only do pointers.
272 */
273 Expressions values; // values on the stack
274 VarDeclarations vars; // corresponding variables
275 Array!(void*) savedId; // id of the previous state of that var
276
277 Array!(void*) frames; // all previous frame pointers
278 Expressions savedThis; // all previous values of localThis
279
280 /* Global constants get saved here after evaluation, so we never
281 * have to redo them. This saves a lot of time and memory.
282 */
283 Expressions globalValues; // values of global constants
284
285 size_t framepointer; // current frame pointer
286 size_t maxStackPointer; // most stack we've ever used
287 Expression localThis; // value of 'this', or NULL if none
288
289 public:
290 size_t stackPointer() @safe
291 {
292 return values.length;
293 }
294
295 // The current value of 'this', or NULL if none
296 Expression getThis() @safe
297 {
298 return localThis;
299 }
300
301 // Largest number of stack positions we've used
302 size_t maxStackUsage() @safe
303 {
304 return maxStackPointer;
305 }
306
307 // Start a new stack frame, using the provided 'this'.
308 void startFrame(Expression thisexp)
309 {
310 frames.push(cast(void*)cast(size_t)framepointer);
311 savedThis.push(localThis);
312 framepointer = stackPointer();
313 localThis = thisexp;
314 }
315
316 void endFrame()
317 {
318 size_t oldframe = cast(size_t)frames[frames.length - 1];
319 localThis = savedThis[savedThis.length - 1];
320 popAll(framepointer);
321 framepointer = oldframe;
322 frames.setDim(frames.length - 1);
323 savedThis.setDim(savedThis.length - 1);
324 }
325
326 bool isInCurrentFrame(VarDeclaration v)
327 {
328 if (v.isDataseg() && !v.isCTFE())
329 return false; // It's a global
330 return v.ctfeAdrOnStack >= framepointer;
331 }
332
333 Expression getValue(VarDeclaration v)
334 {
335 //printf("getValue() %s\n", v.toChars());
336 if ((v.isDataseg() || v.storage_class & STC.manifest) && !v.isCTFE())
337 {
338 assert(v.ctfeAdrOnStack < globalValues.length);
339 return globalValues[v.ctfeAdrOnStack];
340 }
341 assert(v.ctfeAdrOnStack < stackPointer());
342 return values[v.ctfeAdrOnStack];
343 }
344
345 void setValue(VarDeclaration v, Expression e)
346 {
347 //printf("setValue() %s : %s\n", v.toChars(), e.toChars());
348 assert(!v.isDataseg() || v.isCTFE());
349 assert(v.ctfeAdrOnStack < stackPointer());
350 values[v.ctfeAdrOnStack] = e;
351 }
352
353 void push(VarDeclaration v)
354 {
355 //printf("push() %s\n", v.toChars());
356 assert(!v.isDataseg() || v.isCTFE());
357 if (v.ctfeAdrOnStack != VarDeclaration.AdrOnStackNone && v.ctfeAdrOnStack >= framepointer)
358 {
359 // Already exists in this frame, reuse it.
360 values[v.ctfeAdrOnStack] = null;
361 return;
362 }
363 savedId.push(cast(void*)cast(size_t)v.ctfeAdrOnStack);
364 v.ctfeAdrOnStack = cast(uint)values.length;
365 vars.push(v);
366 values.push(null);
367 }
368
369 void pop(VarDeclaration v)
370 {
371 assert(!v.isDataseg() || v.isCTFE());
372 assert(!v.isReference());
373 const oldid = v.ctfeAdrOnStack;
374 v.ctfeAdrOnStack = cast(uint)cast(size_t)savedId[oldid];
375 if (v.ctfeAdrOnStack == values.length - 1)
376 {
377 values.pop();
378 vars.pop();
379 savedId.pop();
380 }
381 }
382
383 void popAll(size_t stackpointer)
384 {
385 if (stackPointer() > maxStackPointer)
386 maxStackPointer = stackPointer();
387 assert(values.length >= stackpointer);
388 for (size_t i = stackpointer; i < values.length; ++i)
389 {
390 VarDeclaration v = vars[i];
391 v.ctfeAdrOnStack = cast(uint)cast(size_t)savedId[i];
392 }
393 values.setDim(stackpointer);
394 vars.setDim(stackpointer);
395 savedId.setDim(stackpointer);
396 }
397
398 void saveGlobalConstant(VarDeclaration v, Expression e)
399 {
400 assert(v._init && (v.isConst() || v.isImmutable() || v.storage_class & STC.manifest) && !v.isCTFE());
401 v.ctfeAdrOnStack = cast(uint)globalValues.length;
402 globalValues.push(copyRegionExp(e));
403 }
404 }
405
406 private struct InterState
407 {
408 InterState* caller; // calling function's InterState
409 FuncDeclaration fd; // function being interpreted
410 Statement start; // if !=NULL, start execution at this statement
411
412 /* target of CTFEExp result; also
413 * target of labelled CTFEExp or
414 * CTFEExp. (null if no label).
415 */
416 Statement gotoTarget;
417 }
418
419 /*************************************
420 * Attempt to interpret a function given the arguments.
421 * Params:
422 * pue = storage for result
423 * fd = function being called
424 * istate = state for calling function (NULL if none)
425 * arguments = function arguments
426 * thisarg = 'this', if a needThis() function, NULL if not.
427 *
428 * Returns:
429 * result expression if successful, EXP.cantExpression if not,
430 * or CTFEExp if function returned void.
431 */
432 private Expression interpretFunction(UnionExp* pue, FuncDeclaration fd, InterState* istate, Expressions* arguments, Expression thisarg)
433 {
434 debug (LOG)
435 {
436 printf("\n********\n%s FuncDeclaration::interpret(istate = %p) %s\n", fd.loc.toChars(), istate, fd.toChars());
437 }
438
439 scope dlg = () {
440 import dmd.common.outbuffer;
441 auto strbuf = OutBuffer(20);
442 strbuf.writestring(fd.toPrettyChars());
443 strbuf.write("(");
444 if (arguments)
445 {
446 foreach (i, arg; *arguments)
447 {
448 if (i > 0)
449 strbuf.write(", ");
450 strbuf.writestring(arg.toChars());
451 }
452 }
453 strbuf.write(")");
454 return strbuf.extractSlice();
455 };
456 import dmd.timetrace;
457 timeTraceBeginEvent(TimeTraceEventType.ctfeCall);
458 scope (exit) timeTraceEndEvent(TimeTraceEventType.ctfeCall, fd, dlg);
459
460 void fdError(const(char)* msg)
461 {
462 error(fd.loc, "%s `%s` %s", fd.kind, fd.toPrettyChars, msg);
463 }
464
465 assert(pue);
466 if (fd.semanticRun == PASS.semantic3)
467 {
468 fdError("circular dependency. Functions cannot be interpreted while being compiled");
469 return CTFEExp.cantexp;
470 }
471 if (!functionSemantic3(fd))
472 return CTFEExp.cantexp;
473 if (fd.semanticRun < PASS.semantic3done)
474 {
475 fdError("circular dependency. Functions cannot be interpreted while being compiled");
476 return CTFEExp.cantexp;
477 }
478
479 auto tf = fd.type.toBasetype().isTypeFunction();
480 if (tf.parameterList.varargs != VarArg.none && arguments &&
481 ((fd.parameters && arguments.length != fd.parameters.length) || (!fd.parameters && arguments.length)))
482 {
483 fdError("C-style variadic functions are not yet implemented in CTFE");
484 return CTFEExp.cantexp;
485 }
486
487 // Nested functions always inherit the 'this' pointer from the parent,
488 // except for delegates. (Note that the 'this' pointer may be null).
489 // Func literals report isNested() even if they are in global scope,
490 // so we need to check that the parent is a function.
491 if (fd.isNested() && fd.toParentLocal().isFuncDeclaration() && !thisarg && istate)
492 thisarg = ctfeGlobals.stack.getThis();
493
494 if (fd.needThis() && !thisarg)
495 {
496 // error, no this. Prevent segfault.
497 // Here should be unreachable by the strict 'this' check in front-end.
498 error(fd.loc, "%s `%s` need `this` to access member `%s`", fd.kind, fd.toPrettyChars, fd.toChars());
499 return CTFEExp.cantexp;
500 }
501
502 // Place to hold all the arguments to the function while
503 // we are evaluating them.
504 size_t dim = arguments ? arguments.length : 0;
505 assert((fd.parameters ? fd.parameters.length : 0) == dim);
506
507 /* Evaluate all the arguments to the function,
508 * store the results in eargs[]
509 */
510 Expressions eargs = Expressions(dim);
511 for (size_t i = 0; i < dim; i++)
512 {
513 Expression earg = (*arguments)[i];
514 Parameter fparam = tf.parameterList[i];
515
516 if (fparam.isReference())
517 {
518 if (!istate && (fparam.storageClass & STC.out_))
519 {
520 // initializing an out parameter involves writing to it.
521 error(earg.loc, "global `%s` cannot be passed as an `out` parameter at compile time", earg.toChars());
522 return CTFEExp.cantexp;
523 }
524 // Convert all reference arguments into lvalue references
525 earg = interpretRegion(earg, istate, CTFEGoal.LValue);
526 if (CTFEExp.isCantExp(earg))
527 return earg;
528 }
529 else if (fparam.isLazy())
530 {
531 }
532 else
533 {
534 /* Value parameters
535 */
536 Type ta = fparam.type.toBasetype();
537 if (ta.ty == Tsarray)
538 if (auto eaddr = earg.isAddrExp())
539 {
540 /* Static arrays are passed by a simple pointer.
541 * Skip past this to get at the actual arg.
542 */
543 earg = eaddr.e1;
544 }
545
546 earg = interpretRegion(earg, istate);
547 if (CTFEExp.isCantExp(earg))
548 return earg;
549
550 /* Struct literals are passed by value, but we don't need to
551 * copy them if they are passed as const
552 */
553 if (earg.op == EXP.structLiteral && !(fparam.storageClass & (STC.const_ | STC.immutable_)))
554 earg = copyLiteral(earg).copy();
555 }
556 if (auto tee = earg.isThrownExceptionExp())
557 {
558 if (istate)
559 return tee;
560 tee.generateUncaughtError();
561 return CTFEExp.cantexp;
562 }
563 eargs[i] = earg;
564 }
565
566 // Now that we've evaluated all the arguments, we can start the frame
567 // (this is the moment when the 'call' actually takes place).
568 InterState istatex;
569 istatex.caller = istate;
570 istatex.fd = fd;
571
572 if (fd.hasDualContext())
573 {
574 Expression arg0 = thisarg;
575 if (arg0 && arg0.type.ty == Tstruct)
576 {
577 Type t = arg0.type.pointerTo();
578 arg0 = ctfeEmplaceExp!AddrExp(arg0.loc, arg0);
579 arg0.type = t;
580 }
581 auto elements = new Expressions(2);
582 (*elements)[0] = arg0;
583 (*elements)[1] = ctfeGlobals.stack.getThis();
584 Type t2 = Type.tvoidptr.sarrayOf(2);
585 const loc = thisarg ? thisarg.loc : fd.loc;
586 thisarg = ctfeEmplaceExp!ArrayLiteralExp(loc, t2, elements);
587 thisarg = ctfeEmplaceExp!AddrExp(loc, thisarg);
588 thisarg.type = t2.pointerTo();
589 }
590
591 ctfeGlobals.stack.startFrame(thisarg);
592 if (fd.vthis && thisarg)
593 {
594 ctfeGlobals.stack.push(fd.vthis);
595 setValue(fd.vthis, thisarg);
596 }
597
598 for (size_t i = 0; i < dim; i++)
599 {
600 Expression earg = eargs[i];
601 Parameter fparam = tf.parameterList[i];
602 VarDeclaration v = (*fd.parameters)[i];
603 debug (LOG)
604 {
605 printf("arg[%zu] = %s\n", i, earg.toChars());
606 }
607 ctfeGlobals.stack.push(v);
608
609 if (fparam.isReference() && earg.op == EXP.variable &&
610 earg.isVarExp().var.toParent2() == fd)
611 {
612 VarDeclaration vx = earg.isVarExp().var.isVarDeclaration();
613 if (!vx)
614 {
615 error(fd.loc, "%s `%s` cannot interpret `%s` as a `ref` parameter", fd.kind, fd.toPrettyChars, earg.toChars());
616 return CTFEExp.cantexp;
617 }
618
619 /* vx is a variable that is declared in fd.
620 * It means that fd is recursively called. e.g.
621 *
622 * void fd(int n, ref int v = dummy) {
623 * int vx;
624 * if (n == 1) fd(2, vx);
625 * }
626 * fd(1);
627 *
628 * The old value of vx on the stack in fd(1)
629 * should be saved at the start of fd(2, vx) call.
630 */
631 const oldadr = vx.ctfeAdrOnStack;
632
633 ctfeGlobals.stack.push(vx);
634 assert(!hasValue(vx)); // vx is made uninitialized
635
636 // https://issues.dlang.org/show_bug.cgi?id=14299
637 // v.ctfeAdrOnStack should be saved already
638 // in the stack before the overwrite.
639 v.ctfeAdrOnStack = oldadr;
640 assert(hasValue(v)); // ref parameter v should refer existing value.
641 }
642 else
643 {
644 // Value parameters and non-trivial references
645 setValueWithoutChecking(v, earg);
646 }
647 debug (LOG)
648 {
649 printf("interpreted arg[%zu] = %s\n", i, earg.toChars());
650 showCtfeExpr(earg);
651 }
652 debug (LOGASSIGN)
653 {
654 printf("interpreted arg[%zu] = %s\n", i, earg.toChars());
655 showCtfeExpr(earg);
656 }
657 }
658
659 if (fd.vresult)
660 ctfeGlobals.stack.push(fd.vresult);
661
662 // Enter the function
663 ++ctfeGlobals.callDepth;
664 if (ctfeGlobals.callDepth > ctfeGlobals.maxCallDepth)
665 ctfeGlobals.maxCallDepth = ctfeGlobals.callDepth;
666
667 Expression e = null;
668 while (1)
669 {
670 if (ctfeGlobals.callDepth > CTFE_RECURSION_LIMIT)
671 {
672 fdError("CTFE recursion limit exceeded");
673 e = CTFEExp.cantexp;
674 break;
675 }
676 e = interpretStatement(pue, fd.fbody, &istatex);
677 if (CTFEExp.isCantExp(e))
678 {
679 debug (LOG)
680 {
681 printf("function body failed to interpret\n");
682 }
683 }
684
685 if (istatex.start)
686 {
687 error(fd.loc, "%s `%s` CTFE internal error: failed to resume at statement `%s`", fd.kind, fd.toPrettyChars, istatex.start.toChars());
688 return CTFEExp.cantexp;
689 }
690
691 /* This is how we deal with a recursive statement AST
692 * that has arbitrary goto statements in it.
693 * Bubble up a 'result' which is the target of the goto
694 * statement, then go recursively down the AST looking
695 * for that statement, then execute starting there.
696 */
697 if (CTFEExp.isGotoExp(e))
698 {
699 istatex.start = istatex.gotoTarget; // set starting statement
700 istatex.gotoTarget = null;
701 }
702 else
703 {
704 assert(!e || (e.op != EXP.continue_ && e.op != EXP.break_));
705 break;
706 }
707 }
708 // If fell off the end of a void function, return void
709 if (!e)
710 {
711 if (tf.next.ty == Tvoid)
712 e = CTFEExp.voidexp;
713 else
714 {
715 /* missing a return statement can happen with C functions
716 * https://issues.dlang.org/show_bug.cgi?id=23056
717 */
718 fdError("no return value from function");
719 e = CTFEExp.cantexp;
720 }
721 }
722
723 if (tf.isRef && e.op == EXP.variable && e.isVarExp().var == fd.vthis)
724 e = thisarg;
725 if (tf.isRef && fd.hasDualContext() && e.op == EXP.index)
726 {
727 auto ie = e.isIndexExp();
728 auto pe = ie.e1.isPtrExp();
729 auto ve = !pe ? null : pe.e1.isVarExp();
730 if (ve && ve.var == fd.vthis)
731 {
732 auto ne = ie.e2.isIntegerExp();
733 assert(ne);
734 auto ale = thisarg.isAddrExp().e1.isArrayLiteralExp();
735 e = (*ale.elements)[cast(size_t)ne.getInteger()];
736 if (auto ae = e.isAddrExp())
737 {
738 e = ae.e1;
739 }
740 }
741 }
742
743 // Leave the function
744 --ctfeGlobals.callDepth;
745
746 ctfeGlobals.stack.endFrame();
747
748 // If it generated an uncaught exception, report error.
749 if (!istate && e.isThrownExceptionExp())
750 {
751 if (e == pue.exp())
752 e = pue.copy();
753 e.isThrownExceptionExp().generateUncaughtError();
754 e = CTFEExp.cantexp;
755 }
756
757 return e;
758 }
759
760 /// used to collect coverage information in ctfe
761 void incUsageCtfe(InterState* istate, Loc loc)
762 {
763 if (global.params.ctfe_cov && istate)
764 {
765 auto line = loc.linnum;
766 auto mod = istate.fd.getModule();
767
768 ++mod.ctfe_cov[line];
769 }
770 }
771
772 /***********************************
773 * Interpret the statement.
774 * Params:
775 * s = Statement to interpret
776 * istate = context
777 * Returns:
778 * NULL continue to next statement
779 * EXP.cantExpression cannot interpret statement at compile time
780 * !NULL expression from return statement, or thrown exception
781 */
782
783 Expression interpretStatement(Statement s, InterState* istate)
784 {
785 UnionExp ue = void;
786 auto result = interpretStatement(&ue, s, istate);
787 if (result == ue.exp())
788 result = ue.copy();
789 return result;
790 }
791
792 ///
793 Expression interpretStatement(UnionExp* pue, Statement s, InterState* istate)
794 {
795 Expression result;
796
797 // If e is EXP.throw_exception or EXP.cantExpression,
798 // set it to 'result' and returns true.
799 bool exceptionOrCant(Expression e)
800 {
801 if (exceptionOrCantInterpret(e))
802 {
803 // Make sure e is not pointing to a stack temporary
804 result = (e.op == EXP.cantExpression) ? CTFEExp.cantexp : e;
805 return true;
806 }
807 return false;
808 }
809
810 /******************************** Statement ***************************/
811
812 void visitDefaultCase(Statement s)
813 {
814 debug (LOG)
815 {
816 printf("%s Statement::interpret() %s\n", s.loc.toChars(), s.toChars());
817 }
818 if (istate.start)
819 {
820 if (istate.start != s)
821 return;
822 istate.start = null;
823 }
824
825 error(s.loc, "statement `%s` cannot be interpreted at compile time", s.toChars());
826 result = CTFEExp.cantexp;
827 }
828
829 void visitExp(ExpStatement s)
830 {
831 debug (LOG)
832 {
833 printf("%s ExpStatement::interpret(%s)\n", s.loc.toChars(), s.exp ? s.exp.toChars() : "");
834 }
835 if (istate.start)
836 {
837 if (istate.start != s)
838 return;
839 istate.start = null;
840 }
841 if (s.exp && s.exp.hasCode)
842 incUsageCtfe(istate, s.loc);
843
844 Expression e = interpret(pue, s.exp, istate, CTFEGoal.Nothing);
845 if (exceptionOrCant(e))
846 return;
847 }
848
849 void visitDtorExp(DtorExpStatement s)
850 {
851 visitExp(s);
852 }
853
854 void visitCompound(CompoundStatement s)
855 {
856 debug (LOG)
857 {
858 printf("%s CompoundStatement::interpret()\n", s.loc.toChars());
859 }
860 if (istate.start == s)
861 istate.start = null;
862
863 const dim = s.statements ? s.statements.length : 0;
864 foreach (i; 0 .. dim)
865 {
866 Statement sx = (*s.statements)[i];
867 result = interpretStatement(pue, sx, istate);
868 if (result)
869 break;
870 }
871 debug (LOG)
872 {
873 printf("%s -CompoundStatement::interpret() %p\n", s.loc.toChars(), result);
874 }
875 }
876
877 void visitCompoundAsm(CompoundAsmStatement s)
878 {
879 visitCompound(s);
880 }
881
882 void visitUnrolledLoop(UnrolledLoopStatement s)
883 {
884 debug (LOG)
885 {
886 printf("%s UnrolledLoopStatement::interpret()\n", s.loc.toChars());
887 }
888 if (istate.start == s)
889 istate.start = null;
890
891 const dim = s.statements ? s.statements.length : 0;
892 foreach (i; 0 .. dim)
893 {
894 Statement sx = (*s.statements)[i];
895 Expression e = interpretStatement(pue, sx, istate);
896 if (!e) // succeeds to interpret, or goto target was not found
897 continue;
898 if (exceptionOrCant(e))
899 return;
900 if (e.op == EXP.break_)
901 {
902 if (istate.gotoTarget && istate.gotoTarget != s)
903 {
904 result = e; // break at a higher level
905 return;
906 }
907 istate.gotoTarget = null;
908 result = null;
909 return;
910 }
911 if (e.op == EXP.continue_)
912 {
913 if (istate.gotoTarget && istate.gotoTarget != s)
914 {
915 result = e; // continue at a higher level
916 return;
917 }
918 istate.gotoTarget = null;
919 continue;
920 }
921
922 // expression from return statement, or thrown exception
923 result = e;
924 break;
925 }
926 }
927
928 void visitIf(IfStatement s)
929 {
930 debug (LOG)
931 {
932 printf("%s IfStatement::interpret(%s)\n", s.loc.toChars(), s.condition.toChars());
933 }
934 incUsageCtfe(istate, s.loc);
935 if (istate.start == s)
936 istate.start = null;
937 if (istate.start)
938 {
939 Expression e = null;
940 e = interpretStatement(s.ifbody, istate);
941 if (!e && istate.start)
942 e = interpretStatement(s.elsebody, istate);
943 result = e;
944 return;
945 }
946
947 UnionExp ue = void;
948 Expression e = interpret(&ue, s.condition, istate);
949 assert(e);
950 if (exceptionOrCant(e))
951 return;
952
953 if (isTrueBool(e))
954 result = interpretStatement(pue, s.ifbody, istate);
955 else if (e.toBool().hasValue(false))
956 result = interpretStatement(pue, s.elsebody, istate);
957 else
958 {
959 // no error, or assert(0)?
960 result = CTFEExp.cantexp;
961 }
962 }
963
964 void visitScope(ScopeStatement s)
965 {
966 debug (LOG)
967 {
968 printf("%s ScopeStatement::interpret()\n", s.loc.toChars());
969 }
970 if (istate.start == s)
971 istate.start = null;
972
973 result = interpretStatement(pue, s.statement, istate);
974 }
975
976 void visitReturn(ReturnStatement s)
977 {
978 debug (LOG)
979 {
980 printf("%s ReturnStatement::interpret(%s)\n", s.loc.toChars(), s.exp ? s.exp.toChars() : "");
981 }
982 if (istate.start)
983 {
984 if (istate.start != s)
985 return;
986 istate.start = null;
987 }
988
989 if (!s.exp)
990 {
991 result = CTFEExp.voidexp;
992 return;
993 }
994
995 incUsageCtfe(istate, s.loc);
996 assert(istate && istate.fd && istate.fd.type && istate.fd.type.ty == Tfunction);
997 TypeFunction tf = cast(TypeFunction)istate.fd.type;
998
999 /* If the function returns a ref AND it's been called from an assignment,
1000 * we need to return an lvalue. Otherwise, just do an (rvalue) interpret.
1001 */
1002 if (tf.isRef)
1003 {
1004 result = interpret(pue, s.exp, istate, CTFEGoal.LValue);
1005 return;
1006 }
1007 if (tf.next && tf.next.ty == Tdelegate && istate.fd.closureVars.length > 0)
1008 {
1009 // To support this, we need to copy all the closure vars
1010 // into the delegate literal.
1011 error(s.loc, "closures are not yet supported in CTFE");
1012 result = CTFEExp.cantexp;
1013 return;
1014 }
1015
1016 // We need to treat pointers specially, because EXP.symbolOffset can be used to
1017 // return a value OR a pointer
1018 Expression e = interpret(pue, s.exp, istate);
1019 if (exceptionOrCant(e))
1020 return;
1021
1022 /**
1023 * Interpret `return a ~= b` (i.e. `return _d_arrayappendT{,Trace}(a, b)`) as:
1024 * a ~= b;
1025 * return a;
1026 * This is needed because `a ~= b` has to be interpreted as an lvalue, in order to avoid
1027 * assigning a larger array into a smaller one, such as:
1028 * `a = [1, 2], a ~= [3]` => `[1, 2] ~= [3]` => `[1, 2] = [1, 2, 3]`
1029 */
1030 if (isRuntimeHook(s.exp, Id._d_arrayappendT) || isRuntimeHook(s.exp, Id._d_arrayappendTTrace))
1031 {
1032 auto rs = new ReturnStatement(s.loc, e);
1033 visitReturn(rs);
1034 return;
1035 }
1036
1037 // Disallow returning pointers to stack-allocated variables (bug 7876)
1038 if (!stopPointersEscaping(s.loc, e))
1039 {
1040 result = CTFEExp.cantexp;
1041 return;
1042 }
1043
1044 if (needToCopyLiteral(e))
1045 e = copyLiteral(e).copy();
1046 debug (LOGASSIGN)
1047 {
1048 printf("RETURN %s\n", s.loc.toChars());
1049 showCtfeExpr(e);
1050 }
1051 result = e;
1052 }
1053
1054 void visitBreak(BreakStatement s)
1055 {
1056 debug (LOG)
1057 {
1058 printf("%s BreakStatement::interpret()\n", s.loc.toChars());
1059 }
1060 incUsageCtfe(istate, s.loc);
1061 if (istate.start)
1062 {
1063 if (istate.start != s)
1064 return;
1065 istate.start = null;
1066 }
1067
1068 istate.gotoTarget = findGotoTarget(istate, s.ident);
1069 result = CTFEExp.breakexp;
1070 }
1071
1072 void visitContinue(ContinueStatement s)
1073 {
1074 debug (LOG)
1075 {
1076 printf("%s ContinueStatement::interpret()\n", s.loc.toChars());
1077 }
1078 incUsageCtfe(istate, s.loc);
1079 if (istate.start)
1080 {
1081 if (istate.start != s)
1082 return;
1083 istate.start = null;
1084 }
1085
1086 istate.gotoTarget = findGotoTarget(istate, s.ident);
1087 result = CTFEExp.continueexp;
1088 }
1089
1090 void visitWhile(WhileStatement s)
1091 {
1092 debug (LOG)
1093 {
1094 printf("WhileStatement::interpret()\n");
1095 }
1096 assert(0); // rewritten to ForStatement
1097 }
1098
1099 void visitDo(DoStatement s)
1100 {
1101 debug (LOG)
1102 {
1103 printf("%s DoStatement::interpret()\n", s.loc.toChars());
1104 }
1105 if (istate.start == s)
1106 istate.start = null;
1107
1108 while (1)
1109 {
1110 Expression e = interpretStatement(s._body, istate);
1111 if (!e && istate.start) // goto target was not found
1112 return;
1113 assert(!istate.start);
1114
1115 if (exceptionOrCant(e))
1116 return;
1117 if (e && e.op == EXP.break_)
1118 {
1119 if (istate.gotoTarget && istate.gotoTarget != s)
1120 {
1121 result = e; // break at a higher level
1122 return;
1123 }
1124 istate.gotoTarget = null;
1125 break;
1126 }
1127 if (e && e.op == EXP.continue_)
1128 {
1129 if (istate.gotoTarget && istate.gotoTarget != s)
1130 {
1131 result = e; // continue at a higher level
1132 return;
1133 }
1134 istate.gotoTarget = null;
1135 e = null;
1136 }
1137 if (e)
1138 {
1139 result = e; // bubbled up from ReturnStatement
1140 return;
1141 }
1142
1143 UnionExp ue = void;
1144 incUsageCtfe(istate, s.condition.loc);
1145 e = interpret(&ue, s.condition, istate);
1146 if (exceptionOrCant(e))
1147 return;
1148 if (!e.isConst())
1149 {
1150 result = CTFEExp.cantexp;
1151 return;
1152 }
1153 if (e.toBool().hasValue(false))
1154 break;
1155 assert(isTrueBool(e));
1156 }
1157 assert(result is null);
1158 }
1159
1160 void visitFor(ForStatement s)
1161 {
1162 debug (LOG)
1163 {
1164 printf("%s ForStatement::interpret()\n", s.loc.toChars());
1165 }
1166 if (istate.start == s)
1167 istate.start = null;
1168
1169 UnionExp ueinit = void;
1170 Expression ei = interpretStatement(&ueinit, s._init, istate);
1171 if (exceptionOrCant(ei))
1172 return;
1173 assert(!ei); // s.init never returns from function, or jumps out from it
1174
1175 while (1)
1176 {
1177 if (s.condition && !istate.start)
1178 {
1179 UnionExp ue = void;
1180 incUsageCtfe(istate, s.condition.loc);
1181 Expression e = interpret(&ue, s.condition, istate);
1182 if (exceptionOrCant(e))
1183 return;
1184 if (e.toBool().hasValue(false))
1185 break;
1186 assert(isTrueBool(e));
1187 }
1188
1189 Expression e = interpretStatement(pue, s._body, istate);
1190 if (!e && istate.start) // goto target was not found
1191 return;
1192 assert(!istate.start);
1193
1194 if (exceptionOrCant(e))
1195 return;
1196 if (e && e.op == EXP.break_)
1197 {
1198 if (istate.gotoTarget && istate.gotoTarget != s)
1199 {
1200 result = e; // break at a higher level
1201 return;
1202 }
1203 istate.gotoTarget = null;
1204 break;
1205 }
1206 if (e && e.op == EXP.continue_)
1207 {
1208 if (istate.gotoTarget && istate.gotoTarget != s)
1209 {
1210 result = e; // continue at a higher level
1211 return;
1212 }
1213 istate.gotoTarget = null;
1214 e = null;
1215 }
1216 if (e)
1217 {
1218 result = e; // bubbled up from ReturnStatement
1219 return;
1220 }
1221
1222 UnionExp uei = void;
1223 if (s.increment)
1224 incUsageCtfe(istate, s.increment.loc);
1225 e = interpret(&uei, s.increment, istate, CTFEGoal.Nothing);
1226 if (exceptionOrCant(e))
1227 return;
1228 }
1229 assert(result is null);
1230 }
1231
1232 void visitForeach(ForeachStatement s)
1233 {
1234 assert(0); // rewritten to ForStatement
1235 }
1236
1237 void visitForeachRange(ForeachRangeStatement s)
1238 {
1239 assert(0); // rewritten to ForStatement
1240 }
1241
1242 void visitSwitch(SwitchStatement s)
1243 {
1244 debug (LOG)
1245 {
1246 printf("%s SwitchStatement::interpret()\n", s.loc.toChars());
1247 }
1248 incUsageCtfe(istate, s.loc);
1249 if (istate.start == s)
1250 istate.start = null;
1251 if (istate.start)
1252 {
1253 Expression e = interpretStatement(s._body, istate);
1254 if (istate.start) // goto target was not found
1255 return;
1256 if (exceptionOrCant(e))
1257 return;
1258 if (e && e.op == EXP.break_)
1259 {
1260 if (istate.gotoTarget && istate.gotoTarget != s)
1261 {
1262 result = e; // break at a higher level
1263 return;
1264 }
1265 istate.gotoTarget = null;
1266 e = null;
1267 }
1268 result = e;
1269 return;
1270 }
1271
1272 UnionExp uecond = void;
1273 Expression econdition = interpret(&uecond, s.condition, istate);
1274 if (exceptionOrCant(econdition))
1275 return;
1276
1277 Statement scase = null;
1278 if (s.cases)
1279 foreach (cs; *s.cases)
1280 {
1281 UnionExp uecase = void;
1282 Expression ecase = interpret(&uecase, cs.exp, istate);
1283 if (exceptionOrCant(ecase))
1284 return;
1285 if (ctfeEqual(cs.exp.loc, EXP.equal, econdition, ecase))
1286 {
1287 scase = cs;
1288 break;
1289 }
1290 }
1291 if (!scase)
1292 {
1293 if (!s.hasDefault)
1294 error(s.loc, "no `default` or `case` for `%s` in `switch` statement", econdition.toChars());
1295 scase = s.sdefault;
1296 }
1297
1298 assert(scase);
1299
1300 /* Jump to scase
1301 */
1302 istate.start = scase;
1303 Expression e = interpretStatement(pue, s._body, istate);
1304 assert(!istate.start); // jump must not fail
1305 if (e && e.op == EXP.break_)
1306 {
1307 if (istate.gotoTarget && istate.gotoTarget != s)
1308 {
1309 result = e; // break at a higher level
1310 return;
1311 }
1312 istate.gotoTarget = null;
1313 e = null;
1314 }
1315 result = e;
1316 }
1317
1318 void visitCase(CaseStatement s)
1319 {
1320 debug (LOG)
1321 {
1322 printf("%s CaseStatement::interpret(%s) this = %p\n", s.loc.toChars(), s.exp.toChars(), s);
1323 }
1324 incUsageCtfe(istate, s.loc);
1325 if (istate.start == s)
1326 istate.start = null;
1327
1328 result = interpretStatement(pue, s.statement, istate);
1329 }
1330
1331 void visitDefault(DefaultStatement s)
1332 {
1333 debug (LOG)
1334 {
1335 printf("%s DefaultStatement::interpret()\n", s.loc.toChars());
1336 }
1337 incUsageCtfe(istate, s.loc);
1338 if (istate.start == s)
1339 istate.start = null;
1340
1341 result = interpretStatement(pue, s.statement, istate);
1342 }
1343
1344 void visitGoto(GotoStatement s)
1345 {
1346 debug (LOG)
1347 {
1348 printf("%s GotoStatement::interpret()\n", s.loc.toChars());
1349 }
1350 if (istate.start)
1351 {
1352 if (istate.start != s)
1353 return;
1354 istate.start = null;
1355 }
1356 incUsageCtfe(istate, s.loc);
1357
1358 assert(s.label && s.label.statement);
1359 istate.gotoTarget = s.label.statement;
1360 result = CTFEExp.gotoexp;
1361 }
1362
1363 void visitGotoCase(GotoCaseStatement s)
1364 {
1365 debug (LOG)
1366 {
1367 printf("%s GotoCaseStatement::interpret()\n", s.loc.toChars());
1368 }
1369 if (istate.start)
1370 {
1371 if (istate.start != s)
1372 return;
1373 istate.start = null;
1374 }
1375 incUsageCtfe(istate, s.loc);
1376
1377 assert(s.cs);
1378 istate.gotoTarget = s.cs;
1379 result = CTFEExp.gotoexp;
1380 }
1381
1382 void visitGotoDefault(GotoDefaultStatement s)
1383 {
1384 debug (LOG)
1385 {
1386 printf("%s GotoDefaultStatement::interpret()\n", s.loc.toChars());
1387 }
1388 if (istate.start)
1389 {
1390 if (istate.start != s)
1391 return;
1392 istate.start = null;
1393 }
1394 incUsageCtfe(istate, s.loc);
1395
1396 assert(s.sw && s.sw.sdefault);
1397 istate.gotoTarget = s.sw.sdefault;
1398 result = CTFEExp.gotoexp;
1399 }
1400
1401 void visitLabel(LabelStatement s)
1402 {
1403 debug (LOG)
1404 {
1405 printf("%s LabelStatement::interpret()\n", s.loc.toChars());
1406 }
1407 if (istate.start == s)
1408 istate.start = null;
1409
1410 result = interpretStatement(pue, s.statement, istate);
1411 }
1412
1413 void visitTryCatch(TryCatchStatement s)
1414 {
1415 debug (LOG)
1416 {
1417 printf("%s TryCatchStatement::interpret()\n", s.loc.toChars());
1418 }
1419 if (istate.start == s)
1420 istate.start = null;
1421 if (istate.start)
1422 {
1423 Expression e = null;
1424 e = interpretStatement(pue, s._body, istate);
1425 foreach (ca; *s.catches)
1426 {
1427 if (e || !istate.start) // goto target was found
1428 break;
1429 e = interpretStatement(pue, ca.handler, istate);
1430 }
1431 result = e;
1432 return;
1433 }
1434
1435 Expression e = interpretStatement(s._body, istate);
1436
1437 // An exception was thrown
1438 if (e && e.isThrownExceptionExp())
1439 {
1440 ThrownExceptionExp ex = e.isThrownExceptionExp();
1441 Type extype = ex.thrown.originalClass().type;
1442
1443 // Search for an appropriate catch clause.
1444 foreach (ca; *s.catches)
1445 {
1446 Type catype = ca.type;
1447 import dmd.typesem : isBaseOf;
1448 if (!catype.equals(extype) && !catype.isBaseOf(extype, null))
1449 continue;
1450
1451 // Execute the handler
1452 if (ca.var)
1453 {
1454 ctfeGlobals.stack.push(ca.var);
1455 setValue(ca.var, ex.thrown);
1456 }
1457 e = interpretStatement(ca.handler, istate);
1458 while (CTFEExp.isGotoExp(e))
1459 {
1460 /* This is an optimization that relies on the locality of the jump target.
1461 * If the label is in the same catch handler, the following scan
1462 * would find it quickly and can reduce jump cost.
1463 * Otherwise, the catch block may be unnnecessary scanned again
1464 * so it would make CTFE speed slower.
1465 */
1466 InterState istatex = *istate;
1467 istatex.start = istate.gotoTarget; // set starting statement
1468 istatex.gotoTarget = null;
1469 Expression eh = interpretStatement(ca.handler, &istatex);
1470 if (istatex.start)
1471 {
1472 // The goto target is outside the current scope.
1473 break;
1474 }
1475 // The goto target was within the body.
1476 if (CTFEExp.isCantExp(eh))
1477 {
1478 e = eh;
1479 break;
1480 }
1481 *istate = istatex;
1482 e = eh;
1483 }
1484 break;
1485 }
1486 }
1487 result = e;
1488 }
1489
1490 void visitTryFinally(TryFinallyStatement s)
1491 {
1492 debug (LOG)
1493 {
1494 printf("%s TryFinallyStatement::interpret()\n", s.loc.toChars());
1495 }
1496 if (istate.start == s)
1497 istate.start = null;
1498 if (istate.start)
1499 {
1500 Expression e = null;
1501 e = interpretStatement(pue, s._body, istate);
1502 // Jump into/out from finalbody is disabled in semantic analysis.
1503 // and jump inside will be handled by the ScopeStatement == finalbody.
1504 result = e;
1505 return;
1506 }
1507
1508 Expression ex = interpretStatement(s._body, istate);
1509 if (CTFEExp.isCantExp(ex))
1510 {
1511 result = ex;
1512 return;
1513 }
1514 while (CTFEExp.isGotoExp(ex))
1515 {
1516 // If the goto target is within the body, we must not interpret the finally statement,
1517 // because that will call destructors for objects within the scope, which we should not do.
1518 InterState istatex = *istate;
1519 istatex.start = istate.gotoTarget; // set starting statement
1520 istatex.gotoTarget = null;
1521 Expression bex = interpretStatement(s._body, &istatex);
1522 if (istatex.start)
1523 {
1524 // The goto target is outside the current scope.
1525 break;
1526 }
1527 // The goto target was within the body.
1528 if (CTFEExp.isCantExp(bex))
1529 {
1530 result = bex;
1531 return;
1532 }
1533 *istate = istatex;
1534 ex = bex;
1535 }
1536
1537 Expression ey = interpretStatement(s.finalbody, istate);
1538 if (CTFEExp.isCantExp(ey))
1539 {
1540 result = ey;
1541 return;
1542 }
1543 if (ey && ey.isThrownExceptionExp())
1544 {
1545 // Check for collided exceptions
1546 if (ex && ex.isThrownExceptionExp())
1547 ex = chainExceptions(ex.isThrownExceptionExp(), ey.isThrownExceptionExp());
1548 else
1549 ex = ey;
1550 }
1551 result = ex;
1552 }
1553
1554 void visitThrow(ThrowStatement s)
1555 {
1556 debug (LOG)
1557 {
1558 printf("%s ThrowStatement::interpret()\n", s.loc.toChars());
1559 }
1560 if (istate.start)
1561 {
1562 if (istate.start != s)
1563 return;
1564 istate.start = null;
1565 }
1566
1567 interpretThrow(result, s.exp, s.loc, istate);
1568 }
1569
1570 void visitScopeGuard(ScopeGuardStatement s)
1571 {
1572 assert(0);
1573 }
1574
1575 void visitWith(WithStatement s)
1576 {
1577 debug (LOG)
1578 {
1579 printf("%s WithStatement::interpret()\n", s.loc.toChars());
1580 }
1581 if (istate.start == s)
1582 istate.start = null;
1583 if (istate.start)
1584 {
1585 result = s._body ? interpretStatement(s._body, istate) : null;
1586 return;
1587 }
1588
1589 // If it is with(Enum) {...}, just execute the body.
1590 if (s.exp.op == EXP.scope_ || s.exp.op == EXP.type)
1591 {
1592 result = interpretStatement(pue, s._body, istate);
1593 return;
1594 }
1595
1596 incUsageCtfe(istate, s.loc);
1597
1598 Expression e = interpret(s.exp, istate);
1599 if (exceptionOrCant(e))
1600 return;
1601
1602 if (s.wthis.type.ty == Tpointer && s.exp.type.ty != Tpointer)
1603 {
1604 e = ctfeEmplaceExp!AddrExp(s.loc, e, s.wthis.type);
1605 }
1606 ctfeGlobals.stack.push(s.wthis);
1607 setValue(s.wthis, e);
1608 e = interpretStatement(s._body, istate);
1609 while (CTFEExp.isGotoExp(e))
1610 {
1611 /* This is an optimization that relies on the locality of the jump target.
1612 * If the label is in the same WithStatement, the following scan
1613 * would find it quickly and can reduce jump cost.
1614 * Otherwise, the statement body may be unnnecessary scanned again
1615 * so it would make CTFE speed slower.
1616 */
1617 InterState istatex = *istate;
1618 istatex.start = istate.gotoTarget; // set starting statement
1619 istatex.gotoTarget = null;
1620 Expression ex = interpretStatement(s._body, &istatex);
1621 if (istatex.start)
1622 {
1623 // The goto target is outside the current scope.
1624 break;
1625 }
1626 // The goto target was within the body.
1627 if (CTFEExp.isCantExp(ex))
1628 {
1629 e = ex;
1630 break;
1631 }
1632 *istate = istatex;
1633 e = ex;
1634 }
1635 ctfeGlobals.stack.pop(s.wthis);
1636 result = e;
1637 }
1638
1639 void visitAsm(AsmStatement s)
1640 {
1641 debug (LOG)
1642 {
1643 printf("%s AsmStatement::interpret()\n", s.loc.toChars());
1644 }
1645 if (istate.start)
1646 {
1647 if (istate.start != s)
1648 return;
1649 istate.start = null;
1650 }
1651 error(s.loc, "`asm` statements cannot be interpreted at compile time");
1652 result = CTFEExp.cantexp;
1653 }
1654
1655 void visitInlineAsm(InlineAsmStatement s)
1656 {
1657 visitAsm(s);
1658 }
1659
1660 void visitGccAsm(GccAsmStatement s)
1661 {
1662 visitAsm(s);
1663 }
1664
1665 void visitImport(ImportStatement s)
1666 {
1667 debug (LOG)
1668 {
1669 printf("ImportStatement::interpret()\n");
1670 }
1671 if (istate.start)
1672 {
1673 if (istate.start != s)
1674 return;
1675 istate.start = null;
1676 }
1677 }
1678
1679 if (!s)
1680 return null;
1681
1682 mixin VisitStatement!void visit;
1683 visit.VisitStatement(s);
1684 return result;
1685 }
1686
1687 ///
1688
1689 private extern (C++) final class Interpreter : Visitor
1690 {
1691 alias visit = Visitor.visit;
1692 public:
1693 InterState* istate;
1694 CTFEGoal goal;
1695 Expression result;
1696 UnionExp* pue; // storage for `result`
1697
1698 extern (D) this(UnionExp* pue, InterState* istate, CTFEGoal goal) scope @safe
1699 {
1700 this.pue = pue;
1701 this.istate = istate;
1702 this.goal = goal;
1703 }
1704
1705 // If e is EXP.throw_exception or EXP.cantExpression,
1706 // set it to 'result' and returns true.
1707 bool exceptionOrCant(Expression e)
1708 {
1709 if (exceptionOrCantInterpret(e))
1710 {
1711 // Make sure e is not pointing to a stack temporary
1712 result = (e.op == EXP.cantExpression) ? CTFEExp.cantexp : e;
1713 return true;
1714 }
1715 return false;
1716 }
1717
1718 /******************************** Expression ***************************/
1719
1720 override void visit(Expression e)
1721 {
1722 debug (LOG)
1723 {
1724 printf("%s Expression::interpret() '%s' %s\n", e.loc.toChars(), EXPtoString(e.op).ptr, e.toChars());
1725 printf("type = %s\n", e.type.toChars());
1726 showCtfeExpr(e);
1727 }
1728 error(e.loc, "cannot interpret `%s` at compile time", e.toChars());
1729 result = CTFEExp.cantexp;
1730 }
1731
1732 override void visit(TypeExp e)
1733 {
1734 debug (LOG)
1735 {
1736 printf("%s TypeExp.interpret() %s\n", e.loc.toChars(), e.toChars());
1737 }
1738 result = e;
1739 }
1740
1741 override void visit(ThisExp e)
1742 {
1743 debug (LOG)
1744 {
1745 printf("%s ThisExp::interpret() %s\n", e.loc.toChars(), e.toChars());
1746 }
1747 if (goal == CTFEGoal.LValue)
1748 {
1749 // We might end up here with istate being zero
1750 // https://issues.dlang.org/show_bug.cgi?id=16382
1751 if (istate && istate.fd.vthis)
1752 {
1753 result = ctfeEmplaceExp!VarExp(e.loc, istate.fd.vthis);
1754 if (istate.fd.hasDualContext())
1755 {
1756 result = ctfeEmplaceExp!PtrExp(e.loc, result);
1757 result.type = Type.tvoidptr.sarrayOf(2);
1758 result = ctfeEmplaceExp!IndexExp(e.loc, result, IntegerExp.literal!0);
1759 }
1760 result.type = e.type;
1761 }
1762 else
1763 result = e;
1764 return;
1765 }
1766
1767 result = ctfeGlobals.stack.getThis();
1768 if (result)
1769 {
1770 if (istate && istate.fd.hasDualContext())
1771 {
1772 assert(result.op == EXP.address);
1773 result = result.isAddrExp().e1;
1774 assert(result.op == EXP.arrayLiteral);
1775 result = (*result.isArrayLiteralExp().elements)[0];
1776 if (e.type.ty == Tstruct)
1777 {
1778 result = result.isAddrExp().e1;
1779 }
1780 return;
1781 }
1782 assert(result.op == EXP.structLiteral || result.op == EXP.classReference || result.op == EXP.type);
1783 return;
1784 }
1785 error(e.loc, "value of `this` is not known at compile time");
1786 result = CTFEExp.cantexp;
1787 }
1788
1789 override void visit(NullExp e)
1790 {
1791 result = e;
1792 }
1793
1794 override void visit(IntegerExp e)
1795 {
1796 debug (LOG)
1797 {
1798 printf("%s IntegerExp::interpret() %s\n", e.loc.toChars(), e.toChars());
1799 }
1800 result = e;
1801 }
1802
1803 override void visit(RealExp e)
1804 {
1805 debug (LOG)
1806 {
1807 printf("%s RealExp::interpret() %s\n", e.loc.toChars(), e.toChars());
1808 }
1809 result = e;
1810 }
1811
1812 override void visit(ComplexExp e)
1813 {
1814 result = e;
1815 }
1816
1817 override void visit(StringExp e)
1818 {
1819 debug (LOG)
1820 {
1821 printf("%s StringExp::interpret() %s\n", e.loc.toChars(), e.toChars());
1822 }
1823 if (e.ownedByCtfe >= OwnedBy.ctfe) // We've already interpreted the string
1824 {
1825 result = e;
1826 return;
1827 }
1828
1829 if (e.type.ty != Tsarray ||
1830 (cast(TypeNext)e.type).next.mod & (MODFlags.const_ | MODFlags.immutable_))
1831 {
1832 // If it's immutable, we don't need to dup it. Attempts to modify
1833 // string literals are prevented in BinExp::interpretAssignCommon.
1834 result = e;
1835 }
1836 else
1837 {
1838 // https://issues.dlang.org/show_bug.cgi?id=20811
1839 // Create a copy of mutable string literals, so that any change in
1840 // value via an index or slice will not survive CTFE.
1841 *pue = copyLiteral(e);
1842 result = pue.exp();
1843 }
1844 }
1845
1846 override void visit(FuncExp e)
1847 {
1848 debug (LOG)
1849 {
1850 printf("%s FuncExp::interpret() %s\n", e.loc.toChars(), e.toChars());
1851 }
1852 result = e;
1853 }
1854
1855 override void visit(SymOffExp e)
1856 {
1857 debug (LOG)
1858 {
1859 printf("%s SymOffExp::interpret() %s\n", e.loc.toChars(), e.toChars());
1860 }
1861 if (e.var.isFuncDeclaration() && e.offset == 0)
1862 {
1863 result = e;
1864 return;
1865 }
1866 if (isTypeInfo_Class(e.type) && e.offset == 0)
1867 {
1868 result = e;
1869 return;
1870 }
1871 if (e.type.ty != Tpointer)
1872 {
1873 // Probably impossible
1874 error(e.loc, "cannot interpret `%s` at compile time", e.toChars());
1875 result = CTFEExp.cantexp;
1876 return;
1877 }
1878 Type pointee = (cast(TypePointer)e.type).next;
1879 if (e.var.isThreadlocal())
1880 {
1881 error(e.loc, "cannot take address of thread-local variable %s at compile time", e.var.toChars());
1882 result = CTFEExp.cantexp;
1883 return;
1884 }
1885 // Check for taking an address of a shared variable.
1886 // If the shared variable is an array, the offset might not be zero.
1887 Type fromType = null;
1888 if (e.var.type.isStaticOrDynamicArray())
1889 {
1890 fromType = (cast(TypeArray)e.var.type).next;
1891 }
1892 if (e.var.isDataseg() && ((e.offset == 0 && isSafePointerCast(e.var.type, pointee)) ||
1893 (fromType && isSafePointerCast(fromType, pointee)) ||
1894 (e.var.isCsymbol() && e.offset + pointee.size() <= e.var.type.size())))
1895 {
1896 result = e;
1897 return;
1898 }
1899
1900 Expression val = getVarExp(e.loc, istate, e.var, goal);
1901 if (exceptionOrCant(val))
1902 return;
1903 if (val.type.isStaticOrDynamicArray())
1904 {
1905 // Check for unsupported type painting operations
1906 Type elemtype = (cast(TypeArray)val.type).next;
1907 const elemsize = elemtype.size();
1908
1909 // It's OK to cast from fixed length to fixed length array, eg &int[n] to int[d]*.
1910 if (val.type.ty == Tsarray && pointee.ty == Tsarray && elemsize == pointee.nextOf().size())
1911 {
1912 size_t d = cast(size_t)(cast(TypeSArray)pointee).dim.toInteger();
1913 Expression elwr = ctfeEmplaceExp!IntegerExp(e.loc, e.offset / elemsize, Type.tsize_t);
1914 Expression eupr = ctfeEmplaceExp!IntegerExp(e.loc, e.offset / elemsize + d, Type.tsize_t);
1915
1916 // Create a CTFE pointer &val[ofs..ofs+d]
1917 auto se = ctfeEmplaceExp!SliceExp(e.loc, val, elwr, eupr);
1918 se.type = pointee;
1919 emplaceExp!(AddrExp)(pue, e.loc, se, e.type);
1920 result = pue.exp();
1921 return;
1922 }
1923
1924 if (!isSafePointerCast(elemtype, pointee))
1925 {
1926 // It's also OK to cast from &string to string*.
1927 if (e.offset == 0 && isSafePointerCast(e.var.type, pointee))
1928 {
1929 // Create a CTFE pointer &var
1930 auto ve = ctfeEmplaceExp!VarExp(e.loc, e.var);
1931 ve.type = elemtype;
1932 emplaceExp!(AddrExp)(pue, e.loc, ve, e.type);
1933 result = pue.exp();
1934 return;
1935 }
1936 error(e.loc, "reinterpreting cast from `%s` to `%s` is not supported in CTFE", val.type.toChars(), e.type.toChars());
1937 result = CTFEExp.cantexp;
1938 return;
1939 }
1940
1941 const dinteger_t sz = pointee.size();
1942 dinteger_t indx = e.offset / sz;
1943 assert(sz * indx == e.offset);
1944 Expression aggregate = null;
1945 if (val.op == EXP.arrayLiteral || val.op == EXP.string_)
1946 {
1947 aggregate = val;
1948 }
1949 else if (auto se = val.isSliceExp())
1950 {
1951 aggregate = se.e1;
1952 UnionExp uelwr = void;
1953 Expression lwr = interpret(&uelwr, se.lwr, istate);
1954 indx += lwr.toInteger();
1955 }
1956 if (aggregate)
1957 {
1958 // Create a CTFE pointer &aggregate[ofs]
1959 auto ofs = ctfeEmplaceExp!IntegerExp(e.loc, indx, Type.tsize_t);
1960 auto ei = ctfeEmplaceExp!IndexExp(e.loc, aggregate, ofs);
1961 ei.type = elemtype;
1962 emplaceExp!(AddrExp)(pue, e.loc, ei, e.type);
1963 result = pue.exp();
1964 return;
1965 }
1966 }
1967 else if (e.offset == 0 && isSafePointerCast(e.var.type, pointee))
1968 {
1969 // Create a CTFE pointer &var
1970 auto ve = ctfeEmplaceExp!VarExp(e.loc, e.var);
1971 ve.type = e.var.type;
1972 emplaceExp!(AddrExp)(pue, e.loc, ve, e.type);
1973 result = pue.exp();
1974 return;
1975 }
1976
1977 error(e.loc, "cannot convert `&%s` to `%s` at compile time", e.var.type.toChars(), e.type.toChars());
1978 result = CTFEExp.cantexp;
1979 }
1980
1981 override void visit(AddrExp e)
1982 {
1983 debug (LOG)
1984 {
1985 printf("%s AddrExp::interpret() %s\n", e.loc.toChars(), e.toChars());
1986 }
1987 if (auto ve = e.e1.isVarExp())
1988 {
1989 Declaration decl = ve.var;
1990
1991 // We cannot take the address of an imported symbol at compile time
1992 if (decl.isImportedSymbol())
1993 {
1994 error(e.loc, "cannot take address of imported symbol `%s` at compile time", decl.toChars());
1995 result = CTFEExp.cantexp;
1996 return;
1997 }
1998
1999 if (decl.isDataseg())
2000 {
2001 // Normally this is already done by optimize()
2002 // Do it here in case optimize(WANTvalue) wasn't run before CTFE
2003 emplaceExp!(SymOffExp)(pue, e.loc, e.e1.isVarExp().var, 0);
2004 result = pue.exp();
2005 result.type = e.type;
2006 return;
2007 }
2008 }
2009 auto er = interpret(e.e1, istate, CTFEGoal.LValue);
2010 if (auto ve = er.isVarExp())
2011 if (istate && ve.var == istate.fd.vthis)
2012 er = interpret(er, istate);
2013
2014 if (exceptionOrCant(er))
2015 return;
2016
2017 // Return a simplified address expression
2018 emplaceExp!(AddrExp)(pue, e.loc, er, e.type);
2019 result = pue.exp();
2020 }
2021
2022 override void visit(DelegateExp e)
2023 {
2024 debug (LOG)
2025 {
2026 printf("%s DelegateExp::interpret() %s\n", e.loc.toChars(), e.toChars());
2027 }
2028 // TODO: Really we should create a CTFE-only delegate expression
2029 // of a pointer and a funcptr.
2030
2031 // If it is &nestedfunc, just return it
2032 // TODO: We should save the context pointer
2033 if (auto ve1 = e.e1.isVarExp())
2034 if (ve1.var == e.func)
2035 {
2036 result = e;
2037 return;
2038 }
2039
2040 auto er = interpret(pue, e.e1, istate);
2041 if (exceptionOrCant(er))
2042 return;
2043 if (er == e.e1)
2044 {
2045 // If it has already been CTFE'd, just return it
2046 result = e;
2047 }
2048 else
2049 {
2050 er = (er == pue.exp()) ? pue.copy() : er;
2051 emplaceExp!(DelegateExp)(pue, e.loc, er, e.func, false);
2052 result = pue.exp();
2053 result.type = e.type;
2054 }
2055 }
2056
2057 static Expression getVarExp(Loc loc, InterState* istate, Declaration d, CTFEGoal goal)
2058 {
2059 Expression e = CTFEExp.cantexp;
2060 if (VarDeclaration v = d.isVarDeclaration())
2061 {
2062 /* Magic variable __ctfe always returns true when interpreting
2063 */
2064 if (v.ident == Id.ctfe)
2065 return IntegerExp.createBool(true);
2066
2067 if (!v.originalType && v.semanticRun < PASS.semanticdone) // semantic() not yet run
2068 {
2069 v.dsymbolSemantic(null);
2070 if (v.type.ty == Terror)
2071 return CTFEExp.cantexp;
2072 }
2073
2074 if ((v.isConst() || v.isImmutable() || v.storage_class & STC.manifest) && !hasValue(v) && v._init && !v.isCTFE())
2075 {
2076 if (v.inuse)
2077 {
2078 error(loc, "circular initialization of %s `%s`", v.kind(), v.toPrettyChars());
2079 return CTFEExp.cantexp;
2080 }
2081 if (v._scope)
2082 {
2083 v.inuse++;
2084 v._init = v._init.initializerSemantic(v._scope, v.type, INITinterpret); // might not be run on aggregate members
2085 v.inuse--;
2086 }
2087 e = v._init.initializerToExpression(v.type);
2088 if (!e)
2089 return CTFEExp.cantexp;
2090 assert(e.type);
2091
2092 // There's a terrible hack in `dmd.dsymbolsem` that special case
2093 // a struct with all zeros to an `ExpInitializer(BlitExp(IntegerExp(0)))`
2094 // There's matching code for it in e2ir (toElem's visitAssignExp),
2095 // so we need the same hack here.
2096 // This does not trigger for global as they get a normal initializer.
2097 if (auto ts = e.type.isTypeStruct())
2098 if (auto ae = e.isBlitExp())
2099 if (ae.e2.op == EXP.int64)
2100 e = ts.defaultInitLiteral(loc);
2101
2102 if (e.op == EXP.construct || e.op == EXP.blit)
2103 {
2104 AssignExp ae = cast(AssignExp)e;
2105 e = ae.e2;
2106 }
2107
2108 if (e.op == EXP.error)
2109 {
2110 // FIXME: Ultimately all errors should be detected in prior semantic analysis stage.
2111 }
2112 else if (v.isDataseg() || (v.storage_class & STC.manifest))
2113 {
2114 /* https://issues.dlang.org/show_bug.cgi?id=14304
2115 * e is a value that is not yet owned by CTFE.
2116 * Mark as "cached", and use it directly during interpretation.
2117 */
2118 e = scrubCacheValue(e);
2119 ctfeGlobals.stack.saveGlobalConstant(v, e);
2120 }
2121 else
2122 {
2123 v.inuse++;
2124 e = interpret(e, istate);
2125 v.inuse--;
2126 if (CTFEExp.isCantExp(e) && !global.gag && !ctfeGlobals.stackTraceCallsToSuppress)
2127 errorSupplemental(loc, "while evaluating %s.init", v.toChars());
2128 if (exceptionOrCantInterpret(e))
2129 return e;
2130 }
2131 }
2132 else if (v.isCTFE() && !hasValue(v))
2133 {
2134 if (v._init && v.type.size() != 0)
2135 {
2136 if (v._init.isVoidInitializer())
2137 {
2138 // var should have been initialized when it was created
2139 error(loc, "CTFE internal error: trying to access uninitialized var");
2140 assert(0);
2141 }
2142 e = v._init.initializerToExpression();
2143 }
2144 else
2145 // Zero-length arrays don't have an initializer
2146 e = v.type.defaultInitLiteral(e.loc);
2147
2148 e = interpret(e, istate);
2149 }
2150 else if (!(v.isDataseg() || v.storage_class & STC.manifest) && !v.isCTFE() && !istate)
2151 {
2152 error(loc, "variable `%s` cannot be read at compile time", v.toChars());
2153 return CTFEExp.cantexp;
2154 }
2155 else
2156 {
2157 e = hasValue(v) ? getValue(v) : null;
2158 if (!e)
2159 {
2160 // Zero-length arrays don't have an initializer
2161 if (v.type.size() == 0)
2162 e = v.type.defaultInitLiteral(loc);
2163 else if (!v.isCTFE() && v.isDataseg())
2164 {
2165 error(loc, "static variable `%s` cannot be read at compile time", v.toChars());
2166 return CTFEExp.cantexp;
2167 }
2168 else
2169 {
2170 assert(!(v._init && v._init.isVoidInitializer()));
2171 // CTFE initiated from inside a function
2172 error(loc, "variable `%s` cannot be read at compile time", v.toChars());
2173 return CTFEExp.cantexp;
2174 }
2175 }
2176 if (auto vie = e.isVoidInitExp())
2177 {
2178 error(loc, "cannot read uninitialized variable `%s` in ctfe", v.toPrettyChars());
2179 errorSupplemental(vie.var.loc, "`%s` was uninitialized and used before set", vie.var.toChars());
2180 return CTFEExp.cantexp;
2181 }
2182 if (goal != CTFEGoal.LValue && v.isReference())
2183 e = interpret(e, istate, goal);
2184 }
2185 if (!e)
2186 e = CTFEExp.cantexp;
2187 }
2188 else if (SymbolDeclaration s = d.isSymbolDeclaration())
2189 {
2190 // exclude void[]-typed `__traits(initSymbol)`
2191 if (auto ta = s.type.toBasetype().isTypeDArray())
2192 {
2193 assert(ta.next.ty == Tvoid);
2194 error(loc, "cannot determine the address of the initializer symbol during CTFE");
2195 return CTFEExp.cantexp;
2196 }
2197
2198 // Struct static initializers, for example
2199 e = s.dsym.type.defaultInitLiteral(loc);
2200 if (e.op == EXP.error)
2201 error(loc, "CTFE failed because of previous errors in `%s.init`", s.toChars());
2202 e = e.expressionSemantic(null);
2203 if (e.op == EXP.error)
2204 e = CTFEExp.cantexp;
2205 else // Convert NULL to CTFEExp
2206 e = interpret(e, istate, goal);
2207 }
2208 else
2209 error(loc, "cannot interpret declaration `%s` at compile time", d.toChars());
2210 return e;
2211 }
2212
2213 override void visit(VarExp e)
2214 {
2215 debug (LOG)
2216 {
2217 printf("%s VarExp::interpret() `%s`, goal = %d\n", e.loc.toChars(), e.toChars(), goal);
2218 }
2219 if (e.var.isFuncDeclaration())
2220 {
2221 result = e;
2222 return;
2223 }
2224
2225 if (goal == CTFEGoal.LValue)
2226 {
2227 if (auto v = e.var.isVarDeclaration())
2228 {
2229 if (!hasValue(v))
2230 {
2231 // Compile-time known non-CTFE variable from an outer context
2232 // e.g. global or from a ref argument
2233 if (v.isConst() || v.isImmutable())
2234 {
2235 result = getVarExp(e.loc, istate, v, goal);
2236 return;
2237 }
2238
2239 if (!v.isCTFE() && v.isDataseg())
2240 error(e.loc, "static variable `%s` cannot be read at compile time", v.toChars());
2241 else // CTFE initiated from inside a function
2242 error(e.loc, "variable `%s` cannot be read at compile time", v.toChars());
2243 result = CTFEExp.cantexp;
2244 return;
2245 }
2246
2247 if (v.storage_class & (STC.out_ | STC.ref_))
2248 {
2249 // Strip off the nest of ref variables
2250 Expression ev = getValue(v);
2251 if (ev.op == EXP.variable ||
2252 ev.op == EXP.index ||
2253 (ev.op == EXP.slice && ev.type.toBasetype().ty == Tsarray) ||
2254 ev.op == EXP.dotVariable)
2255 {
2256 result = interpret(pue, ev, istate, goal);
2257 return;
2258 }
2259 }
2260 }
2261 result = e;
2262 return;
2263 }
2264 result = getVarExp(e.loc, istate, e.var, goal);
2265 if (exceptionOrCant(result))
2266 return;
2267
2268 // Visit the default initializer for noreturn variables
2269 // (Custom initializers would abort the current function call and exit above)
2270 if (result.type.ty == Tnoreturn)
2271 {
2272 result.accept(this);
2273 return;
2274 }
2275
2276 if ((e.var.storage_class & (STC.ref_ | STC.out_)) == 0 && e.type.baseElemOf().ty != Tstruct)
2277 {
2278 /* Ultimately, STC.ref_|STC.out_ check should be enough to see the
2279 * necessity of type repainting. But currently front-end paints
2280 * non-ref struct variables by the const type.
2281 *
2282 * auto foo(ref const S cs);
2283 * S s;
2284 * foo(s); // VarExp('s') will have const(S)
2285 */
2286 // A VarExp may include an implicit cast. It must be done explicitly.
2287 result = paintTypeOntoLiteral(pue, e.type, result);
2288 }
2289 }
2290
2291 override void visit(DeclarationExp e)
2292 {
2293 debug (LOG)
2294 {
2295 printf("%s DeclarationExp::interpret() %s\n", e.loc.toChars(), e.toChars());
2296 }
2297 Dsymbol s = e.declaration;
2298 while (s.isAttribDeclaration())
2299 {
2300 auto ad = cast(AttribDeclaration)s;
2301 assert(ad.decl && ad.decl.length == 1); // Currently, only one allowed when parsing
2302 s = (*ad.decl)[0];
2303 }
2304 if (VarDeclaration v = s.isVarDeclaration())
2305 {
2306 if (TupleDeclaration td = v.toAlias().isTupleDeclaration())
2307 {
2308 result = null;
2309
2310 // Reserve stack space for all tuple members
2311 td.foreachVar((s)
2312 {
2313 VarDeclaration v2 = s.isVarDeclaration();
2314 assert(v2);
2315 if (v2.isDataseg() && !v2.isCTFE())
2316 return 0;
2317
2318 ctfeGlobals.stack.push(v2);
2319 if (v2._init)
2320 {
2321 Expression einit;
2322 if (ExpInitializer ie = v2._init.isExpInitializer())
2323 {
2324 einit = interpretRegion(ie.exp, istate, goal);
2325 if (exceptionOrCant(einit))
2326 return 1;
2327 }
2328 else if (v2._init.isVoidInitializer())
2329 {
2330 einit = voidInitLiteral(v2.type, v2).copy();
2331 }
2332 else
2333 {
2334 error(e.loc, "declaration `%s` is not yet implemented in CTFE", e.toChars());
2335 result = CTFEExp.cantexp;
2336 return 1;
2337 }
2338 setValue(v2, einit);
2339 }
2340 return 0;
2341 });
2342 return;
2343 }
2344 if (v.isStatic())
2345 {
2346 // Just ignore static variables which aren't read or written yet
2347 result = null;
2348 return;
2349 }
2350 if (!(v.isDataseg() || v.storage_class & STC.manifest) || v.isCTFE())
2351 ctfeGlobals.stack.push(v);
2352 if (v._init)
2353 {
2354 if (ExpInitializer ie = v._init.isExpInitializer())
2355 {
2356 result = interpretRegion(ie.exp, istate, goal);
2357 return;
2358 }
2359 else if (v._init.isVoidInitializer())
2360 {
2361 result = voidInitLiteral(v.type, v).copy();
2362 // There is no AssignExp for void initializers,
2363 // so set it here.
2364 setValue(v, result);
2365 return;
2366 }
2367 else if (v._init.isArrayInitializer())
2368 {
2369 result = v._init.initializerToExpression(v.type);
2370 if (result !is null)
2371 return;
2372 }
2373 error(e.loc, "declaration `%s` is not yet implemented in CTFE", e.toChars());
2374 result = CTFEExp.cantexp;
2375 }
2376 else if (v.type.size() == 0)
2377 {
2378 // Zero-length arrays don't need an initializer
2379 result = v.type.defaultInitLiteral(e.loc);
2380 }
2381 else
2382 {
2383 error(e.loc, "variable `%s` cannot be modified at compile time", v.toChars());
2384 result = CTFEExp.cantexp;
2385 }
2386 return;
2387 }
2388 if (s.isTemplateMixin() || s.isTupleDeclaration())
2389 {
2390 // These can be made to work, too lazy now
2391 error(e.loc, "declaration `%s` is not yet implemented in CTFE", e.toChars());
2392 result = CTFEExp.cantexp;
2393 return;
2394 }
2395
2396 // Others should not contain executable code, so are trivial to evaluate
2397 result = null;
2398 debug (LOG)
2399 {
2400 printf("-DeclarationExp::interpret(%s): %p\n", e.toChars(), result);
2401 }
2402 }
2403
2404 override void visit(TypeidExp e)
2405 {
2406 debug (LOG)
2407 {
2408 printf("%s TypeidExp::interpret() %s\n", e.loc.toChars(), e.toChars());
2409 }
2410 if (Type t = isType(e.obj))
2411 {
2412 result = e;
2413 return;
2414 }
2415 if (Expression ex = isExpression(e.obj))
2416 {
2417 result = interpret(pue, ex, istate);
2418 if (exceptionOrCant(ex))
2419 return;
2420
2421 if (result.op == EXP.null_)
2422 {
2423 error(e.loc, "null pointer dereference evaluating typeid. `%s` is `null`", ex.toChars());
2424 result = CTFEExp.cantexp;
2425 return;
2426 }
2427 if (result.op != EXP.classReference)
2428 {
2429 error(e.loc, "CTFE internal error: determining classinfo");
2430 result = CTFEExp.cantexp;
2431 return;
2432 }
2433
2434 ClassDeclaration cd = result.isClassReferenceExp().originalClass();
2435 assert(cd);
2436
2437 emplaceExp!(TypeidExp)(pue, e.loc, cd.type);
2438 result = pue.exp();
2439 result.type = e.type;
2440 return;
2441 }
2442 visit(cast(Expression)e);
2443 }
2444
2445 override void visit(TupleExp e)
2446 {
2447 debug (LOG)
2448 {
2449 printf("%s TupleExp::interpret() %s\n", e.loc.toChars(), e.toChars());
2450 }
2451 if (exceptionOrCant(interpretRegion(e.e0, istate, CTFEGoal.Nothing)))
2452 return;
2453
2454 auto expsx = e.exps;
2455 foreach (i, exp; *expsx)
2456 {
2457 Expression ex = interpretRegion(exp, istate);
2458 if (exceptionOrCant(ex))
2459 return;
2460
2461 // A tuple of assignments can contain void (Bug 5676).
2462 if (goal == CTFEGoal.Nothing)
2463 continue;
2464 if (ex.op == EXP.voidExpression)
2465 {
2466 error(e.loc, "CTFE internal error: void element `%s` in sequence", exp.toChars());
2467 assert(0);
2468 }
2469
2470 /* If any changes, do Copy On Write
2471 */
2472 if (ex !is exp)
2473 {
2474 expsx = copyArrayOnWrite(expsx, e.exps);
2475 (*expsx)[i] = copyRegionExp(ex);
2476 }
2477 }
2478
2479 if (expsx !is e.exps)
2480 {
2481 expandTuples(expsx);
2482 emplaceExp!(TupleExp)(pue, e.loc, expsx);
2483 result = pue.exp();
2484 result.type = new TypeTuple(expsx);
2485 }
2486 else
2487 result = e;
2488 }
2489
2490 override void visit(ArrayLiteralExp e)
2491 {
2492 debug (LOG)
2493 {
2494 printf("%s ArrayLiteralExp::interpret() %s, %s\n", e.loc.toChars(), e.type.toChars(), e.toChars());
2495 }
2496 if (e.ownedByCtfe >= OwnedBy.ctfe) // We've already interpreted all the elements
2497 {
2498 result = e;
2499 return;
2500 }
2501
2502 Type tb = e.type.toBasetype();
2503 Type tn = tb.nextOf().toBasetype();
2504 bool wantCopy = (tn.ty == Tsarray || tn.ty == Tstruct);
2505
2506 auto basis = interpretRegion(e.basis, istate);
2507 if (exceptionOrCant(basis))
2508 return;
2509
2510 auto expsx = e.elements;
2511 size_t dim = expsx ? expsx.length : 0;
2512
2513 for (size_t i = 0; i < dim; i++)
2514 {
2515 Expression exp = (*expsx)[i];
2516 Expression ex;
2517 if (!exp)
2518 {
2519 ex = copyLiteral(basis).copy();
2520 }
2521 else
2522 {
2523 // segfault bug 6250
2524 assert(exp.op != EXP.index || exp.isIndexExp().e1 != e);
2525
2526 ex = interpretRegion(exp, istate);
2527 if (exceptionOrCant(ex))
2528 return;
2529
2530 /* Each elements should have distinct CTFE memory.
2531 * int[1] z = 7;
2532 * int[1][] pieces = [z,z]; // here
2533 */
2534 if (wantCopy)
2535 ex = copyLiteral(ex).copy();
2536 }
2537
2538 /* If any changes, do Copy On Write
2539 */
2540 if (ex !is exp)
2541 {
2542 expsx = copyArrayOnWrite(expsx, e.elements);
2543 (*expsx)[i] = ex;
2544 }
2545 }
2546
2547 if (expsx !is e.elements)
2548 {
2549 // todo: all tuple expansions should go in semantic phase.
2550 expandTuples(expsx);
2551 if (expsx.length != dim)
2552 {
2553 error(e.loc, "CTFE internal error: invalid array literal");
2554 result = CTFEExp.cantexp;
2555 return;
2556 }
2557 emplaceExp!(ArrayLiteralExp)(pue, e.loc, e.type, basis, expsx);
2558 auto ale = pue.exp().isArrayLiteralExp();
2559 ale.ownedByCtfe = OwnedBy.ctfe;
2560 result = ale;
2561 }
2562 else if ((cast(TypeNext)e.type).next.mod & (MODFlags.const_ | MODFlags.immutable_))
2563 {
2564 // If it's immutable, we don't need to dup it
2565 result = e;
2566 }
2567 else
2568 {
2569 *pue = copyLiteral(e);
2570 result = pue.exp();
2571 }
2572 }
2573
2574 override void visit(AssocArrayLiteralExp e)
2575 {
2576 debug (LOG)
2577 {
2578 printf("%s AssocArrayLiteralExp::interpret() %s\n", e.loc.toChars(), e.toChars());
2579 }
2580 if (e.ownedByCtfe >= OwnedBy.ctfe) // We've already interpreted all the elements
2581 {
2582 result = e;
2583 return;
2584 }
2585
2586 auto keysx = e.keys;
2587 auto valuesx = e.values;
2588 foreach (i, ekey; *keysx)
2589 {
2590 auto evalue = (*valuesx)[i];
2591
2592 auto ek = interpretRegion(ekey, istate);
2593 if (exceptionOrCant(ek))
2594 return;
2595 auto ev = interpretRegion(evalue, istate);
2596 if (exceptionOrCant(ev))
2597 return;
2598
2599 /* If any changes, do Copy On Write
2600 */
2601 if (ek !is ekey ||
2602 ev !is evalue)
2603 {
2604 keysx = copyArrayOnWrite(keysx, e.keys);
2605 valuesx = copyArrayOnWrite(valuesx, e.values);
2606 (*keysx)[i] = ek;
2607 (*valuesx)[i] = ev;
2608 }
2609 }
2610 if (keysx !is e.keys)
2611 expandTuples(keysx);
2612 if (valuesx !is e.values)
2613 expandTuples(valuesx);
2614 if (keysx.length != valuesx.length)
2615 {
2616 error(e.loc, "CTFE internal error: invalid AA");
2617 result = CTFEExp.cantexp;
2618 return;
2619 }
2620
2621 /* Remove duplicate keys
2622 */
2623 for (size_t i = 1; i < keysx.length; i++)
2624 {
2625 auto ekey = (*keysx)[i - 1];
2626 for (size_t j = i; j < keysx.length; j++)
2627 {
2628 auto ekey2 = (*keysx)[j];
2629 if (!ctfeEqual(e.loc, EXP.equal, ekey, ekey2))
2630 continue;
2631
2632 // Remove ekey
2633 keysx = copyArrayOnWrite(keysx, e.keys);
2634 valuesx = copyArrayOnWrite(valuesx, e.values);
2635 keysx.remove(i - 1);
2636 valuesx.remove(i - 1);
2637
2638 i -= 1; // redo the i'th iteration
2639 break;
2640 }
2641 }
2642
2643 if (keysx !is e.keys ||
2644 valuesx !is e.values)
2645 {
2646 assert(keysx !is e.keys &&
2647 valuesx !is e.values);
2648 auto aae = ctfeEmplaceExp!AssocArrayLiteralExp(e.loc, keysx, valuesx);
2649 aae.type = e.type;
2650 aae.ownedByCtfe = OwnedBy.ctfe;
2651 result = aae;
2652 }
2653 else
2654 {
2655 *pue = copyLiteral(e);
2656 result = pue.exp();
2657 }
2658 }
2659
2660 override void visit(StructLiteralExp e)
2661 {
2662 debug (LOG)
2663 {
2664 printf("%s StructLiteralExp::interpret() %s ownedByCtfe = %d\n", e.loc.toChars(), e.toChars(), e.ownedByCtfe);
2665 }
2666 if (e.ownedByCtfe >= OwnedBy.ctfe)
2667 {
2668 result = e;
2669 return;
2670 }
2671
2672 size_t dim = e.elements ? e.elements.length : 0;
2673 auto expsx = e.elements;
2674
2675 if (dim != e.sd.fields.length)
2676 {
2677 // guaranteed by AggregateDeclaration.fill and TypeStruct.defaultInitLiteral
2678 const nvthis = e.sd.fields.length - e.sd.nonHiddenFields();
2679 assert(e.sd.fields.length - dim == nvthis);
2680
2681 /* If a nested struct has no initialized hidden pointer,
2682 * set it to null to match the runtime behaviour.
2683 */
2684 foreach (const i; 0 .. nvthis)
2685 {
2686 auto ne = ctfeEmplaceExp!NullExp(e.loc);
2687 auto vthis = i == 0 ? e.sd.vthis : e.sd.vthis2;
2688 ne.type = vthis.type;
2689
2690 expsx = copyArrayOnWrite(expsx, e.elements);
2691 expsx.push(ne);
2692 ++dim;
2693 }
2694 }
2695 assert(dim == e.sd.fields.length);
2696
2697 foreach (i; 0 .. dim)
2698 {
2699 auto v = e.sd.fields[i];
2700 Expression exp = (*expsx)[i];
2701 Expression ex;
2702 if (!exp)
2703 {
2704 ex = voidInitLiteral(v.type, v).copy();
2705 }
2706 else
2707 {
2708 ex = interpretRegion(exp, istate);
2709 if (exceptionOrCant(ex))
2710 return;
2711 if ((v.type.ty != ex.type.ty) && v.type.ty == Tsarray)
2712 {
2713 // Block assignment from inside struct literals
2714 auto tsa = cast(TypeSArray)v.type;
2715 auto len = cast(size_t)tsa.dim.toInteger();
2716 UnionExp ue = void;
2717 ex = createBlockDuplicatedArrayLiteral(&ue, ex.loc, v.type, ex, len);
2718 if (ex == ue.exp())
2719 ex = ue.copy();
2720 }
2721 }
2722
2723 /* If any changes, do Copy On Write
2724 */
2725 if (ex !is exp)
2726 {
2727 expsx = copyArrayOnWrite(expsx, e.elements);
2728 (*expsx)[i] = ex;
2729 }
2730 }
2731
2732 if (expsx !is e.elements)
2733 {
2734 expandTuples(expsx);
2735 if (expsx.length != e.sd.fields.length)
2736 {
2737 error(e.loc, "CTFE internal error: invalid struct literal");
2738 result = CTFEExp.cantexp;
2739 return;
2740 }
2741 emplaceExp!(StructLiteralExp)(pue, e.loc, e.sd, expsx);
2742 auto sle = pue.exp().isStructLiteralExp();
2743 sle.type = e.type;
2744 sle.ownedByCtfe = OwnedBy.ctfe;
2745 sle.origin = e.origin;
2746 result = sle;
2747 }
2748 else
2749 {
2750 *pue = copyLiteral(e);
2751 result = pue.exp();
2752 }
2753 }
2754
2755 // Create an array literal of type 'newtype' with dimensions given by
2756 // 'arguments'[argnum..$]
2757 static Expression recursivelyCreateArrayLiteral(UnionExp* pue, Loc loc, Type newtype, InterState* istate, Expressions* arguments, int argnum)
2758 {
2759 Expression lenExpr = interpret(pue, (*arguments)[argnum], istate);
2760 if (exceptionOrCantInterpret(lenExpr))
2761 return lenExpr;
2762 size_t len = cast(size_t)lenExpr.toInteger();
2763 Type elemType = (cast(TypeArray)newtype).next;
2764 if (elemType.ty == Tarray && argnum < arguments.length - 1)
2765 {
2766 Expression elem = recursivelyCreateArrayLiteral(pue, loc, elemType, istate, arguments, argnum + 1);
2767 if (exceptionOrCantInterpret(elem))
2768 return elem;
2769
2770 auto elements = new Expressions(len);
2771 foreach (ref element; *elements)
2772 element = copyLiteral(elem).copy();
2773 emplaceExp!(ArrayLiteralExp)(pue, loc, newtype, elements);
2774 auto ae = pue.exp().isArrayLiteralExp();
2775 ae.ownedByCtfe = OwnedBy.ctfe;
2776 return ae;
2777 }
2778 assert(argnum == arguments.length - 1);
2779 if (elemType.ty.isSomeChar)
2780 {
2781 const ch = cast(dchar)elemType.defaultInitLiteral(loc).toInteger();
2782 const sz = cast(ubyte)elemType.size();
2783 return createBlockDuplicatedStringLiteral(pue, loc, newtype, ch, len, sz);
2784 }
2785 else
2786 {
2787 auto el = interpret(elemType.defaultInitLiteral(loc), istate);
2788 return createBlockDuplicatedArrayLiteral(pue, loc, newtype, el, len);
2789 }
2790 }
2791
2792 override void visit(NewExp e)
2793 {
2794 debug (LOG)
2795 {
2796 printf("%s NewExp::interpret() %s\n", e.loc.toChars(), e.toChars());
2797 }
2798
2799 if (e.placement)
2800 {
2801 error(e.placement.loc, "`new ( %s )` PlacementExpression cannot be evaluated at compile time", e.placement.toChars());
2802 result = CTFEExp.cantexp;
2803 return;
2804 }
2805
2806 Expression epre = interpret(pue, e.argprefix, istate, CTFEGoal.Nothing);
2807 if (exceptionOrCant(epre))
2808 return;
2809
2810 if (e.newtype.ty == Tarray && e.arguments)
2811 {
2812 result = recursivelyCreateArrayLiteral(pue, e.loc, e.newtype, istate, e.arguments, 0);
2813 return;
2814 }
2815 if (auto ts = e.newtype.toBasetype().isTypeStruct())
2816 {
2817 if (e.member)
2818 {
2819 Expression se = e.newtype.defaultInitLiteral(e.loc);
2820 se = interpret(se, istate);
2821 if (exceptionOrCant(se))
2822 return;
2823 result = interpretFunction(pue, e.member, istate, e.arguments, se);
2824
2825 // Repaint as same as CallExp::interpret() does.
2826 result.loc = e.loc;
2827 }
2828 else
2829 {
2830 StructDeclaration sd = ts.sym;
2831 auto exps = new Expressions();
2832 exps.reserve(sd.fields.length);
2833 if (e.arguments)
2834 {
2835 exps.setDim(e.arguments.length);
2836 foreach (i, ex; *e.arguments)
2837 {
2838 ex = interpretRegion(ex, istate);
2839 if (exceptionOrCant(ex))
2840 return;
2841 (*exps)[i] = ex;
2842 }
2843 }
2844 sd.fill(e.loc, *exps, false);
2845
2846 auto se = ctfeEmplaceExp!StructLiteralExp(e.loc, sd, exps, e.newtype);
2847 se.origin = se;
2848 se.type = e.newtype;
2849 se.ownedByCtfe = OwnedBy.ctfe;
2850 result = interpret(pue, se, istate);
2851 }
2852 if (exceptionOrCant(result))
2853 return;
2854 Expression ev = (result == pue.exp()) ? pue.copy() : result;
2855 emplaceExp!(AddrExp)(pue, e.loc, ev, e.type);
2856 result = pue.exp();
2857 return;
2858 }
2859 if (auto tc = e.newtype.toBasetype().isTypeClass())
2860 {
2861 ClassDeclaration cd = tc.sym;
2862 size_t totalFieldCount = 0;
2863 for (ClassDeclaration c = cd; c; c = c.baseClass)
2864 totalFieldCount += c.fields.length;
2865 auto elems = new Expressions(totalFieldCount);
2866 size_t fieldsSoFar = totalFieldCount;
2867 for (ClassDeclaration c = cd; c; c = c.baseClass)
2868 {
2869 fieldsSoFar -= c.fields.length;
2870 foreach (i, v; c.fields)
2871 {
2872 if (v.inuse)
2873 {
2874 error(e.loc, "circular reference to `%s`", v.toPrettyChars());
2875 result = CTFEExp.cantexp;
2876 return;
2877 }
2878 Expression m;
2879 if (v._init)
2880 {
2881 if (v._init.isVoidInitializer())
2882 m = voidInitLiteral(v.type, v).copy();
2883 else
2884 m = v.getConstInitializer(true);
2885 }
2886 else if (v.type.isTypeNoreturn())
2887 {
2888 // Noreturn field with default initializer
2889 (*elems)[fieldsSoFar + i] = null;
2890 continue;
2891 }
2892 else
2893 m = v.type.defaultInitLiteral(e.loc);
2894 if (exceptionOrCant(m))
2895 return;
2896 (*elems)[fieldsSoFar + i] = copyLiteral(m).copy();
2897 }
2898 }
2899 // Hack: we store a ClassDeclaration instead of a StructDeclaration.
2900 // We probably won't get away with this.
2901 // auto se = new StructLiteralExp(e.loc, cast(StructDeclaration)cd, elems, e.newtype);
2902 auto se = ctfeEmplaceExp!StructLiteralExp(e.loc, cast(StructDeclaration)cd, elems, e.newtype);
2903 se.origin = se;
2904 se.ownedByCtfe = OwnedBy.ctfe;
2905 Expression eref = ctfeEmplaceExp!ClassReferenceExp(e.loc, se, e.type);
2906 if (e.member)
2907 {
2908 // Call constructor
2909 if (!e.member.fbody)
2910 {
2911 Expression ctorfail = evaluateIfBuiltin(pue, istate, e.loc, e.member, e.arguments, eref);
2912 if (ctorfail)
2913 {
2914 if (exceptionOrCant(ctorfail))
2915 return;
2916 result = eref;
2917 return;
2918 }
2919 auto m = e.member;
2920 error(m.loc, "%s `%s` `%s` cannot be constructed at compile time, because the constructor has no available source code",
2921 m.kind, m.toPrettyChars, e.newtype.toChars());
2922 result = CTFEExp.cantexp;
2923 return;
2924 }
2925 UnionExp ue = void;
2926 Expression ctorfail = interpretFunction(&ue, e.member, istate, e.arguments, eref);
2927 if (exceptionOrCant(ctorfail))
2928 return;
2929
2930 /* https://issues.dlang.org/show_bug.cgi?id=14465
2931 * Repaint the loc, because a super() call
2932 * in the constructor modifies the loc of ClassReferenceExp
2933 * in CallExp::interpret().
2934 */
2935 eref.loc = e.loc;
2936 }
2937 result = eref;
2938 return;
2939 }
2940 if (e.newtype.toBasetype().isScalar())
2941 {
2942 Expression newval;
2943 if (e.arguments && e.arguments.length)
2944 newval = (*e.arguments)[0];
2945 else
2946 newval = e.newtype.defaultInitLiteral(e.loc);
2947 newval = interpretRegion(newval, istate);
2948 if (exceptionOrCant(newval))
2949 return;
2950
2951 // Create a CTFE pointer &[newval][0]
2952 auto elements = new Expressions(1);
2953 (*elements)[0] = newval;
2954 auto ae = ctfeEmplaceExp!ArrayLiteralExp(e.loc, e.newtype.arrayOf(), elements);
2955 ae.ownedByCtfe = OwnedBy.ctfe;
2956
2957 auto ei = ctfeEmplaceExp!IndexExp(e.loc, ae, ctfeEmplaceExp!IntegerExp(Loc.initial, 0, Type.tsize_t));
2958 ei.type = e.newtype;
2959 emplaceExp!(AddrExp)(pue, e.loc, ei, e.type);
2960 result = pue.exp();
2961 return;
2962 }
2963 error(e.loc, "cannot interpret `%s` at compile time", e.toChars());
2964 result = CTFEExp.cantexp;
2965 }
2966
2967 override void visit(UnaExp e)
2968 {
2969 debug (LOG)
2970 {
2971 printf("%s UnaExp::interpret() %s\n", e.loc.toChars(), e.toChars());
2972 }
2973 UnionExp ue = void;
2974 Expression e1 = interpret(&ue, e.e1, istate);
2975 if (exceptionOrCant(e1))
2976 return;
2977 switch (e.op)
2978 {
2979 case EXP.negate:
2980 *pue = Neg(e.type, e1);
2981 break;
2982
2983 case EXP.tilde:
2984 *pue = Com(e.type, e1);
2985 break;
2986
2987 case EXP.not:
2988 *pue = Not(e.type, e1);
2989 break;
2990
2991 default:
2992 assert(0);
2993 }
2994 result = (*pue).exp();
2995 }
2996
2997 override void visit(DotTypeExp e)
2998 {
2999 debug (LOG)
3000 {
3001 printf("%s DotTypeExp::interpret() %s\n", e.loc.toChars(), e.toChars());
3002 }
3003 UnionExp ue = void;
3004 Expression e1 = interpret(&ue, e.e1, istate);
3005 if (exceptionOrCant(e1))
3006 return;
3007 if (e1 == e.e1)
3008 result = e; // optimize: reuse this CTFE reference
3009 else
3010 {
3011 auto edt = e.copy().isDotTypeExp();
3012 edt.e1 = (e1 == ue.exp()) ? e1.copy() : e1; // don't return pointer to ue
3013 result = edt;
3014 }
3015 }
3016
3017 private alias fp_t = extern (D) UnionExp function(Loc loc, Type, Expression, Expression);
3018 private alias fp2_t = extern (D) bool function(Loc loc, EXP, Expression, Expression);
3019
3020 extern (D) private void interpretCommon(BinExp e, fp_t fp)
3021 {
3022 debug (LOG)
3023 {
3024 printf("%s BinExp::interpretCommon() %s\n", e.loc.toChars(), e.toChars());
3025 }
3026 if (e.e1.type.ty == Tpointer && e.e2.type.ty == Tpointer && e.op == EXP.min)
3027 {
3028 UnionExp ue1 = void;
3029 Expression e1 = interpret(&ue1, e.e1, istate);
3030 if (exceptionOrCant(e1))
3031 return;
3032 UnionExp ue2 = void;
3033 Expression e2 = interpret(&ue2, e.e2, istate);
3034 if (exceptionOrCant(e2))
3035 return;
3036 result = pointerDifference(pue, e.loc, e.type, e1, e2);
3037 return;
3038 }
3039 if (e.e1.type.ty == Tpointer && e.e2.type.isIntegral())
3040 {
3041 UnionExp ue1 = void;
3042 Expression e1 = interpret(&ue1, e.e1, istate);
3043 if (exceptionOrCant(e1))
3044 return;
3045 UnionExp ue2 = void;
3046 Expression e2 = interpret(&ue2, e.e2, istate);
3047 if (exceptionOrCant(e2))
3048 return;
3049 result = pointerArithmetic(pue, e.loc, e.op, e.type, e1, e2);
3050 return;
3051 }
3052 if (e.e2.type.ty == Tpointer && e.e1.type.isIntegral() && e.op == EXP.add)
3053 {
3054 UnionExp ue1 = void;
3055 Expression e1 = interpret(&ue1, e.e1, istate);
3056 if (exceptionOrCant(e1))
3057 return;
3058 UnionExp ue2 = void;
3059 Expression e2 = interpret(&ue2, e.e2, istate);
3060 if (exceptionOrCant(e2))
3061 return;
3062 result = pointerArithmetic(pue, e.loc, e.op, e.type, e2, e1);
3063 return;
3064 }
3065 if (e.e1.type.ty == Tpointer || e.e2.type.ty == Tpointer)
3066 {
3067 error(e.loc, "pointer expression `%s` cannot be interpreted at compile time", e.toChars());
3068 result = CTFEExp.cantexp;
3069 return;
3070 }
3071
3072 bool evalOperand(UnionExp* pue, Expression ex, out Expression er)
3073 {
3074 er = interpret(pue, ex, istate);
3075 if (exceptionOrCant(er))
3076 return false;
3077 return true;
3078 }
3079
3080 UnionExp ue1 = void;
3081 Expression e1;
3082 if (!evalOperand(&ue1, e.e1, e1))
3083 return;
3084
3085 UnionExp ue2 = void;
3086 Expression e2;
3087 if (!evalOperand(&ue2, e.e2, e2))
3088 return;
3089
3090 if (e.op == EXP.rightShift || e.op == EXP.leftShift || e.op == EXP.unsignedRightShift)
3091 {
3092 const sinteger_t i2 = e2.toInteger();
3093 const uinteger_t sz = e1.type.size() * 8;
3094 if (i2 < 0 || i2 >= sz)
3095 {
3096 error(e.loc, "shift by %lld is outside the range 0..%llu", i2, cast(ulong)sz - 1);
3097 result = CTFEExp.cantexp;
3098 return;
3099 }
3100 }
3101
3102 /******************************************
3103 * Perform the operation fp on operands e1 and e2.
3104 */
3105 UnionExp evaluate(Loc loc, Type type, Expression e1, Expression e2)
3106 {
3107 UnionExp ue = void;
3108 auto ae1 = e1.isArrayLiteralExp();
3109 auto ae2 = e2.isArrayLiteralExp();
3110 if (ae1 || ae2)
3111 {
3112 /* Cases:
3113 * 1. T[] op T[]
3114 * 2. T op T[]
3115 * 3. T[] op T
3116 */
3117 if (ae1 && e2.implicitConvTo(e1.type.toBasetype().nextOf())) // case 3
3118 ae2 = null;
3119 else if (ae2 && e1.implicitConvTo(e2.type.toBasetype().nextOf())) // case 2
3120 ae1 = null;
3121 // else case 1
3122
3123 auto aex = ae1 ? ae1 : ae2;
3124 if (!aex.elements)
3125 {
3126 emplaceExp!ArrayLiteralExp(&ue, loc, type, cast(Expressions*) null);
3127 return ue;
3128 }
3129 const length = aex.elements.length;
3130 Expressions* elements = new Expressions(length);
3131
3132 emplaceExp!ArrayLiteralExp(&ue, loc, type, elements);
3133 foreach (i; 0 .. length)
3134 {
3135 Expression e1x = ae1 ? ae1[i] : e1;
3136 Expression e2x = ae2 ? ae2[i] : e2;
3137 UnionExp uex = evaluate(loc, e1x.type, e1x, e2x);
3138 // This can be made more efficient by making use of ue.basis
3139 (*elements)[i] = uex.copy();
3140 }
3141 return ue;
3142 }
3143
3144 if (e1.isConst() != 1)
3145 {
3146 // The following should really be an assert()
3147 error(e1.loc, "CTFE internal error: non-constant value `%s`", e1.toChars());
3148 emplaceExp!CTFEExp(&ue, EXP.cantExpression);
3149 return ue;
3150 }
3151 if (e2.isConst() != 1)
3152 {
3153 error(e2.loc, "CTFE internal error: non-constant value `%s`", e2.toChars());
3154 emplaceExp!CTFEExp(&ue, EXP.cantExpression);
3155 return ue;
3156 }
3157
3158 return (*fp)(loc, type, e1, e2);
3159 }
3160
3161 *pue = evaluate(e.loc, e.type, e1, e2);
3162 result = (*pue).exp();
3163 if (CTFEExp.isCantExp(result))
3164 error(e.loc, "`%s` cannot be interpreted at compile time", e.toChars());
3165 }
3166
3167 extern (D) private void interpretCompareCommon(BinExp e, fp2_t fp)
3168 {
3169 debug (LOG)
3170 {
3171 printf("%s BinExp::interpretCompareCommon() %s\n", e.loc.toChars(), e.toChars());
3172 }
3173 UnionExp ue1 = void;
3174 UnionExp ue2 = void;
3175 if (e.e1.type.ty == Tpointer && e.e2.type.ty == Tpointer)
3176 {
3177 Expression e1 = interpret(&ue1, e.e1, istate);
3178 if (exceptionOrCant(e1))
3179 return;
3180 Expression e2 = interpret(&ue2, e.e2, istate);
3181 if (exceptionOrCant(e2))
3182 return;
3183 //printf("e1 = %s %s, e2 = %s %s\n", e1.type.toChars(), e1.toChars(), e2.type.toChars(), e2.toChars());
3184 dinteger_t ofs1, ofs2;
3185 Expression agg1 = getAggregateFromPointer(e1, &ofs1);
3186 Expression agg2 = getAggregateFromPointer(e2, &ofs2);
3187 //printf("agg1 = %p %s, agg2 = %p %s\n", agg1, agg1.toChars(), agg2, agg2.toChars());
3188 const cmp = comparePointers(e.op, agg1, ofs1, agg2, ofs2);
3189 if (cmp == -1)
3190 {
3191 char dir = (e.op == EXP.greaterThan || e.op == EXP.greaterOrEqual) ? '<' : '>';
3192 error(e.loc, "the ordering of pointers to unrelated memory blocks is indeterminate in CTFE. To check if they point to the same memory block, use both `>` and `<` inside `&&` or `||`, eg `%s && %s %c= %s + 1`", e.toChars(), e.e1.toChars(), dir, e.e2.toChars());
3193 result = CTFEExp.cantexp;
3194 return;
3195 }
3196 if (e.type.equals(Type.tbool))
3197 result = IntegerExp.createBool(cmp != 0);
3198 else
3199 {
3200 emplaceExp!(IntegerExp)(pue, e.loc, cmp, e.type);
3201 result = (*pue).exp();
3202 }
3203 return;
3204 }
3205 Expression e1 = interpret(&ue1, e.e1, istate);
3206 if (exceptionOrCant(e1))
3207 return;
3208 if (!isCtfeComparable(e1))
3209 {
3210 error(e.loc, "cannot compare `%s` at compile time", e1.toChars());
3211 result = CTFEExp.cantexp;
3212 return;
3213 }
3214 Expression e2 = interpret(&ue2, e.e2, istate);
3215 if (exceptionOrCant(e2))
3216 return;
3217 if (!isCtfeComparable(e2))
3218 {
3219 error(e.loc, "cannot compare `%s` at compile time", e2.toChars());
3220 result = CTFEExp.cantexp;
3221 return;
3222 }
3223 const cmp = (*fp)(e.loc, e.op, e1, e2);
3224 if (e.type.equals(Type.tbool))
3225 result = IntegerExp.createBool(cmp);
3226 else
3227 {
3228 emplaceExp!(IntegerExp)(pue, e.loc, cmp, e.type);
3229 result = (*pue).exp();
3230 }
3231 }
3232
3233 override void visit(BinExp e)
3234 {
3235 switch (e.op)
3236 {
3237 case EXP.add:
3238 interpretCommon(e, &Add);
3239 return;
3240
3241 case EXP.min:
3242 interpretCommon(e, &Min);
3243 return;
3244
3245 case EXP.mul:
3246 interpretCommon(e, &Mul);
3247 return;
3248
3249 case EXP.div:
3250 interpretCommon(e, &Div);
3251 return;
3252
3253 case EXP.mod:
3254 interpretCommon(e, &Mod);
3255 return;
3256
3257 case EXP.leftShift:
3258 interpretCommon(e, &Shl);
3259 return;
3260
3261 case EXP.rightShift:
3262 interpretCommon(e, &Shr);
3263 return;
3264
3265 case EXP.unsignedRightShift:
3266 interpretCommon(e, &Ushr);
3267 return;
3268
3269 case EXP.and:
3270 interpretCommon(e, &And);
3271 return;
3272
3273 case EXP.or:
3274 interpretCommon(e, &Or);
3275 return;
3276
3277 case EXP.xor:
3278 interpretCommon(e, &Xor);
3279 return;
3280
3281 case EXP.pow:
3282 interpretCommon(e, &Pow);
3283 return;
3284
3285 case EXP.equal:
3286 case EXP.notEqual:
3287 interpretCompareCommon(e, &ctfeEqual);
3288 return;
3289
3290 case EXP.identity:
3291 case EXP.notIdentity:
3292 interpretCompareCommon(e, &ctfeIdentity);
3293 return;
3294
3295 case EXP.lessThan:
3296 case EXP.lessOrEqual:
3297 case EXP.greaterThan:
3298 case EXP.greaterOrEqual:
3299 interpretCompareCommon(e, &ctfeCmp);
3300 return;
3301
3302 default:
3303 printf("be = '%s' %s at [%s]\n", EXPtoString(e.op).ptr, e.toChars(), e.loc.toChars());
3304 assert(0);
3305 }
3306 }
3307
3308 /* Helper functions for BinExp::interpretAssignCommon
3309 */
3310 // Returns the variable which is eventually modified, or NULL if an rvalue.
3311 // thisval is the current value of 'this'.
3312 static VarDeclaration findParentVar(Expression e) @safe
3313 {
3314 for (;;)
3315 {
3316 if (auto ve = e.isVarExp())
3317 {
3318 VarDeclaration v = ve.var.isVarDeclaration();
3319 assert(v);
3320 return v;
3321 }
3322 if (auto ie = e.isIndexExp())
3323 e = ie.e1;
3324 else if (auto dve = e.isDotVarExp())
3325 e = dve.e1;
3326 else if (auto dtie = e.isDotTemplateInstanceExp())
3327 e = dtie.e1;
3328 else if (auto se = e.isSliceExp())
3329 e = se.e1;
3330 else
3331 return null;
3332 }
3333 }
3334
3335 extern (D) private void interpretAssignCommon(BinExp e, fp_t fp, int post = 0)
3336 {
3337 debug (LOG)
3338 {
3339 printf("%s BinExp::interpretAssignCommon() %s\n", e.loc.toChars(), e.toChars());
3340 }
3341 result = CTFEExp.cantexp;
3342
3343 Expression e1 = e.e1;
3344 if (!istate)
3345 {
3346 error(e.loc, "value of `%s` is not known at compile time", e1.toChars());
3347 return;
3348 }
3349
3350 ++ctfeGlobals.numAssignments;
3351
3352 /* Before we begin, we need to know if this is a reference assignment
3353 * (dynamic array, AA, or class) or a value assignment.
3354 * Determining this for slice assignments are tricky: we need to know
3355 * if it is a block assignment (a[] = e) rather than a direct slice
3356 * assignment (a[] = b[]). Note that initializers of multi-dimensional
3357 * static arrays can have 2D block assignments (eg, int[7][7] x = 6;).
3358 * So we need to recurse to determine if it is a block assignment.
3359 */
3360 bool isBlockAssignment = false;
3361 if (e1.op == EXP.slice)
3362 {
3363 // a[] = e can have const e. So we compare the naked types.
3364 Type tdst = e1.type.toBasetype();
3365 Type tsrc = e.e2.type.toBasetype();
3366 while (tdst.isStaticOrDynamicArray())
3367 {
3368 tdst = (cast(TypeArray)tdst).next.toBasetype();
3369 if (tsrc.equivalent(tdst))
3370 {
3371 isBlockAssignment = true;
3372 break;
3373 }
3374 }
3375 }
3376
3377 // ---------------------------------------
3378 // Deal with reference assignment
3379 // ---------------------------------------
3380 // If it is a construction of a ref variable, it is a ref assignment
3381 if ((e.op == EXP.construct || e.op == EXP.blit) &&
3382 ((cast(AssignExp)e).memset == MemorySet.referenceInit))
3383 {
3384 assert(!fp);
3385
3386 Expression newval = interpretRegion(e.e2, istate, CTFEGoal.LValue);
3387 if (exceptionOrCant(newval))
3388 return;
3389
3390 VarDeclaration v = e1.isVarExp().var.isVarDeclaration();
3391 setValue(v, newval);
3392
3393 // Get the value to return. Note that 'newval' is an Lvalue,
3394 // so if we need an Rvalue, we have to interpret again.
3395 if (goal == CTFEGoal.RValue)
3396 result = interpretRegion(newval, istate);
3397 else
3398 result = e1; // VarExp is a CTFE reference
3399 return;
3400 }
3401
3402 if (fp)
3403 {
3404 while (e1.op == EXP.cast_)
3405 {
3406 CastExp ce = e1.isCastExp();
3407 e1 = ce.e1;
3408 }
3409 }
3410
3411 // ---------------------------------------
3412 // Interpret left hand side
3413 // ---------------------------------------
3414 AssocArrayLiteralExp existingAA = null;
3415 Expression lastIndex = null;
3416 Expression oldval = null;
3417 if (e1.op == EXP.index && e1.isIndexExp().e1.type.toBasetype().ty == Taarray)
3418 {
3419 // ---------------------------------------
3420 // Deal with AA index assignment
3421 // ---------------------------------------
3422 /* This needs special treatment if the AA doesn't exist yet.
3423 * There are two special cases:
3424 * (1) If the AA is itself an index of another AA, we may need to create
3425 * multiple nested AA literals before we can insert the new value.
3426 * (2) If the ultimate AA is null, no insertion happens at all. Instead,
3427 * we create nested AA literals, and change it into a assignment.
3428 */
3429 IndexExp ie = e1.isIndexExp();
3430 int depth = 0; // how many nested AA indices are there?
3431 while (ie.e1.op == EXP.index && ie.e1.isIndexExp().e1.type.toBasetype().ty == Taarray)
3432 {
3433 assert(ie.modifiable);
3434 ie = ie.e1.isIndexExp();
3435 ++depth;
3436 }
3437
3438 // Get the AA value to be modified.
3439 Expression aggregate = interpretRegion(ie.e1, istate);
3440 if (exceptionOrCant(aggregate))
3441 return;
3442 if ((existingAA = aggregate.isAssocArrayLiteralExp()) !is null)
3443 {
3444 // Normal case, ultimate parent AA already exists
3445 // We need to walk from the deepest index up, checking that an AA literal
3446 // already exists on each level.
3447 lastIndex = interpretRegion(e1.isIndexExp().e2, istate);
3448 lastIndex = resolveSlice(lastIndex); // only happens with AA assignment
3449 if (exceptionOrCant(lastIndex))
3450 return;
3451
3452 while (depth > 0)
3453 {
3454 // Walk the syntax tree to find the indexExp at this depth
3455 IndexExp xe = e1.isIndexExp();
3456 foreach (d; 0 .. depth)
3457 xe = xe.e1.isIndexExp();
3458
3459 Expression ekey = interpretRegion(xe.e2, istate);
3460 if (exceptionOrCant(ekey))
3461 return;
3462 UnionExp ekeyTmp = void;
3463 ekey = resolveSlice(ekey, &ekeyTmp); // only happens with AA assignment
3464
3465 // Look up this index in it up in the existing AA, to get the next level of AA.
3466 AssocArrayLiteralExp newAA = cast(AssocArrayLiteralExp)findKeyInAA(e.loc, existingAA, ekey);
3467 if (exceptionOrCant(newAA))
3468 return;
3469 if (!newAA)
3470 {
3471 // Doesn't exist yet, create an empty AA...
3472 auto keysx = new Expressions();
3473 auto valuesx = new Expressions();
3474 newAA = ctfeEmplaceExp!AssocArrayLiteralExp(e.loc, keysx, valuesx);
3475 newAA.type = xe.type;
3476 newAA.ownedByCtfe = OwnedBy.ctfe;
3477 //... and insert it into the existing AA.
3478 existingAA.keys.push(ekey);
3479 existingAA.values.push(newAA);
3480 }
3481 existingAA = newAA;
3482 --depth;
3483 }
3484
3485 if (fp)
3486 {
3487 oldval = findKeyInAA(e.loc, existingAA, lastIndex);
3488 if (!oldval)
3489 oldval = copyLiteral(e.e1.type.defaultInitLiteral(e.loc)).copy();
3490 }
3491 }
3492 else
3493 {
3494 /* The AA is currently null. 'aggregate' is actually a reference to
3495 * whatever contains it. It could be anything: var, dotvarexp, ...
3496 * We rewrite the assignment from:
3497 * aa[i][j] op= newval;
3498 * into:
3499 * aa = [i:[j:T.init]];
3500 * aa[j] op= newval;
3501 */
3502 oldval = copyLiteral(e.e1.type.defaultInitLiteral(e.loc)).copy();
3503
3504 Expression newaae = oldval;
3505 while (e1.op == EXP.index && e1.isIndexExp().e1.type.toBasetype().ty == Taarray)
3506 {
3507 Expression ekey = interpretRegion(e1.isIndexExp().e2, istate);
3508 if (exceptionOrCant(ekey))
3509 return;
3510 ekey = resolveSlice(ekey); // only happens with AA assignment
3511
3512 auto keysx = new Expressions();
3513 auto valuesx = new Expressions();
3514 keysx.push(ekey);
3515 valuesx.push(newaae);
3516
3517 auto aae = ctfeEmplaceExp!AssocArrayLiteralExp(e.loc, keysx, valuesx);
3518 aae.type = e1.isIndexExp().e1.type;
3519 aae.ownedByCtfe = OwnedBy.ctfe;
3520 if (!existingAA)
3521 {
3522 existingAA = aae;
3523 lastIndex = ekey;
3524 }
3525 newaae = aae;
3526 e1 = e1.isIndexExp().e1;
3527 }
3528
3529 // We must set to aggregate with newaae
3530 e1 = interpretRegion(e1, istate, CTFEGoal.LValue);
3531 if (exceptionOrCant(e1))
3532 return;
3533 e1 = assignToLvalue(e, e1, newaae);
3534 if (exceptionOrCant(e1))
3535 return;
3536 }
3537 assert(existingAA && lastIndex);
3538 e1 = null; // stomp
3539 }
3540 else if (e1.op == EXP.arrayLength)
3541 {
3542 oldval = interpretRegion(e1, istate);
3543 if (exceptionOrCant(oldval))
3544 return;
3545 }
3546 else if (e.op == EXP.construct || e.op == EXP.blit)
3547 {
3548 // Unless we have a simple var assignment, we're
3549 // only modifying part of the variable. So we need to make sure
3550 // that the parent variable exists.
3551 VarDeclaration ultimateVar = findParentVar(e1);
3552 if (auto ve = e1.isVarExp())
3553 {
3554 VarDeclaration v = ve.var.isVarDeclaration();
3555 assert(v);
3556 if (v.storage_class & STC.out_)
3557 goto L1;
3558 }
3559 else if (ultimateVar && !getValue(ultimateVar))
3560 {
3561 Expression ex = interpretRegion(ultimateVar.type.defaultInitLiteral(e.loc), istate);
3562 if (exceptionOrCant(ex))
3563 return;
3564 setValue(ultimateVar, ex);
3565 }
3566 else
3567 goto L1;
3568 }
3569 else
3570 {
3571 L1:
3572 e1 = interpretRegion(e1, istate, CTFEGoal.LValue);
3573 if (exceptionOrCant(e1))
3574 return;
3575
3576 if (e1.op == EXP.index && e1.isIndexExp().e1.type.toBasetype().ty == Taarray)
3577 {
3578 IndexExp ie = e1.isIndexExp();
3579 assert(ie.e1.op == EXP.assocArrayLiteral);
3580 existingAA = ie.e1.isAssocArrayLiteralExp();
3581 lastIndex = ie.e2;
3582 }
3583 }
3584
3585 // ---------------------------------------
3586 // Interpret right hand side
3587 // ---------------------------------------
3588 Expression newval = interpretRegion(e.e2, istate);
3589 if (exceptionOrCant(newval))
3590 return;
3591 if (e.op == EXP.blit && newval.op == EXP.int64)
3592 {
3593 Type tbn = e.type.baseElemOf();
3594 if (tbn.ty == Tstruct)
3595 {
3596 /* Look for special case of struct being initialized with 0.
3597 */
3598 newval = e.type.defaultInitLiteral(e.loc);
3599 if (newval.op == EXP.error)
3600 {
3601 result = CTFEExp.cantexp;
3602 return;
3603 }
3604 newval = interpretRegion(newval, istate); // copy and set ownedByCtfe flag
3605 if (exceptionOrCant(newval))
3606 return;
3607 }
3608 }
3609
3610 // ----------------------------------------------------
3611 // Deal with read-modify-write assignments.
3612 // Set 'newval' to the final assignment value
3613 // Also determine the return value (except for slice
3614 // assignments, which are more complicated)
3615 // ----------------------------------------------------
3616 if (fp)
3617 {
3618 if (!oldval)
3619 {
3620 // Load the left hand side after interpreting the right hand side.
3621 oldval = interpretRegion(e1, istate);
3622 if (exceptionOrCant(oldval))
3623 return;
3624 }
3625
3626 if (e.e1.type.ty != Tpointer)
3627 {
3628 // ~= can create new values (see bug 6052)
3629 if (e.op == EXP.concatenateAssign || e.op == EXP.concatenateElemAssign || e.op == EXP.concatenateDcharAssign)
3630 {
3631 // We need to dup it and repaint the type. For a dynamic array
3632 // we can skip duplication, because it gets copied later anyway.
3633 if (newval.type.ty != Tarray)
3634 {
3635 newval = copyLiteral(newval).copy();
3636 newval.type = e.e2.type; // repaint type
3637 }
3638 else
3639 {
3640 newval = paintTypeOntoLiteral(e.e2.type, newval);
3641 newval = resolveSlice(newval);
3642 }
3643 }
3644 oldval = resolveSlice(oldval);
3645
3646 newval = (*fp)(e.loc, e.type, oldval, newval).copy();
3647 }
3648 else if (e.e2.type.isIntegral() &&
3649 (e.op == EXP.addAssign ||
3650 e.op == EXP.minAssign ||
3651 e.op == EXP.plusPlus ||
3652 e.op == EXP.minusMinus))
3653 {
3654 newval = pointerArithmetic(pue, e.loc, e.op, e.type, oldval, newval).copy();
3655 if (newval == pue.exp())
3656 newval = pue.copy();
3657 }
3658 else
3659 {
3660 error(e.loc, "pointer expression `%s` cannot be interpreted at compile time", e.toChars());
3661 result = CTFEExp.cantexp;
3662 return;
3663 }
3664 if (exceptionOrCant(newval))
3665 {
3666 if (CTFEExp.isCantExp(newval))
3667 error(e.loc, "cannot interpret `%s` at compile time", e.toChars());
3668 return;
3669 }
3670 }
3671
3672 if (existingAA)
3673 {
3674 if (existingAA.ownedByCtfe != OwnedBy.ctfe)
3675 {
3676 error(e.loc, "cannot modify read-only constant `%s`", existingAA.toChars());
3677 result = CTFEExp.cantexp;
3678 return;
3679 }
3680
3681 //printf("\t+L%d existingAA = %s, lastIndex = %s, oldval = %s, newval = %s\n",
3682 // __LINE__, existingAA.toChars(), lastIndex.toChars(), oldval ? oldval.toChars() : NULL, newval.toChars());
3683 assignAssocArrayElement(e.loc, existingAA, lastIndex, newval);
3684
3685 // Determine the return value
3686 result = ctfeCast(pue, e.loc, e.type, e.type, fp && post ? oldval : newval);
3687 return;
3688 }
3689 if (e1.op == EXP.arrayLength)
3690 {
3691 /* Change the assignment from:
3692 * arr.length = n;
3693 * into:
3694 * arr = new_length_array; (result is n)
3695 */
3696
3697 // Determine the return value
3698 result = ctfeCast(pue, e.loc, e.type, e.type, fp && post ? oldval : newval);
3699 if (exceptionOrCant(result))
3700 return;
3701
3702 if (result == pue.exp())
3703 result = pue.copy();
3704
3705 size_t oldlen = cast(size_t)oldval.toInteger();
3706 size_t newlen = cast(size_t)newval.toInteger();
3707 if (oldlen == newlen) // no change required -- we're done!
3708 return;
3709
3710 // We have changed it into a reference assignment
3711 // Note that returnValue is still the new length.
3712 e1 = e1.isArrayLengthExp().e1;
3713 Type t = e1.type.toBasetype();
3714 if (t.ty != Tarray)
3715 {
3716 error(e.loc, "`%s` is not yet supported at compile time", e.toChars());
3717 result = CTFEExp.cantexp;
3718 return;
3719 }
3720 e1 = interpretRegion(e1, istate, CTFEGoal.LValue);
3721 if (exceptionOrCant(e1))
3722 return;
3723
3724 if (oldlen != 0) // Get the old array literal.
3725 oldval = interpretRegion(e1, istate);
3726 UnionExp utmp = void;
3727 oldval = resolveSlice(oldval, &utmp);
3728
3729 newval = changeArrayLiteralLength(pue, e.loc, cast(TypeArray)t, oldval, oldlen, newlen);
3730 if (newval == pue.exp())
3731 newval = pue.copy();
3732
3733 e1 = assignToLvalue(e, e1, newval);
3734 if (exceptionOrCant(e1))
3735 return;
3736
3737 return;
3738 }
3739
3740 if (!isBlockAssignment)
3741 {
3742 newval = ctfeCast(pue, e.loc, e.type, e.type, newval);
3743 if (exceptionOrCant(newval))
3744 return;
3745 if (newval == pue.exp())
3746 newval = pue.copy();
3747
3748 // Determine the return value
3749 if (goal == CTFEGoal.LValue) // https://issues.dlang.org/show_bug.cgi?id=14371
3750 result = e1;
3751 else
3752 {
3753 result = ctfeCast(pue, e.loc, e.type, e.type, fp && post ? oldval : newval);
3754 if (result == pue.exp())
3755 result = pue.copy();
3756 }
3757 if (exceptionOrCant(result))
3758 return;
3759 }
3760 if (exceptionOrCant(newval))
3761 return;
3762
3763 debug (LOGASSIGN)
3764 {
3765 printf("ASSIGN: %s=%s\n", e1.toChars(), newval.toChars());
3766 showCtfeExpr(newval);
3767 }
3768
3769 /* Block assignment or element-wise assignment.
3770 */
3771 if (e1.op == EXP.slice ||
3772 e1.op == EXP.vector ||
3773 e1.op == EXP.arrayLiteral ||
3774 e1.op == EXP.string_ ||
3775 e1.op == EXP.null_ && e1.type.toBasetype().ty == Tarray)
3776 {
3777 // Note that slice assignments don't support things like ++, so
3778 // we don't need to remember 'returnValue'.
3779 result = interpretAssignToSlice(pue, e, e1, newval, isBlockAssignment);
3780 if (exceptionOrCant(result))
3781 return;
3782 if (auto se = e.e1.isSliceExp())
3783 {
3784 Expression e1x = interpretRegion(se.e1, istate, CTFEGoal.LValue);
3785 if (auto dve = e1x.isDotVarExp())
3786 {
3787 auto ex = dve.e1;
3788 auto sle = ex.op == EXP.structLiteral ? ex.isStructLiteralExp()
3789 : ex.op == EXP.classReference ? ex.isClassReferenceExp().value
3790 : null;
3791 auto v = dve.var.isVarDeclaration();
3792 if (!sle || !v)
3793 {
3794 error(e.loc, "CTFE internal error: dotvar slice assignment");
3795 result = CTFEExp.cantexp;
3796 return;
3797 }
3798 stompOverlappedFields(sle, v);
3799 }
3800 }
3801 return;
3802 }
3803 assert(result);
3804
3805 /* Assignment to a CTFE reference.
3806 */
3807 if (Expression ex = assignToLvalue(e, e1, newval))
3808 result = ex;
3809
3810 return;
3811 }
3812
3813 /* Set all sibling fields which overlap with v to VoidExp.
3814 */
3815 private void stompOverlappedFields(StructLiteralExp sle, VarDeclaration v)
3816 {
3817 if (!v.overlapped)
3818 return;
3819 foreach (size_t i, v2; sle.sd.fields)
3820 {
3821 if (v is v2 || !v.isOverlappedWith(v2))
3822 continue;
3823 auto e = (*sle.elements)[i];
3824 if (e !is null && e.op != EXP.void_)
3825 (*sle.elements)[i] = voidInitLiteral(e.type, v).copy();
3826 }
3827 }
3828
3829 private Expression assignToLvalue(BinExp e, Expression e1, Expression newval)
3830 {
3831 //printf("assignToLvalue() e: %s e1: %s newval: %s\n", e.toChars(), e1.toChars(), newval.toChars());
3832 VarDeclaration vd = null;
3833 Expression* payload = null; // dead-store to prevent spurious warning
3834 Expression oldval;
3835
3836 if (auto ve = e1.isVarExp())
3837 {
3838 vd = ve.var.isVarDeclaration();
3839 oldval = getValue(vd);
3840 }
3841 else if (auto dve = e1.isDotVarExp())
3842 {
3843 /* Assignment to member variable of the form:
3844 * e.v = newval
3845 */
3846 auto ex = dve.e1;
3847 auto sle = ex.op == EXP.structLiteral ? ex.isStructLiteralExp()
3848 : ex.op == EXP.classReference ? ex.isClassReferenceExp().value
3849 : null;
3850 auto v = e1.isDotVarExp().var.isVarDeclaration();
3851 if (!sle || !v)
3852 {
3853 error(e.loc, "CTFE internal error: dotvar assignment");
3854 return CTFEExp.cantexp;
3855 }
3856 if (sle.ownedByCtfe != OwnedBy.ctfe)
3857 {
3858 error(e.loc, "cannot modify read-only constant `%s`", sle.toChars());
3859 return CTFEExp.cantexp;
3860 }
3861
3862 int fieldi = ex.op == EXP.structLiteral ? findFieldIndexByName(sle.sd, v)
3863 : ex.isClassReferenceExp().findFieldIndexByName(v);
3864 if (fieldi == -1)
3865 {
3866 error(e.loc, "CTFE internal error: cannot find field `%s` in `%s`", v.toChars(), ex.toChars());
3867 return CTFEExp.cantexp;
3868 }
3869 assert(0 <= fieldi && fieldi < sle.elements.length);
3870
3871 // If it's a union, set all other members of this union to void
3872 stompOverlappedFields(sle, v);
3873
3874 payload = &(*sle.elements)[fieldi];
3875 oldval = *payload;
3876 if (auto ival = newval.isIntegerExp())
3877 {
3878 if (auto bf = v.isBitFieldDeclaration())
3879 {
3880 sinteger_t value = ival.toInteger();
3881 if (bf.type.isUnsigned())
3882 value &= (1L << bf.fieldWidth) - 1; // zero extra bits
3883 else
3884 { // sign extend extra bits
3885 value = value << (64 - bf.fieldWidth);
3886 value = value >> (64 - bf.fieldWidth);
3887 }
3888 ival.setInteger(value);
3889 }
3890 }
3891 }
3892 else if (auto ie = e1.isIndexExp())
3893 {
3894 assert(ie.e1.type.toBasetype().ty != Taarray);
3895
3896 Expression aggregate;
3897 uinteger_t indexToModify;
3898 if (!resolveIndexing(ie, istate, &aggregate, &indexToModify, true))
3899 {
3900 return CTFEExp.cantexp;
3901 }
3902 size_t index = cast(size_t)indexToModify;
3903
3904 if (auto existingSE = aggregate.isStringExp())
3905 {
3906 if (existingSE.ownedByCtfe != OwnedBy.ctfe)
3907 {
3908 error(e.loc, "cannot modify read-only string literal `%s`", ie.e1.toChars());
3909 return CTFEExp.cantexp;
3910 }
3911 existingSE.setCodeUnit(index, cast(dchar)newval.toInteger());
3912 return null;
3913 }
3914 if (aggregate.op != EXP.arrayLiteral)
3915 {
3916 error(e.loc, "index assignment `%s` is not yet supported in CTFE ", e.toChars());
3917 return CTFEExp.cantexp;
3918 }
3919
3920 ArrayLiteralExp existingAE = aggregate.isArrayLiteralExp();
3921 if (existingAE.ownedByCtfe != OwnedBy.ctfe)
3922 {
3923 error(e.loc, "cannot modify read-only constant `%s`", existingAE.toChars());
3924 return CTFEExp.cantexp;
3925 }
3926
3927 payload = &(*existingAE.elements)[index];
3928 oldval = *payload;
3929 }
3930 else
3931 {
3932 error(e.loc, "`%s` cannot be evaluated at compile time", e.toChars());
3933 return CTFEExp.cantexp;
3934 }
3935
3936 Type t1b = e1.type.toBasetype();
3937 bool wantCopy = t1b.baseElemOf().ty == Tstruct;
3938
3939 if (auto ve = newval.isVectorExp())
3940 {
3941 // Ensure ve is an array literal, and not a broadcast
3942 if (ve.e1.op == EXP.int64 || ve.e1.op == EXP.float64) // if broadcast
3943 {
3944 UnionExp ue = void;
3945 Expression ex = interpretVectorToArray(&ue, ve);
3946 ve.e1 = (ex == ue.exp()) ? ue.copy() : ex;
3947 }
3948 }
3949
3950 if (newval.op == EXP.structLiteral && oldval)
3951 {
3952 assert(oldval.op == EXP.structLiteral || oldval.op == EXP.arrayLiteral || oldval.op == EXP.string_);
3953 newval = copyLiteral(newval).copy();
3954 assignInPlace(oldval, newval);
3955 }
3956 else if (wantCopy && (e.op == EXP.assign || e.op == EXP.loweredAssignExp))
3957 {
3958 // Currently postblit/destructor calls on static array are done
3959 // in the druntime internal functions so they don't appear in AST.
3960 // Therefore interpreter should handle them specially.
3961
3962 assert(oldval);
3963 version (all) // todo: instead we can directly access to each elements of the slice
3964 {
3965 newval = resolveSlice(newval);
3966 if (CTFEExp.isCantExp(newval))
3967 {
3968 error(e.loc, "CTFE internal error: assignment `%s`", e.toChars());
3969 return CTFEExp.cantexp;
3970 }
3971 }
3972 assert(oldval.op == EXP.arrayLiteral);
3973 assert(newval.op == EXP.arrayLiteral);
3974
3975 Expressions* oldelems = oldval.isArrayLiteralExp().elements;
3976 Expressions* newelems = newval.isArrayLiteralExp().elements;
3977 assert(oldelems.length == newelems.length);
3978
3979 Type elemtype = oldval.type.nextOf();
3980 foreach (i, ref oldelem; *oldelems)
3981 {
3982 Expression newelem = paintTypeOntoLiteral(elemtype, (*newelems)[i]);
3983 // https://issues.dlang.org/show_bug.cgi?id=9245
3984 if (e.e2.isLvalue())
3985 {
3986 if (Expression ex = evaluatePostblit(istate, newelem))
3987 return ex;
3988 }
3989 // https://issues.dlang.org/show_bug.cgi?id=13661
3990 if (Expression ex = evaluateDtor(istate, oldelem))
3991 return ex;
3992 oldelem = newelem;
3993 }
3994 }
3995 else
3996 {
3997 // e1 has its own payload, so we have to create a new literal.
3998 if (wantCopy)
3999 newval = copyLiteral(newval).copy();
4000
4001 if (t1b.ty == Tsarray && e.op == EXP.construct && e.e2.isLvalue())
4002 {
4003 // https://issues.dlang.org/show_bug.cgi?id=9245
4004 if (Expression ex = evaluatePostblit(istate, newval))
4005 return ex;
4006 }
4007
4008 oldval = newval;
4009 }
4010
4011 if (vd)
4012 setValue(vd, oldval);
4013 else
4014 *payload = oldval;
4015
4016 // Blit assignment should return the newly created value.
4017 if (e.op == EXP.blit)
4018 return oldval;
4019
4020 return null;
4021 }
4022
4023 /*************
4024 * Deal with assignments of the form:
4025 * dest[] = newval
4026 * dest[low..upp] = newval
4027 * where newval has already been interpreted
4028 *
4029 * This could be a slice assignment or a block assignment, and
4030 * dest could be either an array literal, or a string.
4031 *
4032 * Returns EXP.cantExpression on failure. If there are no errors,
4033 * it returns aggregate[low..upp], except that as an optimisation,
4034 * if goal == CTFEGoal.Nothing, it will return NULL
4035 */
4036 private Expression interpretAssignToSlice(UnionExp* pue, BinExp e, Expression e1, Expression newval, bool isBlockAssignment)
4037 {
4038 //printf("interpretAssignToSlice(e: %s e1: %s newval: %s\n", e.toChars(), e1.toChars(), newval.toChars());
4039
4040 dinteger_t lowerbound;
4041 dinteger_t upperbound;
4042 dinteger_t firstIndex;
4043
4044 Expression aggregate;
4045
4046 if (auto se = e1.isSliceExp())
4047 {
4048 // ------------------------------
4049 // aggregate[] = newval
4050 // aggregate[low..upp] = newval
4051 // ------------------------------
4052 aggregate = interpretRegion(se.e1, istate);
4053 lowerbound = se.lwr ? se.lwr.toInteger() : 0;
4054 upperbound = se.upr ? se.upr.toInteger() : resolveArrayLength(aggregate);
4055
4056 // Slice of a slice --> change the bounds
4057 if (auto oldse = aggregate.isSliceExp())
4058 {
4059 aggregate = oldse.e1;
4060 firstIndex = lowerbound + oldse.lwr.toInteger();
4061 }
4062 else
4063 firstIndex = lowerbound;
4064 }
4065 else
4066 {
4067 if (auto ale = e1.isArrayLiteralExp())
4068 {
4069 lowerbound = 0;
4070 upperbound = ale.elements.length;
4071 }
4072 else if (auto se = e1.isStringExp())
4073 {
4074 lowerbound = 0;
4075 upperbound = se.len;
4076 }
4077 else if (e1.op == EXP.null_)
4078 {
4079 lowerbound = 0;
4080 upperbound = 0;
4081 }
4082 else if (VectorExp ve = e1.isVectorExp())
4083 {
4084 // ve is not handled but a proper error message is returned
4085 // this is to prevent https://issues.dlang.org/show_bug.cgi?id=20042
4086 lowerbound = 0;
4087 upperbound = ve.dim;
4088 }
4089 else
4090 assert(0);
4091
4092 aggregate = e1;
4093 firstIndex = lowerbound;
4094 }
4095 if (upperbound == lowerbound)
4096 return newval;
4097
4098 // For slice assignment, we check that the lengths match.
4099 if (!isBlockAssignment && e1.type.ty != Tpointer)
4100 {
4101 const srclen = resolveArrayLength(newval);
4102 if (srclen != (upperbound - lowerbound))
4103 {
4104 error(e.loc, "array length mismatch assigning `[0..%llu]` to `[%llu..%llu]`",
4105 ulong(srclen), ulong(lowerbound), ulong(upperbound));
4106 return CTFEExp.cantexp;
4107 }
4108 }
4109
4110 if (auto existingSE = aggregate.isStringExp())
4111 {
4112 if (existingSE.ownedByCtfe != OwnedBy.ctfe)
4113 {
4114 error(e.loc, "cannot modify read-only string literal `%s`", existingSE.toChars());
4115 return CTFEExp.cantexp;
4116 }
4117
4118 if (auto se = newval.isSliceExp())
4119 {
4120 auto aggr2 = se.e1;
4121 const srclower = se.lwr.toInteger();
4122 const srcupper = se.upr.toInteger();
4123
4124 if (aggregate == aggr2 &&
4125 lowerbound < srcupper && srclower < upperbound)
4126 {
4127 error(e.loc, "overlapping slice assignment `[%llu..%llu] = [%llu..%llu]`",
4128 ulong(lowerbound), ulong(upperbound), ulong(srclower), ulong(srcupper));
4129 return CTFEExp.cantexp;
4130 }
4131 version (all) // todo: instead we can directly access to each elements of the slice
4132 {
4133 Expression orignewval = newval;
4134 newval = resolveSlice(newval);
4135 if (CTFEExp.isCantExp(newval))
4136 {
4137 error(e.loc, "CTFE internal error: slice `%s`", orignewval.toChars());
4138 return CTFEExp.cantexp;
4139 }
4140 }
4141 assert(newval.op != EXP.slice);
4142 }
4143 if (auto se = newval.isStringExp())
4144 {
4145 sliceAssignStringFromString(existingSE, se, cast(size_t)firstIndex);
4146 return newval;
4147 }
4148 if (auto ale = newval.isArrayLiteralExp())
4149 {
4150 /* Mixed slice: it was initialized as a string literal.
4151 * Now a slice of it is being set with an array literal.
4152 */
4153 sliceAssignStringFromArrayLiteral(existingSE, ale, cast(size_t)firstIndex);
4154 return newval;
4155 }
4156
4157 // String literal block slice assign
4158 const value = cast(dchar)newval.toInteger();
4159 foreach (i; 0 .. upperbound - lowerbound)
4160 {
4161 existingSE.setCodeUnit(cast(size_t)(i + firstIndex), value);
4162 }
4163 if (goal == CTFEGoal.Nothing)
4164 return null; // avoid creating an unused literal
4165 auto retslice = ctfeEmplaceExp!SliceExp(e.loc, existingSE,
4166 ctfeEmplaceExp!IntegerExp(e.loc, firstIndex, Type.tsize_t),
4167 ctfeEmplaceExp!IntegerExp(e.loc, firstIndex + upperbound - lowerbound, Type.tsize_t));
4168 retslice.type = e.type;
4169 return interpret(pue, retslice, istate);
4170 }
4171 if (auto existingAE = aggregate.isArrayLiteralExp())
4172 {
4173 if (existingAE.ownedByCtfe != OwnedBy.ctfe)
4174 {
4175 error(e.loc, "cannot modify read-only constant `%s`", existingAE.toChars());
4176 return CTFEExp.cantexp;
4177 }
4178
4179 if (newval.op == EXP.slice && !isBlockAssignment)
4180 {
4181 auto se = newval.isSliceExp();
4182 auto aggr2 = se.e1;
4183 const srclower = se.lwr.toInteger();
4184 const srcupper = se.upr.toInteger();
4185 const wantCopy = (newval.type.toBasetype().nextOf().baseElemOf().ty == Tstruct);
4186
4187 //printf("oldval = %p %s[%d..%u]\nnewval = %p %s[%llu..%llu] wantCopy = %d\n",
4188 // aggregate, aggregate.toChars(), lowerbound, upperbound,
4189 // aggr2, aggr2.toChars(), srclower, srcupper, wantCopy);
4190 if (wantCopy)
4191 {
4192 // Currently overlapping for struct array is allowed.
4193 // The order of elements processing depends on the overlapping.
4194 // https://issues.dlang.org/show_bug.cgi?id=14024
4195 assert(aggr2.op == EXP.arrayLiteral);
4196 Expressions* oldelems = existingAE.elements;
4197 Expressions* newelems = aggr2.isArrayLiteralExp().elements;
4198
4199 Type elemtype = aggregate.type.nextOf();
4200 bool needsPostblit = e.e2.isLvalue();
4201
4202 if (aggregate == aggr2 && srclower < lowerbound && lowerbound < srcupper)
4203 {
4204 // reverse order
4205 for (auto i = upperbound - lowerbound; 0 < i--;)
4206 {
4207 Expression oldelem = (*oldelems)[cast(size_t)(i + firstIndex)];
4208 Expression newelem = (*newelems)[cast(size_t)(i + srclower)];
4209 newelem = copyLiteral(newelem).copy();
4210 newelem.type = elemtype;
4211 if (needsPostblit)
4212 {
4213 if (Expression x = evaluatePostblit(istate, newelem))
4214 return x;
4215 }
4216 if (Expression x = evaluateDtor(istate, oldelem))
4217 return x;
4218 (*oldelems)[cast(size_t)(lowerbound + i)] = newelem;
4219 }
4220 }
4221 else
4222 {
4223 // normal order
4224 for (auto i = 0; i < upperbound - lowerbound; i++)
4225 {
4226 Expression oldelem = (*oldelems)[cast(size_t)(i + firstIndex)];
4227 Expression newelem = (*newelems)[cast(size_t)(i + srclower)];
4228 newelem = copyLiteral(newelem).copy();
4229 newelem.type = elemtype;
4230 if (needsPostblit)
4231 {
4232 if (Expression x = evaluatePostblit(istate, newelem))
4233 return x;
4234 }
4235 if (Expression x = evaluateDtor(istate, oldelem))
4236 return x;
4237 (*oldelems)[cast(size_t)(lowerbound + i)] = newelem;
4238 }
4239 }
4240
4241 //assert(0);
4242 return newval; // oldval?
4243 }
4244 if (aggregate == aggr2 &&
4245 lowerbound < srcupper && srclower < upperbound)
4246 {
4247 error(e.loc, "overlapping slice assignment `[%llu..%llu] = [%llu..%llu]`",
4248 ulong(lowerbound), ulong(upperbound), ulong(srclower), ulong(srcupper));
4249 return CTFEExp.cantexp;
4250 }
4251 version (all) // todo: instead we can directly access to each elements of the slice
4252 {
4253 Expression orignewval = newval;
4254 newval = resolveSlice(newval);
4255 if (CTFEExp.isCantExp(newval))
4256 {
4257 error(e.loc, "CTFE internal error: slice `%s`", orignewval.toChars());
4258 return CTFEExp.cantexp;
4259 }
4260 }
4261 // no overlapping
4262 //length?
4263 assert(newval.op != EXP.slice);
4264 }
4265 if (newval.op == EXP.string_ && !isBlockAssignment)
4266 {
4267 /* Mixed slice: it was initialized as an array literal of chars/integers.
4268 * Now a slice of it is being set with a string.
4269 */
4270 sliceAssignArrayLiteralFromString(existingAE, newval.isStringExp(), cast(size_t)firstIndex);
4271 return newval;
4272 }
4273 if (newval.op == EXP.arrayLiteral && !isBlockAssignment)
4274 {
4275 Expressions* oldelems = existingAE.elements;
4276 Expressions* newelems = newval.isArrayLiteralExp().elements;
4277 Type elemtype = existingAE.type.nextOf();
4278 bool needsPostblit = e.op != EXP.blit && e.e2.isLvalue();
4279 foreach (j, newelem; *newelems)
4280 {
4281 newelem = paintTypeOntoLiteral(elemtype, newelem);
4282 if (needsPostblit)
4283 {
4284 Expression x = evaluatePostblit(istate, newelem);
4285 if (exceptionOrCantInterpret(x))
4286 return x;
4287 }
4288 (*oldelems)[cast(size_t)(j + firstIndex)] = newelem;
4289 }
4290 return newval;
4291 }
4292
4293 /* Block assignment, initialization of static arrays
4294 * x[] = newval
4295 * x may be a multidimensional static array. (Note that this
4296 * only happens with array literals, never with strings).
4297 */
4298 struct RecursiveBlock
4299 {
4300 InterState* istate;
4301 Expression newval;
4302 bool refCopy;
4303 bool needsPostblit;
4304 bool needsDtor;
4305
4306 Expression assignTo(ArrayLiteralExp ae)
4307 {
4308 return assignTo(ae, 0, ae.elements.length);
4309 }
4310
4311 Expression assignTo(ArrayLiteralExp ae, size_t lwr, size_t upr)
4312 {
4313 Expressions* w = ae.elements;
4314 assert(ae.type.isStaticOrDynamicArray() || ae.type.ty == Tpointer);
4315 bool directblk = (cast(TypeNext)ae.type).next.equivalent(newval.type);
4316 for (size_t k = lwr; k < upr; k++)
4317 {
4318 if (!directblk && (*w)[k].op == EXP.arrayLiteral)
4319 {
4320 // Multidimensional array block assign
4321 if (Expression ex = assignTo((*w)[k].isArrayLiteralExp()))
4322 return ex;
4323 }
4324 else if (refCopy)
4325 {
4326 (*w)[k] = newval;
4327 }
4328 else if (!needsPostblit && !needsDtor)
4329 {
4330 assignInPlace((*w)[k], newval);
4331 }
4332 else
4333 {
4334 Expression oldelem = (*w)[k];
4335 Expression tmpelem = needsDtor ? copyLiteral(oldelem).copy() : null;
4336 assignInPlace(oldelem, newval);
4337 if (needsPostblit)
4338 {
4339 if (Expression ex = evaluatePostblit(istate, oldelem))
4340 return ex;
4341 }
4342 if (needsDtor)
4343 {
4344 // https://issues.dlang.org/show_bug.cgi?id=14860
4345 if (Expression ex = evaluateDtor(istate, tmpelem))
4346 return ex;
4347 }
4348 }
4349 }
4350 return null;
4351 }
4352 }
4353
4354 Type tn = newval.type.toBasetype();
4355 bool wantRef = (tn.ty == Tarray || isAssocArray(tn) || tn.ty == Tclass);
4356 bool cow = newval.op != EXP.structLiteral && newval.op != EXP.arrayLiteral && newval.op != EXP.string_;
4357 Type tb = tn.baseElemOf();
4358 StructDeclaration sd = (tb.ty == Tstruct ? (cast(TypeStruct)tb).sym : null);
4359
4360 RecursiveBlock rb;
4361 rb.istate = istate;
4362 rb.newval = newval;
4363 rb.refCopy = wantRef || cow;
4364 rb.needsPostblit = sd && sd.postblit && e.op != EXP.blit && e.e2.isLvalue();
4365 rb.needsDtor = sd && sd.dtor && (e.op == EXP.assign || e.op == EXP.loweredAssignExp);
4366 if (Expression ex = rb.assignTo(existingAE, cast(size_t)lowerbound, cast(size_t)upperbound))
4367 return ex;
4368
4369 if (goal == CTFEGoal.Nothing)
4370 return null; // avoid creating an unused literal
4371 auto retslice = ctfeEmplaceExp!SliceExp(e.loc, existingAE,
4372 ctfeEmplaceExp!IntegerExp(e.loc, firstIndex, Type.tsize_t),
4373 ctfeEmplaceExp!IntegerExp(e.loc, firstIndex + upperbound - lowerbound, Type.tsize_t));
4374 retslice.type = e.type;
4375 return interpret(pue, retslice, istate);
4376 }
4377
4378 error(e.loc, "slice operation `%s = %s` cannot be evaluated at compile time", e1.toChars(), newval.toChars());
4379 return CTFEExp.cantexp;
4380 }
4381
4382 override void visit(AssignExp e)
4383 {
4384 interpretAssignCommon(e, null);
4385 }
4386
4387 override void visit(BinAssignExp e)
4388 {
4389 switch (e.op)
4390 {
4391 case EXP.addAssign:
4392 interpretAssignCommon(e, &Add);
4393 return;
4394
4395 case EXP.minAssign:
4396 interpretAssignCommon(e, &Min);
4397 return;
4398
4399 case EXP.concatenateAssign:
4400 case EXP.concatenateElemAssign:
4401 case EXP.concatenateDcharAssign:
4402 interpretAssignCommon(e, &ctfeCat);
4403 return;
4404
4405 case EXP.mulAssign:
4406 interpretAssignCommon(e, &Mul);
4407 return;
4408
4409 case EXP.divAssign:
4410 interpretAssignCommon(e, &Div);
4411 return;
4412
4413 case EXP.modAssign:
4414 interpretAssignCommon(e, &Mod);
4415 return;
4416
4417 case EXP.leftShiftAssign:
4418 interpretAssignCommon(e, &Shl);
4419 return;
4420
4421 case EXP.rightShiftAssign:
4422 interpretAssignCommon(e, &Shr);
4423 return;
4424
4425 case EXP.unsignedRightShiftAssign:
4426 interpretAssignCommon(e, &Ushr);
4427 return;
4428
4429 case EXP.andAssign:
4430 interpretAssignCommon(e, &And);
4431 return;
4432
4433 case EXP.orAssign:
4434 interpretAssignCommon(e, &Or);
4435 return;
4436
4437 case EXP.xorAssign:
4438 interpretAssignCommon(e, &Xor);
4439 return;
4440
4441 case EXP.powAssign:
4442 interpretAssignCommon(e, &Pow);
4443 return;
4444
4445 default:
4446 assert(0);
4447 }
4448 }
4449
4450 override void visit(PostExp e)
4451 {
4452 debug (LOG)
4453 {
4454 printf("%s PostExp::interpret() %s\n", e.loc.toChars(), e.toChars());
4455 }
4456 if (e.op == EXP.plusPlus)
4457 interpretAssignCommon(e, &Add, 1);
4458 else
4459 interpretAssignCommon(e, &Min, 1);
4460 debug (LOG)
4461 {
4462 if (CTFEExp.isCantExp(result))
4463 printf("PostExp::interpret() CANT\n");
4464 }
4465 }
4466
4467 /* Return 1 if e is a p1 > p2 or p1 >= p2 pointer comparison;
4468 * -1 if e is a p1 < p2 or p1 <= p2 pointer comparison;
4469 * 0 otherwise
4470 */
4471 static int isPointerCmpExp(Expression e, Expression* p1, Expression* p2)
4472 {
4473 int ret = 1;
4474 while (e.op == EXP.not)
4475 {
4476 ret *= -1;
4477 e = e.isNotExp().e1;
4478 }
4479 switch (e.op)
4480 {
4481 case EXP.lessThan:
4482 case EXP.lessOrEqual:
4483 ret *= -1;
4484 goto case; /+ fall through +/
4485 case EXP.greaterThan:
4486 case EXP.greaterOrEqual:
4487 *p1 = e.isBinExp().e1;
4488 *p2 = e.isBinExp().e2;
4489 if (!(isPointer((*p1).type) && isPointer((*p2).type)))
4490 ret = 0;
4491 break;
4492
4493 default:
4494 ret = 0;
4495 break;
4496 }
4497 return ret;
4498 }
4499
4500 /** If this is a four pointer relation, evaluate it, else return NULL.
4501 *
4502 * This is an expression of the form (p1 > q1 && p2 < q2) or (p1 < q1 || p2 > q2)
4503 * where p1, p2 are expressions yielding pointers to memory block p,
4504 * and q1, q2 are expressions yielding pointers to memory block q.
4505 * This expression is valid even if p and q are independent memory
4506 * blocks and are therefore not normally comparable; the && form returns true
4507 * if [p1..p2] lies inside [q1..q2], and false otherwise; the || form returns
4508 * true if [p1..p2] lies outside [q1..q2], and false otherwise.
4509 *
4510 * Within the expression, any ordering of p1, p2, q1, q2 is permissible;
4511 * the comparison operators can be any of >, <, <=, >=, provided that
4512 * both directions (p > q and p < q) are checked. Additionally the
4513 * relational sub-expressions can be negated, eg
4514 * (!(q1 < p1) && p2 <= q2) is valid.
4515 */
4516 private void interpretFourPointerRelation(UnionExp* pue, BinExp e)
4517 {
4518 assert(e.op == EXP.andAnd || e.op == EXP.orOr);
4519
4520 /* It can only be an isInside expression, if both e1 and e2 are
4521 * directional pointer comparisons.
4522 * Note that this check can be made statically; it does not depends on
4523 * any runtime values. This allows a JIT implementation to compile a
4524 * special AndAndPossiblyInside, keeping the normal AndAnd case efficient.
4525 */
4526
4527 // Save the pointer expressions and the comparison directions,
4528 // so we can use them later.
4529 Expression p1 = null;
4530 Expression p2 = null;
4531 Expression p3 = null;
4532 Expression p4 = null;
4533 int dir1 = isPointerCmpExp(e.e1, &p1, &p2);
4534 int dir2 = isPointerCmpExp(e.e2, &p3, &p4);
4535 if (dir1 == 0 || dir2 == 0)
4536 {
4537 result = null;
4538 return;
4539 }
4540
4541 //printf("FourPointerRelation %s\n", toChars());
4542
4543 UnionExp ue1 = void;
4544 UnionExp ue2 = void;
4545 UnionExp ue3 = void;
4546 UnionExp ue4 = void;
4547
4548 // Evaluate the first two pointers
4549 p1 = interpret(&ue1, p1, istate);
4550 if (exceptionOrCant(p1))
4551 return;
4552 p2 = interpret(&ue2, p2, istate);
4553 if (exceptionOrCant(p2))
4554 return;
4555 dinteger_t ofs1, ofs2;
4556 Expression agg1 = getAggregateFromPointer(p1, &ofs1);
4557 Expression agg2 = getAggregateFromPointer(p2, &ofs2);
4558
4559 if (!pointToSameMemoryBlock(agg1, agg2) && agg1.op != EXP.null_ && agg2.op != EXP.null_)
4560 {
4561 // Here it is either CANT_INTERPRET,
4562 // or an IsInside comparison returning false.
4563 p3 = interpret(&ue3, p3, istate);
4564 if (CTFEExp.isCantExp(p3))
4565 return;
4566 // Note that it is NOT legal for it to throw an exception!
4567 Expression except = null;
4568 if (exceptionOrCantInterpret(p3))
4569 except = p3;
4570 else
4571 {
4572 p4 = interpret(&ue4, p4, istate);
4573 if (CTFEExp.isCantExp(p4))
4574 {
4575 result = p4;
4576 return;
4577 }
4578 if (exceptionOrCantInterpret(p4))
4579 except = p4;
4580 }
4581 if (except)
4582 {
4583 error(e.loc, "comparison `%s` of pointers to unrelated memory blocks remains indeterminate at compile time because exception `%s` was thrown while evaluating `%s`", e.e1.toChars(), except.toChars(), e.e2.toChars());
4584 result = CTFEExp.cantexp;
4585 return;
4586 }
4587 dinteger_t ofs3, ofs4;
4588 Expression agg3 = getAggregateFromPointer(p3, &ofs3);
4589 Expression agg4 = getAggregateFromPointer(p4, &ofs4);
4590 // The valid cases are:
4591 // p1 > p2 && p3 > p4 (same direction, also for < && <)
4592 // p1 > p2 && p3 < p4 (different direction, also < && >)
4593 // Changing any > into >= doesn't affect the result
4594 if ((dir1 == dir2 && pointToSameMemoryBlock(agg1, agg4) && pointToSameMemoryBlock(agg2, agg3)) ||
4595 (dir1 != dir2 && pointToSameMemoryBlock(agg1, agg3) && pointToSameMemoryBlock(agg2, agg4)))
4596 {
4597 // it's a legal two-sided comparison
4598 emplaceExp!(IntegerExp)(pue, e.loc, (e.op == EXP.andAnd) ? 0 : 1, e.type);
4599 result = pue.exp();
4600 return;
4601 }
4602 // It's an invalid four-pointer comparison. Either the second
4603 // comparison is in the same direction as the first, or else
4604 // more than two memory blocks are involved (either two independent
4605 // invalid comparisons are present, or else agg3 == agg4).
4606 error(e.loc, "comparison `%s` of pointers to unrelated memory blocks is indeterminate at compile time, even when combined with `%s`.", e.e1.toChars(), e.e2.toChars());
4607 result = CTFEExp.cantexp;
4608 return;
4609 }
4610 // The first pointer expression didn't need special treatment, so we
4611 // we need to interpret the entire expression exactly as a normal && or ||.
4612 // This is easy because we haven't evaluated e2 at all yet, and we already
4613 // know it will return a bool.
4614 // But we mustn't evaluate the pointer expressions in e1 again, in case
4615 // they have side-effects.
4616 bool nott = false;
4617 Expression ex = e.e1;
4618 while (1)
4619 {
4620 if (auto ne = ex.isNotExp())
4621 {
4622 nott = !nott;
4623 ex = ne.e1;
4624 }
4625 else
4626 break;
4627 }
4628
4629 /** Negate relational operator, eg >= becomes <
4630 * Params:
4631 * op = comparison operator to negate
4632 * Returns:
4633 * negate operator
4634 */
4635 static EXP negateRelation(EXP op) pure
4636 {
4637 switch (op)
4638 {
4639 case EXP.greaterOrEqual: op = EXP.lessThan; break;
4640 case EXP.greaterThan: op = EXP.lessOrEqual; break;
4641 case EXP.lessOrEqual: op = EXP.greaterThan; break;
4642 case EXP.lessThan: op = EXP.greaterOrEqual; break;
4643 default: assert(0);
4644 }
4645 return op;
4646 }
4647
4648 const EXP cmpop = nott ? negateRelation(ex.op) : ex.op;
4649 const cmp = comparePointers(cmpop, agg1, ofs1, agg2, ofs2);
4650 // We already know this is a valid comparison.
4651 assert(cmp >= 0);
4652 if (e.op == EXP.andAnd && cmp == 1 || e.op == EXP.orOr && cmp == 0)
4653 {
4654 result = interpret(pue, e.e2, istate);
4655 return;
4656 }
4657 emplaceExp!(IntegerExp)(pue, e.loc, (e.op == EXP.andAnd) ? 0 : 1, e.type);
4658 result = pue.exp();
4659 }
4660
4661 override void visit(LogicalExp e)
4662 {
4663 debug (LOG)
4664 {
4665 printf("%s LogicalExp::interpret() %s\n", e.loc.toChars(), e.toChars());
4666 }
4667 // Check for an insidePointer expression, evaluate it if so
4668 interpretFourPointerRelation(pue, e);
4669 if (result)
4670 return;
4671
4672 UnionExp ue1 = void;
4673 result = interpret(&ue1, e.e1, istate);
4674 if (exceptionOrCant(result))
4675 return;
4676
4677 bool res;
4678 const andand = e.op == EXP.andAnd;
4679 if (andand ? result.toBool().hasValue(false) : isTrueBool(result))
4680 res = !andand;
4681 else if (andand ? isTrueBool(result) : result.toBool().hasValue(false))
4682 {
4683 UnionExp ue2 = void;
4684 result = interpret(&ue2, e.e2, istate);
4685 if (exceptionOrCant(result))
4686 return;
4687 if (result.op == EXP.voidExpression)
4688 {
4689 assert(e.type.ty == Tvoid);
4690 result = null;
4691 return;
4692 }
4693 if (result.toBool().hasValue(false))
4694 res = false;
4695 else if (isTrueBool(result))
4696 res = true;
4697 else
4698 {
4699 error(e.loc, "`%s` does not evaluate to a `bool`", result.toChars());
4700 result = CTFEExp.cantexp;
4701 return;
4702 }
4703 }
4704 else
4705 {
4706 error(e.loc, "`%s` cannot be interpreted as a `bool`", result.toChars());
4707 result = CTFEExp.cantexp;
4708 return;
4709 }
4710 incUsageCtfe(istate, e.e2.loc);
4711
4712 if (goal != CTFEGoal.Nothing)
4713 {
4714 if (e.type.equals(Type.tbool))
4715 result = IntegerExp.createBool(res);
4716 else
4717 {
4718 emplaceExp!(IntegerExp)(pue, e.loc, res, e.type);
4719 result = pue.exp();
4720 }
4721 }
4722 }
4723
4724
4725 // Print a stack trace, starting from callingExp which called fd.
4726 // To shorten the stack trace, try to detect recursion.
4727 private void showCtfeBackTrace(CallExp callingExp, FuncDeclaration fd)
4728 {
4729 if (ctfeGlobals.stackTraceCallsToSuppress > 0)
4730 {
4731 --ctfeGlobals.stackTraceCallsToSuppress;
4732 return;
4733 }
4734 errorSupplemental(callingExp.loc, "called from here: `%s`", callingExp.toChars());
4735 // Quit if it's not worth trying to compress the stack trace
4736 if (ctfeGlobals.callDepth < 6 || global.params.v.verbose)
4737 return;
4738 // Recursion happens if the current function already exists in the call stack.
4739 int numToSuppress = 0;
4740 int recurseCount = 0;
4741 int depthSoFar = 0;
4742 InterState* lastRecurse = istate;
4743 for (InterState* cur = istate; cur; cur = cur.caller)
4744 {
4745 if (cur.fd == fd)
4746 {
4747 ++recurseCount;
4748 numToSuppress = depthSoFar;
4749 lastRecurse = cur;
4750 }
4751 ++depthSoFar;
4752 }
4753 // We need at least three calls to the same function, to make compression worthwhile
4754 if (recurseCount < 2)
4755 return;
4756 // We found a useful recursion. Print all the calls involved in the recursion
4757 errorSupplemental(fd.loc, "%d recursive calls to function `%s`", recurseCount, fd.toChars());
4758 for (InterState* cur = istate; cur.fd != fd; cur = cur.caller)
4759 {
4760 errorSupplemental(cur.fd.loc, "recursively called from function `%s`", cur.fd.toChars());
4761 }
4762 // We probably didn't enter the recursion in this function.
4763 // Go deeper to find the real beginning.
4764 InterState* cur = istate;
4765 while (lastRecurse.caller && cur.fd == lastRecurse.caller.fd)
4766 {
4767 cur = cur.caller;
4768 lastRecurse = lastRecurse.caller;
4769 ++numToSuppress;
4770 }
4771 ctfeGlobals.stackTraceCallsToSuppress = numToSuppress;
4772 }
4773
4774 override void visit(CallExp e)
4775 {
4776 debug (LOG)
4777 {
4778 printf("%s CallExp::interpret() %s\n", e.loc.toChars(), e.toChars());
4779 }
4780 Expression pthis = null;
4781 FuncDeclaration fd = null;
4782
4783 Expression ecall = interpretRegion(e.e1, istate);
4784 if (exceptionOrCant(ecall))
4785 return;
4786
4787 if (auto dve = ecall.isDotVarExp())
4788 {
4789 // Calling a member function
4790 pthis = dve.e1;
4791 fd = dve.var.isFuncDeclaration();
4792 assert(fd);
4793
4794 if (auto dte = pthis.isDotTypeExp())
4795 pthis = dte.e1;
4796 }
4797 else if (auto ve = ecall.isVarExp())
4798 {
4799 fd = ve.var.isFuncDeclaration();
4800 assert(fd);
4801
4802 // If `_d_HookTraceImpl` is found, resolve the underlying hook and replace `e` and `fd` with it.
4803 removeHookTraceImpl(e, fd);
4804
4805 if (fd.ident == Id.__ArrayPostblit || fd.ident == Id.__ArrayDtor)
4806 {
4807 assert(e.arguments.length == 1);
4808 Expression ea = (*e.arguments)[0];
4809 // printf("1 ea = %s %s\n", ea.type.toChars(), ea.toChars());
4810 if (auto se = ea.isSliceExp())
4811 ea = se.e1;
4812 if (auto ce = ea.isCastExp())
4813 ea = ce.e1;
4814
4815 // printf("2 ea = %s, %s %s\n", ea.type.toChars(), EXPtoString(ea.op).ptr, ea.toChars());
4816 if (ea.op == EXP.variable || ea.op == EXP.symbolOffset)
4817 result = getVarExp(e.loc, istate, (cast(SymbolExp)ea).var, CTFEGoal.RValue);
4818 else if (auto ae = ea.isAddrExp())
4819 result = interpretRegion(ae.e1, istate);
4820
4821 // https://issues.dlang.org/show_bug.cgi?id=18871
4822 // https://issues.dlang.org/show_bug.cgi?id=18819
4823 else if (auto ale = ea.isArrayLiteralExp())
4824 result = interpretRegion(ale, istate);
4825
4826 else
4827 assert(0);
4828 if (CTFEExp.isCantExp(result))
4829 return;
4830
4831 if (fd.ident == Id.__ArrayPostblit)
4832 result = evaluatePostblit(istate, result);
4833 else
4834 result = evaluateDtor(istate, result);
4835 if (!result)
4836 result = CTFEExp.voidexp;
4837 return;
4838 }
4839 else if (isArrayConstruction(fd.ident))
4840 {
4841 // In expressionsem.d, `T[x] ea = eb;` was lowered to:
4842 // `_d_array{,set}ctor(ea[], eb[]);`.
4843 // The following code will rewrite it back to `ea = eb` and
4844 // then interpret that expression.
4845
4846 if (fd.ident == Id._d_arrayctor)
4847 assert(e.arguments.length == 3);
4848 else
4849 assert(e.arguments.length == 2);
4850
4851 Expression ea = (*e.arguments)[0];
4852 if (ea.isCastExp)
4853 ea = ea.isCastExp.e1;
4854
4855 Expression eb = (*e.arguments)[1];
4856 if (eb.isCastExp() && fd.ident == Id._d_arrayctor)
4857 eb = eb.isCastExp.e1;
4858
4859 ConstructExp ce = new ConstructExp(e.loc, ea, eb);
4860 ce.type = ea.type;
4861
4862 ce.type = ea.type;
4863 result = interpret(ce, istate);
4864
4865 return;
4866 }
4867 }
4868 else if (auto soe = ecall.isSymOffExp())
4869 {
4870 fd = soe.var.isFuncDeclaration();
4871 assert(fd && soe.offset == 0);
4872 }
4873 else if (auto de = ecall.isDelegateExp())
4874 {
4875 // Calling a delegate
4876 fd = de.func;
4877 pthis = de.e1;
4878
4879 // Special handling for: &nestedfunc --> DelegateExp(VarExp(nestedfunc), nestedfunc)
4880 if (auto ve = pthis.isVarExp())
4881 if (ve.var == fd)
4882 pthis = null; // context is not necessary for CTFE
4883 }
4884 else if (auto fe = ecall.isFuncExp())
4885 {
4886 // Calling a delegate literal
4887 fd = fe.fd;
4888 }
4889 else
4890 {
4891 // delegate.funcptr()
4892 // others
4893 error(e.loc, "cannot call `%s` at compile time", e.toChars());
4894 result = CTFEExp.cantexp;
4895 return;
4896 }
4897 if (!fd)
4898 {
4899 error(e.loc, "CTFE internal error: cannot evaluate `%s` at compile time", e.toChars());
4900 result = CTFEExp.cantexp;
4901 return;
4902 }
4903 if (pthis)
4904 {
4905 // Member function call
4906
4907 // Currently this is satisfied because closure is not yet supported.
4908 assert(!fd.isNested() || fd.needThis());
4909
4910 if (pthis.op == EXP.typeid_)
4911 {
4912 error(pthis.loc, "static variable `%s` cannot be read at compile time", pthis.toChars());
4913 result = CTFEExp.cantexp;
4914 return;
4915 }
4916 assert(pthis);
4917
4918 if (pthis.op == EXP.null_)
4919 {
4920 assert(pthis.type.toBasetype().ty == Tclass);
4921 error(e.loc, "function call through null class reference `%s`", pthis.toChars());
4922 result = CTFEExp.cantexp;
4923 return;
4924 }
4925
4926 assert(pthis.op == EXP.structLiteral || pthis.op == EXP.classReference || pthis.op == EXP.type);
4927
4928 if (fd.isVirtual() && !e.directcall)
4929 {
4930 // Make a virtual function call.
4931 // Get the function from the vtable of the original class
4932 ClassDeclaration cd = pthis.isClassReferenceExp().originalClass();
4933
4934 // We can't just use the vtable index to look it up, because
4935 // vtables for interfaces don't get populated until the glue layer.
4936 fd = cd.findFunc(fd.ident, fd.type.isTypeFunction());
4937 assert(fd);
4938 }
4939 }
4940
4941 if (fd && fd.semanticRun >= PASS.semantic3done && fd.hasSemantic3Errors())
4942 {
4943 error(e.loc, "CTFE failed because of previous errors in `%s`", fd.toChars());
4944 result = CTFEExp.cantexp;
4945 return;
4946 }
4947
4948 // Check for built-in functions
4949 result = evaluateIfBuiltin(pue, istate, e.loc, fd, e.arguments, pthis);
4950 if (result)
4951 return;
4952
4953 if (!fd.fbody)
4954 {
4955 error(e.loc, "`%s` cannot be interpreted at compile time, because it has no available source code", fd.toChars());
4956 result = CTFEExp.showcontext;
4957 return;
4958 }
4959
4960 result = interpretFunction(pue, fd, istate, e.arguments, pthis);
4961 if (result.op == EXP.voidExpression)
4962 return;
4963 if (!exceptionOrCantInterpret(result))
4964 {
4965 if (goal != CTFEGoal.LValue) // Peel off CTFE reference if it's unnecessary
4966 {
4967 if (result == pue.exp())
4968 result = pue.copy();
4969 result = interpret(pue, result, istate);
4970 }
4971 }
4972 if (!exceptionOrCantInterpret(result))
4973 {
4974 result = paintTypeOntoLiteral(pue, e.type, result);
4975 result.loc = e.loc;
4976 }
4977 else if (CTFEExp.isCantExp(result) && !global.gag)
4978 showCtfeBackTrace(e, fd); // Print a stack trace.
4979 }
4980
4981 override void visit(CommaExp e)
4982 {
4983 /****************************************
4984 * Find the first non-comma expression.
4985 * Params:
4986 * e = Expressions connected by commas
4987 * Returns:
4988 * left-most non-comma expression
4989 */
4990 static inout(Expression) firstComma(inout Expression e)
4991 {
4992 Expression ex = cast()e;
4993 while (ex.op == EXP.comma)
4994 ex = (cast(CommaExp)ex).e1;
4995 return cast(inout)ex;
4996
4997 }
4998
4999 debug (LOG)
5000 {
5001 printf("%s CommaExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5002 }
5003
5004 bool isNewThrowableHook()
5005 {
5006 auto de = e.e1.isDeclarationExp();
5007 if (de is null)
5008 return false;
5009
5010 auto vd = de.declaration.isVarDeclaration();
5011 if (vd is null)
5012 return false;
5013
5014 auto ei = vd._init.isExpInitializer();
5015 if (ei is null)
5016 return false;
5017
5018 auto ce = ei.exp.isConstructExp();
5019 if (ce is null)
5020 return false;
5021
5022 return isRuntimeHook(ce.e2, Id._d_newThrowable) !is null;
5023 }
5024
5025 if (auto ce = isRuntimeHook(e.e1, Id._d_arrayappendcTX))
5026 {
5027 // In expressionsem.d `arr ~= elem` was lowered to
5028 // `_d_arrayappendcTX(arr, elem), arr[arr.length - 1] = elem, elem;`.
5029 // The following code will rewrite it back to `arr ~= elem`
5030 // and then interpret that expression.
5031 assert(ce.arguments.length == 2);
5032
5033 auto arr = (*ce.arguments)[0];
5034 auto elem = e.e2.isConstructExp().e2;
5035 assert(elem);
5036
5037 auto cae = new CatAssignExp(e.loc, arr, elem);
5038 cae.type = arr.type;
5039
5040 result = interpret(cae, istate);
5041 return;
5042 }
5043 else if (isNewThrowableHook())
5044 {
5045 // In expressionsem.d `throw new Exception(args)` was lowered to
5046 // `throw (tmp = _d_newThrowable!Exception(), tmp.ctor(args), tmp)`.
5047 // The following code will rewrite it back to `throw new Exception(args)`
5048 // and then interpret this expression instead.
5049 auto ce = e.e2.isCallExp();
5050 assert(ce);
5051
5052 auto ne = new NewExp(e.loc, null, null, e.type, ce.arguments);
5053 ne.type = e.e1.type;
5054
5055 result = interpret(ne, istate);
5056 return;
5057 }
5058
5059 // If it creates a variable, and there's no context for
5060 // the variable to be created in, we need to create one now.
5061 InterState istateComma;
5062 if (!istate && firstComma(e.e1).op == EXP.declaration)
5063 {
5064 ctfeGlobals.stack.startFrame(null);
5065 istate = &istateComma;
5066 }
5067
5068 void endTempStackFrame()
5069 {
5070 // If we created a temporary stack frame, end it now.
5071 if (istate == &istateComma)
5072 ctfeGlobals.stack.endFrame();
5073 }
5074
5075 result = CTFEExp.cantexp;
5076
5077 // If the comma returns a temporary variable, it needs to be an lvalue
5078 // (this is particularly important for struct constructors)
5079 if (e.e1.op == EXP.declaration &&
5080 e.e2.op == EXP.variable &&
5081 e.e1.isDeclarationExp().declaration == e.e2.isVarExp().var &&
5082 e.e2.isVarExp().var.storage_class & STC.ctfe)
5083 {
5084 VarExp ve = e.e2.isVarExp();
5085 VarDeclaration v = ve.var.isVarDeclaration();
5086 ctfeGlobals.stack.push(v);
5087 if (!v._init && !getValue(v))
5088 {
5089 setValue(v, copyLiteral(v.type.defaultInitLiteral(e.loc)).copy());
5090 }
5091 if (!getValue(v))
5092 {
5093 Expression newval = v._init.initializerToExpression();
5094 // Bug 4027. Copy constructors are a weird case where the
5095 // initializer is a void function (the variable is modified
5096 // through a reference parameter instead).
5097 newval = interpretRegion(newval, istate);
5098 if (exceptionOrCant(newval))
5099 return endTempStackFrame();
5100 if (newval.op != EXP.voidExpression)
5101 {
5102 // v isn't necessarily null.
5103 setValueWithoutChecking(v, copyLiteral(newval).copy());
5104 }
5105 }
5106 }
5107 else
5108 {
5109 UnionExp ue = void;
5110 auto e1 = interpret(&ue, e.e1, istate, CTFEGoal.Nothing);
5111 if (exceptionOrCant(e1))
5112 return endTempStackFrame();
5113 }
5114 result = interpret(pue, e.e2, istate, goal);
5115 return endTempStackFrame();
5116 }
5117
5118 override void visit(CondExp e)
5119 {
5120 debug (LOG)
5121 {
5122 printf("%s CondExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5123 }
5124 UnionExp uecond = void;
5125 Expression econd;
5126 econd = interpret(&uecond, e.econd, istate);
5127 if (exceptionOrCant(econd))
5128 return;
5129
5130 if (isPointer(e.econd.type))
5131 {
5132 if (econd.op != EXP.null_)
5133 {
5134 econd = IntegerExp.createBool(true);
5135 }
5136 }
5137
5138 if (isTrueBool(econd))
5139 {
5140 result = interpret(pue, e.e1, istate, goal);
5141 incUsageCtfe(istate, e.e1.loc);
5142 }
5143 else if (econd.toBool().hasValue(false))
5144 {
5145 result = interpret(pue, e.e2, istate, goal);
5146 incUsageCtfe(istate, e.e2.loc);
5147 }
5148 else
5149 {
5150 error(e.loc, "`%s` does not evaluate to boolean result at compile time", e.econd.toChars());
5151 result = CTFEExp.cantexp;
5152 }
5153 }
5154
5155 override void visit(ArrayLengthExp e)
5156 {
5157 debug (LOG)
5158 {
5159 printf("%s ArrayLengthExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5160 }
5161 UnionExp ue1;
5162 Expression e1 = interpret(&ue1, e.e1, istate);
5163 assert(e1);
5164 if (exceptionOrCant(e1))
5165 return;
5166 if (e1.op != EXP.string_ && e1.op != EXP.arrayLiteral && e1.op != EXP.slice && e1.op != EXP.null_)
5167 {
5168 error(e.loc, "`%s` cannot be evaluated at compile time", e.toChars());
5169 result = CTFEExp.cantexp;
5170 return;
5171 }
5172 emplaceExp!(IntegerExp)(pue, e.loc, resolveArrayLength(e1), e.type);
5173 result = pue.exp();
5174 }
5175
5176 /**
5177 * Interpret the vector expression as an array literal.
5178 * Params:
5179 * pue = non-null pointer to temporary storage that can be used to store the return value
5180 * e = Expression to interpret
5181 * Returns:
5182 * resulting array literal or 'e' if unable to interpret
5183 */
5184 static Expression interpretVectorToArray(UnionExp* pue, VectorExp e)
5185 {
5186 if (auto ale = e.e1.isArrayLiteralExp())
5187 return ale; // it's already an array literal
5188 if (e.e1.op == EXP.int64 || e.e1.op == EXP.float64)
5189 {
5190 // Convert literal __vector(int) -> __vector([array])
5191 auto elements = new Expressions(e.dim);
5192 foreach (ref element; *elements)
5193 element = copyLiteral(e.e1).copy();
5194 auto type = (e.type.ty == Tvector) ? e.type.isTypeVector().basetype : e.type.isTypeSArray();
5195 assert(type);
5196 emplaceExp!(ArrayLiteralExp)(pue, e.loc, type, elements);
5197 auto ale = pue.exp().isArrayLiteralExp();
5198 ale.ownedByCtfe = OwnedBy.ctfe;
5199 return ale;
5200 }
5201 return e;
5202 }
5203
5204 override void visit(VectorExp e)
5205 {
5206 debug (LOG)
5207 {
5208 printf("%s VectorExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5209 }
5210 if (e.ownedByCtfe >= OwnedBy.ctfe) // We've already interpreted all the elements
5211 {
5212 result = e;
5213 return;
5214 }
5215 Expression e1 = interpret(pue, e.e1, istate);
5216 assert(e1);
5217 if (exceptionOrCant(e1))
5218 return;
5219 if (e1.op != EXP.arrayLiteral && e1.op != EXP.int64 && e1.op != EXP.float64)
5220 {
5221 error(e.loc, "`%s` cannot be evaluated at compile time", e.toChars());
5222 result = CTFEExp.cantexp;
5223 return;
5224 }
5225 if (e1 == pue.exp())
5226 e1 = pue.copy();
5227 emplaceExp!(VectorExp)(pue, e.loc, e1, e.to);
5228 auto ve = pue.exp().isVectorExp();
5229 ve.type = e.type;
5230 ve.dim = e.dim;
5231 ve.ownedByCtfe = OwnedBy.ctfe;
5232 result = ve;
5233 }
5234
5235 override void visit(VectorArrayExp e)
5236 {
5237 debug (LOG)
5238 {
5239 printf("%s VectorArrayExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5240 }
5241 Expression e1 = interpret(pue, e.e1, istate);
5242 assert(e1);
5243 if (exceptionOrCant(e1))
5244 return;
5245 if (auto ve = e1.isVectorExp())
5246 {
5247 result = interpretVectorToArray(pue, ve);
5248 if (result.op != EXP.vector)
5249 return;
5250 }
5251 error(e.loc, "`%s` cannot be evaluated at compile time", e.toChars());
5252 result = CTFEExp.cantexp;
5253 }
5254
5255 override void visit(DelegatePtrExp e)
5256 {
5257 debug (LOG)
5258 {
5259 printf("%s DelegatePtrExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5260 }
5261 Expression e1 = interpret(pue, e.e1, istate);
5262 assert(e1);
5263 if (exceptionOrCant(e1))
5264 return;
5265 error(e.loc, "`%s` cannot be evaluated at compile time", e.toChars());
5266 result = CTFEExp.cantexp;
5267 }
5268
5269 override void visit(DelegateFuncptrExp e)
5270 {
5271 debug (LOG)
5272 {
5273 printf("%s DelegateFuncptrExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5274 }
5275 Expression e1 = interpret(pue, e.e1, istate);
5276 assert(e1);
5277 if (exceptionOrCant(e1))
5278 return;
5279 error(e.loc, "`%s` cannot be evaluated at compile time", e.toChars());
5280 result = CTFEExp.cantexp;
5281 }
5282
5283 static bool resolveIndexing(IndexExp e, InterState* istate, Expression* pagg, uinteger_t* pidx, bool modify)
5284 {
5285 assert(e.e1.type.toBasetype().ty != Taarray);
5286
5287 if (e.e1.type.toBasetype().ty == Tpointer)
5288 {
5289 // Indexing a pointer. Note that there is no $ in this case.
5290 Expression e1 = interpretRegion(e.e1, istate);
5291 if (exceptionOrCantInterpret(e1))
5292 return false;
5293
5294 Expression e2 = interpretRegion(e.e2, istate);
5295 if (exceptionOrCantInterpret(e2))
5296 return false;
5297 sinteger_t indx = e2.toInteger();
5298
5299 dinteger_t ofs;
5300 Expression agg = getAggregateFromPointer(e1, &ofs);
5301
5302 if (agg.op == EXP.null_)
5303 {
5304 error(e.loc, "cannot index through null pointer `%s`", e.e1.toChars());
5305 return false;
5306 }
5307 if (agg.op == EXP.int64)
5308 {
5309 error(e.loc, "cannot index through invalid pointer `%s` of value `%s`", e.e1.toChars(), e1.toChars());
5310 return false;
5311 }
5312 // Pointer to a non-array variable
5313 if (agg.op == EXP.symbolOffset)
5314 {
5315 error(e.loc, "mutable variable `%s` cannot be %s at compile time, even through a pointer", cast(char*)(modify ? "modified" : "read"), agg.isSymOffExp().var.toChars());
5316 return false;
5317 }
5318
5319 if (agg.op == EXP.arrayLiteral || agg.op == EXP.string_)
5320 {
5321 dinteger_t len = resolveArrayLength(agg);
5322 if (ofs + indx >= len)
5323 {
5324 error(e.loc, "pointer index `[%lld]` exceeds allocated memory block `[0..%lld]`", ofs + indx, len);
5325 return false;
5326 }
5327 }
5328 else
5329 {
5330 if (ofs + indx != 0)
5331 {
5332 error(e.loc, "pointer index `[%lld]` lies outside memory block `[0..1]`", ofs + indx);
5333 return false;
5334 }
5335 }
5336 *pagg = agg;
5337 *pidx = ofs + indx;
5338 return true;
5339 }
5340
5341 Expression e1 = interpretRegion(e.e1, istate);
5342 if (exceptionOrCantInterpret(e1))
5343 return false;
5344 if (e1.op == EXP.null_)
5345 {
5346 error(e.loc, "cannot index null array `%s`", e.e1.toChars());
5347 return false;
5348 }
5349 if (auto ve = e1.isVectorExp())
5350 {
5351 UnionExp ue = void;
5352 e1 = interpretVectorToArray(&ue, ve);
5353 e1 = (e1 == ue.exp()) ? ue.copy() : e1;
5354 }
5355
5356 // Set the $ variable, and find the array literal to modify
5357 dinteger_t len;
5358 if (e1.op == EXP.variable && e1.type.toBasetype().ty == Tsarray)
5359 len = e1.type.toBasetype().isTypeSArray().dim.toInteger();
5360 else
5361 {
5362 if (e1.op != EXP.arrayLiteral && e1.op != EXP.string_ && e1.op != EXP.slice && e1.op != EXP.vector)
5363 {
5364 error(e.loc, "cannot determine length of `%s` at compile time", e.e1.toChars());
5365 return false;
5366 }
5367 len = resolveArrayLength(e1);
5368 }
5369
5370 if (e.lengthVar)
5371 {
5372 Expression dollarExp = ctfeEmplaceExp!IntegerExp(e.loc, len, Type.tsize_t);
5373 ctfeGlobals.stack.push(e.lengthVar);
5374 setValue(e.lengthVar, dollarExp);
5375 }
5376 Expression e2 = interpretRegion(e.e2, istate);
5377 if (e.lengthVar)
5378 ctfeGlobals.stack.pop(e.lengthVar); // $ is defined only inside []
5379 if (exceptionOrCantInterpret(e2))
5380 return false;
5381 if (e2.op != EXP.int64)
5382 {
5383 error(e.loc, "CTFE internal error: non-integral index `[%s]`", e.e2.toChars());
5384 return false;
5385 }
5386
5387 if (auto se = e1.isSliceExp())
5388 {
5389 // Simplify index of slice: agg[lwr..upr][indx] --> agg[indx']
5390 uinteger_t index = e2.toInteger();
5391 uinteger_t ilwr = se.lwr.toInteger();
5392 uinteger_t iupr = se.upr.toInteger();
5393
5394 if (index > iupr - ilwr)
5395 {
5396 error(e.loc, "index %llu exceeds array length %llu", index, iupr - ilwr);
5397 return false;
5398 }
5399 *pagg = e1.isSliceExp().e1;
5400 *pidx = index + ilwr;
5401 }
5402 else
5403 {
5404 *pagg = e1;
5405 *pidx = e2.toInteger();
5406 if (len <= *pidx)
5407 {
5408 error(e.loc, "array index %lld is out of bounds `[0..%lld]`", *pidx, len);
5409 return false;
5410 }
5411 }
5412 return true;
5413 }
5414
5415 override void visit(IndexExp e)
5416 {
5417 debug (LOG)
5418 {
5419 printf("%s IndexExp::interpret() %s, goal = %d\n", e.loc.toChars(), e.toChars(), goal);
5420 }
5421 if (e.e1.type.toBasetype().ty == Tpointer)
5422 {
5423 Expression agg;
5424 uinteger_t indexToAccess;
5425 if (!resolveIndexing(e, istate, &agg, &indexToAccess, false))
5426 {
5427 result = CTFEExp.cantexp;
5428 return;
5429 }
5430 if (agg.op == EXP.arrayLiteral || agg.op == EXP.string_)
5431 {
5432 if (goal == CTFEGoal.LValue)
5433 {
5434 // if we need a reference, IndexExp shouldn't be interpreting
5435 // the expression to a value, it should stay as a reference
5436 emplaceExp!(IndexExp)(pue, e.loc, agg, ctfeEmplaceExp!IntegerExp(e.e2.loc, indexToAccess, e.e2.type));
5437 result = pue.exp();
5438 result.type = e.type;
5439 return;
5440 }
5441 result = ctfeIndex(pue, e.loc, e.type, agg, indexToAccess);
5442 return;
5443 }
5444 else
5445 {
5446 assert(indexToAccess == 0);
5447 result = interpretRegion(agg, istate, goal);
5448 if (exceptionOrCant(result))
5449 return;
5450 result = paintTypeOntoLiteral(pue, e.type, result);
5451 return;
5452 }
5453 }
5454
5455 if (e.e1.type.toBasetype().ty == Taarray)
5456 {
5457 Expression e1 = interpretRegion(e.e1, istate);
5458 if (exceptionOrCant(e1))
5459 return;
5460 if (e1.op == EXP.null_)
5461 {
5462 if (goal == CTFEGoal.LValue && e1.type.ty == Taarray && e.modifiable)
5463 {
5464 assert(0); // does not reach here?
5465 }
5466 error(e.loc, "cannot index null array `%s`", e.e1.toChars());
5467 result = CTFEExp.cantexp;
5468 return;
5469 }
5470 Expression e2 = interpretRegion(e.e2, istate);
5471 if (exceptionOrCant(e2))
5472 return;
5473
5474 if (goal == CTFEGoal.LValue)
5475 {
5476 // Pointer or reference of a scalar type
5477 if (e1 == e.e1 && e2 == e.e2)
5478 result = e;
5479 else
5480 {
5481 emplaceExp!(IndexExp)(pue, e.loc, e1, e2);
5482 result = pue.exp();
5483 result.type = e.type;
5484 }
5485 return;
5486 }
5487
5488 assert(e1.op == EXP.assocArrayLiteral);
5489 UnionExp e2tmp = void;
5490 e2 = resolveSlice(e2, &e2tmp);
5491 result = findKeyInAA(e.loc, e1.isAssocArrayLiteralExp(), e2);
5492 if (!result)
5493 {
5494 error(e.loc, "key `%s` not found in associative array `%s`", e2.toChars(), e.e1.toChars());
5495 result = CTFEExp.cantexp;
5496 }
5497 return;
5498 }
5499
5500 Expression agg;
5501 uinteger_t indexToAccess;
5502 if (!resolveIndexing(e, istate, &agg, &indexToAccess, false))
5503 {
5504 result = CTFEExp.cantexp;
5505 return;
5506 }
5507
5508 if (goal == CTFEGoal.LValue)
5509 {
5510 Expression e2 = ctfeEmplaceExp!IntegerExp(e.e2.loc, indexToAccess, Type.tsize_t);
5511 emplaceExp!(IndexExp)(pue, e.loc, agg, e2);
5512 result = pue.exp();
5513 result.type = e.type;
5514 return;
5515 }
5516
5517 result = ctfeIndex(pue, e.loc, e.type, agg, indexToAccess);
5518 if (exceptionOrCant(result))
5519 return;
5520 if (result.op == EXP.void_)
5521 {
5522 error(e.loc, "`%s` is used before initialized", e.toChars());
5523 errorSupplemental(result.loc, "originally uninitialized here");
5524 result = CTFEExp.cantexp;
5525 return;
5526 }
5527 if (result == pue.exp())
5528 result = result.copy();
5529 }
5530
5531 override void visit(SliceExp e)
5532 {
5533 debug (LOG)
5534 {
5535 printf("%s SliceExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5536 }
5537 if (e.e1.type.toBasetype().ty == Tpointer)
5538 {
5539 // Slicing a pointer. Note that there is no $ in this case.
5540 Expression e1 = interpretRegion(e.e1, istate);
5541 if (exceptionOrCant(e1))
5542 return;
5543 if (e1.op == EXP.int64)
5544 {
5545 error(e.loc, "cannot slice invalid pointer `%s` of value `%s`", e.e1.toChars(), e1.toChars());
5546 result = CTFEExp.cantexp;
5547 return;
5548 }
5549
5550 /* Evaluate lower and upper bounds of slice
5551 */
5552 Expression lwr = interpretRegion(e.lwr, istate);
5553 if (exceptionOrCant(lwr))
5554 return;
5555 Expression upr = interpretRegion(e.upr, istate);
5556 if (exceptionOrCant(upr))
5557 return;
5558 uinteger_t ilwr = lwr.toInteger();
5559 uinteger_t iupr = upr.toInteger();
5560
5561 dinteger_t ofs;
5562 Expression agg = getAggregateFromPointer(e1, &ofs);
5563 ilwr += ofs;
5564 iupr += ofs;
5565 if (agg.op == EXP.null_)
5566 {
5567 if (iupr == ilwr)
5568 {
5569 result = ctfeEmplaceExp!NullExp(e.loc);
5570 result.type = e.type;
5571 return;
5572 }
5573 error(e.loc, "cannot slice null pointer `%s`", e.e1.toChars());
5574 result = CTFEExp.cantexp;
5575 return;
5576 }
5577 if (agg.op == EXP.symbolOffset)
5578 {
5579 error(e.loc, "slicing pointers to static variables is not supported in CTFE");
5580 result = CTFEExp.cantexp;
5581 return;
5582 }
5583 if (agg.op != EXP.arrayLiteral && agg.op != EXP.string_)
5584 {
5585 error(e.loc, "pointer `%s` cannot be sliced at compile time (it does not point to an array)", e.e1.toChars());
5586 result = CTFEExp.cantexp;
5587 return;
5588 }
5589 assert(agg.op == EXP.arrayLiteral || agg.op == EXP.string_);
5590 dinteger_t len = ArrayLength(Type.tsize_t, agg).exp().toInteger();
5591 //Type *pointee = ((TypePointer *)agg.type)->next;
5592 if (sliceBoundsCheck(0, len, ilwr, iupr))
5593 {
5594 error(e.loc, "pointer slice `[%lld..%lld]` exceeds allocated memory block `[0..%lld]`", ilwr, iupr, len);
5595 result = CTFEExp.cantexp;
5596 return;
5597 }
5598 if (ofs != 0)
5599 {
5600 lwr = ctfeEmplaceExp!IntegerExp(e.loc, ilwr, lwr.type);
5601 upr = ctfeEmplaceExp!IntegerExp(e.loc, iupr, upr.type);
5602 }
5603 emplaceExp!(SliceExp)(pue, e.loc, agg, lwr, upr);
5604 result = pue.exp();
5605 result.type = e.type;
5606 return;
5607 }
5608
5609 CTFEGoal goal1 = CTFEGoal.RValue;
5610 if (goal == CTFEGoal.LValue)
5611 {
5612 if (e.e1.type.toBasetype().ty == Tsarray)
5613 if (auto ve = e.e1.isVarExp())
5614 if (auto vd = ve.var.isVarDeclaration())
5615 if (vd.storage_class & STC.ref_)
5616 goal1 = CTFEGoal.LValue;
5617 }
5618 Expression e1 = interpret(e.e1, istate, goal1);
5619 if (exceptionOrCant(e1))
5620 return;
5621
5622 if (!e.lwr)
5623 {
5624 result = paintTypeOntoLiteral(pue, e.type, e1);
5625 return;
5626 }
5627 if (auto ve = e1.isVectorExp())
5628 {
5629 e1 = interpretVectorToArray(pue, ve);
5630 e1 = (e1 == pue.exp()) ? pue.copy() : e1;
5631 }
5632
5633 /* Set dollar to the length of the array
5634 */
5635 uinteger_t dollar;
5636 if ((e1.op == EXP.variable || e1.op == EXP.dotVariable) && e1.type.toBasetype().ty == Tsarray)
5637 dollar = e1.type.toBasetype().isTypeSArray().dim.toInteger();
5638 else
5639 {
5640 if (e1.op != EXP.arrayLiteral && e1.op != EXP.string_ && e1.op != EXP.null_ && e1.op != EXP.slice && e1.op != EXP.vector)
5641 {
5642 error(e.loc, "cannot determine length of `%s` at compile time", e1.toChars());
5643 result = CTFEExp.cantexp;
5644 return;
5645 }
5646 dollar = resolveArrayLength(e1);
5647 }
5648
5649 /* Set the $ variable
5650 */
5651 if (e.lengthVar)
5652 {
5653 auto dollarExp = ctfeEmplaceExp!IntegerExp(e.loc, dollar, Type.tsize_t);
5654 ctfeGlobals.stack.push(e.lengthVar);
5655 setValue(e.lengthVar, dollarExp);
5656 }
5657
5658 /* Evaluate lower and upper bounds of slice
5659 */
5660 Expression lwr = interpretRegion(e.lwr, istate);
5661 if (exceptionOrCant(lwr))
5662 {
5663 if (e.lengthVar)
5664 ctfeGlobals.stack.pop(e.lengthVar);
5665 return;
5666 }
5667 Expression upr = interpretRegion(e.upr, istate);
5668 if (exceptionOrCant(upr))
5669 {
5670 if (e.lengthVar)
5671 ctfeGlobals.stack.pop(e.lengthVar);
5672 return;
5673 }
5674 if (e.lengthVar)
5675 ctfeGlobals.stack.pop(e.lengthVar); // $ is defined only inside [L..U]
5676
5677 uinteger_t ilwr = lwr.toInteger();
5678 uinteger_t iupr = upr.toInteger();
5679 if (e1.op == EXP.null_)
5680 {
5681 if (ilwr == 0 && iupr == 0)
5682 {
5683 result = e1;
5684 return;
5685 }
5686 error(e1.loc, "slice `[%llu..%llu]` is out of bounds", ilwr, iupr);
5687 result = CTFEExp.cantexp;
5688 return;
5689 }
5690 if (auto se = e1.isSliceExp())
5691 {
5692 // Simplify slice of slice:
5693 // aggregate[lo1..up1][lwr..upr] ---> aggregate[lwr'..upr']
5694 uinteger_t lo1 = se.lwr.toInteger();
5695 uinteger_t up1 = se.upr.toInteger();
5696 if (sliceBoundsCheck(0, up1 - lo1, ilwr, iupr))
5697 {
5698 error(e.loc, "slice `[%llu..%llu]` exceeds array bounds `[0..%llu]`", ilwr, iupr, up1 - lo1);
5699 result = CTFEExp.cantexp;
5700 return;
5701 }
5702 ilwr += lo1;
5703 iupr += lo1;
5704 emplaceExp!(SliceExp)(pue, e.loc, se.e1,
5705 ctfeEmplaceExp!IntegerExp(e.loc, ilwr, lwr.type),
5706 ctfeEmplaceExp!IntegerExp(e.loc, iupr, upr.type));
5707 result = pue.exp();
5708 result.type = e.type;
5709 return;
5710 }
5711 if (e1.op == EXP.arrayLiteral || e1.op == EXP.string_)
5712 {
5713 if (sliceBoundsCheck(0, dollar, ilwr, iupr))
5714 {
5715 error(e.loc, "slice `[%lld..%lld]` exceeds array bounds `[0..%lld]`", ilwr, iupr, dollar);
5716 result = CTFEExp.cantexp;
5717 return;
5718 }
5719 }
5720 emplaceExp!(SliceExp)(pue, e.loc, e1, lwr, upr);
5721 result = pue.exp();
5722 result.type = e.type;
5723 }
5724
5725 override void visit(InExp e)
5726 {
5727 debug (LOG)
5728 {
5729 printf("%s InExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5730 }
5731 Expression e1 = interpretRegion(e.e1, istate);
5732 if (exceptionOrCant(e1))
5733 return;
5734 Expression e2 = interpretRegion(e.e2, istate);
5735 if (exceptionOrCant(e2))
5736 return;
5737 if (e2.op == EXP.null_)
5738 {
5739 emplaceExp!(NullExp)(pue, e.loc, e.type);
5740 result = pue.exp();
5741 return;
5742 }
5743 if (e2.op != EXP.assocArrayLiteral)
5744 {
5745 error(e.loc, "`%s` cannot be interpreted at compile time", e.toChars());
5746 result = CTFEExp.cantexp;
5747 return;
5748 }
5749
5750 e1 = resolveSlice(e1);
5751 result = findKeyInAA(e.loc, e2.isAssocArrayLiteralExp(), e1);
5752 if (exceptionOrCant(result))
5753 return;
5754 if (!result)
5755 {
5756 emplaceExp!(NullExp)(pue, e.loc, e.type);
5757 result = pue.exp();
5758 }
5759 else
5760 {
5761 // Create a CTFE pointer &aa[index]
5762 result = ctfeEmplaceExp!IndexExp(e.loc, e2, e1);
5763 result.type = e.type.nextOf();
5764 emplaceExp!(AddrExp)(pue, e.loc, result, e.type);
5765 result = pue.exp();
5766 }
5767 }
5768
5769 override void visit(CatExp e)
5770 {
5771 debug (LOG)
5772 {
5773 printf("%s CatExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5774 }
5775
5776 UnionExp ue1 = void;
5777 Expression e1 = interpret(&ue1, e.e1, istate);
5778 if (exceptionOrCant(e1))
5779 return;
5780
5781 UnionExp ue2 = void;
5782 Expression e2 = interpret(&ue2, e.e2, istate);
5783 if (exceptionOrCant(e2))
5784 return;
5785
5786 UnionExp e1tmp = void;
5787 e1 = resolveSlice(e1, &e1tmp);
5788
5789 UnionExp e2tmp = void;
5790 e2 = resolveSlice(e2, &e2tmp);
5791
5792 /* e1 and e2 can't go on the stack because of x~[y] and [x]~y will
5793 * result in [x,y] and then x or y is on the stack.
5794 * But if they are both strings, we can, because it isn't the x~[y] case.
5795 */
5796 if (!(e1.op == EXP.string_ && e2.op == EXP.string_))
5797 {
5798 if (e1 == ue1.exp())
5799 e1 = ue1.copy();
5800 if (e2 == ue2.exp())
5801 e2 = ue2.copy();
5802 }
5803
5804 Expression prepareCatOperand(Expression exp)
5805 {
5806 /* Convert `elem ~ array` to `[elem] ~ array` if `elem` is itself an
5807 * array. This is needed because interpreting the `CatExp` calls
5808 * `Cat()`, which cannot handle concatenations between different
5809 * types, except for strings and chars.
5810 */
5811 auto tb = e.type.toBasetype();
5812 auto tbNext = tb.nextOf();
5813 auto expTb = exp.type.toBasetype();
5814
5815 if (exp.type.implicitConvTo(tbNext) >= MATCH.convert &&
5816 tb.isStaticOrDynamicArray() && expTb.isStaticOrDynamicArray())
5817 return new ArrayLiteralExp(exp.loc, e.type, exp);
5818 return exp;
5819 }
5820
5821 *pue = ctfeCat(e.loc, e.type, prepareCatOperand(e1), prepareCatOperand(e2));
5822 result = pue.exp();
5823
5824 if (CTFEExp.isCantExp(result))
5825 {
5826 error(e.loc, "`%s` cannot be interpreted at compile time", e.toChars());
5827 return;
5828 }
5829 // We know we still own it, because we interpreted both e1 and e2
5830 if (auto ale = result.isArrayLiteralExp())
5831 {
5832 ale.ownedByCtfe = OwnedBy.ctfe;
5833
5834 // https://issues.dlang.org/show_bug.cgi?id=14686
5835 foreach (elem; *ale.elements)
5836 {
5837 Expression ex = evaluatePostblit(istate, elem);
5838 if (exceptionOrCant(ex))
5839 return;
5840 }
5841 }
5842 else if (auto se = result.isStringExp())
5843 se.ownedByCtfe = OwnedBy.ctfe;
5844 }
5845
5846 override void visit(DeleteExp e)
5847 {
5848 debug (LOG)
5849 {
5850 printf("%s DeleteExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5851 }
5852 result = interpretRegion(e.e1, istate);
5853 if (exceptionOrCant(result))
5854 return;
5855
5856 if (result.op == EXP.null_)
5857 {
5858 result = CTFEExp.voidexp;
5859 return;
5860 }
5861
5862 auto tb = e.e1.type.toBasetype();
5863 switch (tb.ty)
5864 {
5865 case Tclass:
5866 if (result.op != EXP.classReference)
5867 {
5868 error(e.loc, "`delete` on invalid class reference `%s`", result.toChars());
5869 result = CTFEExp.cantexp;
5870 return;
5871 }
5872
5873 auto cre = result.isClassReferenceExp();
5874 auto cd = cre.originalClass();
5875
5876 // Find dtor(s) in inheritance chain
5877 do
5878 {
5879 if (cd.dtor)
5880 {
5881 result = interpretFunction(pue, cd.dtor, istate, null, cre);
5882 if (exceptionOrCant(result))
5883 return;
5884
5885 // Dtors of Non-extern(D) classes use implicit chaining (like structs)
5886 import dmd.aggregate : ClassKind;
5887 if (cd.classKind != ClassKind.d)
5888 break;
5889 }
5890
5891 // Emulate manual chaining as done in rt_finalize2
5892 cd = cd.baseClass;
5893
5894 } while (cd); // Stop after Object
5895
5896 break;
5897
5898 default:
5899 assert(0);
5900 }
5901 result = CTFEExp.voidexp;
5902 }
5903
5904 override void visit(CastExp e)
5905 {
5906 debug (LOG)
5907 {
5908 printf("%s CastExp::interpret() %s\n", e.loc.toChars(), e.toChars());
5909 }
5910 Expression e1 = interpretRegion(e.e1, istate, goal);
5911 if (exceptionOrCant(e1))
5912 return;
5913 // If the expression has been cast to void, do nothing.
5914 if (e.to.ty == Tvoid)
5915 {
5916 result = CTFEExp.voidexp;
5917 return;
5918 }
5919 if (e.to.ty == Tpointer && e1.op != EXP.null_)
5920 {
5921 Type pointee = (cast(TypePointer)e.type).next;
5922 // Implement special cases of normally-unsafe casts
5923 if (e1.op == EXP.int64)
5924 {
5925 // Happens with Windows HANDLEs, for example.
5926 result = paintTypeOntoLiteral(pue, e.to, e1);
5927 return;
5928 }
5929
5930 bool castToSarrayPointer = false;
5931 bool castBackFromVoid = false;
5932 if (e1.type.isStaticOrDynamicArray() || e1.type.ty == Tpointer)
5933 {
5934 // Check for unsupported type painting operations
5935 // For slices, we need the type being sliced,
5936 // since it may have already been type painted
5937 Type elemtype = e1.type.nextOf();
5938 if (auto se = e1.isSliceExp())
5939 elemtype = se.e1.type.nextOf();
5940
5941 // Allow casts from X* to void *, and X** to void** for any X.
5942 // But don't allow cast from X* to void**.
5943 // So, we strip all matching * from source and target to find X.
5944 // Allow casts to X* from void* only if the 'void' was originally an X;
5945 // we check this later on.
5946 Type ultimatePointee = pointee;
5947 Type ultimateSrc = elemtype;
5948 while (ultimatePointee.ty == Tpointer && ultimateSrc.ty == Tpointer)
5949 {
5950 ultimatePointee = ultimatePointee.nextOf();
5951 ultimateSrc = ultimateSrc.nextOf();
5952 }
5953 if (ultimatePointee.ty == Tsarray && ultimatePointee.nextOf().equivalent(ultimateSrc))
5954 {
5955 castToSarrayPointer = true;
5956 }
5957 else if (ultimatePointee.ty != Tvoid && ultimateSrc.ty != Tvoid && !isSafePointerCast(elemtype, pointee))
5958 {
5959 error(e.loc, "reinterpreting cast from `%s*` to `%s*` is not supported in CTFE", elemtype.toChars(), pointee.toChars());
5960 result = CTFEExp.cantexp;
5961 return;
5962 }
5963 if (ultimateSrc.ty == Tvoid)
5964 castBackFromVoid = true;
5965 }
5966
5967 if (auto se = e1.isSliceExp())
5968 {
5969 if (se.e1.op == EXP.null_)
5970 {
5971 result = paintTypeOntoLiteral(pue, e.type, se.e1);
5972 return;
5973 }
5974 // Create a CTFE pointer &aggregate[1..2]
5975 auto ei = ctfeEmplaceExp!IndexExp(e.loc, se.e1, se.lwr);
5976 ei.type = e.type.nextOf();
5977 emplaceExp!(AddrExp)(pue, e.loc, ei, e.type);
5978 result = pue.exp();
5979 return;
5980 }
5981 if (e1.op == EXP.arrayLiteral || e1.op == EXP.string_)
5982 {
5983 // Create a CTFE pointer &[1,2,3][0] or &"abc"[0]
5984 auto ei = ctfeEmplaceExp!IndexExp(e.loc, e1, ctfeEmplaceExp!IntegerExp(e.loc, 0, Type.tsize_t));
5985 ei.type = e.type.nextOf();
5986 emplaceExp!(AddrExp)(pue, e.loc, ei, e.type);
5987 result = pue.exp();
5988 return;
5989 }
5990 if (e1.op == EXP.index && !e1.isIndexExp().e1.type.equals(e1.type))
5991 {
5992 // type painting operation
5993 IndexExp ie = e1.isIndexExp();
5994 if (castBackFromVoid)
5995 {
5996 // get the original type. For strings, it's just the type...
5997 Type origType = ie.e1.type.nextOf();
5998 // ..but for arrays of type void*, it's the type of the element
5999 if (ie.e1.op == EXP.arrayLiteral && ie.e2.op == EXP.int64)
6000 {
6001 ArrayLiteralExp ale = ie.e1.isArrayLiteralExp();
6002 const indx = cast(size_t)ie.e2.toInteger();
6003 if (indx < ale.elements.length)
6004 {
6005 if (Expression xx = (*ale.elements)[indx])
6006 {
6007 if (auto iex = xx.isIndexExp())
6008 origType = iex.e1.type.nextOf();
6009 else if (auto ae = xx.isAddrExp())
6010 origType = ae.e1.type;
6011 else if (auto ve = xx.isVarExp())
6012 origType = ve.var.type;
6013 }
6014 }
6015 }
6016 if (!isSafePointerCast(origType, pointee))
6017 {
6018 error(e.loc, "using `void*` to reinterpret cast from `%s*` to `%s*` is not supported in CTFE", origType.toChars(), pointee.toChars());
6019 result = CTFEExp.cantexp;
6020 return;
6021 }
6022 }
6023 emplaceExp!(IndexExp)(pue, e1.loc, ie.e1, ie.e2);
6024 result = pue.exp();
6025 result.type = e.type;
6026 return;
6027 }
6028
6029 if (auto ae = e1.isAddrExp())
6030 {
6031 Type origType = ae.e1.type;
6032 if (isSafePointerCast(origType, pointee))
6033 {
6034 emplaceExp!(AddrExp)(pue, e.loc, ae.e1, e.type);
6035 result = pue.exp();
6036 return;
6037 }
6038
6039 if (castToSarrayPointer && pointee.toBasetype().ty == Tsarray && ae.e1.op == EXP.index)
6040 {
6041 // &val[idx]
6042 dinteger_t dim = (cast(TypeSArray)pointee.toBasetype()).dim.toInteger();
6043 IndexExp ie = ae.e1.isIndexExp();
6044 Expression lwr = ie.e2;
6045 Expression upr = ctfeEmplaceExp!IntegerExp(ie.e2.loc, ie.e2.toInteger() + dim, Type.tsize_t);
6046
6047 // Create a CTFE pointer &val[idx..idx+dim]
6048 auto er = ctfeEmplaceExp!SliceExp(e.loc, ie.e1, lwr, upr);
6049 er.type = pointee;
6050 emplaceExp!(AddrExp)(pue, e.loc, er, e.type);
6051 result = pue.exp();
6052 return;
6053 }
6054 }
6055
6056 if (e1.op == EXP.variable || e1.op == EXP.symbolOffset)
6057 {
6058 // type painting operation
6059 Type origType = (cast(SymbolExp)e1).var.type;
6060 if (castBackFromVoid && !isSafePointerCast(origType, pointee))
6061 {
6062 error(e.loc, "using `void*` to reinterpret cast from `%s*` to `%s*` is not supported in CTFE", origType.toChars(), pointee.toChars());
6063 result = CTFEExp.cantexp;
6064 return;
6065 }
6066 if (auto ve = e1.isVarExp())
6067 emplaceExp!(VarExp)(pue, e.loc, ve.var);
6068 else
6069 emplaceExp!(SymOffExp)(pue, e.loc, e1.isSymOffExp().var, e1.isSymOffExp().offset);
6070 result = pue.exp();
6071 result.type = e.to;
6072 return;
6073 }
6074
6075 // Check if we have a null pointer (eg, inside a struct)
6076 e1 = interpretRegion(e1, istate);
6077 if (e1.op != EXP.null_)
6078 {
6079 error(e.loc, "pointer cast from `%s` to `%s` is not supported at compile time", e1.type.toChars(), e.to.toChars());
6080 result = CTFEExp.cantexp;
6081 return;
6082 }
6083 }
6084 if (e.to.ty == Tsarray && e.e1.type.ty == Tvector)
6085 {
6086 // Special handling for: cast(float[4])__vector([w, x, y, z])
6087 e1 = interpretRegion(e.e1, istate);
6088 if (exceptionOrCant(e1))
6089 return;
6090 assert(e1.op == EXP.vector);
6091 e1 = interpretVectorToArray(pue, e1.isVectorExp());
6092 }
6093 if (e.to.ty == Tarray && e1.op == EXP.slice)
6094 {
6095 // Note that the slice may be void[], so when checking for dangerous
6096 // casts, we need to use the original type, which is se.e1.
6097 SliceExp se = e1.isSliceExp();
6098 if (!isSafePointerCast(se.e1.type.nextOf(), e.to.nextOf()))
6099 {
6100 error(e.loc, "array cast from `%s` to `%s` is not supported at compile time", se.e1.type.toChars(), e.to.toChars());
6101 result = CTFEExp.cantexp;
6102 return;
6103 }
6104 emplaceExp!(SliceExp)(pue, e1.loc, se.e1, se.lwr, se.upr);
6105 result = pue.exp();
6106 result.type = e.to;
6107 return;
6108 }
6109
6110 // Disallow array type painting, except for conversions between built-in
6111 // types of identical size.
6112 if (e.to.isStaticOrDynamicArray() && e1.type.isStaticOrDynamicArray() && !isSafePointerCast(e1.type.nextOf(), e.to.nextOf()))
6113 {
6114 auto se = e1.isStringExp();
6115 // Allow casting a hex string literal to short[], int[] or long[]
6116 if (se && se.hexString && se.postfix == StringExp.NoPostfix && e.to.nextOf().isIntegral)
6117 {
6118 const sz = cast(size_t) e.to.nextOf().size;
6119 if ((se.len % sz) != 0)
6120 {
6121 error(e.loc, "hex string length %d must be a multiple of %d to cast to `%s`",
6122 cast(int) se.len, cast(int) sz, e.to.toChars());
6123 result = CTFEExp.cantexp;
6124 return;
6125 }
6126
6127 auto str = arrayCastBigEndian(se.peekData(), sz);
6128 emplaceExp!(StringExp)(pue, e1.loc, str, se.len / sz, cast(ubyte) sz);
6129 result = pue.exp();
6130 result.type = e.to;
6131 return;
6132 }
6133 error(e.loc, "array cast from `%s` to `%s` is not supported at compile time", e1.type.toChars(), e.to.toChars());
6134 if (se && se.hexString && se.postfix != StringExp.NoPostfix)
6135 errorSupplemental(e.loc, "perhaps remove postfix `%.*s` from hex string", 1, &se.postfix);
6136
6137 result = CTFEExp.cantexp;
6138 return;
6139 }
6140 if (e.to.ty == Tsarray)
6141 e1 = resolveSlice(e1);
6142
6143 auto tobt = e.to.toBasetype();
6144 if (tobt.ty == Tbool && e1.type.ty == Tpointer)
6145 {
6146 emplaceExp!(IntegerExp)(pue, e.loc, e1.op != EXP.null_, e.to);
6147 result = pue.exp();
6148 return;
6149 }
6150 else if (tobt.isTypeBasic() && e1.op == EXP.null_)
6151 {
6152 if (tobt.isIntegral())
6153 emplaceExp!(IntegerExp)(pue, e.loc, 0, e.to);
6154 else if (tobt.isReal())
6155 emplaceExp!(RealExp)(pue, e.loc, CTFloat.zero, e.to);
6156 result = pue.exp();
6157 return;
6158 }
6159 result = ctfeCast(pue, e.loc, e.type, e.to, e1, true);
6160 }
6161
6162 override void visit(AssertExp e)
6163 {
6164 debug (LOG)
6165 {
6166 printf("%s AssertExp::interpret() %s\n", e.loc.toChars(), e.toChars());
6167 }
6168 Expression e1 = interpret(pue, e.e1, istate);
6169 if (exceptionOrCant(e1))
6170 return;
6171 if (isTrueBool(e1))
6172 {
6173 }
6174 else if (e1.toBool().hasValue(false))
6175 {
6176 if (e.msg)
6177 {
6178 UnionExp ue = void;
6179 result = interpret(&ue, e.msg, istate);
6180 if (exceptionOrCant(result))
6181 return;
6182 result = scrubReturnValue(e.loc, result);
6183 if (StringExp se = result.toStringExp())
6184 error(e.loc, "%s", se.toStringz().ptr);
6185 else
6186 error(e.loc, "%s", result.toChars());
6187 }
6188 else
6189 error(e.loc, "`%s` failed", e.toChars());
6190 result = CTFEExp.cantexp;
6191 return;
6192 }
6193 else
6194 {
6195 error(e.loc, "`%s` is not a compile time boolean expression", e1.toChars());
6196 result = CTFEExp.cantexp;
6197 return;
6198 }
6199 result = e1;
6200 return;
6201 }
6202
6203 override void visit(ThrowExp te)
6204 {
6205 debug (LOG)
6206 {
6207 printf("%s ThrowExpression::interpret()\n", te.loc.toChars());
6208 }
6209 interpretThrow(result, te.e1, te.loc, istate);
6210 }
6211
6212 override void visit(PtrExp e)
6213 {
6214 // Called for both lvalues and rvalues
6215 const lvalue = goal == CTFEGoal.LValue;
6216 debug (LOG)
6217 {
6218 printf("%s PtrExp::interpret(%d) %s, %s\n", e.loc.toChars(), lvalue, e.type.toChars(), e.toChars());
6219 }
6220
6221 // Check for int<->float and long<->double casts.
6222 if (auto soe1 = e.e1.isSymOffExp())
6223 if (soe1.offset == 0 && soe1.var.isVarDeclaration() && isFloatIntPaint(e.type, soe1.var.type))
6224 {
6225 // *(cast(int*)&v), where v is a float variable
6226 result = paintFloatInt(pue, getVarExp(e.loc, istate, soe1.var, CTFEGoal.RValue), e.type);
6227 return;
6228 }
6229
6230 if (auto ce1 = e.e1.isCastExp())
6231 if (auto ae11 = ce1.e1.isAddrExp())
6232 {
6233 // *(cast(int*)&x), where x is a float expression
6234 Expression x = ae11.e1;
6235 if (isFloatIntPaint(e.type, x.type))
6236 {
6237 result = paintFloatInt(pue, interpretRegion(x, istate), e.type);
6238 return;
6239 }
6240 }
6241
6242 // Constant fold *(&structliteral + offset)
6243 if (auto ae = e.e1.isAddExp())
6244 {
6245 if (ae.e1.op == EXP.address && ae.e2.op == EXP.int64)
6246 {
6247 AddrExp ade = ae.e1.isAddrExp();
6248 Expression ex = interpretRegion(ade.e1, istate);
6249 if (exceptionOrCant(ex))
6250 return;
6251 if (auto se = ex.isStructLiteralExp())
6252 {
6253 dinteger_t offset = ae.e2.toInteger();
6254 result = se.getField(e.type, cast(uint)offset);
6255 if (result)
6256 return;
6257 }
6258 }
6259 }
6260
6261 // It's possible we have an array bounds error. We need to make sure it
6262 // errors with this line number, not the one where the pointer was set.
6263 result = interpretRegion(e.e1, istate);
6264 if (exceptionOrCant(result))
6265 return;
6266
6267 if (result.op == EXP.function_)
6268 return;
6269 if (auto soe = result.isSymOffExp())
6270 {
6271 if (soe.offset == 0 && soe.var.isFuncDeclaration())
6272 return;
6273 if (soe.offset == 0 && soe.var.isVarDeclaration() && soe.var.isImmutable())
6274 {
6275 result = getVarExp(e.loc, istate, soe.var, CTFEGoal.RValue);
6276 return;
6277 }
6278 error(e.loc, "cannot dereference pointer to static variable `%s` at compile time", soe.var.toChars());
6279 result = CTFEExp.cantexp;
6280 return;
6281 }
6282
6283 if (!lvalue && result.isArrayLiteralExp() &&
6284 result.type.isTypePointer())
6285 {
6286 /* A pointer variable can point to an array literal like `[3]`.
6287 * Dereferencing it means accessing the first element value.
6288 * Dereference it only if result should be an rvalue
6289 */
6290 auto ae = result.isArrayLiteralExp();
6291 if (ae.elements.length == 1)
6292 {
6293 result = (*ae.elements)[0];
6294 return;
6295 }
6296 }
6297 if (result.isStringExp() || result.isArrayLiteralExp())
6298 return;
6299
6300 if (result.op != EXP.address)
6301 {
6302 if (result.op == EXP.null_)
6303 error(e.loc, "dereference of null pointer `%s`", e.e1.toChars());
6304 else
6305 error(e.loc, "dereference of invalid pointer `%s`", result.toChars());
6306 result = CTFEExp.cantexp;
6307 return;
6308 }
6309
6310 // *(&x) ==> x
6311 result = result.isAddrExp().e1;
6312
6313 if (result.op == EXP.slice && e.type.toBasetype().ty == Tsarray)
6314 {
6315 /* aggr[lwr..upr]
6316 * upr may exceed the upper boundary of aggr, but the check is deferred
6317 * until those out-of-bounds elements will be touched.
6318 */
6319 return;
6320 }
6321 result = interpret(pue, result, istate, goal);
6322 if (exceptionOrCant(result))
6323 return;
6324
6325 debug (LOG)
6326 {
6327 if (CTFEExp.isCantExp(result))
6328 printf("PtrExp::interpret() %s = CTFEExp::cantexp\n", e.toChars());
6329 }
6330 }
6331
6332 override void visit(DotVarExp e)
6333 {
6334 void notImplementedYet()
6335 {
6336 error(e.loc, "`%s.%s` is not yet implemented at compile time", e.e1.toChars(), e.var.toChars());
6337 result = CTFEExp.cantexp;
6338 return;
6339 }
6340
6341 debug (LOG)
6342 {
6343 printf("%s DotVarExp::interpret() %s, goal = %d\n", e.loc.toChars(), e.toChars(), goal);
6344 }
6345 Expression ex = interpretRegion(e.e1, istate);
6346 if (exceptionOrCant(ex))
6347 return;
6348
6349 if (FuncDeclaration f = e.var.isFuncDeclaration())
6350 {
6351 if (ex == e.e1)
6352 result = e; // optimize: reuse this CTFE reference
6353 else
6354 {
6355 emplaceExp!(DotVarExp)(pue, e.loc, ex, f, false);
6356 result = pue.exp();
6357 result.type = e.type;
6358 }
6359 return;
6360 }
6361
6362 VarDeclaration v = e.var.isVarDeclaration();
6363 if (!v)
6364 {
6365 error(e.loc, "CTFE internal error: `%s`", e.toChars());
6366 result = CTFEExp.cantexp;
6367 return;
6368 }
6369
6370 if (ex.op == EXP.null_)
6371 {
6372 if (ex.type.toBasetype().ty == Tclass)
6373 error(e.loc, "class `%s` is `null` and cannot be dereferenced", e.e1.toChars());
6374 else
6375 error(e.loc, "CTFE internal error: null this `%s`", e.e1.toChars());
6376 result = CTFEExp.cantexp;
6377 return;
6378 }
6379
6380 StructLiteralExp se;
6381 int i;
6382
6383 if (ex.op != EXP.structLiteral && ex.op != EXP.classReference && ex.op != EXP.typeid_)
6384 {
6385 return notImplementedYet();
6386 }
6387
6388 // We can't use getField, because it makes a copy
6389 if (ex.op == EXP.classReference)
6390 {
6391 se = ex.isClassReferenceExp().value;
6392 i = ex.isClassReferenceExp().findFieldIndexByName(v);
6393 }
6394 else if (ex.op == EXP.typeid_)
6395 {
6396 if (v.ident == Identifier.idPool("name"))
6397 {
6398 if (auto t = isType(ex.isTypeidExp().obj))
6399 {
6400 import dmd.typesem : toDsymbol;
6401 auto sym = t.toDsymbol(null);
6402 if (auto ident = (sym ? sym.ident : null))
6403 {
6404 result = new StringExp(e.loc, ident.toString());
6405 result.expressionSemantic(null);
6406 return ;
6407 }
6408 }
6409 }
6410 return notImplementedYet();
6411 }
6412 else
6413 {
6414 se = ex.isStructLiteralExp();
6415 i = findFieldIndexByName(se.sd, v);
6416 }
6417 if (i == -1)
6418 {
6419 error(e.loc, "couldn't find field `%s` of type `%s` in `%s`", v.toChars(), e.type.toChars(), se.toChars());
6420 result = CTFEExp.cantexp;
6421 return;
6422 }
6423
6424 // https://issues.dlang.org/show_bug.cgi?id=19897
6425 // https://issues.dlang.org/show_bug.cgi?id=20710
6426 // Zero-elements fields don't have an initializer. See: scrubArray function
6427 if ((*se.elements)[i] is null)
6428 (*se.elements)[i] = voidInitLiteral(e.type, v).copy();
6429
6430 if (goal == CTFEGoal.LValue)
6431 {
6432 // just return the (simplified) dotvar expression as a CTFE reference
6433 if (e.e1 == ex)
6434 result = e;
6435 else
6436 {
6437 emplaceExp!(DotVarExp)(pue, e.loc, ex, v);
6438 result = pue.exp();
6439 result.type = e.type;
6440 }
6441 return;
6442 }
6443
6444 result = (*se.elements)[i];
6445 if (!result)
6446 {
6447 error(e.loc, "internal compiler error: null field `%s`", v.toChars());
6448 result = CTFEExp.cantexp;
6449 return;
6450 }
6451 if (auto vie = result.isVoidInitExp())
6452 {
6453 const s = vie.var.toChars();
6454 if (v.overlapped)
6455 {
6456 error(e.loc, "reinterpretation through overlapped field `%s` is not allowed in CTFE", s);
6457 result = CTFEExp.cantexp;
6458 return;
6459 }
6460 error(e.loc, "cannot read uninitialized variable `%s` in CTFE", s);
6461 result = CTFEExp.cantexp;
6462 return;
6463 }
6464
6465 if (v.type.ty != result.type.ty && v.type.ty == Tsarray)
6466 {
6467 // Block assignment from inside struct literals
6468 auto tsa = cast(TypeSArray)v.type;
6469 auto len = cast(size_t)tsa.dim.toInteger();
6470 UnionExp ue = void;
6471 result = createBlockDuplicatedArrayLiteral(&ue, e.loc, v.type, result, len);
6472 if (result == ue.exp())
6473 result = ue.copy();
6474 (*se.elements)[i] = result;
6475 }
6476 debug (LOG)
6477 {
6478 if (CTFEExp.isCantExp(result))
6479 printf("DotVarExp::interpret() %s = CTFEExp::cantexp\n", e.toChars());
6480 }
6481 }
6482
6483 override void visit(RemoveExp e)
6484 {
6485 debug (LOG)
6486 {
6487 printf("%s RemoveExp::interpret() %s\n", e.loc.toChars(), e.toChars());
6488 }
6489 Expression agg = interpret(e.e1, istate);
6490 if (exceptionOrCant(agg))
6491 return;
6492 Expression index = interpret(e.e2, istate);
6493 if (exceptionOrCant(index))
6494 return;
6495 if (agg.op == EXP.null_)
6496 {
6497 result = CTFEExp.voidexp;
6498 return;
6499 }
6500
6501 AssocArrayLiteralExp aae = agg.isAssocArrayLiteralExp();
6502 Expressions* keysx = aae.keys;
6503 Expressions* valuesx = aae.values;
6504 size_t removed = 0;
6505 foreach (j, evalue; *valuesx)
6506 {
6507 Expression ekey = (*keysx)[j];
6508 int eq = ctfeEqual(e.loc, EXP.equal, ekey, index);
6509 if (eq)
6510 ++removed;
6511 else if (removed != 0)
6512 {
6513 (*keysx)[j - removed] = ekey;
6514 (*valuesx)[j - removed] = evalue;
6515 }
6516 }
6517 valuesx.length = valuesx.length - removed;
6518 keysx.length = keysx.length - removed;
6519 result = IntegerExp.createBool(removed != 0);
6520 }
6521
6522 override void visit(ClassReferenceExp e)
6523 {
6524 //printf("ClassReferenceExp::interpret() %s\n", e.value.toChars());
6525 result = e;
6526 }
6527
6528 override void visit(VoidInitExp e)
6529 {
6530 error(e.loc, "CTFE internal error: trying to read uninitialized variable");
6531 assert(0);
6532 }
6533
6534 override void visit(ThrownExceptionExp e)
6535 {
6536 assert(0); // This should never be interpreted
6537 }
6538 }
6539
6540 /// Interpret `throw <exp>` found at the specified location `loc`
6541 private
6542 void interpretThrow(ref Expression result, Expression exp, Loc loc, InterState* istate)
6543 {
6544 incUsageCtfe(istate, loc);
6545
6546 Expression e = interpretRegion(exp, istate);
6547 if (exceptionOrCantInterpret(e))
6548 {
6549 // Make sure e is not pointing to a stack temporary
6550 result = (e.op == EXP.cantExpression) ? CTFEExp.cantexp : e;
6551 }
6552 else if (e.op == EXP.classReference)
6553 {
6554 result = ctfeEmplaceExp!ThrownExceptionExp(loc, e.isClassReferenceExp());
6555 }
6556 else
6557 {
6558 error(exp.loc, "to be thrown `%s` must be non-null", exp.toChars());
6559 result = ErrorExp.get();
6560 }
6561 }
6562
6563 /*********************************************
6564 * Checks if the given expresion is a call to the runtime hook `id`.
6565 *
6566 * Params:
6567 * e = the expression to check
6568 * id = the identifier of the runtime hook
6569 * Returns:
6570 * `e` cast to `CallExp` if it's the hook, `null` otherwise
6571 */
6572 public CallExp isRuntimeHook(Expression e, Identifier id)
6573 {
6574 if (auto ce = e.isCallExp())
6575 {
6576 if (auto ve = ce.e1.isVarExp())
6577 {
6578 if (auto fd = ve.var.isFuncDeclaration())
6579 {
6580 // If `_d_HookTraceImpl` is found, resolve the underlying hook
6581 // and replace `e` and `fd` with it.
6582 removeHookTraceImpl(ce, fd);
6583 return fd.ident == id ? ce : null;
6584 }
6585 }
6586 }
6587
6588 return null;
6589 }
6590
6591 /********************************************
6592 * Interpret the expression.
6593 * Params:
6594 * pue = non-null pointer to temporary storage that can be used to store the return value
6595 * e = Expression to interpret
6596 * istate = context
6597 * goal = what the result will be used for
6598 * Returns:
6599 * resulting expression
6600 */
6601
6602 Expression interpret(UnionExp* pue, Expression e, InterState* istate, CTFEGoal goal = CTFEGoal.RValue)
6603 {
6604 if (!e)
6605 return null;
6606 //printf("+interpret() e : %s, %s\n", e.type.toChars(), e.toChars());
6607 scope Interpreter v = new Interpreter(pue, istate, goal);
6608 e.accept(v);
6609 Expression ex = v.result;
6610 assert(goal == CTFEGoal.Nothing || ex !is null);
6611 //if (ex) printf("-interpret() ex: %s, %s\n", ex.type.toChars(), ex.toChars()); else printf("-interpret()\n");
6612 return ex;
6613 }
6614
6615 ///
6616 Expression interpret(Expression e, InterState* istate, CTFEGoal goal = CTFEGoal.RValue)
6617 {
6618 UnionExp ue = void;
6619 auto result = interpret(&ue, e, istate, goal);
6620 if (result == ue.exp())
6621 result = ue.copy();
6622 return result;
6623 }
6624
6625 /*****************************
6626 * Same as interpret(), but return result allocated in Region.
6627 * Params:
6628 * e = Expression to interpret
6629 * istate = context
6630 * goal = what the result will be used for
6631 * Returns:
6632 * resulting expression
6633 */
6634 Expression interpretRegion(Expression e, InterState* istate, CTFEGoal goal = CTFEGoal.RValue)
6635 {
6636 UnionExp ue = void;
6637 auto result = interpret(&ue, e, istate, goal);
6638 auto uexp = ue.exp();
6639 if (result != uexp)
6640 return result;
6641 if (mem.isGCEnabled)
6642 return ue.copy();
6643
6644 // mimicking UnionExp.copy, but with region allocation
6645 switch (uexp.op)
6646 {
6647 case EXP.cantExpression: return CTFEExp.cantexp;
6648 case EXP.voidExpression: return CTFEExp.voidexp;
6649 case EXP.break_: return CTFEExp.breakexp;
6650 case EXP.continue_: return CTFEExp.continueexp;
6651 case EXP.goto_: return CTFEExp.gotoexp;
6652 default: break;
6653 }
6654 auto p = ctfeGlobals.region.malloc(uexp.size);
6655 return cast(Expression)memcpy(p, cast(void*)uexp, uexp.size);
6656 }
6657
6658 private
6659 Expressions* copyArrayOnWrite(Expressions* exps, Expressions* original)
6660 {
6661 if (exps is original)
6662 {
6663 if (!original)
6664 exps = new Expressions();
6665 else
6666 exps = original.copy();
6667 ++ctfeGlobals.numArrayAllocs;
6668 }
6669 return exps;
6670 }
6671
6672 /**
6673 Given an expression e which is about to be returned from the current
6674 function, generate an error if it contains pointers to local variables.
6675
6676 Only checks expressions passed by value (pointers to local variables
6677 may already be stored in members of classes, arrays, or AAs which
6678 were passed as mutable function parameters).
6679 Returns:
6680 true if it is safe to return, false if an error was generated.
6681 */
6682 private
6683 bool stopPointersEscaping(Loc loc, Expression e)
6684 {
6685 import dmd.typesem : hasPointers;
6686 if (!e.type.hasPointers())
6687 return true;
6688 if (isPointer(e.type))
6689 {
6690 Expression x = e;
6691 if (auto eaddr = e.isAddrExp())
6692 x = eaddr.e1;
6693 VarDeclaration v;
6694 while (x.op == EXP.variable && (v = x.isVarExp().var.isVarDeclaration()) !is null)
6695 {
6696 if (v.storage_class & STC.ref_)
6697 {
6698 x = getValue(v);
6699 if (auto eaddr = e.isAddrExp())
6700 eaddr.e1 = x;
6701 continue;
6702 }
6703 if (ctfeGlobals.stack.isInCurrentFrame(v))
6704 {
6705 error(loc, "returning a pointer to a local stack variable");
6706 return false;
6707 }
6708 else
6709 break;
6710 }
6711 // TODO: If it is a EXP.dotVariable or EXP.index, we should check that it is not
6712 // pointing to a local struct or static array.
6713 }
6714 if (auto se = e.isStructLiteralExp())
6715 {
6716 return stopPointersEscapingFromArray(loc, se.elements);
6717 }
6718 if (auto ale = e.isArrayLiteralExp())
6719 {
6720 return stopPointersEscapingFromArray(loc, ale.elements);
6721 }
6722 if (auto aae = e.isAssocArrayLiteralExp())
6723 {
6724 if (!stopPointersEscapingFromArray(loc, aae.keys))
6725 return false;
6726 return stopPointersEscapingFromArray(loc, aae.values);
6727 }
6728 return true;
6729 }
6730
6731 // Check all elements of an array for escaping local variables. Return false if error
6732 private
6733 bool stopPointersEscapingFromArray(Loc loc, Expressions* elems)
6734 {
6735 foreach (e; *elems)
6736 {
6737 if (e && !stopPointersEscaping(loc, e))
6738 return false;
6739 }
6740 return true;
6741 }
6742
6743 private
6744 Statement findGotoTarget(InterState* istate, Identifier ident)
6745 {
6746 Statement target = null;
6747 if (ident)
6748 {
6749 LabelDsymbol label = istate.fd.searchLabel(ident, Loc.initial);
6750 assert(label && label.statement);
6751 LabelStatement ls = label.statement;
6752 target = ls.gotoTarget ? ls.gotoTarget : ls.statement;
6753 }
6754 return target;
6755 }
6756
6757 private
6758 ThrownExceptionExp chainExceptions(ThrownExceptionExp oldest, ThrownExceptionExp newest)
6759 {
6760 debug (LOG)
6761 {
6762 printf("Collided exceptions %s %s\n", oldest.thrown.toChars(), newest.thrown.toChars());
6763 }
6764 // Little sanity check to make sure it's really a Throwable
6765 ClassReferenceExp boss = oldest.thrown;
6766 const next = 5; // index of Throwable.next
6767 assert((*boss.value.elements)[next].type.ty == Tclass); // Throwable.next
6768 ClassReferenceExp collateral = newest.thrown;
6769 if (collateral.originalClass().isErrorException() && !boss.originalClass().isErrorException())
6770 {
6771 /* Find the index of the Error.bypassException field
6772 */
6773 auto bypass = next + 1;
6774 if ((*collateral.value.elements)[bypass].type.ty == Tuns32)
6775 bypass += 1; // skip over _refcount field
6776 assert((*collateral.value.elements)[bypass].type.ty == Tclass);
6777
6778 // The new exception bypass the existing chain
6779 (*collateral.value.elements)[bypass] = boss;
6780 return newest;
6781 }
6782 while ((*boss.value.elements)[next].op == EXP.classReference)
6783 {
6784 boss = (*boss.value.elements)[next].isClassReferenceExp();
6785 }
6786 (*boss.value.elements)[next] = collateral;
6787 return oldest;
6788 }
6789
6790 /**
6791 * All results destined for use outside of CTFE need to have their CTFE-specific
6792 * features removed.
6793 * In particular,
6794 * 1. all slices must be resolved.
6795 * 2. all .ownedByCtfe set to OwnedBy.code
6796 */
6797 private Expression scrubReturnValue(Loc loc, Expression e)
6798 {
6799 /* Returns: true if e is void,
6800 * or is an array literal or struct literal of void elements.
6801 */
6802 static bool isVoid(const Expression e, bool checkArrayType = false) pure
6803 {
6804 if (e.op == EXP.void_)
6805 return true;
6806
6807 static bool isEntirelyVoid(const Expressions* elems)
6808 {
6809 foreach (e; *elems)
6810 {
6811 // It can be NULL for performance reasons,
6812 // see StructLiteralExp::interpret().
6813 if (e && !isVoid(e))
6814 return false;
6815 }
6816 return true;
6817 }
6818
6819 if (auto sle = e.isStructLiteralExp())
6820 return isEntirelyVoid(sle.elements);
6821
6822 if (checkArrayType && e.type.ty != Tsarray)
6823 return false;
6824
6825 if (auto ale = e.isArrayLiteralExp())
6826 return isEntirelyVoid(ale.elements);
6827
6828 return false;
6829 }
6830
6831
6832 /* Scrub all elements of elems[].
6833 * Returns: null for success, error Expression for failure
6834 */
6835 Expression scrubArray(Expressions* elems, bool structlit = false)
6836 {
6837 foreach (ref e; *elems)
6838 {
6839 // It can be NULL for performance reasons,
6840 // see StructLiteralExp::interpret().
6841 if (!e)
6842 continue;
6843
6844 // A struct .init may contain void members.
6845 // Static array members are a weird special case https://issues.dlang.org/show_bug.cgi?id=10994
6846 if (structlit && isVoid(e, true))
6847 {
6848 e = null;
6849 }
6850 else
6851 {
6852 e = scrubReturnValue(loc, e);
6853 if (CTFEExp.isCantExp(e) || e.op == EXP.error)
6854 return e;
6855 }
6856 }
6857 return null;
6858 }
6859
6860 Expression scrubSE(StructLiteralExp sle)
6861 {
6862 sle.ownedByCtfe = OwnedBy.code;
6863 if (!(sle.stageflags & StructLiteralExp.StageFlags.scrub))
6864 {
6865 const old = sle.stageflags;
6866 sle.stageflags |= StructLiteralExp.StageFlags.scrub; // prevent infinite recursion
6867 if (auto ex = scrubArray(sle.elements, true))
6868 return ex;
6869 sle.stageflags = old;
6870 }
6871 return null;
6872 }
6873
6874 if (e.op == EXP.classReference)
6875 {
6876 StructLiteralExp sle = e.isClassReferenceExp().value;
6877 if (auto ex = scrubSE(sle))
6878 return ex;
6879 }
6880 else if (auto vie = e.isVoidInitExp())
6881 {
6882 error(loc, "uninitialized variable `%s` cannot be returned from CTFE", vie.var.toChars());
6883 return ErrorExp.get();
6884 }
6885
6886 e = resolveSlice(e);
6887
6888 if (auto sle = e.isStructLiteralExp())
6889 {
6890 if (auto ex = scrubSE(sle))
6891 return ex;
6892 }
6893 else if (auto se = e.isStringExp())
6894 {
6895 se.ownedByCtfe = OwnedBy.code;
6896 }
6897 else if (auto ale = e.isArrayLiteralExp())
6898 {
6899 ale.ownedByCtfe = OwnedBy.code;
6900 if (auto ex = scrubArray(ale.elements))
6901 return ex;
6902 }
6903 else if (auto aae = e.isAssocArrayLiteralExp())
6904 {
6905 aae.ownedByCtfe = OwnedBy.code;
6906 if (auto ex = scrubArray(aae.keys))
6907 return ex;
6908 if (auto ex = scrubArray(aae.values))
6909 return ex;
6910 aae.type = toBuiltinAAType(aae.type);
6911 }
6912 else if (auto ve = e.isVectorExp())
6913 {
6914 ve.ownedByCtfe = OwnedBy.code;
6915 if (auto ale = ve.e1.isArrayLiteralExp())
6916 {
6917 ale.ownedByCtfe = OwnedBy.code;
6918 if (auto ex = scrubArray(ale.elements))
6919 return ex;
6920 }
6921 }
6922 return e;
6923 }
6924
6925 /**************************************
6926 * Transitively set all .ownedByCtfe to OwnedBy.cache
6927 */
6928 private Expression scrubCacheValue(Expression e)
6929 {
6930 if (!e)
6931 return e;
6932
6933 Expression scrubArrayCache(Expressions* elems)
6934 {
6935 foreach (ref e; *elems)
6936 e = scrubCacheValue(e);
6937 return null;
6938 }
6939
6940 Expression scrubSE(StructLiteralExp sle)
6941 {
6942 sle.ownedByCtfe = OwnedBy.cache;
6943 if (!(sle.stageflags & StructLiteralExp.StageFlags.scrub))
6944 {
6945 const old = sle.stageflags;
6946 sle.stageflags |= StructLiteralExp.StageFlags.scrub; // prevent infinite recursion
6947 if (auto ex = scrubArrayCache(sle.elements))
6948 return ex;
6949 sle.stageflags = old;
6950 }
6951 return null;
6952 }
6953
6954 if (e.op == EXP.classReference)
6955 {
6956 if (auto ex = scrubSE(e.isClassReferenceExp().value))
6957 return ex;
6958 }
6959 else if (auto sle = e.isStructLiteralExp())
6960 {
6961 if (auto ex = scrubSE(sle))
6962 return ex;
6963 }
6964 else if (auto se = e.isStringExp())
6965 {
6966 se.ownedByCtfe = OwnedBy.cache;
6967 }
6968 else if (auto ale = e.isArrayLiteralExp())
6969 {
6970 ale.ownedByCtfe = OwnedBy.cache;
6971 if (Expression ex = scrubArrayCache(ale.elements))
6972 return ex;
6973 }
6974 else if (auto aae = e.isAssocArrayLiteralExp())
6975 {
6976 aae.ownedByCtfe = OwnedBy.cache;
6977 if (auto ex = scrubArrayCache(aae.keys))
6978 return ex;
6979 if (auto ex = scrubArrayCache(aae.values))
6980 return ex;
6981 }
6982 else if (auto ve = e.isVectorExp())
6983 {
6984 ve.ownedByCtfe = OwnedBy.cache;
6985 if (auto ale = ve.e1.isArrayLiteralExp())
6986 {
6987 ale.ownedByCtfe = OwnedBy.cache;
6988 if (auto ex = scrubArrayCache(ale.elements))
6989 return ex;
6990 }
6991 }
6992 return e;
6993 }
6994
6995 /********************************************
6996 * Transitively replace all Expressions allocated in ctfeGlobals.region
6997 * with Mem owned copies.
6998 * Params:
6999 * e = possible ctfeGlobals.region owned expression
7000 * Returns:
7001 * Mem owned expression
7002 */
7003 private Expression copyRegionExp(Expression e)
7004 {
7005 if (!e)
7006 return e;
7007
7008 static void copyArray(Expressions* elems)
7009 {
7010 foreach (ref e; *elems)
7011 {
7012 auto ex = e;
7013 e = null;
7014 e = copyRegionExp(ex);
7015 }
7016 }
7017
7018 static void copySE(StructLiteralExp sle)
7019 {
7020 if (1 || !(sle.stageflags & StructLiteralExp.StageFlags.scrub))
7021 {
7022 const old = sle.stageflags;
7023 sle.stageflags |= StructLiteralExp.StageFlags.scrub; // prevent infinite recursion
7024 copyArray(sle.elements);
7025 sle.stageflags = old;
7026 }
7027 }
7028
7029 switch (e.op)
7030 {
7031 case EXP.classReference:
7032 {
7033 auto cre = e.isClassReferenceExp();
7034 cre.value = copyRegionExp(cre.value).isStructLiteralExp();
7035 break;
7036 }
7037
7038 case EXP.structLiteral:
7039 {
7040 auto sle = e.isStructLiteralExp();
7041
7042 /* The following is to take care of updating sle.origin correctly,
7043 * which may have multiple objects pointing to it.
7044 */
7045 if (sle.isOriginal && !ctfeGlobals.region.contains(cast(void*)sle.origin))
7046 {
7047 /* This means sle has already been moved out of the region,
7048 * and sle.origin is the new location.
7049 */
7050 return sle.origin;
7051 }
7052 copySE(sle);
7053 sle.isOriginal = sle is sle.origin;
7054
7055 auto slec = ctfeGlobals.region.contains(cast(void*)e)
7056 ? e.copy().isStructLiteralExp() // move sle out of region to slec
7057 : sle;
7058
7059 if (ctfeGlobals.region.contains(cast(void*)sle.origin))
7060 {
7061 auto sleo = sle.origin == sle ? slec : sle.origin.copy().isStructLiteralExp();
7062 sle.origin = sleo;
7063 slec.origin = sleo;
7064 }
7065 return slec;
7066 }
7067
7068 case EXP.arrayLiteral:
7069 {
7070 auto ale = e.isArrayLiteralExp();
7071 ale.basis = copyRegionExp(ale.basis);
7072 copyArray(ale.elements);
7073 break;
7074 }
7075
7076 case EXP.assocArrayLiteral:
7077 copyArray(e.isAssocArrayLiteralExp().keys);
7078 copyArray(e.isAssocArrayLiteralExp().values);
7079 break;
7080
7081 case EXP.slice:
7082 {
7083 auto se = e.isSliceExp();
7084 se.e1 = copyRegionExp(se.e1);
7085 se.upr = copyRegionExp(se.upr);
7086 se.lwr = copyRegionExp(se.lwr);
7087 break;
7088 }
7089
7090 case EXP.tuple:
7091 {
7092 auto te = e.isTupleExp();
7093 te.e0 = copyRegionExp(te.e0);
7094 copyArray(te.exps);
7095 break;
7096 }
7097
7098 case EXP.address:
7099 case EXP.delegate_:
7100 case EXP.vector:
7101 case EXP.dotVariable:
7102 {
7103 UnaExp ue = e.isUnaExp();
7104 ue.e1 = copyRegionExp(ue.e1);
7105 break;
7106 }
7107
7108 case EXP.index:
7109 {
7110 BinExp be = e.isBinExp();
7111 be.e1 = copyRegionExp(be.e1);
7112 be.e2 = copyRegionExp(be.e2);
7113 break;
7114 }
7115
7116 case EXP.this_:
7117 case EXP.super_:
7118 case EXP.variable:
7119 case EXP.type:
7120 case EXP.function_:
7121 case EXP.typeid_:
7122 case EXP.string_:
7123 case EXP.int64:
7124 case EXP.error:
7125 case EXP.float64:
7126 case EXP.complex80:
7127 case EXP.null_:
7128 case EXP.void_:
7129 case EXP.symbolOffset:
7130 break;
7131
7132 case EXP.cantExpression:
7133 case EXP.voidExpression:
7134 case EXP.showCtfeContext:
7135 return e;
7136
7137 default:
7138 printf("e: %s, %s\n", EXPtoString(e.op).ptr, e.toChars());
7139 assert(0);
7140 }
7141
7142 if (ctfeGlobals.region.contains(cast(void*)e))
7143 {
7144 return e.copy();
7145 }
7146 return e;
7147 }
7148
7149 /******************************* Special Functions ***************************/
7150
7151 private Expression interpret_length(UnionExp* pue, InterState* istate, Expression earg)
7152 {
7153 //printf("interpret_length()\n");
7154 earg = interpret(pue, earg, istate);
7155 if (exceptionOrCantInterpret(earg))
7156 return earg;
7157 dinteger_t len = 0;
7158 if (auto aae = earg.isAssocArrayLiteralExp())
7159 len = aae.keys.length;
7160 else
7161 assert(earg.op == EXP.null_);
7162 emplaceExp!(IntegerExp)(pue, earg.loc, len, Type.tsize_t);
7163 return pue.exp();
7164 }
7165
7166 private Expression interpret_keys(UnionExp* pue, InterState* istate, Expression earg, Type returnType)
7167 {
7168 debug (LOG)
7169 {
7170 printf("interpret_keys()\n");
7171 }
7172 earg = interpret(pue, earg, istate);
7173 if (exceptionOrCantInterpret(earg))
7174 return earg;
7175 if (earg.op == EXP.null_)
7176 {
7177 emplaceExp!(NullExp)(pue, earg.loc, earg.type);
7178 return pue.exp();
7179 }
7180 if (earg.op != EXP.assocArrayLiteral && earg.type.toBasetype().ty != Taarray)
7181 return null;
7182 AssocArrayLiteralExp aae = earg.isAssocArrayLiteralExp();
7183 auto ae = ctfeEmplaceExp!ArrayLiteralExp(aae.loc, returnType, aae.keys);
7184 ae.ownedByCtfe = aae.ownedByCtfe;
7185 *pue = copyLiteral(ae);
7186 return pue.exp();
7187 }
7188
7189 private Expression interpret_values(UnionExp* pue, InterState* istate, Expression earg, Type returnType)
7190 {
7191 debug (LOG)
7192 {
7193 printf("interpret_values()\n");
7194 }
7195 earg = interpret(pue, earg, istate);
7196 if (exceptionOrCantInterpret(earg))
7197 return earg;
7198 if (earg.op == EXP.null_)
7199 {
7200 emplaceExp!(NullExp)(pue, earg.loc, earg.type);
7201 return pue.exp();
7202 }
7203 if (earg.op != EXP.assocArrayLiteral && earg.type.toBasetype().ty != Taarray)
7204 return null;
7205 auto aae = earg.isAssocArrayLiteralExp();
7206 auto ae = ctfeEmplaceExp!ArrayLiteralExp(aae.loc, returnType, aae.values);
7207 ae.ownedByCtfe = aae.ownedByCtfe;
7208 //printf("result is %s\n", e.toChars());
7209 *pue = copyLiteral(ae);
7210 return pue.exp();
7211 }
7212
7213 private Expression interpret_dup(UnionExp* pue, InterState* istate, Expression earg)
7214 {
7215 debug (LOG)
7216 {
7217 printf("interpret_dup()\n");
7218 }
7219 earg = interpret(pue, earg, istate);
7220 if (exceptionOrCantInterpret(earg))
7221 return earg;
7222 if (earg.op == EXP.null_)
7223 {
7224 emplaceExp!(NullExp)(pue, earg.loc, earg.type);
7225 return pue.exp();
7226 }
7227 if (earg.op != EXP.assocArrayLiteral && earg.type.toBasetype().ty != Taarray)
7228 return null;
7229 auto aae = copyLiteral(earg).copy().isAssocArrayLiteralExp();
7230 for (size_t i = 0; i < aae.keys.length; i++)
7231 {
7232 if (Expression e = evaluatePostblit(istate, (*aae.keys)[i]))
7233 return e;
7234 if (Expression e = evaluatePostblit(istate, (*aae.values)[i]))
7235 return e;
7236 }
7237 aae.type = earg.type.mutableOf(); // repaint type from const(int[int]) to const(int)[int]
7238 //printf("result is %s\n", aae.toChars());
7239 return aae;
7240 }
7241
7242 // signature is int delegate(ref Value) OR int delegate(ref Key, ref Value)
7243 private Expression interpret_aaApply(UnionExp* pue, InterState* istate, Expression aa, Expression deleg)
7244 {
7245 aa = interpret(aa, istate);
7246 if (exceptionOrCantInterpret(aa))
7247 return aa;
7248 if (aa.op != EXP.assocArrayLiteral)
7249 {
7250 emplaceExp!(IntegerExp)(pue, deleg.loc, 0, Type.tsize_t);
7251 return pue.exp();
7252 }
7253
7254 FuncDeclaration fd = null;
7255 Expression pthis = null;
7256 if (auto de = deleg.isDelegateExp())
7257 {
7258 fd = de.func;
7259 pthis = de.e1;
7260 }
7261 else if (auto fe = deleg.isFuncExp())
7262 fd = fe.fd;
7263
7264 assert(fd && fd.fbody);
7265 assert(fd.parameters);
7266 size_t numParams = fd.parameters.length;
7267 assert(numParams == 1 || numParams == 2);
7268
7269 Parameter fparam = fd.type.isTypeFunction().parameterList[numParams - 1];
7270 const wantRefValue = fparam.isReference();
7271
7272 Expressions args = Expressions(numParams);
7273
7274 AssocArrayLiteralExp ae = aa.isAssocArrayLiteralExp();
7275 if (!ae.keys || ae.keys.length == 0)
7276 return ctfeEmplaceExp!IntegerExp(deleg.loc, 0, Type.tsize_t);
7277 Expression eresult;
7278
7279 for (size_t i = 0; i < ae.keys.length; ++i)
7280 {
7281 Expression ekey = (*ae.keys)[i];
7282 Expression evalue = (*ae.values)[i];
7283 if (wantRefValue)
7284 {
7285 Type t = evalue.type;
7286 evalue = ctfeEmplaceExp!IndexExp(deleg.loc, ae, ekey);
7287 evalue.type = t;
7288 }
7289 args[numParams - 1] = evalue;
7290 if (numParams == 2)
7291 args[0] = ekey;
7292
7293 UnionExp ue = void;
7294 eresult = interpretFunction(&ue, fd, istate, &args, pthis);
7295 if (eresult == ue.exp())
7296 eresult = ue.copy();
7297 if (exceptionOrCantInterpret(eresult))
7298 return eresult;
7299
7300 if (eresult.isIntegerExp().getInteger() != 0)
7301 return eresult;
7302 }
7303 return eresult;
7304 }
7305
7306 /// Returns: equivalent `StringExp` from `ArrayLiteralExp ale` containing only `IntegerExp` elements
7307 StringExp arrayLiteralToString(ArrayLiteralExp ale)
7308 {
7309 const len = ale.elements ? ale.elements.length : 0;
7310 const size = ale.type.nextOf().size();
7311
7312 StringExp impl(T)()
7313 {
7314 T[] result = new T[len];
7315 foreach (i; 0 .. len)
7316 result[i] = cast(T) (*ale.elements)[i].isIntegerExp().getInteger();
7317 return new StringExp(ale.loc, result[], len, cast(ubyte) size);
7318 }
7319
7320 switch (size)
7321 {
7322 case 1:
7323 return impl!char();
7324 case 2:
7325 return impl!wchar();
7326 case 4:
7327 return impl!dchar();
7328 default:
7329 assert(0);
7330 }
7331 }
7332
7333 /* Decoding UTF strings for foreach loops. Duplicates the functionality of
7334 * the twelve _aApplyXXn functions in aApply.d in the runtime.
7335 */
7336 private Expression foreachApplyUtf(UnionExp* pue, InterState* istate, Expression str, Expression deleg, bool rvs)
7337 {
7338 debug (LOG)
7339 {
7340 printf("foreachApplyUtf(%s, %s)\n", str.toChars(), deleg.toChars());
7341 }
7342 FuncDeclaration fd = null;
7343 Expression pthis = null;
7344 if (auto de = deleg.isDelegateExp())
7345 {
7346 fd = de.func;
7347 pthis = de.e1;
7348 }
7349 else if (auto fe = deleg.isFuncExp())
7350 fd = fe.fd;
7351
7352 assert(fd && fd.fbody);
7353 assert(fd.parameters);
7354 size_t numParams = fd.parameters.length;
7355 assert(numParams == 1 || numParams == 2);
7356 Type charType = (*fd.parameters)[numParams - 1].type;
7357 Type indexType = numParams == 2 ? (*fd.parameters)[0].type : Type.tsize_t;
7358 size_t len = cast(size_t)resolveArrayLength(str);
7359 if (len == 0)
7360 {
7361 emplaceExp!(IntegerExp)(pue, deleg.loc, 0, indexType);
7362 return pue.exp();
7363 }
7364
7365 UnionExp strTmp = void;
7366 str = resolveSlice(str, &strTmp);
7367
7368 auto se = str.isStringExp();
7369 if (auto ale = str.isArrayLiteralExp())
7370 se = arrayLiteralToString(ale);
7371
7372 if (!se)
7373 {
7374 error(str.loc, "CTFE internal error: cannot foreach `%s`", str.toChars());
7375 return CTFEExp.cantexp;
7376 }
7377 Expressions args = Expressions(numParams);
7378
7379 Expression eresult = null; // ded-store to prevent spurious warning
7380
7381 // Buffers for encoding
7382 char[4] utf8buf = void;
7383 wchar[2] utf16buf = void;
7384
7385 size_t start = rvs ? len : 0;
7386 size_t end = rvs ? 0 : len;
7387 for (size_t indx = start; indx != end;)
7388 {
7389 // Step 1: Decode the next dchar from the string.
7390
7391 string errmsg = null; // Used for reporting decoding errors
7392 dchar rawvalue; // Holds the decoded dchar
7393 size_t currentIndex = indx; // The index of the decoded character
7394
7395 // String literals
7396 size_t saveindx; // used for reverse iteration
7397
7398 switch (se.sz)
7399 {
7400 case 1:
7401 {
7402 if (rvs)
7403 {
7404 // find the start of the string
7405 --indx;
7406 while (indx > 0 && ((se.getCodeUnit(indx) & 0xC0) == 0x80))
7407 --indx;
7408 saveindx = indx;
7409 }
7410 auto slice = se.peekString();
7411 errmsg = utf_decodeChar(slice, indx, rawvalue);
7412 if (rvs)
7413 indx = saveindx;
7414 break;
7415 }
7416
7417 case 2:
7418 if (rvs)
7419 {
7420 // find the start
7421 --indx;
7422 auto wc = se.getCodeUnit(indx);
7423 if (wc >= 0xDC00 && wc <= 0xDFFF)
7424 --indx;
7425 saveindx = indx;
7426 }
7427 const slice = se.peekWstring();
7428 errmsg = utf_decodeWchar(slice, indx, rawvalue);
7429 if (rvs)
7430 indx = saveindx;
7431 break;
7432
7433 case 4:
7434 if (rvs)
7435 --indx;
7436 rawvalue = se.getCodeUnit(indx);
7437 if (!rvs)
7438 ++indx;
7439 break;
7440
7441 default:
7442 assert(0);
7443 }
7444
7445 if (errmsg)
7446 {
7447 error(deleg.loc, "`%.*s`", cast(int)errmsg.length, errmsg.ptr);
7448 return CTFEExp.cantexp;
7449 }
7450
7451 // Step 2: encode the dchar in the target encoding
7452
7453 int charlen = 1; // How many codepoints are involved?
7454 switch (charType.size())
7455 {
7456 case 1:
7457 charlen = utf_codeLengthChar(rawvalue);
7458 utf_encodeChar(&utf8buf[0], rawvalue);
7459 break;
7460 case 2:
7461 charlen = utf_codeLengthWchar(rawvalue);
7462 utf_encodeWchar(&utf16buf[0], rawvalue);
7463 break;
7464 case 4:
7465 break;
7466 default:
7467 assert(0);
7468 }
7469 if (rvs)
7470 currentIndex = indx;
7471
7472 // Step 3: call the delegate once for each code point
7473
7474 // The index only needs to be set once
7475 if (numParams == 2)
7476 args[0] = ctfeEmplaceExp!IntegerExp(deleg.loc, currentIndex, indexType);
7477
7478 Expression val = null;
7479
7480 foreach (k; 0 .. charlen)
7481 {
7482 dchar codepoint;
7483 switch (charType.size())
7484 {
7485 case 1:
7486 codepoint = utf8buf[k];
7487 break;
7488 case 2:
7489 codepoint = utf16buf[k];
7490 break;
7491 case 4:
7492 codepoint = rawvalue;
7493 break;
7494 default:
7495 assert(0);
7496 }
7497 val = ctfeEmplaceExp!IntegerExp(str.loc, codepoint, charType);
7498
7499 args[numParams - 1] = val;
7500
7501 UnionExp ue = void;
7502 eresult = interpretFunction(&ue, fd, istate, &args, pthis);
7503 if (eresult == ue.exp())
7504 eresult = ue.copy();
7505 if (exceptionOrCantInterpret(eresult))
7506 return eresult;
7507 if (eresult.isIntegerExp().getInteger() != 0)
7508 return eresult;
7509 }
7510 }
7511 return eresult;
7512 }
7513
7514 /* If this is a built-in function, return the interpreted result,
7515 * Otherwise, return NULL.
7516 */
7517 private Expression evaluateIfBuiltin(UnionExp* pue, InterState* istate, Loc loc, FuncDeclaration fd, Expressions* arguments, Expression pthis)
7518 {
7519 Expression e = null;
7520 size_t nargs = arguments ? arguments.length : 0;
7521 if (!pthis)
7522 {
7523 if (isBuiltin(fd) != BUILTIN.unimp)
7524 {
7525 Expressions args = Expressions(nargs);
7526 foreach (i, ref arg; args)
7527 {
7528 Expression earg = (*arguments)[i];
7529 earg = interpret(earg, istate);
7530 if (exceptionOrCantInterpret(earg))
7531 return earg;
7532 arg = earg;
7533 }
7534 e = eval_builtin(loc, fd, &args);
7535 if (!e)
7536 {
7537 error(loc, "cannot evaluate unimplemented builtin `%s` at compile time", fd.toChars());
7538 e = CTFEExp.cantexp;
7539 }
7540 }
7541 }
7542 if (!pthis)
7543 {
7544 if (nargs == 1 || nargs == 3)
7545 {
7546 Expression firstarg = (*arguments)[0];
7547 if (auto firstAAtype = firstarg.type.toBasetype().isTypeAArray())
7548 {
7549 const id = fd.ident;
7550 if (nargs == 1)
7551 {
7552 if (id == Id.aaLen)
7553 return interpret_length(pue, istate, firstarg);
7554
7555 if (fd.toParent2().ident == Id.object)
7556 {
7557 if (id == Id.keys)
7558 return interpret_keys(pue, istate, firstarg, firstAAtype.index.arrayOf());
7559 if (id == Id.values)
7560 return interpret_values(pue, istate, firstarg, firstAAtype.nextOf().arrayOf());
7561 if (id == Id.rehash)
7562 return interpret(pue, firstarg, istate);
7563 if (id == Id.dup)
7564 return interpret_dup(pue, istate, firstarg);
7565 }
7566 }
7567 else // (nargs == 3)
7568 {
7569 if (id == Id._aaApply)
7570 return interpret_aaApply(pue, istate, firstarg, (*arguments)[2]);
7571 if (id == Id._aaApply2)
7572 return interpret_aaApply(pue, istate, firstarg, (*arguments)[2]);
7573 }
7574 }
7575 }
7576 }
7577 if (pthis && !fd.fbody && fd.isCtorDeclaration() && fd.parent && fd.parent.parent && fd.parent.parent.ident == Id.object)
7578 {
7579 if (pthis.op == EXP.classReference && fd.parent.ident == Id.Throwable)
7580 {
7581 // At present, the constructors just copy their arguments into the struct.
7582 // But we might need some magic if stack tracing gets added to druntime.
7583 StructLiteralExp se = pthis.isClassReferenceExp().value;
7584 assert(arguments.length <= se.elements.length);
7585 foreach (i, arg; *arguments)
7586 {
7587 auto elem = interpret(arg, istate);
7588 if (exceptionOrCantInterpret(elem))
7589 return elem;
7590 (*se.elements)[i] = elem;
7591 }
7592 return CTFEExp.voidexp;
7593 }
7594 }
7595 if (nargs == 1 && !pthis && (fd.ident == Id.criticalenter || fd.ident == Id.criticalexit))
7596 {
7597 // Support synchronized{} as a no-op
7598 return CTFEExp.voidexp;
7599 }
7600 if (!pthis)
7601 {
7602 const idlen = fd.ident.toString().length;
7603 const id = fd.ident.toChars();
7604 if (nargs == 2 && (idlen == 10 || idlen == 11) && !strncmp(id, "_aApply", 7))
7605 {
7606 // Functions from aApply.d and aApplyR.d in the runtime
7607 bool rvs = (idlen == 11); // true if foreach_reverse
7608 char c = id[idlen - 3]; // char width: 'c', 'w', or 'd'
7609 char s = id[idlen - 2]; // string width: 'c', 'w', or 'd'
7610 char n = id[idlen - 1]; // numParams: 1 or 2.
7611 // There are 12 combinations
7612 if ((n == '1' || n == '2') &&
7613 (c == 'c' || c == 'w' || c == 'd') &&
7614 (s == 'c' || s == 'w' || s == 'd') &&
7615 c != s)
7616 {
7617 Expression str = (*arguments)[0];
7618 str = interpret(str, istate);
7619 if (exceptionOrCantInterpret(str))
7620 return str;
7621 return foreachApplyUtf(pue, istate, str, (*arguments)[1], rvs);
7622 }
7623 }
7624 }
7625 return e;
7626 }
7627
7628 private Expression evaluatePostblit(InterState* istate, Expression e)
7629 {
7630 auto ts = e.type.baseElemOf().isTypeStruct();
7631 if (!ts)
7632 return null;
7633 StructDeclaration sd = ts.sym;
7634 if (!sd.postblit)
7635 return null;
7636
7637 if (auto ale = e.isArrayLiteralExp())
7638 {
7639 foreach (elem; *ale.elements)
7640 {
7641 if (auto ex = evaluatePostblit(istate, elem))
7642 return ex;
7643 }
7644 return null;
7645 }
7646 if (e.op == EXP.structLiteral)
7647 {
7648 // e.__postblit()
7649 UnionExp ue = void;
7650 e = interpretFunction(&ue, sd.postblit, istate, null, e);
7651 if (e == ue.exp())
7652 e = ue.copy();
7653 if (exceptionOrCantInterpret(e))
7654 return e;
7655 return null;
7656 }
7657 assert(0);
7658 }
7659
7660 private Expression evaluateDtor(InterState* istate, Expression e)
7661 {
7662 auto ts = e.type.baseElemOf().isTypeStruct();
7663 if (!ts)
7664 return null;
7665 StructDeclaration sd = ts.sym;
7666 if (!sd.dtor)
7667 return null;
7668
7669 UnionExp ue = void;
7670 if (auto ale = e.isArrayLiteralExp())
7671 {
7672 foreach_reverse (elem; *ale.elements)
7673 e = evaluateDtor(istate, elem);
7674 }
7675 else if (e.op == EXP.structLiteral)
7676 {
7677 // e.__dtor()
7678 e = interpretFunction(&ue, sd.dtor, istate, null, e);
7679 }
7680 else
7681 assert(0);
7682 if (exceptionOrCantInterpret(e))
7683 {
7684 if (e == ue.exp())
7685 e = ue.copy();
7686 return e;
7687 }
7688 return null;
7689 }
7690
7691 /*************************** CTFE Sanity Checks ***************************/
7692 /* Setter functions for CTFE variable values.
7693 * These functions exist to check for compiler CTFE bugs.
7694 */
7695 private bool hasValue(VarDeclaration vd)
7696 {
7697 return vd.ctfeAdrOnStack != VarDeclaration.AdrOnStackNone &&
7698 getValue(vd) !is null;
7699 }
7700
7701 // Don't check for validity
7702 private void setValueWithoutChecking(VarDeclaration vd, Expression newval)
7703 {
7704 ctfeGlobals.stack.setValue(vd, newval);
7705 }
7706
7707 private void setValue(VarDeclaration vd, Expression newval)
7708 {
7709 //printf("setValue() vd: %s newval: %s\n", vd.toChars(), newval.toChars());
7710 version (none)
7711 {
7712 if (!((vd.storage_class & (STC.out_ | STC.ref_)) ? isCtfeReferenceValid(newval) : isCtfeValueValid(newval)))
7713 {
7714 printf("[%s] vd = %s %s, newval = %s\n", vd.loc.toChars(), vd.type.toChars(), vd.toChars(), newval.toChars());
7715 }
7716 }
7717 assert((vd.storage_class & (STC.out_ | STC.ref_)) ? isCtfeReferenceValid(newval) : isCtfeValueValid(newval));
7718 ctfeGlobals.stack.setValue(vd, newval);
7719 }
7720
7721 /**
7722 * Removes `_d_HookTraceImpl` if found from `ce` and `fd`.
7723 * This is needed for the CTFE interception code to be able to find hooks that are called though the hook's `*Trace`
7724 * wrapper.
7725 *
7726 * This is done by replacing `_d_HookTraceImpl!(T, Hook, errMsg)(..., parameters)` with `Hook(parameters)`.
7727 * Parameters:
7728 * ce = The CallExp that possible will be be replaced
7729 * fd = Fully resolve function declaration that `ce` would call
7730 */
7731 private void removeHookTraceImpl(ref CallExp ce, ref FuncDeclaration fd)
7732 {
7733 if (fd.ident != Id._d_HookTraceImpl)
7734 return;
7735
7736 auto oldCE = ce;
7737
7738 // Get the Hook from the second template parameter
7739 TemplateInstance templateInstance = fd.parent.isTemplateInstance;
7740 RootObject hook = (*templateInstance.tiargs)[1];
7741 assert(hook.isDsymbol(), "Expected _d_HookTraceImpl's second template parameter to be an alias to the hook!");
7742 fd = (cast(Dsymbol)hook).isFuncDeclaration;
7743
7744 // Remove the first three trace parameters
7745 auto arguments = new Expressions();
7746 arguments.reserve(ce.arguments.length - 3);
7747 arguments.pushSlice((*ce.arguments)[3 .. $]);
7748
7749 ce = ctfeEmplaceExp!CallExp(ce.loc, ctfeEmplaceExp!VarExp(ce.loc, fd, false), arguments);
7750
7751 if (global.params.v.verbose)
7752 message("strip %s =>\n %s", oldCE.toChars(), ce.toChars());
7753 }