Debian Codegraph @

gcc/d/dmd/dclass.d

raw
1 /**
2 * Defines a `class` declaration.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/class.html, Classes)
5 *
6 * Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved
7 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
8 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/dclass.d, _dclass.d)
10 * Documentation: https://dlang.org/phobos/dmd_dclass.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/dclass.d
12 */
13
14 module dmd.dclass;
15
16 import core.stdc.stdio;
17 import core.stdc.string;
18
19 import dmd.aggregate;
20 import dmd.arraytypes;
21 import dmd.astenums;
22 import dmd.gluelayer;
23 import dmd.declaration;
24 import dmd.dscope;
25 import dmd.dsymbol;
26 import dmd.dsymbolsem : dsymbolSemantic, addMember, setFieldOffset;
27 import dmd.errors;
28 import dmd.func;
29 import dmd.id;
30 import dmd.identifier;
31 import dmd.location;
32 import dmd.mtype;
33 import dmd.objc;
34 import dmd.root.rmem;
35 import dmd.target;
36 import dmd.typesem : covariant, immutableOf, sarrayOf;
37 import dmd.visitor;
38
39 /***********************************************************
40 */
41 extern (C++) struct BaseClass
42 {
43 Type type; // (before semantic processing)
44
45 ClassDeclaration sym;
46 uint offset; // 'this' pointer offset
47
48 // for interfaces: Array of FuncDeclaration's making up the vtbl[]
49 FuncDeclarations vtbl;
50
51 // if BaseClass is an interface, these
52 // are a copy of the InterfaceDeclaration.interfaces
53 BaseClass[] baseInterfaces;
54
55 extern (D) this(Type type)
56 {
57 //printf("BaseClass(this = %p, '%s')\n", this, type.toChars());
58 this.type = type;
59 }
60
61 /****************************************
62 * Fill in vtbl[] for base class based on member functions of class cd.
63 * Input:
64 * vtbl if !=NULL, fill it in
65 * newinstance !=0 means all entries must be filled in by members
66 * of cd, not members of any base classes of cd.
67 * Returns:
68 * true if any entries were filled in by members of cd (not exclusively
69 * by base classes)
70 */
71 extern (C++) bool fillVtbl(ClassDeclaration cd, FuncDeclarations* vtbl, int newinstance)
72 {
73 bool result = false;
74
75 //printf("BaseClass.fillVtbl(this='%s', cd='%s')\n", sym.toChars(), cd.toChars());
76 if (vtbl)
77 vtbl.setDim(sym.vtbl.length);
78
79 // first entry is ClassInfo reference
80 for (size_t j = sym.vtblOffset(); j < sym.vtbl.length; j++)
81 {
82 FuncDeclaration ifd = sym.vtbl[j].isFuncDeclaration();
83
84 //printf(" vtbl[%d] is '%s'\n", j, ifd ? ifd.toChars() : "null");
85 assert(ifd);
86
87 // Find corresponding function in this class
88 auto tf = ifd.type.toTypeFunction();
89 auto fd = cd.findFunc(ifd.ident, tf);
90 if (fd && !fd.isAbstract())
91 {
92 if (fd.toParent() == cd)
93 result = true;
94 }
95 else
96 fd = null;
97 if (vtbl)
98 (*vtbl)[j] = fd;
99 }
100 return result;
101 }
102
103 extern (D) void copyBaseInterfaces(BaseClasses* vtblInterfaces)
104 {
105 //printf("+copyBaseInterfaces(), %s\n", sym.toChars());
106 // if (baseInterfaces.length)
107 // return;
108 auto bc = cast(BaseClass*)mem.xcalloc(sym.interfaces.length, BaseClass.sizeof);
109 baseInterfaces = bc[0 .. sym.interfaces.length];
110 //printf("%s.copyBaseInterfaces()\n", sym.toChars());
111 for (size_t i = 0; i < baseInterfaces.length; i++)
112 {
113 BaseClass* b = &baseInterfaces[i];
114 BaseClass* b2 = sym.interfaces[i];
115
116 assert(b2.vtbl.length == 0); // should not be filled yet
117 memcpy(b, b2, BaseClass.sizeof);
118
119 if (i) // single inheritance is i==0
120 vtblInterfaces.push(b); // only need for M.I.
121 b.copyBaseInterfaces(vtblInterfaces);
122 }
123 //printf("-copyBaseInterfaces\n");
124 }
125 }
126
127 // These must match the values in druntime/src/object.d
128 enum ClassFlags : uint
129 {
130 none = 0x0,
131 isCOMclass = 0x1,
132 noPointers = 0x2,
133 hasOffTi = 0x4,
134 hasCtor = 0x8,
135 hasGetMembers = 0x10,
136 hasTypeInfo = 0x20,
137 isAbstract = 0x40,
138 isCPPclass = 0x80,
139 hasDtor = 0x100,
140 hasNameSig = 0x200,
141 }
142
143 /***********************************************************
144 */
145 extern (C++) class ClassDeclaration : AggregateDeclaration
146 {
147 extern (C++) __gshared
148 {
149 // Names found by reading object.d in druntime
150 ClassDeclaration object;
151 ClassDeclaration throwable;
152 ClassDeclaration exception;
153 ClassDeclaration errorException;
154 ClassDeclaration cpp_type_info_ptr; // Object.__cpp_type_info_ptr
155 }
156
157 ClassDeclaration baseClass; // NULL only if this is Object
158 FuncDeclaration staticCtor;
159 FuncDeclaration staticDtor;
160 Dsymbols vtbl; // Array of FuncDeclaration's making up the vtbl[]
161 Dsymbols vtblFinal; // More FuncDeclaration's that aren't in vtbl[]
162
163 // Array of BaseClass's; first is super, rest are Interface's
164 BaseClasses* baseclasses;
165
166 /* Slice of baseclasses[] that does not include baseClass
167 */
168 BaseClass*[] interfaces;
169
170 // array of base interfaces that have their own vtbl[]
171 BaseClasses* vtblInterfaces;
172
173 // the ClassInfo object for this ClassDeclaration
174 TypeInfoClassDeclaration vclassinfo;
175
176 // true if this is a COM class
177 bool com;
178
179 /// true if this is a scope class
180 bool stack;
181
182 /// if this is a C++ class, this is the slot reserved for the virtual destructor
183 int cppDtorVtblIndex = -1;
184
185 /// to prevent recursive attempts
186 bool inuse;
187
188 ThreeState isabstract;
189
190 /// set the progress of base classes resolving
191 Baseok baseok;
192
193 /**
194 * Data for a class declaration that is needed for the Objective-C
195 * integration.
196 */
197 ObjcClassDeclaration objc;
198
199 Symbol* cpp_type_info_ptr_sym; // cached instance of class Id.cpp_type_info_ptr
200
201 final extern (D) this(Loc loc, Identifier id, BaseClasses* baseclasses, Dsymbols* members, bool inObject)
202 {
203 objc = ObjcClassDeclaration(this);
204
205 if (!id)
206 id = Identifier.generateAnonymousId("class");
207
208 super(loc, id);
209 this.dsym = DSYM.classDeclaration;
210
211 static immutable msg = "only object.d can define this reserved class name";
212
213 if (baseclasses)
214 {
215 // Actually, this is a transfer
216 this.baseclasses = baseclasses;
217 }
218 else
219 this.baseclasses = new BaseClasses();
220
221 this.members = members;
222
223 //printf("ClassDeclaration(%s), dim = %d\n", ident.toChars(), this.baseclasses.length);
224
225 // For forward references
226 type = new TypeClass(this);
227
228 // Look for special class names
229 if (id == Id.__sizeof || id == Id.__xalignof || id == Id._mangleof)
230 classError("%s `%s` illegal class name", null);
231
232 // BUG: What if this is the wrong TypeInfo, i.e. it is nested?
233 if (id.toChars()[0] == 'T')
234 {
235 if (id == Id.TypeInfo)
236 {
237 if (!inObject)
238 classError("%s `%s` %s", msg.ptr);
239 Type.dtypeinfo = this;
240 }
241 if (id == Id.TypeInfo_Class)
242 {
243 if (!inObject)
244 classError("%s `%s` %s", msg.ptr);
245 Type.typeinfoclass = this;
246 }
247 if (id == Id.TypeInfo_Interface)
248 {
249 if (!inObject)
250 classError("%s `%s` %s", msg.ptr);
251 Type.typeinfointerface = this;
252 }
253 if (id == Id.TypeInfo_Struct)
254 {
255 if (!inObject)
256 classError("%s `%s` %s", msg.ptr);
257 Type.typeinfostruct = this;
258 }
259 if (id == Id.TypeInfo_Pointer)
260 {
261 if (!inObject)
262 classError("%s `%s` %s", msg.ptr);
263 Type.typeinfopointer = this;
264 }
265 if (id == Id.TypeInfo_Array)
266 {
267 if (!inObject)
268 classError("%s `%s` %s", msg.ptr);
269 Type.typeinfoarray = this;
270 }
271 if (id == Id.TypeInfo_StaticArray)
272 {
273 //if (!inObject)
274 // Type.typeinfostaticarray.classError("%s `%s` %s", msg);
275 Type.typeinfostaticarray = this;
276 }
277 if (id == Id.TypeInfo_AssociativeArray)
278 {
279 if (!inObject)
280 classError("%s `%s` %s", msg.ptr);
281 Type.typeinfoassociativearray = this;
282 }
283 if (id == Id.TypeInfo_Enum)
284 {
285 if (!inObject)
286 classError("%s `%s` %s", msg.ptr);
287 Type.typeinfoenum = this;
288 }
289 if (id == Id.TypeInfo_Function)
290 {
291 if (!inObject)
292 classError("%s `%s` %s", msg.ptr);
293 Type.typeinfofunction = this;
294 }
295 if (id == Id.TypeInfo_Delegate)
296 {
297 if (!inObject)
298 classError("%s `%s` %s", msg.ptr);
299 Type.typeinfodelegate = this;
300 }
301 if (id == Id.TypeInfo_Tuple)
302 {
303 if (!inObject)
304 classError("%s `%s` %s", msg.ptr);
305 Type.typeinfotypelist = this;
306 }
307 if (id == Id.TypeInfo_Const)
308 {
309 if (!inObject)
310 classError("%s `%s` %s", msg.ptr);
311 Type.typeinfoconst = this;
312 }
313 if (id == Id.TypeInfo_Invariant)
314 {
315 if (!inObject)
316 classError("%s `%s` %s", msg.ptr);
317 Type.typeinfoinvariant = this;
318 }
319 if (id == Id.TypeInfo_Shared)
320 {
321 if (!inObject)
322 classError("%s `%s` %s", msg.ptr);
323 Type.typeinfoshared = this;
324 }
325 if (id == Id.TypeInfo_Wild)
326 {
327 if (!inObject)
328 classError("%s `%s` %s", msg.ptr);
329 Type.typeinfowild = this;
330 }
331 if (id == Id.TypeInfo_Vector)
332 {
333 if (!inObject)
334 classError("%s `%s` %s", msg.ptr);
335 Type.typeinfovector = this;
336 }
337 }
338
339 if (id == Id.Object)
340 {
341 if (!inObject)
342 classError("%s `%s` %s", msg.ptr);
343 object = this;
344 }
345
346 if (id == Id.Throwable)
347 {
348 if (!inObject)
349 classError("%s `%s` %s", msg.ptr);
350 throwable = this;
351 }
352 if (id == Id.Exception)
353 {
354 if (!inObject)
355 classError("%s `%s` %s", msg.ptr);
356 exception = this;
357 }
358 if (id == Id.Error)
359 {
360 if (!inObject)
361 classError("%s `%s` %s", msg.ptr);
362 errorException = this;
363 }
364 if (id == Id.cpp_type_info_ptr)
365 {
366 if (!inObject)
367 classError("%s `%s` %s", msg.ptr);
368 cpp_type_info_ptr = this;
369 }
370
371 baseok = Baseok.none;
372 }
373
374 extern (D) final void classError(const(char)* fmt, const(char)* arg)
375 {
376 .error(loc, fmt, kind, toPrettyChars, arg);
377 }
378
379 static ClassDeclaration create(Loc loc, Identifier id, BaseClasses* baseclasses, Dsymbols* members, bool inObject)
380 {
381 return new ClassDeclaration(loc, id, baseclasses, members, inObject);
382 }
383
384 override const(char)* toPrettyChars(bool qualifyTypes = false)
385 {
386 if (objc.isMeta)
387 return .objc.toPrettyChars(this, qualifyTypes);
388
389 return super.toPrettyChars(qualifyTypes);
390 }
391
392 override ClassDeclaration syntaxCopy(Dsymbol s)
393 {
394 //printf("ClassDeclaration.syntaxCopy('%s')\n", toChars());
395 ClassDeclaration cd =
396 s ? cast(ClassDeclaration)s
397 : new ClassDeclaration(loc, ident, null, null, false);
398
399 cd.storage_class |= storage_class;
400
401 cd.baseclasses.setDim(this.baseclasses.length);
402 for (size_t i = 0; i < cd.baseclasses.length; i++)
403 {
404 BaseClass* b = (*this.baseclasses)[i];
405 auto b2 = new BaseClass(b.type.syntaxCopy());
406 (*cd.baseclasses)[i] = b2;
407 }
408
409 ScopeDsymbol.syntaxCopy(cd);
410 return cd;
411 }
412
413 override Scope* newScope(Scope* sc)
414 {
415 auto sc2 = super.newScope(sc);
416 if (isCOMclass())
417 {
418 /* This enables us to use COM objects under Linux and
419 * work with things like XPCOM
420 */
421 sc2.linkage = target.systemLinkage();
422 }
423 return sc2;
424 }
425
426 /*********************************************
427 * Determine if 'this' is a base class of cd.
428 * This is used to detect circular inheritance only.
429 */
430 extern (D) final bool isBaseOf2(ClassDeclaration cd) pure nothrow @nogc
431 {
432 if (!cd)
433 return false;
434 //printf("ClassDeclaration.isBaseOf2(this = '%s', cd = '%s')\n", toChars(), cd.toChars());
435 for (size_t i = 0; i < cd.baseclasses.length; i++)
436 {
437 BaseClass* b = (*cd.baseclasses)[i];
438 if (b.sym == this || isBaseOf2(b.sym))
439 return true;
440 }
441 return false;
442 }
443
444 enum OFFSET_RUNTIME = 0x76543210;
445 enum OFFSET_FWDREF = 0x76543211;
446
447 /*******************************************
448 * Determine if 'this' is a base class of cd.
449 */
450 bool isBaseOf(ClassDeclaration cd, int* poffset) pure nothrow @nogc
451 {
452 //printf("ClassDeclaration.isBaseOf(this = '%s', cd = '%s')\n", toChars(), cd.toChars());
453 if (poffset)
454 *poffset = 0;
455 while (cd)
456 {
457 assert(cd.baseClass || cd.semanticRun >= PASS.semanticdone || cd.isInterfaceDeclaration());
458 if (this == cd.baseClass)
459 return true;
460
461 cd = cd.baseClass;
462 }
463 return false;
464 }
465
466 /*********************************************
467 * Determine if 'this' has complete base class information.
468 * This is used to detect forward references in covariant overloads.
469 */
470 final bool isBaseInfoComplete() const
471 {
472 return baseok >= Baseok.done;
473 }
474
475 /************************************
476 * Search base classes in depth-first, left-to-right order for
477 * a class or interface named 'ident'.
478 * Stops at first found. Does not look for additional matches.
479 * Params:
480 * ident = identifier to search for
481 * Returns:
482 * ClassDeclaration if found, null if not
483 */
484 extern (D) final ClassDeclaration searchBase(Identifier ident)
485 {
486 foreach (b; *baseclasses)
487 {
488 auto cdb = b.type.isClassHandle();
489 if (!cdb) // https://issues.dlang.org/show_bug.cgi?id=10616
490 return null;
491 if (cdb.ident.equals(ident))
492 return cdb;
493 if (auto result = cdb.searchBase(ident))
494 return result;
495 }
496 return null;
497 }
498
499 final override void finalizeSize()
500 {
501 assert(sizeok != Sizeok.done);
502
503 // Set the offsets of the fields and determine the size of the class
504 if (baseClass)
505 {
506 assert(baseClass.sizeok == Sizeok.done);
507
508 alignsize = baseClass.alignsize;
509 if (classKind == ClassKind.cpp)
510 structsize = target.cpp.derivedClassOffset(baseClass);
511 else
512 structsize = baseClass.structsize;
513 }
514 else if (classKind == ClassKind.objc)
515 structsize = 0; // no hidden member for an Objective-C class
516 else if (isInterfaceDeclaration())
517 {
518 if (interfaces.length == 0)
519 {
520 alignsize = target.ptrsize;
521 structsize = target.ptrsize; // allow room for __vptr
522 }
523 }
524 else
525 {
526 alignsize = target.ptrsize;
527 structsize = target.ptrsize; // allow room for __vptr
528 if (hasMonitor())
529 structsize += target.ptrsize; // allow room for __monitor
530 }
531
532 //printf("finalizeSize() %s, sizeok = %d\n", toChars(), sizeok);
533 size_t bi = 0; // index into vtblInterfaces[]
534
535 /****
536 * Runs through the inheritance graph to set the BaseClass.offset fields.
537 * Recursive in order to account for the size of the interface classes, if they are
538 * more than just interfaces.
539 * Params:
540 * cd = interface to look at
541 * baseOffset = offset of where cd will be placed
542 * Returns:
543 * subset of instantiated size used by cd for interfaces
544 */
545 uint membersPlace(ClassDeclaration cd, uint baseOffset)
546 {
547 //printf(" membersPlace(%s, %d)\n", cd.toChars(), baseOffset);
548 uint offset = baseOffset;
549
550 foreach (BaseClass* b; cd.interfaces)
551 {
552 if (b.sym.sizeok != Sizeok.done)
553 b.sym.finalizeSize();
554 assert(b.sym.sizeok == Sizeok.done);
555
556 if (!b.sym.alignsize)
557 b.sym.alignsize = target.ptrsize;
558 offset = alignmember(structalign_t(cast(ushort)b.sym.alignsize), b.sym.alignsize, offset);
559 assert(bi < vtblInterfaces.length);
560
561 BaseClass* bv = (*vtblInterfaces)[bi];
562 if (b.sym.interfaces.length == 0)
563 {
564 //printf("\tvtblInterfaces[%d] b=%p b.sym = %s, offset = %d\n", bi, bv, bv.sym.toChars(), offset);
565 bv.offset = offset;
566 ++bi;
567 // All the base interfaces down the left side share the same offset
568 for (BaseClass* b2 = bv; b2.baseInterfaces.length; )
569 {
570 b2 = &b2.baseInterfaces[0];
571 b2.offset = offset;
572 //printf("\tvtblInterfaces[%d] b=%p sym = %s, offset = %d\n", bi, b2, b2.sym.toChars(), b2.offset);
573 }
574 }
575 membersPlace(b.sym, offset);
576 //printf(" %s size = %d\n", b.sym.toChars(), b.sym.structsize);
577 offset += b.sym.structsize;
578 if (alignsize < b.sym.alignsize)
579 alignsize = b.sym.alignsize;
580 }
581 return offset - baseOffset;
582 }
583
584 structsize += membersPlace(this, structsize);
585
586 if (isInterfaceDeclaration())
587 {
588 sizeok = Sizeok.done;
589 return;
590 }
591
592 // FIXME: Currently setFieldOffset functions need to increase fields
593 // to calculate each variable offsets. It can be improved later.
594 fields.setDim(0);
595
596 FieldState fieldState;
597 fieldState.offset = structsize;
598 foreach (s; *members)
599 {
600 s.setFieldOffset(this, &fieldState, false);
601 }
602
603 sizeok = Sizeok.done;
604
605 // Calculate fields[i].overlapped
606 checkOverlappedFields();
607 }
608
609 /**************
610 * Returns: true if there's a __monitor field
611 */
612 final bool hasMonitor()
613 {
614 return classKind == ClassKind.d;
615 }
616
617 /****************
618 * Find virtual function matching identifier and type.
619 * Used to build virtual function tables for interface implementations.
620 * Params:
621 * ident = function's identifier
622 * tf = function's type
623 * Returns:
624 * function symbol if found, null if not
625 * Errors:
626 * prints error message if more than one match
627 */
628 extern (D) final FuncDeclaration findFunc(Identifier ident, TypeFunction tf)
629 {
630 //printf("ClassDeclaration.findFunc(%s, %s) %s\n", ident.toChars(), tf.toChars(), toChars());
631 FuncDeclaration fdmatch = null;
632 FuncDeclaration fdambig = null;
633
634 void updateBestMatch(FuncDeclaration fd)
635 {
636 fdmatch = fd;
637 fdambig = null;
638 //printf("Lfd fdmatch = %s %s [%s]\n", fdmatch.toChars(), fdmatch.type.toChars(), fdmatch.loc.toChars());
639 }
640
641 void searchVtbl(ref Dsymbols vtbl)
642 {
643 import dmd.typesem : covariant;
644 bool seenInterfaceVirtual;
645 foreach (s; vtbl)
646 {
647 auto fd = s.isFuncDeclaration();
648 if (!fd)
649 continue;
650
651 // the first entry might be a ClassInfo
652 //printf("\t[%d] = %s\n", i, fd.toChars());
653 if (ident != fd.ident || fd.type.covariant(tf) != Covariant.yes)
654 {
655 //printf("\t\t%d\n", fd.type.covariant(tf));
656 continue;
657 }
658
659 //printf("fd.parent.isClassDeclaration() = %p\n", fd.parent.isClassDeclaration());
660 if (!fdmatch)
661 {
662 updateBestMatch(fd);
663 continue;
664 }
665 if (fd == fdmatch)
666 continue;
667
668 /* Functions overriding interface functions for extern(C++) with VC++
669 * are not in the normal vtbl, but in vtblFinal. If the implementation
670 * is again overridden in a child class, both would be found here.
671 * The function in the child class should override the function
672 * in the base class, which is done here, because searchVtbl is first
673 * called for the child class. Checking seenInterfaceVirtual makes
674 * sure, that the compared functions are not in the same vtbl.
675 */
676 if (fd.interfaceVirtual &&
677 fd.interfaceVirtual is fdmatch.interfaceVirtual &&
678 !seenInterfaceVirtual &&
679 fdmatch.type.covariant(fd.type) == Covariant.yes)
680 {
681 seenInterfaceVirtual = true;
682 continue;
683 }
684
685 {
686 // Function type matching: exact > covariant
687 MATCH m1 = tf.equals(fd.type) ? MATCH.exact : MATCH.nomatch;
688 MATCH m2 = tf.equals(fdmatch.type) ? MATCH.exact : MATCH.nomatch;
689 if (m1 > m2)
690 {
691 updateBestMatch(fd);
692 continue;
693 }
694 else if (m1 < m2)
695 continue;
696 }
697 {
698 MATCH m1 = (tf.mod == fd.type.mod) ? MATCH.exact : MATCH.nomatch;
699 MATCH m2 = (tf.mod == fdmatch.type.mod) ? MATCH.exact : MATCH.nomatch;
700 if (m1 > m2)
701 {
702 updateBestMatch(fd);
703 continue;
704 }
705 else if (m1 < m2)
706 continue;
707 }
708 {
709 // The way of definition: non-mixin > mixin
710 MATCH m1 = fd.parent.isClassDeclaration() ? MATCH.exact : MATCH.nomatch;
711 MATCH m2 = fdmatch.parent.isClassDeclaration() ? MATCH.exact : MATCH.nomatch;
712 if (m1 > m2)
713 {
714 updateBestMatch(fd);
715 continue;
716 }
717 else if (m1 < m2)
718 continue;
719 }
720
721 fdambig = fd;
722 //printf("Lambig fdambig = %s %s [%s]\n", fdambig.toChars(), fdambig.type.toChars(), fdambig.loc.toChars());
723 }
724 }
725
726 searchVtbl(vtbl);
727 for (auto cd = this; cd; cd = cd.baseClass)
728 {
729 searchVtbl(cd.vtblFinal);
730 }
731
732 if (fdambig)
733 classError("%s `%s` ambiguous virtual function `%s`", fdambig.toChars());
734
735 return fdmatch;
736 }
737
738 /****************************************
739 */
740 final bool isCOMclass() const
741 {
742 return com;
743 }
744
745 bool isCOMinterface() const
746 {
747 return false;
748 }
749
750 final bool isCPPclass() const
751 {
752 return classKind == ClassKind.cpp;
753 }
754
755 bool isCPPinterface() const
756 {
757 return false;
758 }
759
760 /****************************************
761 */
762 final bool isAbstract()
763 {
764 enum log = false;
765 if (isabstract != ThreeState.none)
766 return isabstract == ThreeState.yes;
767
768 if (log) printf("isAbstract(%s)\n", toChars());
769
770 bool no() { if (log) printf("no\n"); isabstract = ThreeState.no; return false; }
771 bool yes() { if (log) printf("yes\n"); isabstract = ThreeState.yes; return true; }
772
773 if (storage_class & STC.abstract_ || _scope && _scope.stc & STC.abstract_)
774 return yes();
775
776 if (errors)
777 return no();
778
779 /* https://issues.dlang.org/show_bug.cgi?id=11169
780 * Resolve forward references to all class member functions,
781 * and determine whether this class is abstract.
782 */
783 static int func(Dsymbol s, void*)
784 {
785 auto fd = s.isFuncDeclaration();
786 if (!fd)
787 return 0;
788 if (fd.storage_class & STC.static_)
789 return 0;
790
791 if (fd.isAbstract())
792 return 1;
793 return 0;
794 }
795
796 // opaque class is not abstract if it is not declared abstract
797 if (!members)
798 return no();
799
800 for (size_t i = 0; i < members.length; i++)
801 {
802 auto s = (*members)[i];
803 if (s.apply(&func, null))
804 {
805 return yes();
806 }
807 }
808
809 /* If the base class is not abstract, then this class cannot
810 * be abstract.
811 */
812 if (!isInterfaceDeclaration() && (!baseClass || !baseClass.isAbstract()))
813 return no();
814
815 /* If any abstract functions are inherited, but not overridden,
816 * then the class is abstract. Do this by checking the vtbl[].
817 * Need to do semantic() on class to fill the vtbl[].
818 */
819 this.dsymbolSemantic(null);
820
821 /* The next line should work, but does not because when ClassDeclaration.dsymbolSemantic()
822 * is called recursively it can set PASS.semanticdone without finishing it.
823 */
824 //if (semanticRun < PASS.semanticdone)
825 {
826 /* Could not complete semantic(). Try running semantic() on
827 * each of the virtual functions,
828 * which will fill in the vtbl[] overrides.
829 */
830 static int virtualSemantic(Dsymbol s, void*)
831 {
832 auto fd = s.isFuncDeclaration();
833 if (fd && !(fd.storage_class & STC.static_) && !fd.isUnitTestDeclaration())
834 fd.dsymbolSemantic(null);
835 return 0;
836 }
837
838 for (size_t i = 0; i < members.length; i++)
839 {
840 auto s = (*members)[i];
841 s.apply(&virtualSemantic,null);
842 }
843 }
844
845 /* Finally, check the vtbl[]
846 */
847 foreach (i; 1 .. vtbl.length)
848 {
849 auto fd = vtbl[i].isFuncDeclaration();
850 //if (fd) printf("\tvtbl[%d] = [%s] %s\n", i, fd.loc.toChars(), fd.toPrettyChars());
851 if (!fd || fd.isAbstract())
852 {
853 return yes();
854 }
855 }
856
857 return no();
858 }
859
860 /****************************************
861 * Determine if slot 0 of the vtbl[] is reserved for something else.
862 * For class objects, yes, this is where the classinfo ptr goes.
863 * For COM interfaces, no.
864 * For non-COM interfaces, yes, this is where the Interface ptr goes.
865 * Returns:
866 * 0 vtbl[0] is first virtual function pointer
867 * 1 vtbl[0] is classinfo/interfaceinfo pointer
868 */
869 int vtblOffset() const
870 {
871 return classKind == ClassKind.cpp ? 0 : 1;
872 }
873
874 /****************************************
875 */
876 override const(char)* kind() const
877 {
878 return "class";
879 }
880
881 /****************************************
882 */
883 override final void addObjcSymbols(ClassDeclarations* classes, ClassDeclarations* categories)
884 {
885 .objc.addSymbols(this, classes, categories);
886 }
887
888 // Back end
889 Dsymbol vtblsym;
890
891 extern (D) final bool isErrorException()
892 {
893 return errorException && (this == errorException || errorException.isBaseOf(this, null));
894 }
895
896 override void accept(Visitor v)
897 {
898 v.visit(this);
899 }
900 }
901
902 /***********************************************************
903 */
904 extern (C++) final class InterfaceDeclaration : ClassDeclaration
905 {
906 extern (D) this(Loc loc, Identifier id, BaseClasses* baseclasses)
907 {
908 super(loc, id, baseclasses, null, false);
909 this.dsym = DSYM.interfaceDeclaration;
910 if (id == Id.IUnknown) // IUnknown is the root of all COM interfaces
911 {
912 com = true;
913 classKind = ClassKind.cpp; // IUnknown is also a C++ interface
914 }
915 }
916
917 override InterfaceDeclaration syntaxCopy(Dsymbol s)
918 {
919 InterfaceDeclaration id =
920 s ? cast(InterfaceDeclaration)s
921 : new InterfaceDeclaration(loc, ident, null);
922 ClassDeclaration.syntaxCopy(id);
923 return id;
924 }
925
926
927 override Scope* newScope(Scope* sc)
928 {
929 auto sc2 = super.newScope(sc);
930 if (com)
931 sc2.linkage = LINK.windows;
932 else if (classKind == ClassKind.cpp)
933 sc2.linkage = LINK.cpp;
934 else if (classKind == ClassKind.objc)
935 sc2.linkage = LINK.objc;
936 return sc2;
937 }
938
939 /*******************************************
940 * Determine if 'this' is a base class of cd.
941 * (Actually, if it is an interface supported by cd)
942 * Output:
943 * *poffset offset to start of class
944 * OFFSET_RUNTIME must determine offset at runtime
945 * Returns:
946 * false not a base
947 * true is a base
948 */
949 override bool isBaseOf(ClassDeclaration cd, int* poffset) pure nothrow @nogc
950 {
951 //printf("%s.InterfaceDeclaration.isBaseOf(cd = '%s')\n", toChars(), cd.toChars());
952 assert(!baseClass);
953 foreach (b; cd.interfaces)
954 {
955 //printf("\tX base %s\n", b.sym.toChars());
956 if (this == b.sym)
957 {
958 //printf("\tfound at offset %d\n", b.offset);
959 if (poffset)
960 {
961 // don't return incorrect offsets
962 // https://issues.dlang.org/show_bug.cgi?id=16980
963 *poffset = cd.sizeok == Sizeok.done ? b.offset : OFFSET_FWDREF;
964 }
965 // printf("\tfound at offset %d\n", b.offset);
966 return true;
967 }
968 if (baseClassImplementsInterface(this, b, poffset))
969 return true;
970 }
971 if (cd.baseClass && isBaseOf(cd.baseClass, poffset))
972 return true;
973
974 if (poffset)
975 *poffset = 0;
976 return false;
977 }
978
979 /*******************************************
980 */
981 override const(char)* kind() const
982 {
983 return "interface";
984 }
985
986 /****************************************
987 * Determine if slot 0 of the vtbl[] is reserved for something else.
988 * For class objects, yes, this is where the ClassInfo ptr goes.
989 * For COM interfaces, no.
990 * For non-COM interfaces, yes, this is where the Interface ptr goes.
991 */
992 override int vtblOffset() const
993 {
994 if (isCOMinterface() || isCPPinterface())
995 return 0;
996 return 1;
997 }
998
999 override bool isCPPinterface() const
1000 {
1001 return classKind == ClassKind.cpp;
1002 }
1003
1004 override bool isCOMinterface() const
1005 {
1006 return com;
1007 }
1008
1009 override void accept(Visitor v)
1010 {
1011 v.visit(this);
1012 }
1013 }
1014
1015 /**
1016 * Returns whether `bc` implements `id`, including indirectly (`bc` implements an interfaces
1017 * that inherits from `id`)
1018 *
1019 * Params:
1020 * id = the interface
1021 * bc = the base class
1022 * poffset = out parameter, offset of the interface in an object
1023 *
1024 * Returns:
1025 * true if the `bc` implements `id`, false otherwise
1026 **/
1027 private bool baseClassImplementsInterface(InterfaceDeclaration id, BaseClass* bc, int* poffset) pure nothrow @nogc @safe
1028 {
1029 //printf("%s.InterfaceDeclaration.isBaseOf(bc = '%s')\n", id.toChars(), bc.sym.toChars());
1030 for (size_t j = 0; j < bc.baseInterfaces.length; j++)
1031 {
1032 BaseClass* b = &bc.baseInterfaces[j];
1033 //printf("\tY base %s\n", b.sym.toChars());
1034 if (id == b.sym)
1035 {
1036 //printf("\tfound at offset %d\n", b.offset);
1037 if (poffset)
1038 {
1039 *poffset = b.offset;
1040 }
1041 return true;
1042 }
1043 if (baseClassImplementsInterface(id, b, poffset))
1044 {
1045 return true;
1046 }
1047 }
1048
1049 if (poffset)
1050 *poffset = 0;
1051 return false;
1052 }