Debian Codegraph @

gcc/d/dmd/aggregate.d

raw
1 /**
2 * Defines a `Dsymbol` representing an aggregate, which is a `struct`, `union` or `class`.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/struct.html, Structs, Unions),
5 * $(LINK2 https://dlang.org/spec/class.html, Class).
6 *
7 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
8 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
9 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
10 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/aggregate.d, _aggregate.d)
11 * Documentation: https://dlang.org/phobos/dmd_aggregate.html
12 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/aggregate.d
13 */
14
15 module dmd.aggregate;
16
17 import core.stdc.stdio;
18 import core.checkedint;
19
20 import dmd.aliasthis;
21 import dmd.arraytypes;
22 import dmd.astenums;
23 import dmd.attrib;
24 import dmd.declaration;
25 import dmd.dscope;
26 import dmd.dstruct;
27 import dmd.dsymbol;
28 import dmd.dsymbolsem : dsymbolSemantic, determineFields, search, determineSize, include;
29 import dmd.dtemplate;
30 import dmd.errors;
31 import dmd.expression;
32 import dmd.func;
33 import dmd.globals;
34 import dmd.hdrgen;
35 import dmd.id;
36 import dmd.identifier;
37 import dmd.location;
38 import dmd.mtype;
39 import dmd.tokens;
40 import dmd.typesem : defaultInit, addMod, size;
41 import dmd.visitor;
42
43 /**
44 * The ClassKind enum is used in AggregateDeclaration AST nodes to
45 * specify the linkage type of the struct/class/interface or if it
46 * is an anonymous class. If the class is anonymous it is also
47 * considered to be a D class.
48 */
49 enum ClassKind : ubyte
50 {
51 /// the aggregate is a d(efault) class
52 d,
53 /// the aggregate is a C++ struct/class/interface
54 cpp,
55 /// the aggregate is an Objective-C class/interface
56 objc,
57 /// the aggregate is a C struct
58 c,
59 }
60
61 /**
62 * Give a nice string for a class kind for error messages
63 * Params:
64 * c = class kind
65 * Returns:
66 * 0-terminated string for `c`
67 */
68 const(char)* ClassKindToChars(ClassKind c) @safe
69 {
70 final switch (c)
71 {
72 case ClassKind.d:
73 return "D";
74 case ClassKind.cpp:
75 return "C++";
76 case ClassKind.objc:
77 return "Objective-C";
78 case ClassKind.c:
79 return "C";
80 }
81 }
82
83 /**
84 * If an aggregate has a pargma(mangle, ...) this holds the information
85 * to mangle.
86 */
87 struct MangleOverride
88 {
89 Dsymbol agg; // The symbol to copy template parameters from (if any)
90 Identifier id; // the name to override the aggregate's with, defaults to agg.ident
91 }
92
93 /***********************************************************
94 * Abstract aggregate as a common ancestor for Class- and StructDeclaration.
95 */
96 extern (C++) abstract class AggregateDeclaration : ScopeDsymbol
97 {
98 Type type; ///
99 STC storage_class; ///
100 uint structsize; /// size of struct
101 uint alignsize; /// size of struct for alignment purposes
102 VarDeclarations fields; /// VarDeclaration fields including flattened AnonDeclaration members
103 Dsymbol deferred; /// any deferred semantic2() or semantic3() symbol
104
105 /// specifies whether this is a D, C++, Objective-C or anonymous struct/class/interface
106 ClassKind classKind;
107 /// Specify whether to mangle the aggregate as a `class` or a `struct`
108 /// This information is used by the MSVC mangler
109 /// Only valid for class and struct. TODO: Merge with ClassKind ?
110 CPPMANGLE cppmangle;
111
112 /// overridden symbol with pragma(mangle, "...") if not null
113 MangleOverride* pMangleOverride;
114
115 /**
116 * !=null if is nested
117 * pointing to the dsymbol that directly enclosing it.
118 * 1. The function that enclosing it (nested struct and class)
119 * 2. The class that enclosing it (nested class only)
120 * 3. If enclosing aggregate is template, its enclosing dsymbol.
121 *
122 * See AggregateDeclaraton::makeNested for the details.
123 */
124 Dsymbol enclosing;
125
126 VarDeclaration vthis; /// 'this' parameter if this aggregate is nested
127 VarDeclaration vthis2; /// 'this' parameter if this aggregate is a template and is nested
128
129 // Special member functions
130 FuncDeclarations invs; /// Array of invariants
131 FuncDeclaration inv; /// Merged invariant calling all members of invs
132
133 /// CtorDeclaration or TemplateDeclaration
134 Dsymbol ctor;
135
136 /// default constructor - should have no arguments, because
137 /// it would be stored in TypeInfo_Class.defaultConstructor
138 CtorDeclaration defaultCtor;
139
140 AliasThis aliasthis; /// forward unresolved lookups to aliasthis
141
142 DtorDeclarations userDtors; /// user-defined destructors (`~this()`) - mixins can yield multiple ones
143 DtorDeclaration aggrDtor; /// aggregate destructor calling userDtors and fieldDtor (and base class aggregate dtor for C++ classes)
144 DtorDeclaration dtor; /// the aggregate destructor exposed as `__xdtor` alias
145 /// (same as aggrDtor, except for C++ classes with virtual dtor on Windows)
146 DtorDeclaration tidtor; /// aggregate destructor used in TypeInfo (must have extern(D) ABI)
147 DtorDeclaration fieldDtor; /// function destructing (non-inherited) fields
148
149 Expression getRTInfo; /// pointer to GC info generated by object.RTInfo(this)
150
151 ///
152 Visibility visibility;
153 bool noDefaultCtor; /// no default construction
154 bool disableNew; /// disallow allocations using `new`
155 Sizeok sizeok = Sizeok.none; /// set when structsize contains valid data
156
157 final extern (D) this(Loc loc, Identifier id)
158 {
159 super(loc, id);
160 visibility = Visibility(Visibility.Kind.public_);
161 }
162
163 /***************************************
164 * Create a new scope from sc.
165 * semantic, semantic2 and semantic3 will use this for aggregate members.
166 */
167 Scope* newScope(Scope* sc)
168 {
169 auto sc2 = sc.push(this);
170 sc2.stc &= STC.flowThruAggregate;
171 sc2.parent = this;
172 sc2.inunion = isUnionDeclaration();
173 sc2.visibility = Visibility(Visibility.Kind.public_);
174 sc2.explicitVisibility = 0;
175 sc2.aligndecl = null;
176 sc2.userAttribDecl = null;
177 sc2.namespace = null;
178 return sc2;
179 }
180
181 /***************************************
182 * Returns:
183 * The total number of fields minus the number of hidden fields.
184 */
185 extern (D) final size_t nonHiddenFields()
186 {
187 return fields.length - isNested() - (vthis2 !is null);
188 }
189
190 abstract void finalizeSize();
191
192 override final uinteger_t size(Loc loc)
193 {
194 //printf("+AggregateDeclaration::size() %s, scope = %p, sizeok = %d\n", toChars(), _scope, sizeok);
195 bool ok = determineSize(this, loc);
196 //printf("-AggregateDeclaration::size() %s, scope = %p, sizeok = %d\n", toChars(), _scope, sizeok);
197 return ok ? structsize : SIZE_INVALID;
198 }
199
200 /***************************************
201 * Calculate field[i].overlapped and overlapUnsafe, and check that all of explicit
202 * field initializers have unique memory space on instance.
203 * Returns:
204 * true if any errors happen.
205 */
206 extern (D) final bool checkOverlappedFields()
207 {
208 //printf("AggregateDeclaration::checkOverlappedFields() %s\n", toChars());
209 assert(sizeok == Sizeok.done);
210 size_t nfields = fields.length;
211 if (isNested())
212 {
213 auto cd = isClassDeclaration();
214 if (!cd || !cd.baseClass || !cd.baseClass.isNested())
215 nfields--;
216 if (vthis2 && !(cd && cd.baseClass && cd.baseClass.vthis2))
217 nfields--;
218 }
219 bool errors = false;
220
221 // Fill in missing any elements with default initializers
222 foreach (i; 0 .. nfields)
223 {
224 auto vd = fields[i];
225 if (vd.errors)
226 {
227 errors = true;
228 continue;
229 }
230
231 const vdIsVoidInit = vd._init && vd._init.isVoidInitializer();
232
233 // Find overlapped fields with the hole [vd.offset .. vd.offset.size()].
234 foreach (j; 0 .. nfields)
235 {
236 if (i == j)
237 continue;
238 auto v2 = fields[j];
239 if (v2.errors)
240 {
241 errors = true;
242 continue;
243 }
244 if (!vd.isOverlappedWith(v2))
245 continue;
246
247 // vd and v2 are overlapping.
248 vd.overlapped = true;
249 v2.overlapped = true;
250
251 if (!MODimplicitConv(vd.type.mod, v2.type.mod))
252 v2.overlapUnsafe = true;
253 if (!MODimplicitConv(v2.type.mod, vd.type.mod))
254 vd.overlapUnsafe = true;
255
256 if (i > j)
257 continue;
258
259 if (!v2._init)
260 continue;
261
262 if (v2._init.isVoidInitializer())
263 continue;
264
265 if (vd._init && !vdIsVoidInit && v2._init)
266 {
267 .error(loc, "overlapping default initialization for field `%s` and `%s`", v2.toChars(), vd.toChars());
268 errors = true;
269 }
270 else if (v2._init && i < j)
271 {
272 .error(v2.loc, "union field `%s` with default initialization `%s` must be before field `%s`",
273 v2.toChars(), dmd.hdrgen.toChars(v2._init), vd.toChars());
274 errors = true;
275 }
276 }
277 }
278 return errors;
279 }
280
281 override final Type getType()
282 {
283 /* Apply storage classes to forward references. (Issue 22254)
284 * Note: Avoid interfaces for now. Implementing qualifiers on interface
285 * definitions exposed some issues in their TypeInfo generation in DMD.
286 * Related PR: https://github.com/dlang/dmd/pull/13312
287 */
288 if (semanticRun == PASS.initial && !isInterfaceDeclaration())
289 {
290 auto stc = storage_class;
291 if (_scope)
292 stc |= _scope.stc;
293 type = type.addSTC(stc);
294 }
295 return type;
296 }
297
298 // is aggregate deprecated?
299 override final bool isDeprecated() const
300 {
301 return !!(this.storage_class & STC.deprecated_);
302 }
303
304 /// Flag this aggregate as deprecated
305 extern (D) final void setDeprecated()
306 {
307 this.storage_class |= STC.deprecated_;
308 }
309
310 /****************************************
311 * Returns true if there's an extra member which is the 'this'
312 * pointer to the enclosing context (enclosing aggregate or function)
313 */
314 final bool isNested() const
315 {
316 return enclosing !is null;
317 }
318
319 /* Append vthis field (this.tupleof[$-1]) to make this aggregate type nested.
320 */
321 extern (D) final void makeNested()
322 {
323 if (enclosing) // if already nested
324 return;
325 if (sizeok == Sizeok.done)
326 return;
327 if (isUnionDeclaration() || isInterfaceDeclaration())
328 return;
329 if (storage_class & STC.static_)
330 return;
331
332 // If nested struct, add in hidden 'this' pointer to outer scope
333 auto s = toParentLocal();
334 if (!s)
335 s = toParent2();
336 if (!s)
337 return;
338 Type t = null;
339 if (auto fd = s.isFuncDeclaration())
340 {
341 enclosing = fd;
342
343 /* https://issues.dlang.org/show_bug.cgi?id=14422
344 * If a nested class parent is a function, its
345 * context pointer (== `outer`) should be void* always.
346 */
347 t = Type.tvoidptr;
348 }
349 else if (auto ad = s.isAggregateDeclaration())
350 {
351 if (isClassDeclaration() && ad.isClassDeclaration())
352 {
353 enclosing = ad;
354 }
355 else if (isStructDeclaration())
356 {
357 if (auto ti = ad.parent.isTemplateInstance())
358 {
359 enclosing = ti.enclosing;
360 }
361 }
362 t = ad.handleType();
363 }
364 if (enclosing)
365 {
366 //printf("makeNested %s, enclosing = %s\n", toChars(), enclosing.toChars());
367 assert(t);
368 if (t.ty == Tstruct)
369 t = Type.tvoidptr; // t should not be a ref type
370
371 assert(!vthis);
372 vthis = new ThisDeclaration(loc, t);
373 //vthis.storage_class |= STC.ref_;
374
375 // Emulate vthis.addMember()
376 members.push(vthis);
377
378 // Emulate vthis.dsymbolSemantic()
379 vthis.storage_class |= STC.field;
380 vthis.parent = this;
381 vthis.visibility = Visibility(Visibility.Kind.public_);
382 vthis.alignment = t.alignment();
383 vthis.semanticRun = PASS.semanticdone;
384
385 if (sizeok == Sizeok.fwd)
386 fields.push(vthis);
387
388 makeNested2();
389 }
390 }
391
392 /* Append vthis2 field (this.tupleof[$-1]) to add a second context pointer.
393 */
394 extern (D) final void makeNested2()
395 {
396 if (vthis2)
397 return;
398 if (!vthis)
399 makeNested(); // can't add second before first
400 if (!vthis)
401 return;
402 if (sizeok == Sizeok.done)
403 return;
404 if (isUnionDeclaration() || isInterfaceDeclaration())
405 return;
406 if (storage_class & STC.static_)
407 return;
408
409 auto s0 = toParentLocal();
410 auto s = toParent2();
411 if (!s || !s0 || s == s0)
412 return;
413 auto cd = s.isClassDeclaration();
414 Type t = cd ? cd.type : Type.tvoidptr;
415
416 vthis2 = new ThisDeclaration(loc, t);
417 //vthis2.storage_class |= STC.ref_;
418
419 // Emulate vthis2.addMember()
420 members.push(vthis2);
421
422 // Emulate vthis2.dsymbolSemantic()
423 vthis2.storage_class |= STC.field;
424 vthis2.parent = this;
425 vthis2.visibility = Visibility(Visibility.Kind.public_);
426 vthis2.alignment = t.alignment();
427 vthis2.semanticRun = PASS.semanticdone;
428
429 if (sizeok == Sizeok.fwd)
430 fields.push(vthis2);
431 }
432
433 override final bool isExport() const
434 {
435 return visibility.kind == Visibility.Kind.export_;
436 }
437
438 /*******************************************
439 * Look for constructor declaration.
440 */
441 extern (D) final Dsymbol searchCtor()
442 {
443 auto s = this.search(Loc.initial, Id.ctor);
444 if (s)
445 {
446 if (!(s.isCtorDeclaration() ||
447 s.isTemplateDeclaration() ||
448 s.isOverloadSet()))
449 {
450 error(s.loc, "%s name `__ctor` is not allowed", s.kind);
451 errorSupplemental(s.loc, "identifiers starting with `__` are reserved for internal use");
452 errors = true;
453 s = null;
454 }
455 }
456 if (s && s.toParent() != this)
457 s = null; // search() looks through ancestor classes
458 if (s)
459 {
460 // Finish all constructors semantics to determine this.noDefaultCtor.
461 static int searchCtor(Dsymbol s, void*)
462 {
463 auto f = s.isCtorDeclaration();
464 if (f && f.semanticRun == PASS.initial)
465 f.dsymbolSemantic(null);
466 return 0;
467 }
468
469 for (size_t i = 0; i < members.length; i++)
470 {
471 auto sm = (*members)[i];
472 sm.apply(&searchCtor, null);
473 }
474 }
475 return s;
476 }
477
478 override final Visibility visible() pure nothrow @nogc @safe
479 {
480 return visibility;
481 }
482
483 // 'this' type
484 final Type handleType()
485 {
486 return type;
487 }
488
489 // Does this class have an invariant function?
490 final bool hasInvariant()
491 {
492 return invs.length != 0;
493 }
494
495 // Back end
496 void* sinit; /// initializer symbol
497
498 override void accept(Visitor v)
499 {
500 v.visit(this);
501 }
502 }
503
504 /*********************************
505 * Iterate this dsymbol or members of this scoped dsymbol, then
506 * call `fp` with the found symbol and `params`.
507 * Params:
508 * symbol = the dsymbol or parent of members to call fp on
509 * fp = function pointer to process the iterated symbol.
510 * If it returns nonzero, the iteration will be aborted.
511 * ctx = context parameter passed to fp.
512 * Returns:
513 * nonzero if the iteration is aborted by the return value of fp,
514 * or 0 if it's completed.
515 */
516 int apply(Dsymbol symbol, int function(Dsymbol, void*) fp, void* ctx)
517 {
518 if (auto nd = symbol.isNspace())
519 {
520 return nd.members.foreachDsymbol( (s) { return s && s.apply(fp, ctx); } );
521 }
522 if (auto ad = symbol.isAttribDeclaration())
523 {
524 return ad.include(ad._scope).foreachDsymbol( (s) { return s && s.apply(fp, ctx); } );
525 }
526 if (auto tm = symbol.isTemplateMixin())
527 {
528 if (tm._scope) // if fwd reference
529 dsymbolSemantic(tm, null); // try to resolve it
530
531 return tm.members.foreachDsymbol( (s) { return s && s.apply(fp, ctx); } );
532 }
533
534 return fp(symbol, ctx);
535 }
536
537 /****************************
538 * Do byte or word alignment as necessary.
539 * Align sizes of 0, as we may not know array sizes yet.
540 * Params:
541 * alignment = struct alignment that is in effect
542 * memalignsize = natural alignment of field
543 * offset = offset to be aligned
544 * Returns:
545 * aligned offset
546 */
547 public uint alignmember(structalign_t alignment, uint memalignsize, uint offset) pure nothrow @safe
548 {
549 //debug printf("alignment = %u %d, size = %u, offset = %u\n", alignment.get(), alignment.isPack(), memalignsize, offset);
550 uint alignvalue;
551
552 if (alignment.isDefault())
553 {
554 // Alignment in Target::fieldalignsize must match what the
555 // corresponding C compiler's default alignment behavior is.
556 alignvalue = memalignsize;
557 }
558 else if (alignment.isPack()) // #pragma pack semantics
559 {
560 alignvalue = alignment.get();
561 if (memalignsize < alignvalue)
562 alignvalue = memalignsize; // align to min(memalignsize, alignment)
563 }
564 else if (alignment.get() > 1)
565 {
566 // Align on alignment boundary, which must be a positive power of 2
567 alignvalue = alignment.get();
568 }
569 else
570 return offset;
571
572 assert(alignvalue && !(alignvalue & (alignvalue - 1))); // non-zero and power of 2
573 return (offset + alignvalue - 1) & ~(alignvalue - 1);
574 }
575
576 /****************************************
577 * Place a field (mem) into an aggregate (agg), which can be a struct, union or class
578 * Params:
579 * loc = source location for error messages
580 * nextoffset = location just past the end of the previous field in the aggregate.
581 * Updated to be just past the end of this field to be placed, i.e. the future nextoffset
582 * memsize = size of field
583 * memalignsize = natural alignment of field
584 * alignment = alignment in effect for this field
585 * aggsize = size of aggregate (updated)
586 * aggalignsize = alignment of aggregate (updated)
587 * isunion = the aggregate is a union
588 * Returns:
589 * aligned offset to place field at
590 *
591 */
592 public uint placeField(Loc loc, ref uint nextoffset, uint memsize, uint memalignsize,
593 structalign_t alignment, ref uint aggsize, ref uint aggalignsize, bool isunion) @trusted nothrow
594 {
595 static if (0)
596 {
597 printf("placeField() nextoffset: %u\n", nextoffset);
598 printf(": memsize: %u\n", memsize);
599 printf(": memalignsize: %u\n", memalignsize);
600 printf(": alignment: %u\n", alignment.get());
601 printf(": aggsize: %u\n", aggsize);
602 printf(": aggalignsize: %u\n", aggalignsize);
603 printf(": isunion: %d\n", isunion);
604 }
605
606 uint ofs = nextoffset;
607
608 const uint actualAlignment =
609 alignment.isDefault() || alignment.isPack() && memalignsize < alignment.get()
610 ? memalignsize : alignment.get();
611
612 // Ensure no overflow for (memsize + actualAlignment + ofs)
613 bool overflow;
614 const sz = addu(memsize, actualAlignment, overflow);
615 addu(ofs, sz, overflow);
616 if (overflow)
617 {
618 error(loc, "max object size %u exceeded from adding field size %u + alignment adjustment %u + field offset %u when placing field in aggregate",
619 uint.max, memsize, actualAlignment, ofs);
620 return 0;
621 }
622
623 // Skip no-op for noreturn without custom aligment
624 if (memalignsize != 0 || !alignment.isDefault())
625 ofs = alignmember(alignment, memalignsize, ofs);
626
627 uint memoffset = ofs;
628 ofs += memsize;
629 if (ofs > aggsize)
630 aggsize = ofs;
631 if (!isunion)
632 {
633 nextoffset = ofs;
634 //printf(" revised nextoffset: %u\n", ofs);
635 }
636
637 if (aggalignsize < actualAlignment)
638 aggalignsize = actualAlignment;
639
640 return memoffset;
641 }