Debian Codegraph @

gcc/d/dmd/initsem.d

raw
1 /**
2 * Semantic analysis of initializers.
3 *
4 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
5 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
6 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
7 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/initsem.d, _initsem.d)
8 * Documentation: https://dlang.org/phobos/dmd_initsem.html
9 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/initsem.d
10 */
11
12 module dmd.initsem;
13
14 import core.stdc.stdio;
15 import core.checkedint;
16
17 import dmd.aggregate;
18 import dmd.aliasthis;
19 import dmd.arraytypes;
20 import dmd.astenums;
21 import dmd.dcast;
22 import dmd.declaration;
23 import dmd.dinterpret;
24 import dmd.dscope;
25 import dmd.dstruct;
26 import dmd.dsymbol;
27 import dmd.dsymbolsem;
28 import dmd.dtemplate;
29 import dmd.errors;
30 import dmd.expression;
31 import dmd.expressionsem;
32 import dmd.func;
33 import dmd.funcsem;
34 import dmd.globals;
35 import dmd.hdrgen;
36 import dmd.id;
37 import dmd.identifier;
38 import dmd.importc;
39 import dmd.init;
40 import dmd.location;
41 import dmd.mtype;
42 import dmd.opover;
43 import dmd.optimize;
44 import dmd.safe : setUnsafe;
45 import dmd.statement;
46 import dmd.target;
47 import dmd.tokens;
48 import dmd.typesem;
49
50 /********************************
51 * If possible, convert array initializer to associative array initializer.
52 *
53 * Params:
54 * ai = array initializer to be converted
55 *
56 * Returns:
57 * The converted associative array initializer or ErrorExp if `ai`
58 * is not an associative array initializer.
59 */
60 Expression toAssocArrayLiteral(ArrayInitializer ai)
61 {
62 //printf("ArrayInitializer::toAssocArrayInitializer(%s)\n", ai.toChars());
63 //static int i; if (++i == 2) assert(0);
64
65 auto no(const char* format, Initializer i)
66 {
67 error(i.loc, format, toChars(i));
68 return ErrorExp.get();
69 }
70
71 const dim = ai.value.length;
72 if (!dim)
73 return no("invalid associative array initializer `%s`, use `null` instead", ai);
74
75 auto keys = new Expressions(dim);
76 auto values = new Expressions(dim);
77 foreach (i, iz; ai.value[])
78 {
79 assert(iz);
80 auto ev = iz.initializerToExpression();
81 if (!ev)
82 return no("invalid value `%s` in initializer", iz);
83 (*values)[i] = ev;
84
85 auto ei = ai.index[i];
86 if (!ei)
87 return no("missing key for value `%s` in initializer", iz);
88 (*keys)[i] = ei;
89 }
90 return new AssocArrayLiteralExp(ai.loc, keys, values);
91 }
92
93 /******************************************
94 * Perform semantic analysis on init.
95 * Params:
96 * init = Initializer AST node
97 * sc = context
98 * tx = type that the initializer needs to become. If tx is an incomplete
99 * type and the initializer completes it, it is updated to be the
100 * complete type. ImportC has incomplete types
101 * needInterpret = if CTFE needs to be run on this,
102 * such as if it is the initializer for a const declaration
103 * Returns:
104 * `Initializer` with completed semantic analysis, `ErrorInitializer` if errors
105 * were encountered
106 */
107 Initializer initializerSemantic(Initializer init, Scope* sc, ref Type tx, NeedInterpret needInterpret)
108 {
109 //printf("initializerSemantic() tx: %p %s\n", tx, tx.toChars());
110 if (init.semanticDone)
111 return init;
112
113 Type t = tx;
114
115 static Initializer err()
116 {
117 return new ErrorInitializer();
118 }
119
120 Initializer visitVoid(VoidInitializer i)
121 {
122 i.type = t;
123 return i;
124 }
125
126 Initializer visitDefault(DefaultInitializer i)
127 {
128 i.type = t;
129 return i;
130 }
131
132 Initializer visitError(ErrorInitializer i)
133 {
134 return i;
135 }
136
137 Initializer visitStruct(StructInitializer i)
138 {
139 //printf("StructInitializer::semantic(t = %s) %s\n", t.toChars(), i.toChars());
140 /* This works by replacing the StructInitializer with an ExpInitializer.
141 */
142 t = t.toBasetype();
143 if (auto tsa = t.isTypeSArray())
144 {
145 auto ts = tsa.nextOf().toBasetype().isTypeStruct();
146 if (ts)
147 t = ts;
148 }
149 if (auto ts = t.isTypeStruct())
150 {
151 StructDeclaration sd = ts.sym;
152 // check if the sd has a regular ctor (user defined non-copy ctor)
153 // that is not disabled.
154 if (sd.hasRegularCtor(true))
155 {
156 error(i.loc, "%s `%s` has constructors, cannot use `{ initializers }`, use `%s( initializers )` instead", sd.kind(), sd.toChars(), sd.toChars());
157 return err();
158 }
159 sd.size(i.loc);
160 if (sd.sizeok != Sizeok.done)
161 return err();
162
163 Expression getExp(size_t j, Type fieldType)
164 {
165 // Convert initializer to Expression `ex`
166 auto tm = fieldType.addMod(t.mod);
167 auto iz = i.value[j].initializerSemantic(sc, tm, needInterpret);
168 auto ex = iz.initializerToExpression(null, sc.inCfile);
169 if (ex.op != EXP.error)
170 i.value[j] = iz;
171 return ex;
172 }
173
174 auto elements = resolveStructLiteralNamedArgs(sd, t, sc, i.loc, i.field[], &getExp, (size_t j) => i.value[j].loc);
175 if (!elements)
176 return err();
177
178 // Make a StructLiteralExp out of elements[]
179 auto sle = new StructLiteralExp(i.loc, sd, elements, t);
180 if (!sd.fill(i.loc, *elements, false))
181 return err();
182 sle.type = t;
183 auto ie = new ExpInitializer(i.loc, sle);
184 return ie.initializerSemantic(sc, t, needInterpret);
185 }
186 else if ((t.ty == Tdelegate || t.isPtrToFunction()) && i.value.length == 0)
187 {
188 const tok = (t.ty == Tdelegate) ? TOK.delegate_ : TOK.function_;
189 /* Rewrite as empty delegate literal { }
190 */
191 Type tf = new TypeFunction(ParameterList(), null, LINK.d);
192 auto fd = new FuncLiteralDeclaration(i.loc, Loc.initial, tf, tok, null);
193 fd.fbody = new CompoundStatement(i.loc, new Statements());
194 fd.endloc = i.loc;
195 Expression e = new FuncExp(i.loc, fd);
196 auto ie = new ExpInitializer(i.loc, e);
197 return ie.initializerSemantic(sc, t, needInterpret);
198 }
199 if (t.ty != Terror)
200 error(i.loc, "a struct is not a valid initializer for a `%s`", t.toChars());
201 return err();
202 }
203
204 Initializer visitArray(ArrayInitializer i)
205 {
206 uint length;
207 const(uint) amax = 0x80000000;
208 bool errors = false;
209 //printf("ArrayInitializer::semantic(%s), ai: %s\n", t.toChars(), toChars(i));
210 t = t.toBasetype();
211 switch (t.ty)
212 {
213 case Tsarray:
214 case Tarray:
215 break;
216 case Tvector:
217 t = t.isTypeVector().basetype;
218 break;
219 case Taarray:
220 case Tstruct: // consider implicit constructor call
221 {
222 Expression e;
223 // note: MyStruct foo = [1:2, 3:4] is correct code if MyStruct has a this(int[int])
224 if (t.ty == Taarray || i.isAssociativeArray())
225 e = i.toAssocArrayLiteral();
226 else
227 e = i.initializerToExpression();
228 // Bugzilla 13987
229 if (!e)
230 {
231 error(i.loc, "cannot use array to initialize `%s`", t.toChars());
232 return err();
233 }
234 auto ei = new ExpInitializer(e.loc, e);
235 return ei.initializerSemantic(sc, t, needInterpret);
236 }
237
238 case Tpointer:
239 if (t.nextOf().isTypeFunction())
240 goto default;
241 break;
242
243 default:
244 error(i.loc, "cannot use array to initialize `%s`", t.toChars());
245 return err();
246 }
247 i.type = t;
248 length = 0;
249 for (size_t j = 0; j < i.index.length; j++) // don't replace with foreach; j is modified
250 {
251 Expression idx = i.index[j];
252 if (idx)
253 {
254 sc = sc.startCTFE();
255 idx = idx.expressionSemantic(sc);
256 sc = sc.endCTFE();
257 idx = idx.ctfeInterpret();
258 i.index[j] = idx;
259 const uinteger_t idxvalue = idx.toInteger();
260 if (idxvalue >= amax)
261 {
262 error(i.loc, "array index %llu overflow", idxvalue);
263 errors = true;
264 }
265 length = cast(uint)idxvalue;
266 if (idx.op == EXP.error)
267 errors = true;
268 }
269 Initializer val = i.value[j];
270 ExpInitializer ei = val.isExpInitializer();
271 if (ei && !idx)
272 ei.expandTuples = true;
273 auto tn = t.nextOf();
274 val = val.initializerSemantic(sc, tn, needInterpret);
275 if (val.isErrorInitializer())
276 errors = true;
277 ei = val.isExpInitializer();
278 // found a tuple, expand it
279 if (ei && ei.exp.op == EXP.tuple)
280 {
281 TupleExp te = ei.exp.isTupleExp();
282 i.index.remove(j);
283 i.value.remove(j);
284 foreach (k, e; (*te.exps)[])
285 {
286 i.index.insert(j + k, cast(Expression)null);
287 i.value.insert(j + k, new ExpInitializer(e.loc, e));
288 }
289 j--;
290 continue;
291 }
292 else
293 {
294 i.value[j] = val;
295 }
296 ++length;
297 if (length == 0)
298 {
299 error(i.loc, "array dimension overflow");
300 return err();
301 }
302 if (length > i.dim)
303 i.dim = length;
304 }
305 if (auto tsa = t.isTypeSArray())
306 {
307 if (sc.inCfile && tsa.isIncomplete())
308 {
309 // Change to array of known length
310 auto tn = tsa.next.toBasetype();
311 tsa = new TypeSArray(tn, new IntegerExp(Loc.initial, i.dim, Type.tsize_t));
312 tx = tsa; // rewrite caller's type
313 i.type = tsa; // remember for later passes
314 }
315 else
316 {
317 ulong edim = tsa.dim.toInteger();
318 if (i.dim > edim)
319 {
320 error(i.loc, "array initializer has %u elements, but array length is %llu", i.dim, edim);
321 return err();
322 }
323 }
324 }
325 if (errors)
326 return err();
327
328 const sz = t.nextOf().size();
329 if (sz == SIZE_INVALID)
330 return err();
331 bool overflow;
332 const max = mulu(i.dim, sz, overflow);
333 if (overflow || max >= amax)
334 {
335 error(i.loc, "array dimension %llu exceeds max of %llu", ulong(i.dim), ulong(amax / sz));
336 return err();
337 }
338 //printf("returns ai: %s\n", i.toChars());
339 return i;
340 }
341
342 Initializer visitExp(ExpInitializer i)
343 {
344 //printf("ExpInitializer::semantic(%s), type = %s\n", i.exp.toChars(), t.toChars());
345 if (needInterpret)
346 sc = sc.startCTFE();
347 i.exp = i.exp.expressionSemantic(sc);
348 i.exp = resolveProperties(sc, i.exp);
349 if (needInterpret)
350 sc = sc.endCTFE();
351 if (i.exp.op == EXP.error)
352 return err();
353 const olderrors = global.errors;
354
355 /* ImportC: convert arrays to pointers, functions to pointers to functions
356 */
357 Type tb = t.toBasetype();
358 if (tb.isTypePointer())
359 i.exp = i.exp.arrayFuncConv(sc);
360
361 /* Save the expression before ctfe
362 * Otherwise the error message would contain for example "&[0][0]" instead of "new int"
363 * Regression: https://issues.dlang.org/show_bug.cgi?id=21687
364 */
365 Expression currExp = i.exp;
366 if (needInterpret)
367 {
368 // If the result will be implicitly cast, move the cast into CTFE
369 // to avoid premature truncation of polysemous types.
370 // eg real [] x = [1.1, 2.2]; should use real precision.
371 if (i.exp.implicitConvTo(t) && !sc.inCfile)
372 {
373 i.exp = i.exp.implicitCastTo(sc, t);
374 }
375 if (!global.gag && olderrors != global.errors)
376 {
377 return i;
378 }
379 if (sc.inCfile)
380 {
381 /* the interpreter turns (char*)"string" into &"string"[0] which then
382 * it cannot interpret. Resolve that case by doing optimize() first
383 */
384 i.exp = i.exp.optimize(WANTvalue);
385 if (i.exp.isSymOffExp())
386 {
387 /* `static variable cannot be read at compile time`
388 * https://issues.dlang.org/show_bug.cgi?id=22513
389 * Maybe this would be better addressed in ctfeInterpret()?
390 */
391 needInterpret = NeedInterpret.INITnointerpret;
392 }
393 }
394 if (needInterpret)
395 i.exp = i.exp.ctfeInterpret();
396 if (i.exp.op == EXP.voidExpression)
397 error(i.loc, "variables cannot be initialized with an expression of type `void`. Use `void` initialization instead.");
398 }
399 else
400 {
401 i.exp = i.exp.optimize(WANTvalue);
402 }
403
404 if (!global.gag && olderrors != global.errors)
405 {
406 return i; // Failed, suppress duplicate error messages
407 }
408 if (i.exp.type.isTypeTuple() && i.exp.type.isTypeTuple().arguments.length == 0)
409 {
410 Type et = i.exp.type;
411 i.exp = new TupleExp(i.exp.loc, new Expressions());
412 i.exp.type = et;
413 }
414 if (i.exp.op == EXP.type)
415 {
416 error(i.exp.loc, "initializer must be an expression, not `%s`", i.exp.toChars());
417 return err();
418 }
419 // Make sure all pointers are constants
420 if (needInterpret && hasNonConstPointers(i.exp))
421 {
422 error(i.exp.loc, "cannot use non-constant CTFE pointer in an initializer `%s`", currExp.toChars());
423 return err();
424 }
425 Type ti = i.exp.type.toBasetype();
426 if (i.exp.op == EXP.tuple && i.expandTuples && !i.exp.implicitConvTo(t))
427 {
428 return new ExpInitializer(i.loc, i.exp);
429 }
430 /* Look for case of initializing a static array with a too-short
431 * string literal, such as:
432 * char[5] foo = "abc";
433 * Allow this by doing an explicit cast, which will lengthen the string
434 * literal.
435 */
436 if (i.exp.op == EXP.string_ && tb.ty == Tsarray)
437 {
438 StringExp se = i.exp.isStringExp();
439 Type typeb = se.type.toBasetype();
440 TY tynto = tb.nextOf().ty;
441 if (!se.committed &&
442 typeb.isStaticOrDynamicArray() && tynto.isSomeChar &&
443 se.numberOfCodeUnits(tynto) < tb.isTypeSArray().dim.toInteger())
444 {
445 i.exp = se.castTo(sc, t);
446 goto L1;
447 }
448
449 /* Lop off terminating 0 of initializer for:
450 * static char s[5] = "hello";
451 */
452 if (sc.inCfile &&
453 typeb.ty == Tsarray &&
454 tynto.isSomeChar &&
455 tb.isTypeSArray().dim.toInteger() + 1 == typeb.isTypeSArray().dim.toInteger())
456 {
457 i.exp = se.castTo(sc, t);
458 goto L1;
459 }
460 }
461 /* C11 6.7.9-14..15
462 * Initialize an array of unknown size with a string.
463 * Change to static array of known size
464 */
465 if (sc.inCfile && i.exp.isStringExp() &&
466 tb.isTypeSArray() && tb.isTypeSArray().isIncomplete())
467 {
468 StringExp se = i.exp.isStringExp();
469 auto ts = new TypeSArray(tb.nextOf(), new IntegerExp(Loc.initial, se.len + 1, Type.tsize_t));
470 t = typeSemantic(ts, Loc.initial, sc);
471 i.exp.type = t;
472 tx = t;
473 }
474
475 // Look for implicit constructor call
476 if (tb.ty == Tstruct && !(ti.ty == Tstruct && tb.toDsymbol(sc) == ti.toDsymbol(sc)) && !i.exp.implicitConvTo(t))
477 {
478 StructDeclaration sd = tb.isTypeStruct().sym;
479 if (sd.ctor)
480 {
481 // Rewrite as S().ctor(exp)
482 Expression e;
483 e = new StructLiteralExp(i.loc, sd, null);
484 e = new DotIdExp(i.loc, e, Id.ctor);
485 e = new CallExp(i.loc, e, i.exp);
486 e = e.expressionSemantic(sc);
487 if (needInterpret)
488 i.exp = e.ctfeInterpret();
489 else
490 i.exp = e.optimize(WANTvalue);
491 }
492 else if (search_function(sd, Id.opCall))
493 {
494 /* https://issues.dlang.org/show_bug.cgi?id=1547
495 *
496 * Look for static opCall
497 *
498 * Rewrite as:
499 * i.exp = typeof(sd).opCall(arguments)
500 */
501
502 Expression e = typeDotIdExp(i.loc, sd.type, Id.opCall);
503 e = new CallExp(i.loc, e, i.exp);
504 e = e.expressionSemantic(sc);
505 e = resolveProperties(sc, e);
506 if (needInterpret)
507 i.exp = e.ctfeInterpret();
508 else
509 i.exp = e.optimize(WANTvalue);
510 }
511 }
512
513 // Look for the case of statically initializing an array with a single member.
514 // Recursively strip static array / enum layers until a compatible element is found,
515 // and return an `ArrayLiteralExp` repeating the initializer, or `null` if no match found
516 // int[2][3] = 7 => [[7, 7], [7, 7], [7, 7]]
517 // int[2] = new Object => null
518 Expression sarrayRepeat(Type tb)
519 {
520 auto tsa = tb.isTypeSArray();
521 if (!tsa)
522 return null;
523
524 // printf("i.exp = %s, tsa = %s\n", i.exp.toChars(), tsa.toChars());
525 Expression elem = null;
526 if (i.exp.implicitConvTo(tb.nextOf()))
527 elem = i.exp.implicitCastTo(sc, tb.nextOf());
528 else if (auto ae = sarrayRepeat(tb.nextOf().toBasetype()))
529 elem = ae;
530 else
531 return null;
532
533 auto arrayElements = new Expressions(cast(size_t) tsa.dim.toInteger());
534 foreach (ref e; *arrayElements)
535 e = elem;
536 return new ArrayLiteralExp(i.exp.loc, tb, elem, arrayElements);
537 }
538
539 if (auto sa = sarrayRepeat(tb))
540 {
541 // printf("sa = %s\n", sa.toChars());
542 i.exp = sa;
543 }
544
545 {
546 auto tta = t.isTypeSArray();
547 if (i.exp.implicitConvTo(t))
548 {
549 i.exp = i.exp.implicitCastTo(sc, t);
550 }
551 else if (sc.inCfile && i.exp.isStringExp() &&
552 tta && (tta.next.ty == Tint8 || tta.next.ty == Tuns8) &&
553 ti.ty == Tsarray && ti.nextOf().ty == Tchar)
554 {
555 /* unsigned char bbb[1] = "";
556 * signed char ccc[1] = "";
557 */
558 i.exp = i.exp.castTo(sc, t);
559 }
560 else
561 {
562 auto tba = tb.isTypeSArray();
563 // Look for mismatch of compile-time known length to emit
564 // better diagnostic message, as same as AssignExp::semantic.
565 if (tba && i.exp.implicitConvTo(tba.next.arrayOf()) > MATCH.nomatch)
566 {
567 uinteger_t dim1 = tba.dim.toInteger();
568 uinteger_t dim2 = dim1;
569 if (auto ale = i.exp.isArrayLiteralExp())
570 {
571 dim2 = ale.elements ? ale.elements.length : 0;
572 }
573 else if (auto se = i.exp.isSliceExp())
574 {
575 if (Type tx = toStaticArrayType(se))
576 dim2 = tx.isTypeSArray().dim.toInteger();
577 }
578 if (dim1 != dim2)
579 {
580 error(i.exp.loc, "mismatched array lengths, %d and %d", cast(int)dim1, cast(int)dim2);
581 i.exp = ErrorExp.get();
582 }
583 }
584 Type et = i.exp.type;
585 const errors = global.startGagging();
586 i.exp = i.exp.implicitCastTo(sc, t);
587 if (global.endGagging(errors))
588 error(currExp.loc, "cannot implicitly convert expression `%s` of type `%s` to `%s`", currExp.toErrMsg(), et.toChars(), t.toChars());
589 }
590 }
591 L1:
592 if (i.exp.op == EXP.error)
593 {
594 return i;
595 }
596 if (needInterpret)
597 i.exp = i.exp.ctfeInterpret();
598 else
599 i.exp = i.exp.optimize(WANTvalue);
600 //printf("-ExpInitializer::semantic(): "); i.exp.print();
601 return i;
602 }
603
604 Initializer visitC(CInitializer ci)
605 {
606 //printf("CInitializer::semantic() tx: %s t: %s ci: %s\n", (tx ? tx.toChars() : "".ptr), t.toChars(), toChars(ci));
607 static if (0)
608 if (auto ts = tx.isTypeStruct())
609 {
610 import dmd.common.outbuffer;
611 OutBuffer buf;
612 HdrGenState hgs;
613 toCBuffer(ts.sym, buf, hgs);
614 printf("%s\n", buf.peekChars());
615 }
616
617 /* Rewrite CInitializer into ExpInitializer, ArrayInitializer, or StructInitializer
618 */
619 t = t.toBasetype();
620
621 if (auto tv = t.isTypeVector())
622 t = tv.basetype;
623
624 /* If `{ expression }` return the expression initializer
625 */
626 ExpInitializer isBraceExpression()
627 {
628 auto dil = ci.initializerList[];
629 return (dil.length == 1 && !dil[0].designatorList)
630 ? dil[0].initializer.isExpInitializer()
631 : null;
632 }
633
634 /********************************
635 */
636 bool overlaps(VarDeclaration field, VarDeclaration[] fields, StructInitializer si)
637 {
638 foreach (fld; fields)
639 {
640 if (field.isOverlappedWith(fld))
641 {
642 // look for initializer corresponding with fld
643 foreach (i, ident; si.field[])
644 {
645 if (ident == fld.ident && si.value[i])
646 return true; // already an initializer for `field`
647 }
648 }
649 }
650 return false;
651 }
652
653 /* Run semantic on ExpInitializer, see if it represents entire struct ts
654 */
655 bool representsStruct(ExpInitializer ei, TypeStruct ts)
656 {
657 if (needInterpret)
658 sc = sc.startCTFE();
659 ei.exp = ei.exp.expressionSemantic(sc);
660 ei.exp = resolveProperties(sc, ei.exp);
661 if (needInterpret)
662 sc = sc.endCTFE();
663 return ei.exp.implicitConvTo(ts) != MATCH.nomatch; // initializer represents the entire struct
664 }
665
666 /* If { } are omitted from substructs, use recursion to reconstruct where
667 * brackets go
668 * Params:
669 * ts = substruct to initialize
670 * index = index into ci.initializer, updated
671 * Returns: struct initializer for this substruct
672 */
673 Initializer subStruct()(TypeStruct ts, ref size_t index)
674 {
675 //printf("subStruct(ts: %s, index %d)\n", ts.toChars(), cast(int)index);
676
677 auto si = new StructInitializer(ci.loc);
678 StructDeclaration sd = ts.sym;
679 sd.size(ci.loc);
680 if (sd.sizeok != Sizeok.done)
681 {
682 index = ci.initializerList.length;
683 return err();
684 }
685 const nfields = sd.fields.length;
686
687 foreach (fieldi; 0 .. nfields)
688 {
689 if (index >= ci.initializerList.length)
690 break; // ran out of initializers
691 auto di = ci.initializerList[index];
692 if (di.designatorList && fieldi != 0)
693 break; // back to top level
694
695 VarDeclaration field;
696 while (1) // skip field if it overlaps with previously seen fields
697 {
698 field = sd.fields[fieldi];
699 ++fieldi;
700 if (!overlaps(field, sd.fields[], si))
701 break;
702 if (fieldi == nfields)
703 break;
704 }
705 auto tn = field.type.toBasetype();
706 auto tnsa = tn.isTypeSArray();
707 auto tns = tn.isTypeStruct();
708 auto ix = di.initializer;
709 if (tnsa && ix.isExpInitializer())
710 {
711 ExpInitializer ei = ix.isExpInitializer();
712 if (ei.exp.isStringExp() && tnsa.nextOf().isIntegral())
713 {
714 si.addInit(field.ident, ei);
715 ++index;
716 }
717 else
718 si.addInit(field.ident, subArray(tnsa, index)); // fwd ref of subArray is why subStruct is a template
719 }
720 else if (tns && ix.isExpInitializer())
721 {
722 /* Disambiguate between an exp representing the entire
723 * struct, and an exp representing the first field of the struct
724 */
725 if (representsStruct(ix.isExpInitializer(), tns)) // initializer represents the entire struct
726 {
727 si.addInit(field.ident, initializerSemantic(ix, sc, tn, needInterpret));
728 ++index;
729 }
730 else // field initializers for struct
731 si.addInit(field.ident, subStruct(tns, index)); // the first field
732 }
733 else
734 {
735 si.addInit(field.ident, ix);
736 ++index;
737 }
738 }
739 //printf("subStruct() returns ai: %s, index: %d\n", si.toChars(), cast(int)index);
740 return si;
741 }
742
743 /* If { } are omitted from subarrays, use recursion to reconstruct where
744 * brackets go
745 * Params:
746 * tsa = subarray to initialize
747 * index = index into ci.initializer, updated
748 * Returns: array initializer for this subarray
749 */
750 Initializer subArray(TypeSArray tsa, ref size_t index)
751 {
752 //printf("array(tsa: %s, index %d)\n", tsa.toChars(), cast(int)index);
753 if (tsa.isIncomplete())
754 {
755 // C11 6.2.5-20 "element type shall be complete whenever the array type is specified"
756 assert(0); // should have been detected by parser
757 }
758
759 auto tnsa = tsa.nextOf().toBasetype().isTypeSArray();
760
761 auto ai = new ArrayInitializer(ci.loc);
762 ai.isCarray = true;
763
764 foreach (n; 0 .. cast(size_t)tsa.dim.toInteger())
765 {
766 if (index >= ci.initializerList.length)
767 break; // ran out of initializers
768 auto di = ci.initializerList[index];
769 if (di.designatorList)
770 break; // back to top level
771 else if (tnsa && di.initializer.isExpInitializer())
772 {
773 ExpInitializer ei = di.initializer.isExpInitializer();
774 if (ei.exp.isStringExp() && tnsa.nextOf().isIntegral())
775 {
776 ai.addInit(null, ei);
777 ++index;
778 }
779 else
780 ai.addInit(null, subArray(tnsa, index));
781 }
782 else
783 {
784 ai.addInit(null, di.initializer);
785 ++index;
786 }
787 }
788 //printf("array() returns ai: %s, index: %d\n", ai.toChars(), cast(int)index);
789 return ai;
790 }
791
792 if (auto ts = t.isTypeStruct())
793 {
794 auto si = new StructInitializer(ci.loc);
795 StructDeclaration sd = ts.sym;
796 sd.size(ci.loc); // run semantic() on sd to get fields
797 if (sd.sizeok != Sizeok.done)
798 {
799 return err();
800 }
801 const nfields = sd.fields.length;
802 size_t fieldi = 0;
803
804 Loop1:
805 for (size_t index = 0; index < ci.initializerList.length; )
806 {
807 DesigInit di = ci.initializerList[index];
808 Designators* dlist = di.designatorList;
809 if (dlist)
810 {
811 const length = (*dlist).length;
812 if (length == 0 || !(*dlist)[0].ident)
813 {
814 error(ci.loc, "`.identifier` expected for C struct field initializer `%s`", toChars(ci));
815 return err();
816 }
817 if (length > 1)
818 {
819 error(ci.loc, "only 1 designator currently allowed for C struct field initializer `%s`", toChars(ci));
820 return err();
821 }
822 auto id = (*dlist)[0].ident;
823 foreach (k, f; sd.fields[]) // linear search for now
824 {
825 if (f.ident == id)
826 {
827 fieldi = k;
828 si.addInit(id, di.initializer);
829 ++fieldi;
830 ++index;
831 continue Loop1;
832 }
833 }
834 error(ci.loc, "`.%s` is not a field of `%s`\n", id.toChars(), sd.toChars());
835 return err();
836 }
837
838 if (fieldi == nfields)
839 break;
840
841 auto ix = di.initializer;
842
843 /* If a C initializer is wrapped in a C initializer, with no designators,
844 * peel off the outer one
845 */
846 if (ix.isCInitializer())
847 {
848 CInitializer cix = ix.isCInitializer();
849 if (cix.initializerList.length == 1)
850 {
851 DesigInit dix = cix.initializerList[0];
852 if (!dix.designatorList)
853 {
854 Initializer inix = dix.initializer;
855 if (inix.isCInitializer())
856 ix = inix;
857 }
858 }
859 }
860
861 if (auto cix = ix.isCInitializer())
862 {
863 /* ImportC loses the structure from anonymous structs, but this is retained
864 * by the initializer syntax. if a CInitializer has a Designator, it is probably
865 * a nested anonymous struct
866 */
867 int found;
868 foreach (dix; cix.initializerList)
869 {
870 Designators* dlistx = dix.designatorList;
871 if (!dlistx)
872 continue;
873 if ((*dlistx).length == 1 && (*dlistx)[0].ident)
874 {
875 auto id = (*dlistx)[0].ident;
876 foreach (k, f; sd.fields[]) // linear search for now
877 {
878 if (f.ident == id)
879 {
880 fieldi = k;
881 si.addInit(id, dix.initializer);
882 ++fieldi;
883 ++index;
884 ++found;
885 break;
886 }
887 }
888 }
889 else {
890 error(ci.loc, "only 1 designator currently allowed for C struct field initializer `%s`", toChars(ci));
891 }
892 }
893
894 if (found == cix.initializerList.length)
895 continue Loop1;
896 }
897
898 VarDeclaration field;
899 while (1) // skip field if it overlaps with previously seen fields
900 {
901 field = sd.fields[fieldi];
902 ++fieldi;
903 if (!overlaps(field, sd.fields[], si))
904 break;
905 if (fieldi == nfields)
906 break;
907 }
908
909 auto tn = field.type.toBasetype();
910 auto tnsa = tn.isTypeSArray();
911 auto tns = tn.isTypeStruct();
912
913 if (tnsa && ix.isExpInitializer())
914 {
915 ExpInitializer ei = ix.isExpInitializer();
916 if (ei.exp.isStringExp() && tnsa.nextOf().isIntegral())
917 {
918 si.addInit(field.ident, ei);
919 ++index;
920 }
921 else
922 si.addInit(field.ident, subArray(tnsa, index));
923 }
924 else if (tns && ix.isExpInitializer())
925 {
926 /* Disambiguate between an exp representing the entire
927 * struct, and an exp representing the first field of the struct
928 */
929 if (representsStruct(ix.isExpInitializer(), tns)) // initializer represents the entire struct
930 {
931 si.addInit(field.ident, initializerSemantic(ix, sc, tn, needInterpret));
932 ++index;
933 }
934 else // field initializers for struct
935 si.addInit(field.ident, subStruct(tns, index)); // the first field
936 }
937 else
938 {
939 si.addInit(field.ident, di.initializer);
940 ++index;
941 }
942 }
943 return initializerSemantic(si, sc, t, needInterpret);
944 }
945 else if (auto ta = t.isTypeSArray())
946 {
947 auto tn = t.nextOf().toBasetype(); // element type of array
948
949 /* If it's an array of integral being initialized by `{ string }`
950 * replace with `string`
951 */
952 if (tn.isIntegral())
953 {
954 if (ExpInitializer ei = isBraceExpression())
955 {
956 if (ei.exp.isStringExp())
957 return ei.initializerSemantic(sc, t, needInterpret);
958 }
959 }
960
961 auto tnsa = tn.isTypeSArray(); // array of array
962 auto tns = tn.isTypeStruct(); // array of struct
963
964 auto ai = new ArrayInitializer(ci.loc);
965 ai.isCarray = true;
966 for (size_t index = 0; index < ci.initializerList.length; )
967 {
968 auto di = ci.initializerList[index];
969 if (auto dlist = di.designatorList)
970 {
971 const length = (*dlist).length;
972 if (length == 0 || !(*dlist)[0].exp)
973 {
974 error(ci.loc, "`[ constant-expression ]` expected for C array element initializer `%s`", toChars(ci));
975 return err();
976 }
977 if (length > 1)
978 {
979 error(ci.loc, "only 1 designator currently allowed for C array element initializer `%s`", toChars(ci));
980 return err();
981 }
982 //printf("tn: %s, di.initializer: %s\n", tn.toChars(), di.initializer.toChars());
983 auto ix = di.initializer;
984 if (tnsa && ix.isExpInitializer())
985 {
986 // Wrap initializer in [ ]
987 auto ain = new ArrayInitializer(ci.loc);
988 ain.addInit(null, di.initializer);
989 ix = ain;
990 ai.addInit((*dlist)[0].exp, initializerSemantic(ix, sc, tn, needInterpret));
991 ++index;
992 }
993 else if (tns && ix.isExpInitializer())
994 {
995 /* Disambiguate between an exp representing the entire
996 * struct, and an exp representing the first field of the struct
997 */
998 if (representsStruct(ix.isExpInitializer(), tns)) // initializer represents the entire struct
999 {
1000 ai.addInit((*dlist)[0].exp, initializerSemantic(ix, sc, tn, needInterpret));
1001 ++index;
1002 }
1003 else // field initializers for struct
1004 ai.addInit((*dlist)[0].exp, subStruct(tns, index)); // the first field
1005 }
1006 else
1007 {
1008 ai.addInit((*dlist)[0].exp, initializerSemantic(ix, sc, tn, needInterpret));
1009 ++index;
1010 }
1011 }
1012 else if (tnsa && di.initializer.isExpInitializer())
1013 {
1014 ExpInitializer ei = di.initializer.isExpInitializer();
1015 if (ei.exp.isStringExp() && tnsa.nextOf().isIntegral())
1016 {
1017 ai.addInit(null, ei);
1018 ++index;
1019 }
1020 else
1021 ai.addInit(null, subArray(tnsa, index));
1022 }
1023 else if (tns && di.initializer.isExpInitializer())
1024 {
1025 /* Disambiguate between an exp representing the entire
1026 * struct, and an exp representing the first field of the struct
1027 */
1028 if (representsStruct(di.initializer.isExpInitializer(), tns)) // initializer represents the entire struct
1029 {
1030 ai.addInit(null, initializerSemantic(di.initializer, sc, tn, needInterpret));
1031 ++index;
1032 }
1033 else // field initializers for struct
1034 ai.addInit(null, subStruct(tns, index)); // the first field
1035 }
1036 else
1037 {
1038 ai.addInit(null, initializerSemantic(di.initializer, sc, tn, needInterpret));
1039 ++index;
1040 }
1041 }
1042 return initializerSemantic(ai, sc, tx, needInterpret);
1043 }
1044 else if (ExpInitializer ei = isBraceExpression())
1045 {
1046 return visitExp(ei);
1047 }
1048 else
1049 {
1050 error(ci.loc, "unrecognized C initializer `%s` for type `%s`", toChars(ci), t.toChars());
1051 return err();
1052 }
1053 }
1054
1055 mixin VisitInitializer!Initializer visit;
1056 auto result = visit.VisitInitializer(init);
1057 result.semanticDone = true;
1058 return (result !is null) ? result : new ErrorInitializer();
1059 }
1060
1061 /***********************
1062 * Translate init to an `Expression` in order to infer the type.
1063 * Params:
1064 * init = `Initializer` AST node
1065 * sc = context
1066 * Returns:
1067 * an equivalent `ExpInitializer` if successful, or `ErrorInitializer` if it cannot be translated
1068 */
1069 Initializer inferType(Initializer init, Scope* sc)
1070 {
1071 Initializer visitVoid(VoidInitializer i)
1072 {
1073 error(i.loc, "cannot infer type from void initializer");
1074 return new ErrorInitializer();
1075 }
1076
1077 Initializer visitDefault(DefaultInitializer i)
1078 {
1079 error(i.loc, "cannot infer type from default initializer");
1080 return new ErrorInitializer();
1081 }
1082
1083 Initializer visitError(ErrorInitializer i)
1084 {
1085 return i;
1086 }
1087
1088 Initializer visitStruct(StructInitializer i)
1089 {
1090 error(i.loc, "cannot infer type from struct initializer");
1091 return new ErrorInitializer();
1092 }
1093
1094 Initializer visitArray(ArrayInitializer init)
1095 {
1096 //printf("ArrayInitializer::inferType() %s\n", toChars());
1097 Expressions* keys = null;
1098 Expressions* values = new Expressions(init.value.length);
1099 Initializer no()
1100 {
1101 if (keys)
1102 error(init.loc, "not an associative array initializer");
1103 else
1104 error(init.loc, "cannot infer type from array initializer");
1105 return new ErrorInitializer();
1106 }
1107 const bool isAssoc = init.isAssociativeArray();
1108 if (isAssoc)
1109 keys = new Expressions(init.value.length);
1110 else
1111 values.zero();
1112
1113 for (size_t i = 0; i < init.value.length; i++)
1114 {
1115 if (isAssoc)
1116 {
1117 Expression e = init.index[i];
1118 if (!e)
1119 return no();
1120 (*keys)[i] = e;
1121 }
1122 else
1123 assert(!init.index[i]); // already asserted by isAssociativeArray()
1124 Initializer iz = init.value[i];
1125 if (!iz)
1126 return no();
1127 iz = iz.inferType(sc);
1128 if (iz.isErrorInitializer())
1129 {
1130 return iz;
1131 }
1132 (*values)[i] = iz.isExpInitializer().exp;
1133 assert(!(*values)[i].isErrorExp());
1134 }
1135
1136 Expression e;
1137 e = isAssoc
1138 ? new AssocArrayLiteralExp(init.loc, keys, values)
1139 : new ArrayLiteralExp(init.loc, null, values);
1140 auto ei = new ExpInitializer(init.loc, e);
1141 return ei.inferType(sc);
1142 }
1143
1144 Initializer visitExp(ExpInitializer init)
1145 {
1146 //printf("ExpInitializer::inferType() %s\n", init.toChars());
1147 init.exp = init.exp.expressionSemantic(sc);
1148
1149 // for static alias this: https://issues.dlang.org/show_bug.cgi?id=17684
1150 if (init.exp.op == EXP.type)
1151 init.exp = resolveAliasThis(sc, init.exp);
1152
1153 init.exp = resolveProperties(sc, init.exp);
1154 if (auto se = init.exp.isScopeExp())
1155 {
1156 TemplateInstance ti = se.sds.isTemplateInstance();
1157 if (ti && ti.semanticRun == PASS.semantic && !ti.aliasdecl)
1158 error(se.loc, "cannot infer type from %s `%s`, possible circular dependency", se.sds.kind(), se.toChars());
1159 else
1160 error(se.loc, "cannot infer type from %s `%s`", se.sds.kind(), se.toChars());
1161 return new ErrorInitializer();
1162 }
1163
1164 // Give error for overloaded function addresses
1165 bool hasOverloads;
1166 if (auto f = isFuncAddress(init.exp, &hasOverloads))
1167 {
1168 if (checkForwardRef(f, init.loc))
1169 {
1170 return new ErrorInitializer();
1171 }
1172 if (hasOverloads && !f.isUnique())
1173 {
1174 error(init.exp.loc, "cannot infer type from overloaded function symbol `%s`", init.exp.toChars());
1175 return new ErrorInitializer();
1176 }
1177 }
1178 if (auto ae = init.exp.isAddrExp())
1179 {
1180 if (ae.e1.op == EXP.overloadSet)
1181 {
1182 error(init.exp.loc, "cannot infer type from overloaded function symbol `%s`", init.exp.toChars());
1183 return new ErrorInitializer();
1184 }
1185 }
1186 if (init.exp.isErrorExp())
1187 {
1188 return new ErrorInitializer();
1189 }
1190 if (!init.exp.type)
1191 {
1192 return new ErrorInitializer();
1193 }
1194 return init;
1195 }
1196
1197 Initializer visitC(CInitializer i)
1198 {
1199 //printf("CInitializer.inferType()\n");
1200 error(i.loc, "TODO C inferType initializers not supported yet");
1201 return new ErrorInitializer();
1202 }
1203
1204 mixin VisitInitializer!Initializer visit;
1205 auto result = visit.VisitInitializer(init);
1206 return (result !is null) ? result : new ErrorInitializer();
1207 }
1208
1209 /***********************
1210 * Translate init to an `Expression`.
1211 * Params:
1212 * init = `Initializer` AST node
1213 * itype = if not `null`, type to coerce expression to
1214 * isCfile = default initializers are different with C
1215 * Returns:
1216 * `Expression` created, `null` if cannot, `ErrorExp` for other errors
1217 */
1218 Expression initializerToExpression(Initializer init, Type itype = null, const bool isCfile = false)
1219 {
1220 //printf("initializerToExpression() isCfile: %d\n", isCfile);
1221
1222 Expression visitVoid(VoidInitializer)
1223 {
1224 return null;
1225 }
1226
1227 Expression visitDefault(DefaultInitializer di)
1228 {
1229 return di.type ? di.type.defaultInit(Loc.initial, isCfile) : null;
1230 }
1231
1232 Expression visitError(ErrorInitializer)
1233 {
1234 return ErrorExp.get();
1235 }
1236
1237 /***************************************
1238 * This works by transforming a struct initializer into
1239 * a struct literal. In the future, the two should be the
1240 * same thing.
1241 */
1242 Expression visitStruct(StructInitializer)
1243 {
1244 // cannot convert to an expression without target 'ad'
1245 return null;
1246 }
1247
1248 /********************************
1249 * If possible, convert array initializer to array literal.
1250 * Otherwise return NULL.
1251 */
1252 Expression visitArray(ArrayInitializer init)
1253 {
1254 //printf("ArrayInitializer::toExpression(), dim = %d\n", dim);
1255 //static int i; if (++i == 2) assert(0);
1256 uint edim; // the length of the resulting array literal
1257 const(uint) amax = 0x80000000;
1258 Type t = null; // type of the array literal being initialized
1259 if (init.type)
1260 {
1261 if (init.type == Type.terror)
1262 {
1263 return ErrorExp.get();
1264 }
1265 t = init.type.toBasetype();
1266 switch (t.ty)
1267 {
1268 case Tvector:
1269 t = t.isTypeVector().basetype;
1270 goto case Tsarray;
1271
1272 case Tsarray:
1273 uinteger_t adim = t.isTypeSArray().dim.toInteger();
1274 if (adim >= amax)
1275 return null;
1276 edim = cast(uint)adim;
1277 break;
1278
1279 case Tpointer:
1280 case Tarray:
1281 edim = init.dim;
1282 break;
1283
1284 default:
1285 assert(0);
1286 }
1287 }
1288 else
1289 {
1290 /* Calculate the length of the array literal
1291 */
1292 edim = cast(uint)init.value.length;
1293 size_t j = 0;
1294 foreach (i; 0 .. init.value.length)
1295 {
1296 if (auto e = init.index[i])
1297 {
1298 if (e.op == EXP.int64)
1299 {
1300 const uinteger_t idxval = e.toInteger();
1301 if (idxval >= amax)
1302 return null;
1303 j = cast(size_t)idxval;
1304 }
1305 else
1306 return null;
1307 }
1308 ++j;
1309 if (j > edim)
1310 edim = cast(uint)j;
1311 }
1312 }
1313
1314 auto elements = new Expressions(edim);
1315 elements.zero();
1316 size_t j = 0;
1317 foreach (i; 0 .. init.value.length)
1318 {
1319 if (auto e = init.index[i])
1320 j = cast(size_t)e.toInteger();
1321 assert(j < edim);
1322 if (Initializer iz = init.value[i])
1323 {
1324 if (Expression ex = iz.initializerToExpression(null, isCfile))
1325 {
1326 (*elements)[j] = ex;
1327 ++j;
1328 }
1329 else
1330 return null;
1331 }
1332 else
1333 return null;
1334 }
1335
1336 /* Fill in any missing elements with the default initializer
1337 */
1338 Expression defaultInit = null; // lazily create it
1339 foreach (ref element; (*elements)[0 .. edim])
1340 {
1341 if (!element)
1342 {
1343 if (!init.type) // don't know what type to use
1344 return null;
1345 if (!defaultInit)
1346 defaultInit = (cast(TypeNext)t).next.defaultInit(Loc.initial, isCfile);
1347 element = defaultInit;
1348 }
1349 }
1350
1351 /* Expand any static array initializers that are a single expression
1352 * into an array of them
1353 * e => [e, e, ..., e, e]
1354 */
1355 if (t)
1356 {
1357 Type tn = t.nextOf().toBasetype();
1358 if (tn.ty == Tsarray)
1359 {
1360 const dim = cast(size_t)(cast(TypeSArray)tn).dim.toInteger();
1361 Type te = tn.nextOf().toBasetype();
1362 foreach (ref e; *elements)
1363 {
1364 if (te.equals(e.type))
1365 {
1366 auto elements2 = new Expressions(dim);
1367 foreach (ref e2; *elements2)
1368 e2 = e;
1369 e = new ArrayLiteralExp(e.loc, tn, elements2);
1370 }
1371 }
1372 }
1373 }
1374
1375 /* If any elements are errors, then the whole thing is an error
1376 */
1377 foreach (e; (*elements)[0 .. edim])
1378 {
1379 if (e.op == EXP.error)
1380 {
1381 return e;
1382 }
1383 }
1384
1385 Expression e = new ArrayLiteralExp(init.loc, init.type, elements);
1386 return e;
1387 }
1388
1389 Expression visitExp(ExpInitializer i)
1390 {
1391 if (itype)
1392 {
1393 //printf("ExpInitializer::toExpression(t = %s) exp = %s\n", itype.toChars(), i.exp.toChars());
1394 Type tb = itype.toBasetype();
1395 Expression e = (i.exp.op == EXP.construct || i.exp.op == EXP.blit) ? (cast(AssignExp)i.exp).e2 : i.exp;
1396 if (tb.ty == Tsarray && e.implicitConvTo(tb.nextOf()))
1397 {
1398 TypeSArray tsa = cast(TypeSArray)tb;
1399 size_t d = cast(size_t)tsa.dim.toInteger();
1400 auto elements = new Expressions(d);
1401 for (size_t j = 0; j < d; j++)
1402 (*elements)[j] = e;
1403 auto ae = new ArrayLiteralExp(e.loc, itype, elements);
1404 return ae;
1405 }
1406 }
1407 return i.exp;
1408 }
1409
1410 Expression visitC(CInitializer i)
1411 {
1412 //printf("CInitializer.initializerToExpression(null, true)\n");
1413 return null;
1414 }
1415
1416 mixin VisitInitializer!Expression visit;
1417 return visit.VisitInitializer(init);
1418 }
1419
1420
1421 /**************************************
1422 * Determine if expression has non-constant pointers, or more precisely,
1423 * a pointer that CTFE cannot handle.
1424 * Params:
1425 * e = expression to check
1426 * Returns:
1427 * true if it has non-constant pointers
1428 */
1429 private bool hasNonConstPointers(Expression e)
1430 {
1431 static bool checkArray(Expressions* elems)
1432 {
1433 foreach (e; *elems)
1434 {
1435 if (e && hasNonConstPointers(e))
1436 return true;
1437 }
1438 return false;
1439 }
1440
1441 if (e.type.ty == Terror)
1442 return false;
1443 if (e.op == EXP.null_)
1444 return false;
1445 if (auto se = e.isStructLiteralExp())
1446 {
1447 return checkArray(se.elements);
1448 }
1449 if (auto ae = e.isArrayLiteralExp())
1450 {
1451 if (!ae.type.nextOf().hasPointers())
1452 return false;
1453 return checkArray(ae.elements);
1454 }
1455 if (auto ae = e.isAssocArrayLiteralExp())
1456 {
1457 if (ae.type.nextOf().hasPointers() && checkArray(ae.values))
1458 return true;
1459 if (ae.type.isTypeAArray().index.hasPointers())
1460 return checkArray(ae.keys);
1461 return false;
1462 }
1463 if (auto ae = e.isAddrExp())
1464 {
1465 if (ae.type.nextOf().isImmutable() || ae.type.nextOf().isConst())
1466 {
1467 return false;
1468 }
1469 if (auto se = ae.e1.isStructLiteralExp())
1470 {
1471 if (!(se.stageflags & StructLiteralExp.StageFlags.searchPointers))
1472 {
1473 const old = se.stageflags;
1474 se.stageflags |= StructLiteralExp.StageFlags.searchPointers;
1475 bool ret = checkArray(se.elements);
1476 se.stageflags = old;
1477 return ret;
1478 }
1479 else
1480 {
1481 return false;
1482 }
1483 }
1484 return true;
1485 }
1486 if (e.type.ty == Tpointer && !e.type.isPtrToFunction())
1487 {
1488 if (e.op == EXP.symbolOffset) // address of a global is OK
1489 return false;
1490 if (e.op == EXP.int64) // cast(void *)int is OK
1491 return false;
1492 if (e.op == EXP.string_) // "abc".ptr is OK
1493 return false;
1494 return true;
1495 }
1496 return false;
1497 }
1498
1499 /**
1500 Given the names and values of a `StructInitializer` or `CallExp`,
1501 resolve it to a list of expressions to construct a `StructLiteralExp`.
1502
1503 Params:
1504 sd = struct
1505 t = type of struct (potentially including qualifiers such as `const` or `immutable`)
1506 sc = scope of the expression initializing the struct
1507 iloc = location of expression initializing the struct
1508 names = identifiers passed in argument list, `null` entries for positional arguments
1509 getExp = function that, given an index into `names` and destination type, returns the initializing expression
1510 getLoc = function that, given an index into `names`, returns a location for error messages
1511
1512 Returns: list of expressions ordered to the struct's fields, or `null` on error
1513 */
1514 Expressions* resolveStructLiteralNamedArgs(StructDeclaration sd, Type t, Scope* sc,
1515 Loc iloc, Identifier[] names, scope Expression delegate(size_t i, Type fieldType) getExp,
1516 scope Loc delegate(size_t i) getLoc
1517 )
1518 {
1519 //expandTuples for non-identity arguments?
1520 const nfields = sd.nonHiddenFields();
1521 auto elements = new Expressions(nfields);
1522 auto elems = (*elements)[];
1523 foreach (ref elem; elems)
1524 elem = null;
1525
1526 // Run semantic for explicitly given initializers
1527 // TODO: this part is slightly different from StructLiteralExp::semantic.
1528 bool errors = false;
1529 size_t fieldi = 0;
1530 foreach (j, id; names)
1531 {
1532 const argLoc = getLoc(j);
1533 if (id)
1534 {
1535 // Determine `fieldi` that `id` matches
1536 Dsymbol s = sd.search(iloc, id);
1537 if (!s)
1538 {
1539 s = sd.search_correct(id);
1540 if (s)
1541 error(argLoc, "`%s` is not a member of `%s`, did you mean %s `%s`?", id.toChars(), sd.toChars(), s.kind(), s.toChars());
1542 else
1543 error(argLoc, "`%s` is not a member of `%s`", id.toChars(), sd.toChars());
1544 return null;
1545 }
1546 s.checkDeprecated(iloc, sc);
1547 s = s.toAlias();
1548
1549 // Find out which field index `s` is
1550 for (fieldi = 0; 1; fieldi++)
1551 {
1552 if (fieldi >= nfields)
1553 {
1554 error(iloc, "`%s.%s` is not a per-instance initializable field", sd.toChars(), s.toChars());
1555 return null;
1556 }
1557 if (s == sd.fields[fieldi])
1558 break;
1559 }
1560 }
1561 if (nfields == 0)
1562 {
1563 error(argLoc, "initializer provided for struct `%s` with no fields", sd.toChars());
1564 return null;
1565 }
1566 if (j >= nfields)
1567 {
1568 error(argLoc, "too many initializers for `%s` with %d field%s", sd.toChars(),
1569 cast(int) nfields, nfields != 1 ? "s".ptr : "".ptr);
1570 return null;
1571 }
1572 if (fieldi >= nfields)
1573 {
1574 error(argLoc, "trying to initialize past the last field `%s` of `%s`", sd.fields[nfields - 1].toChars(), sd.toChars());
1575 return null;
1576 }
1577
1578 VarDeclaration vd = sd.fields[fieldi];
1579 if (elems[fieldi])
1580 {
1581 error(argLoc, "duplicate initializer for field `%s`", vd.toChars());
1582 errors = true;
1583 elems[fieldi] = ErrorExp.get(); // for better diagnostics on multiple errors
1584 ++fieldi;
1585 continue;
1586 }
1587
1588 // Check for @safe violations
1589 if (vd.type.hasPointers)
1590 {
1591 if ((!t.alignment.isDefault() && t.alignment.get() < target.ptrsize ||
1592 (vd.offset & (target.ptrsize - 1))))
1593 {
1594 if (sc.setUnsafe(false, argLoc,
1595 "field `%s.%s` assigning to misaligned pointers", sd, vd))
1596 {
1597 errors = true;
1598 elems[fieldi] = ErrorExp.get(); // for better diagnostics on multiple errors
1599 ++fieldi;
1600 continue;
1601 }
1602 }
1603 }
1604
1605 // Check for overlapping initializations (can happen with unions)
1606 foreach (k, v2; sd.fields[0 .. nfields])
1607 {
1608 if (vd.isOverlappedWith(v2) && elems[k])
1609 {
1610 error(elems[k].loc, "overlapping initialization for field `%s` and `%s`", v2.toChars(), vd.toChars());
1611 enum errorMsg = "`struct` initializers that contain anonymous unions" ~
1612 " must initialize only the first member of a `union`. All subsequent" ~
1613 " non-overlapping fields are default initialized";
1614 if (!sd.isUnionDeclaration())
1615 .errorSupplemental(elems[k].loc, errorMsg);
1616 errors = true;
1617 continue;
1618 }
1619 }
1620
1621 assert(sc);
1622
1623 auto ex = getExp(j, vd.type);
1624
1625 if (ex.op == EXP.error)
1626 {
1627 errors = true;
1628 elems[fieldi] = ErrorExp.get(); // for better diagnostics on multiple errors
1629 ++fieldi;
1630 continue;
1631 }
1632
1633 elems[fieldi] = doCopyOrMove(sc, ex, null, false);
1634 ++fieldi;
1635 }
1636 if (errors)
1637 return null;
1638
1639 return elements;
1640 }