-
-
Notifications
You must be signed in to change notification settings - Fork 594
/
aggregate.d
765 lines (680 loc) · 24.8 KB
/
aggregate.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
/**
* Compiler implementation of the
* $(LINK2 http://www.dlang.org, D programming language).
*
* Copyright: Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/aggregate.d, _aggregate.d)
* Documentation: https://dlang.org/phobos/dmd_aggregate.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/aggregate.d
*/
module dmd.aggregate;
import core.stdc.stdio;
import core.checkedint;
import dmd.arraytypes;
import dmd.gluelayer;
import dmd.declaration;
import dmd.dscope;
import dmd.dstruct;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.dtemplate;
import dmd.errors;
import dmd.expression;
import dmd.func;
import dmd.globals;
import dmd.id;
import dmd.identifier;
import dmd.mtype;
import dmd.semantic2;
import dmd.semantic3;
import dmd.tokens;
import dmd.visitor;
enum Sizeok : int
{
none, // size of aggregate is not yet able to compute
fwd, // size of aggregate is ready to compute
done, // size of aggregate is set correctly
}
enum Baseok : int
{
none, // base classes not computed yet
start, // in process of resolving base classes
done, // all base classes are resolved
semanticdone, // all base classes semantic done
}
/**
* The ClassKind enum is used in AggregateDeclaration AST nodes to
* specify the linkage type of the struct/class/interface or if it
* is an anonymous class. If the class is anonymous it is also
* considered to be a D class.
*/
enum ClassKind : int
{
/// the aggregate is a d(efault) class
d,
/// the aggregate is a C++ struct/class/interface
cpp,
/// the aggregate is an Objective-C class/interface
objc,
}
/***********************************************************
*/
extern (C++) abstract class AggregateDeclaration : ScopeDsymbol
{
Type type;
StorageClass storage_class;
Prot protection;
uint structsize; // size of struct
uint alignsize; // size of struct for alignment purposes
VarDeclarations fields; // VarDeclaration fields
Sizeok sizeok; // set when structsize contains valid data
Dsymbol deferred; // any deferred semantic2() or semantic3() symbol
bool isdeprecated; // true if deprecated
/// specifies whether this is a D, C++, Objective-C or anonymous struct/class/interface
ClassKind classKind;
/* !=null if is nested
* pointing to the dsymbol that directly enclosing it.
* 1. The function that enclosing it (nested struct and class)
* 2. The class that enclosing it (nested class only)
* 3. If enclosing aggregate is template, its enclosing dsymbol.
* See AggregateDeclaraton::makeNested for the details.
*/
Dsymbol enclosing;
VarDeclaration vthis; // 'this' parameter if this aggregate is nested
// Special member functions
FuncDeclarations invs; // Array of invariants
FuncDeclaration inv; // invariant
NewDeclaration aggNew; // allocator
DeleteDeclaration aggDelete; // deallocator
// CtorDeclaration or TemplateDeclaration
Dsymbol ctor;
// default constructor - should have no arguments, because
// it would be stored in TypeInfo_Class.defaultConstructor
CtorDeclaration defaultCtor;
Dsymbol aliasthis; // forward unresolved lookups to aliasthis
bool noDefaultCtor; // no default construction
DtorDeclarations dtors; // Array of destructors
DtorDeclaration dtor; // aggregate destructor
DtorDeclaration primaryDtor; // non-deleting C++ destructor, same as dtor for D
DtorDeclaration tidtor; // aggregate destructor used in TypeInfo (must have extern(D) ABI)
Expression getRTInfo; // pointer to GC info generated by object.RTInfo(this)
final extern (D) this(Loc loc, Identifier id)
{
super(id);
this.loc = loc;
protection = Prot(Prot.Kind.public_);
sizeok = Sizeok.none; // size not determined yet
}
/***************************************
* Create a new scope from sc.
* semantic, semantic2 and semantic3 will use this for aggregate members.
*/
Scope* newScope(Scope* sc)
{
auto sc2 = sc.push(this);
sc2.stc &= STC.safe | STC.trusted | STC.system;
sc2.parent = this;
if (isUnionDeclaration())
sc2.inunion = true;
sc2.protection = Prot(Prot.Kind.public_);
sc2.explicitProtection = 0;
sc2.aligndecl = null;
sc2.userAttribDecl = null;
return sc2;
}
override final void setScope(Scope* sc)
{
// Might need a scope to resolve forward references. The check for
// semanticRun prevents unnecessary setting of _scope during deferred
// setScope phases for aggregates which already finished semantic().
// See https://issues.dlang.org/show_bug.cgi?id=16607
if (semanticRun < PASS.semanticdone)
ScopeDsymbol.setScope(sc);
}
/***************************************
* Find all instance fields, then push them into `fields`.
*
* Runs semantic() for all instance field variables, but also
* the field types can remain yet not resolved forward references,
* except direct recursive definitions.
* After the process sizeok is set to Sizeok.fwd.
*
* Returns:
* false if any errors occur.
*/
final bool determineFields()
{
if (sizeok != Sizeok.none)
return true;
//printf("determineFields() %s, fields.dim = %d\n", toChars(), fields.dim);
// determineFields can be called recursively from one of the fields's v.semantic
fields.setDim(0);
extern (C++) static int func(Dsymbol s, void* param)
{
auto v = s.isVarDeclaration();
if (!v)
return 0;
if (v.storage_class & STC.manifest)
return 0;
auto ad = cast(AggregateDeclaration)param;
if (v.semanticRun < PASS.semanticdone)
v.dsymbolSemantic(null);
// Return in case a recursive determineFields triggered by v.semantic already finished
if (ad.sizeok != Sizeok.none)
return 1;
if (v.aliassym)
return 0; // If this variable was really a tuple, skip it.
if (v.storage_class & (STC.static_ | STC.extern_ | STC.tls | STC.gshared | STC.manifest | STC.ctfe | STC.templateparameter))
return 0;
if (!v.isField() || v.semanticRun < PASS.semanticdone)
return 1; // unresolvable forward reference
ad.fields.push(v);
if (v.storage_class & STC.ref_)
return 0;
auto tv = v.type.baseElemOf();
if (tv.ty != Tstruct)
return 0;
if (ad == (cast(TypeStruct)tv).sym)
{
const(char)* psz = (v.type.toBasetype().ty == Tsarray) ? "static array of " : "";
ad.error("cannot have field `%s` with %ssame struct type", v.toChars(), psz);
ad.type = Type.terror;
ad.errors = true;
return 1;
}
return 0;
}
for (size_t i = 0; i < members.dim; i++)
{
auto s = (*members)[i];
if (s.apply(&func, cast(void*)this))
{
if (sizeok != Sizeok.none)
{
// recursive determineFields already finished
return true;
}
return false;
}
}
if (sizeok != Sizeok.done)
sizeok = Sizeok.fwd;
return true;
}
/***************************************
* Collect all instance fields, then determine instance size.
* Returns:
* false if failed to determine the size.
*/
final bool determineSize(Loc loc)
{
//printf("AggregateDeclaration::determineSize() %s, sizeok = %d\n", toChars(), sizeok);
// The previous instance size finalizing had:
if (type.ty == Terror)
return false; // failed already
if (sizeok == Sizeok.done)
return true; // succeeded
if (!members)
{
error(loc, "unknown size");
return false;
}
if (_scope)
dsymbolSemantic(this, null);
// Determine the instance size of base class first.
if (auto cd = isClassDeclaration())
{
cd = cd.baseClass;
if (cd && !cd.determineSize(loc))
goto Lfail;
}
// Determine instance fields when sizeok == Sizeok.none
if (!determineFields())
goto Lfail;
if (sizeok != Sizeok.done)
finalizeSize();
// this aggregate type has:
if (type.ty == Terror)
return false; // marked as invalid during the finalizing.
if (sizeok == Sizeok.done)
return true; // succeeded to calculate instance size.
Lfail:
// There's unresolvable forward reference.
if (type != Type.terror)
error(loc, "no size because of forward reference");
// Don't cache errors from speculative semantic, might be resolvable later.
// https://issues.dlang.org/show_bug.cgi?id=16574
if (!global.gag)
{
type = Type.terror;
errors = true;
}
return false;
}
abstract void finalizeSize();
override final d_uns64 size(const ref Loc loc)
{
//printf("+AggregateDeclaration::size() %s, scope = %p, sizeok = %d\n", toChars(), _scope, sizeok);
bool ok = determineSize(loc);
//printf("-AggregateDeclaration::size() %s, scope = %p, sizeok = %d\n", toChars(), _scope, sizeok);
return ok ? structsize : SIZE_INVALID;
}
/***************************************
* Calculate field[i].overlapped and overlapUnsafe, and check that all of explicit
* field initializers have unique memory space on instance.
* Returns:
* true if any errors happen.
*/
final bool checkOverlappedFields()
{
//printf("AggregateDeclaration::checkOverlappedFields() %s\n", toChars());
assert(sizeok == Sizeok.done);
size_t nfields = fields.dim;
if (isNested())
{
auto cd = isClassDeclaration();
if (!cd || !cd.baseClass || !cd.baseClass.isNested())
nfields--;
}
bool errors = false;
// Fill in missing any elements with default initializers
foreach (i; 0 .. nfields)
{
auto vd = fields[i];
if (vd.errors)
{
errors = true;
continue;
}
auto vx = vd;
if (vd._init && vd._init.isVoidInitializer())
vx = null;
// Find overlapped fields with the hole [vd.offset .. vd.offset.size()].
foreach (j; 0 .. nfields)
{
if (i == j)
continue;
auto v2 = fields[j];
if (v2.errors)
{
errors = true;
continue;
}
if (!vd.isOverlappedWith(v2))
continue;
// vd and v2 are overlapping.
vd.overlapped = true;
v2.overlapped = true;
if (!MODimplicitConv(vd.type.mod, v2.type.mod))
v2.overlapUnsafe = true;
if (!MODimplicitConv(v2.type.mod, vd.type.mod))
vd.overlapUnsafe = true;
if (!vx)
continue;
if (v2._init && v2._init.isVoidInitializer())
continue;
if (vx._init && v2._init)
{
.error(loc, "overlapping default initialization for field `%s` and `%s`", v2.toChars(), vd.toChars());
errors = true;
}
}
}
return errors;
}
/***************************************
* Fill out remainder of elements[] with default initializers for fields[].
* Params:
* loc = location
* elements = explicit arguments which given to construct object.
* ctorinit = true if the elements will be used for default initialization.
* Returns:
* false if any errors occur.
* Otherwise, returns true and the missing arguments will be pushed in elements[].
*/
final bool fill(Loc loc, Expressions* elements, bool ctorinit)
{
//printf("AggregateDeclaration::fill() %s\n", toChars());
assert(sizeok == Sizeok.done);
assert(elements);
size_t nfields = fields.dim - isNested();
bool errors = false;
size_t dim = elements.dim;
elements.setDim(nfields);
foreach (size_t i; dim .. nfields)
(*elements)[i] = null;
// Fill in missing any elements with default initializers
foreach (i; 0 .. nfields)
{
if ((*elements)[i])
continue;
auto vd = fields[i];
auto vx = vd;
if (vd._init && vd._init.isVoidInitializer())
vx = null;
// Find overlapped fields with the hole [vd.offset .. vd.offset.size()].
size_t fieldi = i;
foreach (j; 0 .. nfields)
{
if (i == j)
continue;
auto v2 = fields[j];
if (!vd.isOverlappedWith(v2))
continue;
if ((*elements)[j])
{
vx = null;
break;
}
if (v2._init && v2._init.isVoidInitializer())
continue;
version (all)
{
/* Prefer first found non-void-initialized field
* union U { int a; int b = 2; }
* U u; // Error: overlapping initialization for field a and b
*/
if (!vx)
{
vx = v2;
fieldi = j;
}
else if (v2._init)
{
.error(loc, "overlapping initialization for field `%s` and `%s`", v2.toChars(), vd.toChars());
errors = true;
}
}
else
{
// fixes https://issues.dlang.org/show_bug.cgi?id=1432 by enabling this path always
/* Prefer explicitly initialized field
* union U { int a; int b = 2; }
* U u; // OK (u.b == 2)
*/
if (!vx || !vx._init && v2._init)
{
vx = v2;
fieldi = j;
}
else if (vx != vd && !vx.isOverlappedWith(v2))
{
// Both vx and v2 fills vd, but vx and v2 does not overlap
}
else if (vx._init && v2._init)
{
.error(loc, "overlapping default initialization for field `%s` and `%s`",
v2.toChars(), vd.toChars());
errors = true;
}
else
assert(vx._init || !vx._init && !v2._init);
}
}
if (vx)
{
Expression e;
if (vx.type.size() == 0)
{
e = null;
}
else if (vx._init)
{
assert(!vx._init.isVoidInitializer());
if (vx.inuse) // https://issues.dlang.org/show_bug.cgi?id=18057
{
vx.error(loc, "recursive initialization of field");
errors = true;
}
else
e = vx.getConstInitializer(false);
}
else
{
if ((vx.storage_class & STC.nodefaultctor) && !ctorinit)
{
.error(loc, "field `%s.%s` must be initialized because it has no default constructor",
type.toChars(), vx.toChars());
errors = true;
}
/* https://issues.dlang.org/show_bug.cgi?id=12509
* Get the element of static array type.
*/
Type telem = vx.type;
if (telem.ty == Tsarray)
{
/* We cannot use Type::baseElemOf() here.
* If the bottom of the Tsarray is an enum type, baseElemOf()
* will return the base of the enum, and its default initializer
* would be different from the enum's.
*/
while (telem.toBasetype().ty == Tsarray)
telem = (cast(TypeSArray)telem.toBasetype()).next;
if (telem.ty == Tvoid)
telem = Type.tuns8.addMod(telem.mod);
}
if (telem.needsNested() && ctorinit)
e = telem.defaultInit(loc);
else
e = telem.defaultInitLiteral(loc);
}
(*elements)[fieldi] = e;
}
}
foreach (e; *elements)
{
if (e && e.op == TOK.error)
return false;
}
return !errors;
}
/****************************
* Do byte or word alignment as necessary.
* Align sizes of 0, as we may not know array sizes yet.
* Params:
* alignment = struct alignment that is in effect
* size = alignment requirement of field
* poffset = pointer to offset to be aligned
*/
static void alignmember(structalign_t alignment, uint size, uint* poffset) pure nothrow @safe
{
//printf("alignment = %d, size = %d, offset = %d\n",alignment,size,offset);
switch (alignment)
{
case cast(structalign_t)1:
// No alignment
break;
case cast(structalign_t)STRUCTALIGN_DEFAULT:
// Alignment in Target::fieldalignsize must match what the
// corresponding C compiler's default alignment behavior is.
assert(size > 0 && !(size & (size - 1)));
*poffset = (*poffset + size - 1) & ~(size - 1);
break;
default:
// Align on alignment boundary, which must be a positive power of 2
assert(alignment > 0 && !(alignment & (alignment - 1)));
*poffset = (*poffset + alignment - 1) & ~(alignment - 1);
break;
}
}
/****************************************
* Place a member (mem) into an aggregate (agg), which can be a struct, union or class
* Returns:
* offset to place field at
*
* nextoffset: next location in aggregate
* memsize: size of member
* memalignsize: natural alignment of member
* alignment: alignment in effect for this member
* paggsize: size of aggregate (updated)
* paggalignsize: alignment of aggregate (updated)
* isunion: the aggregate is a union
*/
static uint placeField(uint* nextoffset, uint memsize, uint memalignsize,
structalign_t alignment, uint* paggsize, uint* paggalignsize, bool isunion)
{
uint ofs = *nextoffset;
const uint actualAlignment =
alignment == STRUCTALIGN_DEFAULT ? memalignsize : alignment;
// Ensure no overflow
bool overflow;
const sz = addu(memsize, actualAlignment, overflow);
const sum = addu(ofs, sz, overflow);
if (overflow) assert(0);
alignmember(alignment, memalignsize, &ofs);
uint memoffset = ofs;
ofs += memsize;
if (ofs > *paggsize)
*paggsize = ofs;
if (!isunion)
*nextoffset = ofs;
if (*paggalignsize < actualAlignment)
*paggalignsize = actualAlignment;
return memoffset;
}
override final Type getType()
{
return type;
}
// is aggregate deprecated?
override final bool isDeprecated()
{
return isdeprecated;
}
/****************************************
* Returns true if there's an extra member which is the 'this'
* pointer to the enclosing context (enclosing aggregate or function)
*/
final bool isNested()
{
return enclosing !is null;
}
/* Append vthis field (this.tupleof[$-1]) to make this aggregate type nested.
*/
final void makeNested()
{
if (enclosing) // if already nested
return;
if (sizeok == Sizeok.done)
return;
if (isUnionDeclaration() || isInterfaceDeclaration())
return;
if (storage_class & STC.static_)
return;
// If nested struct, add in hidden 'this' pointer to outer scope
auto s = toParent2();
if (!s)
return;
Type t = null;
if (auto fd = s.isFuncDeclaration())
{
enclosing = fd;
/* https://issues.dlang.org/show_bug.cgi?id=14422
* If a nested class parent is a function, its
* context pointer (== `outer`) should be void* always.
*/
t = Type.tvoidptr;
}
else if (auto ad = s.isAggregateDeclaration())
{
if (isClassDeclaration() && ad.isClassDeclaration())
{
enclosing = ad;
}
else if (isStructDeclaration())
{
if (auto ti = ad.parent.isTemplateInstance())
{
enclosing = ti.enclosing;
}
}
t = ad.handleType();
}
if (enclosing)
{
//printf("makeNested %s, enclosing = %s\n", toChars(), enclosing.toChars());
assert(t);
if (t.ty == Tstruct)
t = Type.tvoidptr; // t should not be a ref type
assert(!vthis);
vthis = new ThisDeclaration(loc, t);
//vthis.storage_class |= STC.ref_;
// Emulate vthis.addMember()
members.push(vthis);
// Emulate vthis.dsymbolSemantic()
vthis.storage_class |= STC.field;
vthis.parent = this;
vthis.protection = Prot(Prot.Kind.public_);
vthis.alignment = t.alignment();
vthis.semanticRun = PASS.semanticdone;
if (sizeok == Sizeok.fwd)
fields.push(vthis);
}
}
override final bool isExport()
{
return protection.kind == Prot.Kind.export_;
}
/*******************************************
* Look for constructor declaration.
*/
final Dsymbol searchCtor()
{
auto s = search(Loc.initial, Id.ctor);
if (s)
{
if (!(s.isCtorDeclaration() ||
s.isTemplateDeclaration() ||
s.isOverloadSet()))
{
s.error("is not a constructor; identifiers starting with `__` are reserved for the implementation");
errors = true;
s = null;
}
}
if (s && s.toParent() != this)
s = null; // search() looks through ancestor classes
if (s)
{
// Finish all constructors semantics to determine this.noDefaultCtor.
struct SearchCtor
{
extern (C++) static int fp(Dsymbol s, void* ctxt)
{
auto f = s.isCtorDeclaration();
if (f && f.semanticRun == PASS.init)
f.dsymbolSemantic(null);
return 0;
}
}
for (size_t i = 0; i < members.dim; i++)
{
auto sm = (*members)[i];
sm.apply(&SearchCtor.fp, null);
}
}
return s;
}
override final Prot prot()
{
return protection;
}
// 'this' type
final Type handleType()
{
return type;
}
// Back end
Symbol* stag; // tag symbol for debug data
Symbol* sinit;
override final inout(AggregateDeclaration) isAggregateDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}