Debian Codegraph @

gcc/d/dmd/clone.d

raw
1 /**
2 * Builds struct member functions if needed and not defined by the user.
3 * Includes `opEquals`, `opAssign`, post blit, copy constructor and destructor.
4 *
5 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
6 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
7 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
8 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/clone.d, _clone.d)
9 * Documentation: https://dlang.org/phobos/dmd_clone.html
10 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/clone.d
11 */
12
13 module dmd.clone;
14
15 import core.stdc.stdio;
16 import dmd.aggregate;
17 import dmd.arraytypes;
18 import dmd.astenums;
19 import dmd.dclass;
20 import dmd.declaration;
21 import dmd.dscope;
22 import dmd.dstruct;
23 import dmd.dsymbol;
24 import dmd.dsymbolsem;
25 import dmd.dtemplate;
26 import dmd.errors;
27 import dmd.expression;
28 import dmd.expressionsem;
29 import dmd.func;
30 import dmd.funcsem;
31 import dmd.globals;
32 import dmd.id;
33 import dmd.identifier;
34 import dmd.init;
35 import dmd.location;
36 import dmd.mtype;
37 import dmd.opover;
38 import dmd.semantic2;
39 import dmd.semantic3;
40 import dmd.statement;
41 import dmd.target;
42 import dmd.typesem;
43 import dmd.tokens;
44
45 /*******************************************
46 * Merge function attributes pure, nothrow, @safe, @nogc, and @disable
47 * from f into s1.
48 * Params:
49 * s1 = storage class to merge into
50 * f = function
51 * Returns:
52 * merged storage class
53 */
54 STC mergeFuncAttrs(STC s1, const FuncDeclaration f) pure @safe
55 {
56 if (!f)
57 return s1;
58 STC s2 = (f.storage_class & STC.disable);
59
60 auto tf = f.type.isTypeFunction();
61 if (tf.trust == TRUST.safe)
62 s2 |= STC.safe;
63 else if (tf.trust == TRUST.system)
64 s2 |= STC.system;
65 else if (tf.trust == TRUST.trusted)
66 s2 |= STC.trusted;
67
68 if (tf.purity != PURE.impure)
69 s2 |= STC.pure_;
70 if (tf.isNothrow)
71 s2 |= STC.nothrow_;
72 if (tf.isNogc)
73 s2 |= STC.nogc;
74
75 const sa = s1 & s2;
76 const so = s1 | s2;
77
78 STC stc = (sa & (STC.pure_ | STC.nothrow_ | STC.nogc)) | (so & STC.disable);
79
80 if (so & STC.system)
81 stc |= STC.system;
82 else if (sa & STC.trusted)
83 stc |= STC.trusted;
84 else if ((so & (STC.trusted | STC.safe)) == (STC.trusted | STC.safe))
85 stc |= STC.trusted;
86 else if (sa & STC.safe)
87 stc |= STC.safe;
88
89 return stc;
90 }
91
92 /*******************************************
93 * Check given aggregate actually has an identity opAssign or not.
94 * Params:
95 * ad = struct or class
96 * sc = current scope
97 * Returns:
98 * if found, returns FuncDeclaration of opAssign, otherwise null
99 * References:
100 * https://dlang.org/spec/operatoroverloading.html#assignment
101 */
102 FuncDeclaration hasIdentityOpAssign(AggregateDeclaration ad, Scope* sc)
103 {
104 Dsymbol assign = search_function(ad, Id.opAssign);
105 if (!assign)
106 return null;
107
108 /* check identity opAssign exists
109 */
110 scope er = new NullExp(ad.loc, ad.type); // dummy rvalue
111 scope el = new IdentifierExp(ad.loc, Id.p); // dummy lvalue
112 el.type = ad.type;
113 const errors = global.startGagging(); // Do not report errors, even if the template opAssign fbody makes it.
114 sc = sc.push();
115 sc.tinst = null;
116 sc.minst = null;
117
118 auto a = new Expressions(1);
119 (*a)[0] = er;
120 auto f = resolveFuncCall(ad.loc, sc, assign, null, ad.type, ArgumentList(a), FuncResolveFlag.quiet);
121 if (!f)
122 {
123 (*a)[0] = el;
124 f = resolveFuncCall(ad.loc, sc, assign, null, ad.type, ArgumentList(a), FuncResolveFlag.quiet);
125 }
126
127 sc = sc.pop();
128 global.endGagging(errors);
129 if (!f)
130 return null;
131 if (f.errors)
132 return null;
133 auto fparams = f.getParameterList();
134 if (fparams.length)
135 {
136 auto fparam0 = fparams[0];
137 if (fparam0.type.toDsymbol(null) != ad)
138 f = null;
139 }
140 // BUGS: This detection mechanism cannot find some opAssign-s like follows:
141 // struct S { void opAssign(ref immutable S) const; }
142 return f;
143 }
144
145 /*******************************************
146 * We need an opAssign for the struct if
147 * it has a destructor or a postblit.
148 * (We will later generate one if a user-specified one does not exist)
149 * Params:
150 * sd = struct to check
151 * Returns:
152 * true if an opAssign is needed
153 */
154 private bool needOpAssign(StructDeclaration sd)
155 {
156 //printf("StructDeclaration::needOpAssign() %s\n", sd.toChars());
157
158 static bool isNeeded()
159 {
160 //printf("\tneed\n");
161 return true;
162 }
163
164 if (sd.isUnionDeclaration())
165 return !isNeeded();
166
167 if (sd.hasIdentityAssign || // because has identity==elaborate opAssign
168 sd.dtor ||
169 sd.postblit)
170 return isNeeded();
171
172 /* If any of the fields need an opAssign, then we
173 * need it too.
174 */
175 foreach (v; sd.fields)
176 {
177 if (v.storage_class & STC.ref_)
178 continue;
179 if (v.overlapped) // if field of a union
180 continue; // user must handle it themselves
181 Type tv = v.type.baseElemOf();
182 if (auto ts = tv.isTypeStruct())
183 {
184 if (ts.sym.isUnionDeclaration())
185 continue;
186 if (needOpAssign(ts.sym))
187 return isNeeded();
188 }
189 }
190 return !isNeeded();
191 }
192
193 /******************************************
194 * Build opAssign for a `struct`.
195 *
196 * The generated `opAssign` function has the following signature:
197 *---
198 *ref S opAssign(S s) // S is the name of the `struct`
199 *---
200 *
201 * The opAssign function will be built for a struct `S` if the
202 * following constraints are met:
203 *
204 * 1. `S` does not have an identity `opAssign` defined.
205 *
206 * 2. `S` has at least one of the following members: a postblit (user-defined or
207 * generated for fields that have a defined postblit), a destructor
208 * (user-defined or generated for fields that have a defined destructor)
209 * or at least one field that has a defined `opAssign`.
210 *
211 * 3. `S` does not have any non-mutable fields.
212 *
213 * If `S` has a disabled destructor or at least one field that has a disabled
214 * `opAssign`, `S.opAssign` is going to be generated, but marked with `@disable`
215 *
216 * If `S` defines a destructor, the generated code for `opAssign` is:
217 *
218 *---
219 *S __swap = void;
220 *__swap = this; // bit copy
221 *this = s; // bit copy
222 *__swap.dtor();
223 *---
224 *
225 * Otherwise, if `S` defines a postblit, the generated code for `opAssign` is:
226 *
227 *---
228 *this = s;
229 *---
230 *
231 * Note that the parameter to the generated `opAssign` is passed by value, which means
232 * that the postblit is going to be called (if it is defined) in both of the above
233 * situations before entering the body of `opAssign`. The assignments in the above generated
234 * function bodies are blit expressions, so they can be regarded as `memcpy`s
235 * (`opAssign` is not called as this will result in an infinite recursion; the postblit
236 * is not called because it has already been called when the parameter was passed by value).
237 *
238 * If `S` does not have a postblit or a destructor, but contains at least one field that defines
239 * an `opAssign` function (which is not disabled), then the body will make member-wise
240 * assignments:
241 *
242 *---
243 *this.field1 = s.field1;
244 *this.field2 = s.field2;
245 *...;
246 *---
247 *
248 * In this situation, the assignemnts are actual assign expressions (`opAssign` is used
249 * if defined).
250 *
251 * References:
252 * https://dlang.org/spec/struct.html#assign-overload
253 * Params:
254 * sd = struct to generate opAssign for
255 * sc = context
256 * Returns:
257 * generated `opAssign` function, or null if it is not needed
258 */
259 FuncDeclaration buildOpAssign(StructDeclaration sd, Scope* sc)
260 {
261 if (FuncDeclaration f = hasIdentityOpAssign(sd, sc))
262 {
263 sd.hasIdentityAssign = true;
264 return f;
265 }
266 // Even if non-identity opAssign is defined, built-in identity opAssign
267 // will be defined.
268 if (!needOpAssign(sd))
269 return null;
270
271 //printf("StructDeclaration::buildOpAssign() %s\n", sd.toChars());
272 STC stc = STC.safe;
273 Loc declLoc = sd.loc;
274 Loc loc; // internal code should have no loc to prevent coverage
275
276 // One of our sub-field might have `@disable opAssign` so we need to
277 // check for it.
278 // In this event, it will be reflected by having `stc` (opAssign's
279 // storage class) include `STC.disabled`.
280 foreach (v; sd.fields)
281 {
282 if (v.storage_class & STC.ref_)
283 continue;
284 if (v.overlapped)
285 continue;
286 Type tv = v.type.baseElemOf();
287 if (auto tvs = tv.isTypeStruct())
288 {
289 stc = mergeFuncAttrs(stc, hasIdentityOpAssign(tvs.sym, sc));
290 }
291 }
292
293 if (sd.dtor || sd.postblit)
294 {
295 // if the type is not assignable, we cannot generate opAssign
296 if (!sd.type.isAssignable()) // https://issues.dlang.org/show_bug.cgi?id=13044
297 return null;
298 stc = mergeFuncAttrs(stc, sd.dtor);
299 if (stc & STC.safe)
300 stc = (stc & ~STC.safe) | STC.trusted;
301 }
302
303 auto fparams = new Parameters();
304 fparams.push(new Parameter(loc, STC.nodtor, sd.type, Id.p, null, null));
305 auto tf = new TypeFunction(ParameterList(fparams), sd.handleType(), LINK.d, stc | STC.ref_);
306 auto fop = new FuncDeclaration(declLoc, Loc.initial, Id.opAssign, stc, tf);
307 fop.storage_class |= STC.inference;
308 fop.isGenerated = true;
309 Expression e;
310 if (stc & STC.disable)
311 {
312 e = null;
313 }
314 /* Do swap this and rhs.
315 * __swap = this; this = s; __swap.dtor();
316 */
317 else if (sd.dtor)
318 {
319 //printf("\tswap copy\n");
320 auto tdtor = sd.dtor.type.isTypeFunction();
321
322 auto idswap = Identifier.generateId("__swap");
323 auto swap = new VarDeclaration(loc, sd.type, idswap, new VoidInitializer(loc));
324 swap.storage_class |= STC.nodtor | STC.temp | STC.ctfe;
325 if (tdtor.isScopeQual)
326 swap.storage_class |= STC.scope_;
327 auto e1 = new DeclarationExp(loc, swap);
328
329 auto e2 = new BlitExp(loc, new VarExp(loc, swap), new ThisExp(loc));
330 auto e3 = new BlitExp(loc, new ThisExp(loc), new IdentifierExp(loc, Id.p));
331
332 Expression e4;
333 if (target.isCalleeDestroyingArgs(tf))
334 { /* callee destroys s
335 * Instead of running the destructor on s, run it
336 * on swap.
337 */
338 e4 = new CallExp(loc, new DotVarExp(loc, new VarExp(loc, swap), sd.dtor, false));
339 }
340 else
341 { /* caller destroys s, so copy contents of swap back into s
342 */
343 e4 = new BlitExp(loc, new IdentifierExp(loc, Id.p), new VarExp(loc, swap));
344 }
345
346 e = Expression.combine(e1, e2, e3, e4);
347 }
348 /* postblit was called when the value was passed to opAssign, we just need to blit the result */
349 else if (sd.postblit)
350 {
351 e = new BlitExp(loc, new ThisExp(loc), new IdentifierExp(loc, Id.p));
352 sd.hasBlitAssign = true;
353 }
354 else
355 {
356 /* Do memberwise copy.
357 *
358 * If sd is a nested struct, its vthis field assignment is:
359 * 1. If it's nested in a class, it's a rebind of class reference.
360 * 2. If it's nested in a function or struct, it's an update of void*.
361 * In both cases, it will change the parent context.
362 */
363 //printf("\tmemberwise copy\n");
364 e = null;
365 foreach (v; sd.fields)
366 {
367 // this.v = s.v;
368 auto ec = new AssignExp(loc,
369 new DotVarExp(loc, new ThisExp(loc), v),
370 new DotVarExp(loc, new IdentifierExp(loc, Id.p), v));
371 e = Expression.combine(e, ec);
372 }
373 }
374 if (e)
375 {
376 Statement s1 = new ExpStatement(loc, e);
377 /* Add:
378 * return this;
379 */
380 auto er = new ThisExp(loc);
381 Statement s2 = new ReturnStatement(loc, er);
382 fop.fbody = new CompoundStatement(loc, s1, s2);
383 tf.isReturn = true;
384 }
385 sd.members.push(fop);
386 fop.addMember(sc, sd);
387 sd.hasIdentityAssign = true; // temporary mark identity assignable
388 const errors = global.startGagging(); // Do not report errors, even if the template opAssign fbody makes it.
389 Scope* sc2 = sc.push();
390 sc2.stc = STC.none;
391 sc2.linkage = LINK.d;
392 fop.dsymbolSemantic(sc2);
393 fop.semantic2(sc2);
394 // https://issues.dlang.org/show_bug.cgi?id=15044
395 //semantic3(fop, sc2); // isn't run here for lazy forward reference resolution.
396
397 sc2.pop();
398 if (global.endGagging(errors)) // if errors happened
399 {
400 // Disable generated opAssign, because some members forbid identity assignment.
401 fop.storage_class |= STC.disable;
402 fop.fbody = null; // remove fbody which contains the error
403 }
404
405 //printf("-StructDeclaration::buildOpAssign() %s, errors = %d\n", sd.toChars(), (fop.storage_class & STC.disable) != 0);
406 //printf("fop.type: %s\n", fop.type.toPrettyChars());
407 return fop;
408 }
409
410 /*******************************************
411 * We need an opEquals for the struct if
412 * any field has an opEquals and a user-specified one does not exist.
413 * Params:
414 * sd = struct to check
415 * Returns:
416 * true if need to generate one
417 */
418 bool needOpEquals(StructDeclaration sd)
419 {
420 bool dontneed()
421 {
422 //printf("\tdontneed\n");
423 return false;
424 }
425 bool need()
426 {
427 //printf("\tneed\n");
428 return true;
429 }
430 //printf("StructDeclaration::needOpEquals() %s\n", sd.toChars());
431 if (sd.isUnionDeclaration())
432 {
433 /* If a union has only one field, treat it like a struct
434 */
435 if (sd.fields.length != 1)
436 return dontneed();
437 }
438 if (sd.hasIdentityEquals)
439 return need();
440 /* If any of the fields has an opEquals, then we
441 * need it too.
442 */
443 foreach (VarDeclaration v; sd.fields)
444 {
445 if (v.storage_class & STC.ref_)
446 continue;
447 if (v.overlapped)
448 continue;
449 Type tv = v.type.toBasetype();
450 auto tvbase = tv.baseElemOf();
451 if (auto ts = tvbase.isTypeStruct())
452 {
453 if (ts.sym.isUnionDeclaration() && ts.sym.fields.length != 1)
454 continue;
455 if (needOpEquals(ts.sym))
456 return need();
457 }
458 if (tvbase.isFloating())
459 {
460 // This is necessray for:
461 // 1. comparison of +0.0 and -0.0 should be true.
462 // 2. comparison of NANs should be false always.
463 return need();
464 }
465 if (tvbase.ty == Tarray)
466 return need();
467 if (tvbase.ty == Taarray)
468 return need();
469 if (tvbase.ty == Tclass)
470 return need();
471 }
472 return dontneed();
473 }
474
475 /*******************************************
476 * Check given aggregate actually has an identity opEquals or not.
477 * ad = aggregate to check
478 * sc = context
479 * Returns:
480 * identity opEquals if it is there, null if not
481 */
482 private FuncDeclaration hasIdentityOpEquals(AggregateDeclaration ad, Scope* sc)
483 {
484 FuncDeclaration f;
485 Dsymbol eq = search_function(ad, Id.opEquals);
486 if (!eq)
487 return null;
488
489 /* check identity opEquals exists
490 */
491 scope er = new NullExp(ad.loc, null); // dummy rvalue
492 scope el = new IdentifierExp(ad.loc, Id.p); // dummy lvalue
493 auto a = new Expressions(1);
494
495 bool hasIt(Type tthis)
496 {
497 const errors = global.startGagging(); // Do not report errors, even if the template opAssign fbody makes it
498 sc = sc.push();
499 sc.tinst = null;
500 sc.minst = null;
501
502 FuncDeclaration rfc(Expression e)
503 {
504 (*a)[0] = e;
505 (*a)[0].type = tthis;
506 return resolveFuncCall(ad.loc, sc, eq, null, tthis, ArgumentList(a), FuncResolveFlag.quiet);
507 }
508
509 f = rfc(er);
510 if (!f)
511 f = rfc(el);
512
513 sc = sc.pop();
514 global.endGagging(errors);
515
516 return f !is null;
517 }
518
519 if (hasIt(ad.type) ||
520 hasIt(ad.type.constOf()) ||
521 hasIt(ad.type.immutableOf()) ||
522 hasIt(ad.type.sharedOf()) ||
523 hasIt(ad.type.sharedConstOf()))
524 {
525 if (f.errors)
526 return null;
527 }
528
529 return f;
530 }
531
532 /******************************************
533 * Build opEquals for struct.
534 * const bool opEquals(const S s) { ... }
535 *
536 * By fixing https://issues.dlang.org/show_bug.cgi?id=3789
537 * opEquals is changed to be never implicitly generated.
538 * Now, struct objects comparison s1 == s2 is translated to:
539 * s1.tupleof == s2.tupleof
540 * to calculate structural equality. See `opOverloadEquals`.
541 */
542 FuncDeclaration buildOpEquals(StructDeclaration sd, Scope* sc)
543 {
544 if (hasIdentityOpEquals(sd, sc))
545 {
546 sd.hasIdentityEquals = true;
547 }
548 return null;
549 }
550
551 /******************************************
552 * Build __xopEquals for TypeInfo_Struct
553 * bool __xopEquals(ref const S p) const
554 * {
555 * return this == p;
556 * }
557 *
558 * This is called by TypeInfo.equals(p1, p2). If the struct does not support
559 * const objects comparison, it will throw "not implemented" Error in runtime.
560 */
561 FuncDeclaration buildXopEquals(StructDeclaration sd, Scope* sc)
562 {
563 if (!needOpEquals(sd))
564 return null; // bitwise comparison would work
565
566 //printf("StructDeclaration::buildXopEquals() %s\n", sd.toChars());
567 if (Dsymbol eq = search_function(sd, Id.opEquals))
568 {
569 if (FuncDeclaration fd = eq.isFuncDeclaration())
570 {
571 TypeFunction tfeqptr;
572 {
573 Scope scx;
574 scx.eSink = sc.eSink;
575 /* const bool opEquals(ref const S s);
576 */
577 auto parameters = new Parameters();
578 parameters.push(new Parameter(Loc.initial, STC.ref_ | STC.const_, sd.type, null, null, null));
579 tfeqptr = new TypeFunction(ParameterList(parameters), Type.tbool, LINK.d);
580 tfeqptr.mod = MODFlags.const_;
581 tfeqptr = tfeqptr.typeSemantic(Loc.initial, &scx).isTypeFunction();
582 }
583 fd = fd.overloadExactMatch(tfeqptr);
584 if (fd)
585 return fd;
586 }
587 }
588 if (!sd.xerreq)
589 {
590 // object._xopEquals
591 Identifier id = Identifier.idPool("_xopEquals");
592 Expression e = new IdentifierExp(sd.loc, Id.empty);
593 e = new DotIdExp(sd.loc, e, Id.object);
594 e = new DotIdExp(sd.loc, e, id);
595 e = e.expressionSemantic(sc);
596 if (!e.isErrorExp())
597 {
598 Dsymbol s = getDsymbol(e);
599 assert(s);
600 sd.xerreq = s.isFuncDeclaration();
601 }
602 }
603 Loc declLoc; // loc is unnecessary so __xopEquals is never called directly
604 Loc loc; // loc is unnecessary so errors are gagged
605 auto parameters = new Parameters();
606 parameters.push(new Parameter(loc, STC.ref_ | STC.const_, sd.type, Id.p, null, null));
607 auto tf = new TypeFunction(ParameterList(parameters), Type.tbool, LINK.d, STC.const_);
608 tf = tf.addSTC(STC.const_).toTypeFunction();
609 Identifier id = Id.xopEquals;
610 auto fop = new FuncDeclaration(declLoc, Loc.initial, id, STC.none, tf);
611 fop.isGenerated = true;
612 fop.parent = sd;
613 Expression e1 = new IdentifierExp(loc, Id.This);
614 Expression e2 = new IdentifierExp(loc, Id.p);
615 Expression e = new EqualExp(EXP.equal, loc, e1, e2);
616 fop.fbody = new ReturnStatement(loc, e);
617 const errors = global.startGagging(); // Do not report errors
618 Scope* sc2 = sc.push();
619 sc2.stc = STC.none;
620 sc2.linkage = LINK.d;
621 fop.dsymbolSemantic(sc2);
622 fop.semantic2(sc2);
623 sc2.pop();
624 if (global.endGagging(errors)) // if errors happened
625 fop = sd.xerreq;
626 return fop;
627 }
628
629 /******************************************
630 * Build __xopCmp for TypeInfo_Struct
631 * int __xopCmp(ref const S p) const
632 * {
633 * return this.opCmp(p);
634 * }
635 *
636 * This is called by TypeInfo.compare(p1, p2). If the struct does not support
637 * const objects comparison, it will throw "not implemented" Error in runtime.
638 */
639 FuncDeclaration buildXopCmp(StructDeclaration sd, Scope* sc)
640 {
641 //printf("StructDeclaration::buildXopCmp() %s\n", toChars());
642 if (Dsymbol cmp = search_function(sd, Id.opCmp))
643 {
644 if (FuncDeclaration fd = cmp.isFuncDeclaration())
645 {
646 TypeFunction tfcmpptr;
647 {
648 Scope scx;
649 scx.eSink = sc.eSink;
650 /* const int opCmp(ref const S s);
651 */
652 auto parameters = new Parameters();
653 parameters.push(new Parameter(Loc.initial, STC.ref_ | STC.const_, sd.type, null, null, null));
654 tfcmpptr = new TypeFunction(ParameterList(parameters), Type.tint32, LINK.d);
655 tfcmpptr.mod = MODFlags.const_;
656 tfcmpptr = tfcmpptr.typeSemantic(Loc.initial, &scx).isTypeFunction();
657 }
658 if (auto fdo = fd.overloadExactMatch(tfcmpptr))
659 return fdo;
660 }
661 }
662 else
663 {
664 version (none) // FIXME: doesn't work for recursive alias this
665 {
666 /* Check opCmp member exists.
667 * Consider 'alias this', but except opDispatch.
668 */
669 Expression e = new DsymbolExp(sd.loc, sd);
670 e = new DotIdExp(sd.loc, e, Id.opCmp);
671 Scope* sc2 = sc.push();
672 e = e.trySemantic(sc2);
673 sc2.pop();
674 if (e)
675 {
676 Dsymbol s = null;
677 switch (e.op)
678 {
679 case EXP.overloadSet:
680 s = e.isOverExp().vars;
681 break;
682 case EXP.scope_:
683 s = e.isScopeExp().sds;
684 break;
685 case EXP.variable:
686 s = e.isVarExp().var;
687 break;
688 default:
689 break;
690 }
691 if (!s || s.ident != Id.opCmp)
692 e = null; // there's no valid member 'opCmp'
693 }
694 if (!e)
695 return null; // bitwise comparison would work
696 /* Essentially, a struct which does not define opCmp is not comparable.
697 * At this time, typeid(S).compare might be correct that throwing "not implement" Error.
698 * But implementing it would break existing code, such as:
699 *
700 * struct S { int value; } // no opCmp
701 * int[S] aa; // Currently AA key uses bitwise comparison
702 * // (It's default behavior of TypeInfo_Strust.compare).
703 *
704 * Not sure we should fix this inconsistency, so just keep current behavior.
705 */
706 }
707 else
708 {
709 return null;
710 }
711 }
712 if (!sd.xerrcmp)
713 {
714 // object._xopCmp
715 Identifier id = Identifier.idPool("_xopCmp");
716 Expression e = new IdentifierExp(sd.loc, Id.empty);
717 e = new DotIdExp(sd.loc, e, Id.object);
718 e = new DotIdExp(sd.loc, e, id);
719 e = e.expressionSemantic(sc);
720 if (!e.isErrorExp())
721 {
722 Dsymbol s = getDsymbol(e);
723 assert(s);
724 sd.xerrcmp = s.isFuncDeclaration();
725 }
726 }
727 Loc declLoc; // loc is unnecessary so __xopCmp is never called directly
728 Loc loc; // loc is unnecessary so errors are gagged
729 auto parameters = new Parameters();
730 parameters.push(new Parameter(loc, STC.ref_ | STC.const_, sd.type, Id.p, null, null));
731 auto tf = new TypeFunction(ParameterList(parameters), Type.tint32, LINK.d, STC.const_);
732 tf = tf.addSTC(STC.const_).toTypeFunction();
733 Identifier id = Id.xopCmp;
734 auto fop = new FuncDeclaration(declLoc, Loc.initial, id, STC.none, tf);
735 fop.isGenerated = true;
736 fop.parent = sd;
737 Expression e1 = new IdentifierExp(loc, Id.This);
738 Expression e2 = new IdentifierExp(loc, Id.p);
739 Expression e = new CallExp(loc, new DotIdExp(loc, e1, Id.opCmp), e2);
740 fop.fbody = new ReturnStatement(loc, e);
741 const errors = global.startGagging(); // Do not report errors
742 Scope* sc2 = sc.push();
743 sc2.stc = STC.none;
744 sc2.linkage = LINK.d;
745 fop.dsymbolSemantic(sc2);
746 fop.semantic2(sc2);
747 sc2.pop();
748 if (global.endGagging(errors)) // if errors happened
749 fop = sd.xerrcmp;
750 return fop;
751 }
752
753 /*******************************************
754 * We need a toHash for the struct if
755 * any fields has a toHash.
756 * (will generate one if a user-specified one does not exist)
757 * Params:
758 * sd = struct to check
759 * Returns:
760 * need to generate toHash()
761 * References:
762 * https://dlang.org/spec/hash-map.html#using_struct_as_key
763 */
764 private bool needToHash(StructDeclaration sd)
765 {
766 bool dontneed()
767 {
768 //printf("\tdontneed\n");
769 return false;
770 }
771 bool need()
772 {
773 //printf("\tneed\n");
774 return true;
775 }
776 //printf("StructDeclaration::needToHash() %s\n", sd.toChars());
777 if (sd.isUnionDeclaration())
778 return dontneed();
779 if (sd.xhash)
780 return need();
781
782 /* If any of the fields has an toHash, then we
783 * need it too.
784 */
785 foreach (VarDeclaration v; sd.fields)
786 {
787 if (v.storage_class & STC.ref_)
788 continue;
789 if (v.overlapped)
790 continue;
791 Type tv = v.type.toBasetype();
792 auto tvbase = tv.baseElemOf();
793 if (auto ts = tvbase.isTypeStruct())
794 {
795 if (ts.sym.isUnionDeclaration())
796 continue;
797 if (needToHash(ts.sym))
798 return need();
799 }
800 if (tvbase.isFloating())
801 {
802 /* This is necessary because comparison of +0.0 and -0.0 should be true,
803 * i.e. not a bit compare.
804 */
805 return need();
806 }
807 if (tvbase.ty == Tarray)
808 return need();
809 if (tvbase.ty == Taarray)
810 return need();
811 if (tvbase.ty == Tclass)
812 return need();
813 }
814 return dontneed();
815 }
816
817 /******************************************
818 * Build __xtoHash for non-bitwise hashing
819 * static hash_t xtoHash(ref const S p) nothrow @trusted;
820 */
821 FuncDeclaration buildXtoHash(StructDeclaration sd, Scope* sc)
822 {
823 if (Dsymbol s = search_function(sd, Id.tohash))
824 {
825 __gshared TypeFunction tftohash;
826 if (!tftohash)
827 {
828 tftohash = new TypeFunction(ParameterList(), Type.thash_t, LINK.d);
829 tftohash.mod = MODFlags.const_;
830 tftohash = tftohash.merge().isTypeFunction();
831 }
832 if (FuncDeclaration fd = s.isFuncDeclaration())
833 {
834 if (auto fdo = fd.overloadExactMatch(tftohash))
835 return fdo;
836 }
837 }
838 if (!needToHash(sd))
839 return null;
840
841 /* The trouble is that the following code relies on .tupleof, but .tupleof
842 * is not allowed for C files. If we allow it for C files, then that turns on
843 * the other D properties, too, such as .dup which will then conflict with allowed
844 * field names.
845 * One way to fix it is to replace the following foreach and .tupleof with C
846 * statements and expressions.
847 * But, it's debatable whether C structs should even need toHash().
848 * Note that it would only be necessary if it has floating point fields.
849 * For now, we'll just not generate a toHash() for C files.
850 */
851 if (sc.inCfile)
852 return null;
853
854 //printf("StructDeclaration::buildXtoHash() %s\n", sd.toPrettyChars());
855 Loc declLoc; // loc is unnecessary so __xtoHash is never called directly
856 Loc loc; // internal code should have no loc to prevent coverage
857 auto parameters = new Parameters();
858 parameters.push(new Parameter(loc, STC.ref_ | STC.const_, sd.type, Id.p, null, null));
859 auto tf = new TypeFunction(ParameterList(parameters), Type.thash_t, LINK.d, STC.nothrow_ | STC.trusted);
860 Identifier id = Id.xtoHash;
861 auto fop = new FuncDeclaration(declLoc, Loc.initial, id, STC.static_, tf);
862 fop.isGenerated = true;
863
864 /* Do memberwise hashing.
865 *
866 * If sd is a nested struct, and if it's nested in a class, the calculated
867 * hash value will also contain the result of parent class's toHash().
868 */
869 const(char)[] code =
870 ".object.size_t h = 0;" ~
871 "foreach (i, T; typeof(p.tupleof))" ~
872 // workaround https://issues.dlang.org/show_bug.cgi?id=17968
873 " static if(is(T* : const(.object.Object)*)) " ~
874 " h = h * 33 + typeid(const(.object.Object)).getHash(cast(const void*)&p.tupleof[i]);" ~
875 " else " ~
876 " h = h * 33 + typeid(T).getHash(cast(const void*)&p.tupleof[i]);" ~
877 "return h;";
878 fop.fbody = new MixinStatement(loc, new StringExp(loc, code));
879 Scope* sc2 = sc.push();
880 sc2.stc = STC.none;
881 sc2.linkage = LINK.d;
882 fop.dsymbolSemantic(sc2);
883 fop.semantic2(sc2);
884 sc2.pop();
885
886 //printf("%s fop = %s %s\n", sd.toChars(), fop.toChars(), fop.type.toChars());
887 return fop;
888 }
889
890 /*****************************************
891 * Create aggregate destructor for struct/class by aggregating
892 * all the destructors in userDtors[] with the destructors for
893 * all the members.
894 * Sets ad's fieldDtor, aggrDtor, dtor and tidtor fields.
895 * Params:
896 * ad = struct or class to build destructor for
897 * sc = context
898 * Note:
899 * Close similarity with StructDeclaration::buildPostBlit(),
900 * and the ordering changes (runs backward instead of forwards).
901 */
902 void buildDtors(AggregateDeclaration ad, Scope* sc)
903 {
904 //printf("AggregateDeclaration::buildDtor() %s\n", ad.toChars());
905 if (ad.isUnionDeclaration())
906 return; // unions don't have destructors
907
908 STC stc = STC.safe | STC.nothrow_ | STC.pure_ | STC.nogc;
909 Loc declLoc = ad.userDtors.length ? ad.userDtors[0].loc : ad.loc;
910 Loc loc; // internal code should have no loc to prevent coverage
911 FuncDeclaration xdtor_fwd = null;
912
913 // Build the field destructor (`ad.fieldDtor`), if needed.
914 // If the user dtor is an extern(C++) prototype, then we expect it performs a full-destruction and skip building.
915 const bool dtorIsCppPrototype = ad.userDtors.length && ad.userDtors[0]._linkage == LINK.cpp && !ad.userDtors[0].fbody;
916 if (!dtorIsCppPrototype)
917 {
918 Expression e = null;
919 for (size_t i = 0; i < ad.fields.length; i++)
920 {
921 auto v = ad.fields[i];
922 if (v.storage_class & STC.ref_)
923 continue;
924 if (v.overlapped)
925 continue;
926 auto tvs = v.type.baseElemOf().isTypeStruct();
927 if (!tvs)
928 continue;
929 auto sdv = tvs.sym;
930 if (!sdv.dtor)
931 continue;
932
933 // fix: https://issues.dlang.org/show_bug.cgi?id=17257
934 // braces for shrink wrapping scope of a
935 {
936 xdtor_fwd = sdv.dtor; // this dtor is temporary it could be anything
937 auto a = new AliasDeclaration(Loc.initial, Id.__xdtor, xdtor_fwd);
938 a.addMember(sc, ad); // temporarily add to symbol table
939 }
940
941 functionSemantic(sdv.dtor);
942
943 stc = mergeFuncAttrs(stc, sdv.dtor);
944 if (stc & STC.disable)
945 {
946 e = null;
947 break;
948 }
949
950 Expression ex;
951 Type tv = v.type.toBasetype();
952 if (tv.isTypeStruct())
953 {
954 // this.v.__xdtor()
955
956 ex = new ThisExp(loc);
957 ex = new DotVarExp(loc, ex, v);
958
959 // This is a hack so we can call destructors on const/immutable objects.
960 // Do it as a type 'paint', `cast()`
961 ex = new CastExp(loc, ex, MODFlags.none);
962 if (stc & STC.safe)
963 stc = (stc & ~STC.safe) | STC.trusted;
964
965 ex = new DotVarExp(loc, ex, sdv.dtor, false);
966 ex = new CallExp(loc, ex);
967 }
968 else
969 {
970 // __ArrayDtor((cast(S*)this.v.ptr)[0 .. n])
971
972 const n = tv.numberOfElems(loc);
973 if (n == 0)
974 continue;
975
976 ex = new ThisExp(loc);
977 ex = new DotVarExp(loc, ex, v);
978
979 // This is a hack so we can call destructors on const/immutable objects.
980 ex = new DotIdExp(loc, ex, Id.ptr);
981 ex = new CastExp(loc, ex, sdv.type.pointerTo());
982 if (stc & STC.safe)
983 stc = (stc & ~STC.safe) | STC.trusted;
984
985 SliceExp se = new SliceExp(loc, ex, new IntegerExp(loc, 0, Type.tsize_t),
986 new IntegerExp(loc, n, Type.tsize_t));
987 // Prevent redundant bounds check
988 se.upperIsInBounds = true;
989 se.lowerIsLessThanUpper = true;
990
991 ex = new CallExp(loc, new IdentifierExp(loc, Id.__ArrayDtor), se);
992 }
993 e = Expression.combine(ex, e); // combine in reverse order
994 }
995
996 if (e || (stc & STC.disable))
997 {
998 //printf("Building __fieldDtor(), %s\n", e.toChars());
999 auto dd = new DtorDeclaration(declLoc, Loc.initial, stc, Id.__fieldDtor);
1000 dd.isGenerated = true;
1001 dd.storage_class |= STC.inference;
1002 dd.fbody = new ExpStatement(loc, e);
1003 ad.members.push(dd);
1004 dd.dsymbolSemantic(sc);
1005 ad.fieldDtor = dd;
1006 }
1007 }
1008
1009 // Generate list of dtors to call in that order
1010 DtorDeclarations dtors;
1011 foreach_reverse (userDtor; ad.userDtors[])
1012 dtors.push(userDtor);
1013 if (ad.fieldDtor)
1014 dtors.push(ad.fieldDtor);
1015 if (!dtorIsCppPrototype)
1016 {
1017 // extern(C++) destructors call into super to destruct the full hierarchy
1018 ClassDeclaration cldec = ad.isClassDeclaration();
1019 if (cldec && cldec.classKind == ClassKind.cpp && cldec.baseClass && cldec.baseClass.aggrDtor)
1020 dtors.push(cldec.baseClass.aggrDtor);
1021 }
1022
1023 // Set/build `ad.aggrDtor`
1024 switch (dtors.length)
1025 {
1026 case 0:
1027 break;
1028
1029 case 1:
1030 // Use the single existing dtor directly as aggregate dtor.
1031 // Note that this might be `cldec.baseClass.aggrDtor`.
1032 ad.aggrDtor = dtors[0];
1033 break;
1034
1035 default:
1036 // Build the aggregate destructor, calling all dtors in order.
1037 assert(!dtorIsCppPrototype);
1038 Expression e = null;
1039 e = null;
1040 stc = STC.safe | STC.nothrow_ | STC.pure_ | STC.nogc;
1041 foreach (FuncDeclaration fd; dtors)
1042 {
1043 stc = mergeFuncAttrs(stc, fd);
1044 if (stc & STC.disable)
1045 {
1046 e = null;
1047 break;
1048 }
1049 Expression ex = new ThisExp(loc);
1050 ex = new DotVarExp(loc, ex, fd, false);
1051 CallExp ce = new CallExp(loc, ex);
1052 ce.directcall = true;
1053 e = Expression.combine(e, ce);
1054 }
1055 auto dd = new DtorDeclaration(declLoc, Loc.initial, stc, Id.__aggrDtor);
1056 dd.isGenerated = true;
1057 dd.storage_class |= STC.inference;
1058 dd.fbody = new ExpStatement(loc, e);
1059 ad.members.push(dd);
1060 dd.dsymbolSemantic(sc);
1061 ad.aggrDtor = dd;
1062 break;
1063 }
1064
1065 // Set/build `ad.dtor`.
1066 // On Windows, the dtor in the vtable is a shim with different signature.
1067 ad.dtor = (ad.aggrDtor && ad.aggrDtor._linkage == LINK.cpp && !target.cpp.twoDtorInVtable)
1068 ? buildWindowsCppDtor(ad, ad.aggrDtor, sc)
1069 : ad.aggrDtor;
1070
1071 // Add an __xdtor alias to make `ad.dtor` accessible
1072 if (ad.dtor)
1073 {
1074 auto _alias = new AliasDeclaration(Loc.initial, Id.__xdtor, ad.dtor);
1075 _alias.dsymbolSemantic(sc);
1076 ad.members.push(_alias);
1077 if (xdtor_fwd)
1078 ad.symtab.update(_alias); // update forward dtor to correct one
1079 else
1080 _alias.addMember(sc, ad); // add to symbol table
1081 }
1082
1083 // Set/build `ad.tidtor`
1084 ad.tidtor = buildExternDDtor(ad, sc);
1085 }
1086
1087 /**
1088 * build a shim function around the compound dtor that accepts an argument
1089 * that is used to implement the deleting C++ destructor
1090 *
1091 * Params:
1092 * ad = the aggregate that contains the destructor to wrap
1093 * dtor = the destructor to wrap
1094 * sc = the scope in which to analyze the new function
1095 *
1096 * Returns:
1097 * the shim destructor, semantically analyzed and added to the class as a member
1098 */
1099 private DtorDeclaration buildWindowsCppDtor(AggregateDeclaration ad, DtorDeclaration dtor, Scope* sc)
1100 {
1101 auto cldec = ad.isClassDeclaration();
1102 if (!cldec || cldec.cppDtorVtblIndex == -1) // scalar deleting dtor not built for non-virtual dtors
1103 return dtor; // perhaps also do this if STC.scope_ is set
1104
1105 // generate deleting C++ destructor corresponding to:
1106 // void* C::~C(int del)
1107 // {
1108 // this->~C();
1109 // // TODO: if (del) delete (char*)this;
1110 // return (void*) this;
1111 // }
1112 Parameter delparam = new Parameter(Loc.initial, STC.none, Type.tuns32, Identifier.idPool("del"), new IntegerExp(dtor.loc, 0, Type.tuns32), null);
1113 Parameters* params = new Parameters;
1114 params.push(delparam);
1115 const stc = dtor.storage_class & ~STC.scope_; // because we add the `return this;` later
1116 auto ftype = new TypeFunction(ParameterList(params), Type.tvoidptr, LINK.cpp, stc);
1117 auto func = new DtorDeclaration(dtor.loc, dtor.loc, stc, Id.cppdtor);
1118 func.type = ftype;
1119
1120 // Always generate the function with body, because it is not exported from DLLs.
1121 const loc = dtor.loc;
1122 auto stmts = new Statements;
1123 auto call = new CallExp(loc, dtor, null);
1124 call.directcall = true;
1125 stmts.push(new ExpStatement(loc, call));
1126 stmts.push(new ReturnStatement(loc, new CastExp(loc, new ThisExp(loc), Type.tvoidptr)));
1127 func.fbody = new CompoundStatement(loc, stmts);
1128 func.isGenerated = true;
1129
1130 auto sc2 = sc.push();
1131 sc2.stc &= ~STC.static_; // not a static destructor
1132 sc2.linkage = LINK.cpp;
1133
1134 ad.members.push(func);
1135 func.addMember(sc2, ad);
1136 func.dsymbolSemantic(sc2);
1137
1138 sc2.pop();
1139 return func;
1140 }
1141
1142 /**
1143 * build a shim function around the aggregate dtor that translates
1144 * a C++ destructor to a destructor with extern(D) calling convention
1145 *
1146 * Params:
1147 * ad = the aggregate that contains the destructor to wrap
1148 * sc = the scope in which to analyze the new function
1149 *
1150 * Returns:
1151 * the shim destructor, semantically analyzed and added to the class as a member
1152 */
1153 private DtorDeclaration buildExternDDtor(AggregateDeclaration ad, Scope* sc)
1154 {
1155 auto dtor = ad.aggrDtor;
1156 if (!dtor)
1157 return null;
1158
1159 // Don't try to call `@disable`d dtors
1160 if (dtor.storage_class & STC.disable)
1161 return null;
1162
1163 // Generate shim only when ABI incompatible on target platform
1164 if (dtor._linkage != LINK.cpp || !target.cpp.wrapDtorInExternD)
1165 return dtor;
1166
1167 // generate member function that adjusts calling convention
1168 // (EAX used for 'this' instead of ECX on Windows/stack on others):
1169 // extern(D) void __ticppdtor()
1170 // {
1171 // Class.__dtor();
1172 // }
1173 auto ftype = new TypeFunction(ParameterList(), Type.tvoid, LINK.d, dtor.storage_class);
1174 auto func = new DtorDeclaration(dtor.loc, dtor.loc, dtor.storage_class, Id.ticppdtor);
1175 func.type = ftype;
1176
1177 auto call = new CallExp(dtor.loc, dtor, null);
1178 call.directcall = true; // non-virtual call Class.__dtor();
1179 func.fbody = new ExpStatement(dtor.loc, call);
1180 func.isGenerated = true;
1181 func.storage_class |= STC.inference;
1182
1183 auto sc2 = sc.push();
1184 sc2.stc &= ~STC.static_; // not a static destructor
1185 sc2.linkage = LINK.d;
1186
1187 ad.members.push(func);
1188 func.addMember(sc2, ad);
1189 func.dsymbolSemantic(sc2);
1190 functionSemantic(func); // to infer attributes
1191
1192 sc2.pop();
1193 return func;
1194 }
1195
1196 /******************************************
1197 * Create inclusive invariant for struct/class by aggregating
1198 * all the invariants in invs[].
1199 * ---
1200 * void __invariant() const [pure nothrow @trusted]
1201 * {
1202 * invs[0](), invs[1](), ...;
1203 * }
1204 * ---
1205 * Params:
1206 * ad = aggregate for creating invariant
1207 * sc = context
1208 * Returns:
1209 * generated invariant, null if not needed
1210 * References:
1211 * https://dlang.org/spec/class.html#invariants
1212 * https://dlang.org/spec/struct.html#Invariant
1213 */
1214 FuncDeclaration buildInv(AggregateDeclaration ad, Scope* sc)
1215 {
1216 switch (ad.invs.length)
1217 {
1218 case 0:
1219 return null;
1220
1221 case 1:
1222 // Don't return invs[0] so it has uniquely generated name.
1223 goto default;
1224
1225 default:
1226 Expression e = null;
1227 STC stcx = STC.none;
1228 STC stc = STC.safe | STC.nothrow_ | STC.pure_ | STC.nogc;
1229 foreach (i, inv; ad.invs)
1230 {
1231 stc = mergeFuncAttrs(stc, inv);
1232 if (stc & STC.disable)
1233 {
1234 // What should do?
1235 }
1236 const stcy = (inv.storage_class & STC.synchronized_) |
1237 (inv.type.mod & MODFlags.shared_ ? STC.shared_ : STC.none);
1238 if (i == 0)
1239 stcx = stcy;
1240 else if (stcx ^ stcy)
1241 {
1242 version (all)
1243 {
1244 // currently rejects
1245 .error(inv.loc, "%s `%s` mixing invariants with different `shared`/`synchronized` qualifiers is not supported", ad.kind(), ad.toPrettyChars());
1246 e = null;
1247 break;
1248 }
1249 }
1250 e = Expression.combine(e, new CallExp(Loc.initial, new VarExp(Loc.initial, inv, false)));
1251 }
1252 auto inv = new InvariantDeclaration(ad.loc, Loc.initial, stc | stcx,
1253 Id.classInvariant, new ExpStatement(Loc.initial, e));
1254 ad.members.push(inv);
1255 inv.dsymbolSemantic(sc);
1256 return inv;
1257 }
1258 }
1259
1260 /*****************************************
1261 * Create inclusive postblit for struct by aggregating
1262 * all the postblits in postblits[] with the postblits for
1263 * all the members.
1264 * Note the close similarity with AggregateDeclaration::buildDtor(),
1265 * and the ordering changes (runs forward instead of backwards).
1266 * Params:
1267 * sd = struct to create postblit for
1268 * sc = context
1269 * Returns:
1270 * generated postblit, or null if not
1271 */
1272 FuncDeclaration buildPostBlit(StructDeclaration sd, Scope* sc)
1273 {
1274 //printf("buildPostBlit() %s\n", sd.toChars());
1275 if (sd.isUnionDeclaration())
1276 return null;
1277
1278 const hasUserDefinedPosblit = sd.postblits.length && !sd.postblits[0].isDisabled ? true : false;
1279
1280 // by default, the storage class of the created postblit
1281 STC stc = STC.safe;
1282 Loc declLoc = sd.postblits.length ? sd.postblits[0].loc : sd.loc;
1283 Loc loc; // internal code should have no loc to prevent coverage
1284
1285 // if any of the postblits are disabled, then the generated postblit
1286 // will be disabled
1287 foreach (postblit; sd.postblits)
1288 stc |= postblit.storage_class & STC.disable;
1289
1290 VarDeclaration[] fieldsToDestroy;
1291 auto postblitCalls = new Statements();
1292 // iterate through all the struct fields that are not disabled
1293 for (size_t i = 0; i < sd.fields.length && !(stc & STC.disable); i++)
1294 {
1295 auto structField = sd.fields[i];
1296 if (structField.storage_class & STC.ref_)
1297 continue;
1298 if (structField.overlapped)
1299 continue;
1300 // if it's a struct declaration or an array of structs
1301 TypeStruct tvs = structField.type.baseElemOf().isTypeStruct();
1302 if (!tvs)
1303 continue;
1304 auto sdv = tvs.sym;
1305 // which has a postblit declaration
1306 if (!sdv.postblit)
1307 continue;
1308 assert(!sdv.isUnionDeclaration());
1309
1310 // if this field's postblit is not `nothrow`, add a `scope(failure)`
1311 // block to destroy any prior successfully postblitted fields should
1312 // this field's postblit fail.
1313 // Don't generate it for betterC code since it cannot throw exceptions.
1314 if (fieldsToDestroy.length > 0 && !sdv.postblit.type.isTypeFunction().isNothrow && global.params.useExceptions)
1315 {
1316 // create a list of destructors that need to be called
1317 Expression[] dtorCalls;
1318 foreach(sf; fieldsToDestroy)
1319 {
1320 Expression ex;
1321 Type tv = sf.type.toBasetype();
1322 if (auto tvs2 = tv.isTypeStruct())
1323 {
1324 // this.v.__xdtor()
1325
1326 ex = new ThisExp(loc);
1327 ex = new DotVarExp(loc, ex, sf);
1328
1329 // This is a hack so we can call destructors on const/immutable objects.
1330 ex = new AddrExp(loc, ex);
1331 ex = new CastExp(loc, ex, sf.type.mutableOf().pointerTo());
1332 ex = new PtrExp(loc, ex);
1333 if (stc & STC.safe)
1334 stc = (stc & ~STC.safe) | STC.trusted;
1335
1336 ex = new DotVarExp(loc, ex, tvs2.sym.dtor, false);
1337 ex = new CallExp(loc, ex);
1338
1339 dtorCalls ~= ex;
1340 }
1341 else
1342 {
1343 // _ArrayDtor((cast(S*)this.v.ptr)[0 .. n])
1344
1345 const length = tv.numberOfElems(loc);
1346
1347 ex = new ThisExp(loc);
1348 ex = new DotVarExp(loc, ex, sf);
1349
1350 // This is a hack so we can call destructors on const/immutable objects.
1351 ex = new DotIdExp(loc, ex, Id.ptr);
1352 ex = new CastExp(loc, ex, sdv.type.pointerTo());
1353 if (stc & STC.safe)
1354 stc = (stc & ~STC.safe) | STC.trusted;
1355
1356 auto se = new SliceExp(loc, ex, new IntegerExp(loc, 0, Type.tsize_t),
1357 new IntegerExp(loc, length, Type.tsize_t));
1358 // Prevent redundant bounds check
1359 se.upperIsInBounds = true;
1360 se.lowerIsLessThanUpper = true;
1361
1362 ex = new CallExp(loc, new IdentifierExp(loc, Id.__ArrayDtor), se);
1363
1364 dtorCalls ~= ex;
1365 }
1366 }
1367 fieldsToDestroy = [];
1368
1369 // aggregate the destructor calls
1370 auto dtors = new Statements();
1371 foreach_reverse(dc; dtorCalls)
1372 {
1373 dtors.push(new ExpStatement(loc, dc));
1374 }
1375
1376 // put destructor calls in a `scope(failure)` block
1377 postblitCalls.push(new ScopeGuardStatement(loc, TOK.onScopeFailure, new CompoundStatement(loc, dtors)));
1378 }
1379
1380 // perform semantic on the member postblit in order to
1381 // be able to aggregate it later on with the rest of the
1382 // postblits
1383 sdv.postblit.isGenerated = true;
1384 functionSemantic(sdv.postblit);
1385
1386 stc = mergeFuncAttrs(stc, sdv.postblit);
1387 stc = mergeFuncAttrs(stc, sdv.dtor);
1388
1389 // if any of the struct member fields has disabled
1390 // its postblit, then `sd` is not copyable, so no
1391 // postblit is generated
1392 if (stc & STC.disable)
1393 {
1394 postblitCalls.setDim(0);
1395 break;
1396 }
1397
1398 Expression ex;
1399 Type tv = structField.type.toBasetype();
1400 if (tv.isTypeStruct())
1401 {
1402 // this.v.__xpostblit()
1403
1404 ex = new ThisExp(loc);
1405 ex = new DotVarExp(loc, ex, structField);
1406
1407 // This is a hack so we can call postblits on const/immutable objects.
1408 ex = new AddrExp(loc, ex);
1409 ex = new CastExp(loc, ex, structField.type.mutableOf().pointerTo());
1410 ex = new PtrExp(loc, ex);
1411 if (stc & STC.safe)
1412 stc = (stc & ~STC.safe) | STC.trusted;
1413
1414 ex = new DotVarExp(loc, ex, sdv.postblit, false);
1415 ex = new CallExp(loc, ex);
1416 }
1417 else
1418 {
1419 // _ArrayPostblit((cast(S*)this.v.ptr)[0 .. n])
1420
1421 const length = tv.numberOfElems(loc);
1422 if (length == 0)
1423 continue;
1424
1425 ex = new ThisExp(loc);
1426 ex = new DotVarExp(loc, ex, structField);
1427
1428 // This is a hack so we can call postblits on const/immutable objects.
1429 ex = new DotIdExp(loc, ex, Id.ptr);
1430 ex = new CastExp(loc, ex, sdv.type.pointerTo());
1431 if (stc & STC.safe)
1432 stc = (stc & ~STC.safe) | STC.trusted;
1433
1434 auto se = new SliceExp(loc, ex, new IntegerExp(loc, 0, Type.tsize_t),
1435 new IntegerExp(loc, length, Type.tsize_t));
1436 // Prevent redundant bounds check
1437 se.upperIsInBounds = true;
1438 se.lowerIsLessThanUpper = true;
1439 ex = new CallExp(loc, new IdentifierExp(loc, Id.__ArrayPostblit), se);
1440 }
1441 postblitCalls.push(new ExpStatement(loc, ex)); // combine in forward order
1442
1443 /* https://issues.dlang.org/show_bug.cgi?id=10972
1444 * When subsequent field postblit calls fail,
1445 * this field should be destructed for Exception Safety.
1446 */
1447 if (sdv.dtor)
1448 {
1449 sdv.dtor.isGenerated = true;
1450 functionSemantic(sdv.dtor);
1451
1452 // keep a list of fields that need to be destroyed in case
1453 // of a future postblit failure
1454 fieldsToDestroy ~= structField;
1455 }
1456 }
1457
1458 void checkShared()
1459 {
1460 if (sd.type.isShared())
1461 stc |= STC.shared_;
1462 }
1463
1464 // Build our own "postblit" which executes a, but only if needed.
1465 if (postblitCalls.length || (stc & STC.disable))
1466 {
1467 //printf("Building __fieldPostBlit()\n");
1468 checkShared();
1469 auto dd = new PostBlitDeclaration(declLoc, Loc.initial, stc, Id.__fieldPostblit);
1470 dd.isGenerated = true;
1471 dd.storage_class |= STC.inference | STC.scope_;
1472 dd.fbody = (stc & STC.disable) ? null : new CompoundStatement(loc, postblitCalls);
1473 sd.postblits.shift(dd);
1474 sd.members.push(dd);
1475 dd.dsymbolSemantic(sc);
1476 }
1477
1478 // create __xpostblit, which is the generated postblit
1479 FuncDeclaration xpostblit = null;
1480 switch (sd.postblits.length)
1481 {
1482 case 0:
1483 break;
1484
1485 case 1:
1486 xpostblit = sd.postblits[0];
1487 break;
1488
1489 default:
1490 Expression e = null;
1491 stc = STC.safe | STC.nothrow_ | STC.pure_ | STC.nogc;
1492 foreach (fd; sd.postblits)
1493 {
1494 stc = mergeFuncAttrs(stc, fd);
1495 if (stc & STC.disable)
1496 {
1497 e = null;
1498 break;
1499 }
1500 Expression ex = new ThisExp(loc);
1501 ex = new DotVarExp(loc, ex, fd, false);
1502 ex = new CallExp(loc, ex);
1503 e = Expression.combine(e, ex);
1504 }
1505
1506 checkShared();
1507 auto dd = new PostBlitDeclaration(declLoc, Loc.initial, stc, Id.__aggrPostblit);
1508 dd.isGenerated = true;
1509 dd.storage_class |= STC.inference;
1510 dd.fbody = new ExpStatement(loc, e);
1511 sd.members.push(dd);
1512 dd.dsymbolSemantic(sc);
1513 xpostblit = dd;
1514 break;
1515 }
1516
1517 // Add an __xpostblit alias to make the inclusive postblit accessible
1518 if (xpostblit)
1519 {
1520 auto _alias = new AliasDeclaration(Loc.initial, Id.__xpostblit, xpostblit);
1521 _alias.dsymbolSemantic(sc);
1522 sd.members.push(_alias);
1523 _alias.addMember(sc, sd); // add to symbol table
1524 }
1525
1526 if (sd.hasCopyCtor)
1527 {
1528 // we have user defined postblit, so we prioritize it
1529 if (hasUserDefinedPosblit)
1530 {
1531 sd.hasCopyCtor = false;
1532 return xpostblit;
1533 }
1534 // we have fields with postblits, so print deprecations
1535 if (xpostblit && !xpostblit.isDisabled())
1536 {
1537 deprecation(sd.loc, "`struct %s` implicitly-generated postblit hides copy constructor.", sd.toChars);
1538 deprecationSupplemental(sd.loc, "The field postblit will have priority over the copy constructor.");
1539 deprecationSupplemental(sd.loc, "To change this, the postblit should be disabled for `struct %s`", sd.toChars());
1540 sd.hasCopyCtor = false;
1541 }
1542 else
1543 xpostblit = null;
1544 }
1545
1546 return xpostblit;
1547 }
1548
1549 /**
1550 * Generates a copy or move constructor declaration with the specified storage
1551 * class for the parameter and the function.
1552 *
1553 * Params:
1554 * sd = the `struct` that contains the constructor
1555 * paramStc = the storage class of the constructor parameter
1556 * funcStc = the storage class for the constructor declaration
1557 * move = true for move constructor, false for copy constructor
1558 *
1559 * Returns:
1560 * The copy constructor declaration for struct `sd`.
1561 */
1562 private CtorDeclaration generateCtorDeclaration(StructDeclaration sd, const STC paramStc, const STC funcStc, bool move)
1563 {
1564 auto fparams = new Parameters();
1565 auto structType = sd.type;
1566 STC stc = move ? STC.none : STC.ref_; // the only difference between copy or move
1567 fparams.push(new Parameter(Loc.initial, paramStc | stc, structType, Id.p, null, null));
1568 ParameterList pList = ParameterList(fparams);
1569 auto tf = new TypeFunction(pList, structType, LINK.d, STC.ref_);
1570 auto ccd = new CtorDeclaration(sd.loc, Loc.initial, STC.ref_, tf);
1571 ccd.storage_class |= funcStc;
1572 ccd.storage_class |= STC.inference;
1573 ccd.isGenerated = true;
1574 return ccd;
1575 }
1576
1577 /**
1578 * Generates a trivial copy or move constructor body that simply does memberwise
1579 * initialization.
1580 *
1581 * for copy construction:
1582 * this.field1 = rhs.field1;
1583 * this.field2 = rhs.field2;
1584 * ...
1585 * for move construction:
1586 * this.field1 = __rvalue(rhs.field1);
1587 * this.field2 = __rvalue(rhs.field2);
1588 * ...
1589 *
1590 * Params:
1591 * sd = the `struct` declaration that contains the constructor
1592 * move = true for move constructor, false for copy constructor
1593 *
1594 * Returns:
1595 * A `CompoundStatement` containing the body of the constructor.
1596 */
1597 private Statement generateCtorBody(StructDeclaration sd, bool move)
1598 {
1599 Loc loc;
1600 Expression e;
1601 foreach (v; sd.fields)
1602 {
1603 Expression rhs = new DotVarExp(loc, new IdentifierExp(loc, Id.p), v);
1604 if (move)
1605 rhs.rvalue = true;
1606 auto ec = new AssignExp(loc,
1607 new DotVarExp(loc, new ThisExp(loc), v),
1608 rhs);
1609 e = Expression.combine(e, ec);
1610 //printf("e.toChars = %s\n", e.toChars());
1611 }
1612 Statement s1 = new ExpStatement(loc, e);
1613 return new CompoundStatement(loc, s1);
1614 }
1615
1616 /******************************************
1617 * Find root `this` constructor for struct sd.
1618 * (root is starting position for overloaded constructors)
1619 * Params:
1620 * sd = the `struct` to be searched
1621 * ctor = `this` if found, otherwise null
1622 * Result:
1623 * false means `this` found in overload set
1624 */
1625 private bool findStructConstructorRoot(StructDeclaration sd, out Dsymbol ctor)
1626 {
1627 ctor = sd.search(sd.loc, Id.ctor); // Aggregate.searchCtor() ?
1628 if (ctor)
1629 {
1630 if (ctor.isOverloadSet())
1631 return false;
1632 if (auto td = ctor.isTemplateDeclaration())
1633 ctor = td.funcroot;
1634 }
1635 return true;
1636 }
1637
1638 /***********************************************
1639 * Find move and copy constructors (if any) starting at `ctor`
1640 * Params:
1641 * ctor = `this` constructor root
1642 * copyCtor = set to first copy constructor found, or null
1643 * moveCtor = set to first move constructor found, or null
1644 */
1645 private void findMoveAndCopyConstructors(Dsymbol ctor, out CtorDeclaration copyCtor, out CtorDeclaration moveCtor)
1646 {
1647 overloadApply(ctor, (Dsymbol s)
1648 {
1649 if (s.isTemplateDeclaration())
1650 return 0;
1651 auto ctorDecl = s.isCtorDeclaration();
1652 assert(ctorDecl);
1653 if (ctorDecl.isCpCtor)
1654 {
1655 if (!copyCtor)
1656 copyCtor = ctorDecl;
1657 }
1658 else if (ctorDecl.isMoveCtor)
1659 {
1660 if (!moveCtor)
1661 moveCtor = ctorDecl;
1662 }
1663 return 0;
1664 });
1665 }
1666
1667 /**
1668 * Determine if a copy constructor is needed for struct sd,
1669 * if the following conditions are met:
1670 *
1671 * 1. sd does not define a copy constructor
1672 * 2. at least one field of sd defines a copy constructor
1673 *
1674 * Params:
1675 * sd = the `struct` for which the copy constructor is generated
1676 * hasCopyCtor = set to true if a copy constructor is already present
1677 * hasMoveCtor = set to true if a move constructor is already present
1678 * needCopyCtor = set to true if a copy constructor is not present, but needed
1679 * needMoveCtor = set to true if a move constructor is not present, but needed
1680 *
1681 * Returns:
1682 * `true` if one needs to be generated
1683 * `false` otherwise
1684 */
1685 void needCopyOrMoveCtor(StructDeclaration sd, out bool hasCopyCtor, out bool hasMoveCtor, out bool needCopyCtor, out bool needMoveCtor)
1686 {
1687 //printf("needCopyOrMoveCtor() %s\n", sd.toChars());
1688 if (global.errors)
1689 return;
1690
1691 Dsymbol ctor;
1692 if (!findStructConstructorRoot(sd, ctor))
1693 return;
1694
1695 CtorDeclaration copyCtor;
1696 CtorDeclaration moveCtor;
1697
1698 if (ctor)
1699 findMoveAndCopyConstructors(ctor, copyCtor, moveCtor);
1700
1701 if (moveCtor)
1702 hasMoveCtor = true;
1703
1704 if (copyCtor)
1705 hasCopyCtor = true;
1706
1707 if (hasMoveCtor && hasCopyCtor)
1708 return;
1709
1710 VarDeclaration fieldWithCpCtor;
1711 VarDeclaration fieldWithMoveCtor;
1712 // see if any struct members define a copy constructor
1713 foreach (v; sd.fields)
1714 {
1715 if (v.storage_class & STC.ref_)
1716 continue;
1717 if (v.overlapped)
1718 continue;
1719
1720 auto ts = v.type.baseElemOf().isTypeStruct();
1721 if (!ts)
1722 continue;
1723 if (ts.sym.hasCopyCtor)
1724 {
1725 fieldWithCpCtor = v;
1726 }
1727 if (ts.sym.hasMoveCtor)
1728 {
1729 fieldWithMoveCtor = v;
1730 }
1731 }
1732
1733 if (0 && fieldWithCpCtor && moveCtor)
1734 {
1735 .error(sd.loc, "`struct %s` may not define a rvalue constructor and have fields with copy constructors", sd.toChars());
1736 errorSupplemental(moveCtor.loc,"rvalue constructor defined here");
1737 errorSupplemental(fieldWithCpCtor.loc, "field with copy constructor defined here");
1738 return;
1739 }
1740
1741 if (fieldWithCpCtor && !hasCopyCtor)
1742 needCopyCtor = true;
1743 if (fieldWithMoveCtor && !hasMoveCtor)
1744 needMoveCtor = true;
1745 }
1746
1747 /**
1748 * Generates a copy constructor if needCopyCtor() returns true.
1749 * The generated copy constructor will be of the form:
1750 * this(ref return scope inout(S) rhs) inout
1751 * {
1752 * this.field1 = rhs.field1;
1753 * this.field2 = rhs.field2;
1754 * ...
1755 * }
1756 *
1757 * Params:
1758 * sd = the `struct` for which the constructor is generated
1759 * sc = the scope where the constructor is generated
1760 * move = true means generate the move constructor, otherwise copy constructor
1761 * References:
1762 * https://dlang.org/spec/struct.html#struct-copy-constructor
1763 */
1764 void buildCopyOrMoveCtor(StructDeclaration sd, Scope* sc, bool move)
1765 {
1766 //printf("buildCopyOrMoveCtor() generating %s constructor for %s\n", move ? "move".ptr : "copy".ptr, sd.toChars());
1767 const MOD paramMod = MODFlags.wild;
1768 const MOD funcMod = MODFlags.wild;
1769 auto ccd = generateCtorDeclaration(sd, ModToStc(paramMod), ModToStc(funcMod), move);
1770 auto ctorBody = generateCtorBody(sd, move);
1771 ccd.fbody = ctorBody;
1772 sd.members.push(ccd);
1773 ccd.addMember(sc, sd);
1774 const errors = global.startGagging();
1775 Scope* sc2 = sc.push();
1776 sc2.stc = STC.none;
1777 sc2.linkage = LINK.d;
1778 ccd.dsymbolSemantic(sc2);
1779 ccd.semantic2(sc2);
1780 ccd.semantic3(sc2);
1781 //printf("ccd semantic: %s\n", ccd.type.toChars());
1782 sc2.pop();
1783 if (global.endGagging(errors) || sd.isUnionDeclaration())
1784 {
1785 ccd.storage_class |= STC.disable;
1786 ccd.fbody = null;
1787 }
1788 }