Debian Codegraph @

gcc/d/dmd/objc.d

raw
1 /**
2 * Interfacing with Objective-C.
3 *
4 * Specification: $(LINK2 https://dlang.org/spec/objc_interface.html, Interfacing to Objective-C)
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/objc.d, _objc.d)
10 * Documentation: https://dlang.org/phobos/dmd_objc.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/objc.d
12 */
13
14 module dmd.objc;
15
16 import dmd.aggregate;
17 import dmd.arraytypes;
18 import dmd.astenums;
19 import dmd.attrib;
20 import dmd.attribsem;
21 import dmd.cond;
22 import dmd.dclass;
23 import dmd.declaration;
24 import dmd.denum;
25 import dmd.dmodule;
26 import dmd.dscope;
27 import dmd.dstruct;
28 import dmd.dsymbol;
29 import dmd.dsymbolsem;
30 import dmd.errors;
31 import dmd.expression;
32 import dmd.expressionsem;
33 import dmd.func;
34 import dmd.globals;
35 import dmd.gluelayer;
36 import dmd.hdrgen;
37 import dmd.id;
38 import dmd.identifier;
39 import dmd.location;
40 import dmd.mangle;
41 import dmd.mtype;
42 import dmd.root.array;
43 import dmd.common.outbuffer;
44 import dmd.root.stringtable;
45 import dmd.target;
46 import dmd.tokens;
47
48 struct ObjcSelector
49 {
50 // MARK: Selector
51 private __gshared StringTable!(ObjcSelector*) stringtable;
52 private __gshared int incnum = 0;
53 const(char)* stringvalue;
54 size_t stringlen;
55 size_t paramCount;
56
57 extern (C++) static void _init()
58 {
59 stringtable._init();
60 }
61
62 extern (D) this(const(char)* sv, size_t len, size_t pcount) @safe
63 {
64 stringvalue = sv;
65 stringlen = len;
66 paramCount = pcount;
67 }
68
69 extern (D) static ObjcSelector* lookup(const(char)* s)
70 {
71 size_t len = 0;
72 size_t pcount = 0;
73 const(char)* i = s;
74 while (*i != 0)
75 {
76 ++len;
77 if (*i == ':')
78 ++pcount;
79 ++i;
80 }
81 return lookup(s, len, pcount);
82 }
83
84 extern (D) static ObjcSelector* lookup(const(char)* s, size_t len, size_t pcount)
85 {
86 auto sv = stringtable.update(s, len);
87 ObjcSelector* sel = sv.value;
88 if (!sel)
89 {
90 sel = new ObjcSelector(sv.toDchars(), len, pcount);
91 sv.value = sel;
92 }
93 return sel;
94 }
95
96 static const(char)[] toPascalCase(const(char)[] id) {
97 OutBuffer buf;
98 char firstChar = id[0];
99 if (firstChar >= 'a' && firstChar <= 'z')
100 firstChar = cast(char)(firstChar - 'a' + 'A');
101
102 buf.writeByte(firstChar);
103 buf.writestring(id[1..$]);
104 return cast(const(char)[])buf.extractSlice(false);
105 }
106
107 extern (C++) static ObjcSelector* create(FuncDeclaration fdecl)
108 {
109 OutBuffer buf;
110 auto ftype = cast(TypeFunction)fdecl.type;
111 const id = fdecl.ident.toString();
112 const nparams = ftype.parameterList.length;
113
114 // Special case: property setter
115 if (ftype.isProperty && nparams == 1)
116 {
117
118 // Special case: "isXYZ:"
119 if (id.length >= 2 && id[0..2] == "is")
120 {
121 buf.writestring("set");
122 buf.write(toPascalCase(id[2..$]));
123 }
124 else
125 {
126 buf.writestring("set");
127 buf.write(toPascalCase(id));
128 }
129 buf.writeByte(':');
130 goto Lcomplete;
131 }
132
133 // write identifier in selector
134 buf.write(id[]);
135
136 // To make it easier to match the selectors of objects nicely,
137 // the implementation has been replaced so that the parameter name followed by a colon
138 // is used instead.
139 // eg. void myFunction(int a, int b, int c) would be mangled to a selector as `myFunction:b:c:
140 if (nparams > 1)
141 {
142 buf.writeByte(':');
143 foreach(i; 1..nparams)
144 {
145 buf.write(ftype.parameterList[i].ident.toString());
146 buf.writeByte(':');
147 }
148 }
149 else if (nparams == 1)
150 {
151 buf.writeByte(':');
152 }
153 Lcomplete:
154 buf.writeByte('\0');
155
156 // the slice is not expected to include a terminating 0
157 return lookup(cast(const(char)*)buf[].ptr, buf.length - 1, nparams);
158 }
159
160 extern (D) const(char)[] toString() const pure
161 {
162 return stringvalue[0 .. stringlen];
163 }
164 }
165
166 private __gshared Objc _objc;
167
168 Objc objc()
169 {
170 return _objc;
171 }
172
173
174 /**
175 * Contains all data for a class declaration that is needed for the Objective-C
176 * integration.
177 */
178 extern (C++) struct ObjcClassDeclaration
179 {
180 /// `true` if this class is a metaclass.
181 bool isMeta = false;
182
183 /// `true` if this class is externally defined.
184 bool isExtern = false;
185
186 /// Name of this class.
187 Identifier identifier;
188
189 /// The class declaration this belongs to.
190 ClassDeclaration classDeclaration;
191
192 /// The metaclass of this class.
193 ClassDeclaration metaclass;
194
195 /// List of non-inherited methods.
196 FuncDeclaration[] methodList;
197
198 extern (D) this(ClassDeclaration classDeclaration) @safe
199 {
200 this.classDeclaration = classDeclaration;
201 }
202
203 bool isRootClass() const @safe
204 {
205 return classDeclaration.classKind == ClassKind.objc &&
206 !metaclass &&
207 !classDeclaration.baseClass;
208 }
209 }
210
211 /**
212 * Contains all data for a function declaration that is needed for the
213 * Objective-C integration.
214 */
215 extern (C++) struct ObjcFuncDeclaration
216 {
217 /// The method selector (member functions only).
218 ObjcSelector* selector;
219
220 /// The implicit selector parameter.
221 VarDeclaration selectorParameter;
222
223 /// `true` if this function declaration is declared optional.
224 bool isOptional;
225 }
226
227 // Should be an interface
228 extern(C++) abstract class Objc
229 {
230 static void _init()
231 {
232 if (target.objc.supported)
233 _objc = new Supported;
234 else
235 _objc = new Unsupported;
236 }
237
238 /**
239 * Deinitializes the global state of the compiler.
240 *
241 * This can be used to restore the state set by `_init` to its original
242 * state.
243 */
244 static void deinitialize()
245 {
246 _objc = _objc.init;
247 }
248
249 abstract void setObjc(ClassDeclaration cd);
250 abstract void setObjc(InterfaceDeclaration);
251
252 /**
253 * Returns a pretty textual representation of the given class declaration.
254 *
255 * Params:
256 * classDeclaration = the class declaration to return the textual representation for
257 * qualifyTypes = `true` if types should be qualified in the result
258 *
259 * Returns: the textual representation
260 */
261 abstract const(char)* toPrettyChars(ClassDeclaration classDeclaration, bool qualifyTypes) const;
262
263 abstract void setSelector(FuncDeclaration, Scope* sc);
264 abstract void validateSelector(FuncDeclaration fd);
265 abstract void checkLinkage(FuncDeclaration fd);
266
267 /**
268 * Returns `true` if the given function declaration is virtual.
269 *
270 * Function declarations with Objective-C linkage and which are static or
271 * final are considered virtual.
272 *
273 * Params:
274 * fd = the function declaration to check if it's virtual
275 *
276 * Returns: `true` if the given function declaration is virtual
277 */
278 abstract bool isVirtual(const FuncDeclaration fd) const;
279
280 /**
281 * Marks the given function declaration as optional.
282 *
283 * A function declaration is considered optional if it's annotated with the
284 * UDA: `@(core.attribute.optional)`. Only function declarations inside
285 * interface declarations and with Objective-C linkage can be declared as
286 * optional.
287 *
288 * Params:
289 * functionDeclaration = the function declaration to be set as optional
290 * sc = the scope from the semantic phase
291 */
292 abstract void setAsOptional(FuncDeclaration functionDeclaration, Scope* sc) const;
293
294 /**
295 * Validates function declarations declared optional.
296 *
297 * Params:
298 * functionDeclaration = the function declaration to validate
299 */
300 abstract void validateOptional(FuncDeclaration functionDeclaration) const;
301
302 /**
303 * Gets the parent of the given function declaration.
304 *
305 * Handles Objective-C static member functions, which are virtual functions
306 * of the metaclass, by returning the parent class declaration to the
307 * metaclass.
308 *
309 * Params:
310 * fd = the function declaration to get the parent of
311 * cd = the current parent, i.e. the class declaration the given function
312 * declaration belongs to
313 *
314 * Returns: the parent
315 */
316 abstract ClassDeclaration getParent(FuncDeclaration fd,
317 ClassDeclaration cd) const;
318
319 /**
320 * Adds the given function to the list of Objective-C methods.
321 *
322 * This list will later be used output the necessary Objective-C module info.
323 *
324 * Params:
325 * fd = the function declaration to be added to the list
326 * cd = the class declaration the function belongs to
327 */
328 abstract void addToClassMethodList(FuncDeclaration fd,
329 ClassDeclaration cd) const;
330
331 /**
332 * Returns the `this` pointer of the given function declaration.
333 *
334 * This is only used for class/static methods. For instance methods, no
335 * Objective-C specialization is necessary.
336 *
337 * Params:
338 * funcDeclaration = the function declaration to get the `this` pointer for
339 *
340 * Returns: the `this` pointer of the given function declaration, or `null`
341 * if the given function declaration is not an Objective-C method.
342 */
343 abstract inout(AggregateDeclaration) isThis(inout FuncDeclaration funcDeclaration) const;
344
345 /**
346 * Creates the selector parameter for the given function declaration.
347 *
348 * Objective-C methods has an extra hidden parameter that comes after the
349 * `this` parameter. The selector parameter is of the Objective-C type `SEL`
350 * and contains the selector which this method was called with.
351 *
352 * Params:
353 * fd = the function declaration to create the parameter for
354 * sc = the scope from the semantic phase
355 *
356 * Returns: the newly created selector parameter or `null` for
357 * non-Objective-C functions
358 */
359 abstract VarDeclaration createSelectorParameter(FuncDeclaration fd, Scope* sc) const;
360
361 /**
362 * Creates and sets the metaclass on the given class/interface declaration.
363 *
364 * Will only be performed on regular Objective-C classes, not on metaclasses.
365 *
366 * Params:
367 * classDeclaration = the class/interface declaration to set the metaclass on
368 */
369 abstract void setMetaclass(InterfaceDeclaration interfaceDeclaration, Scope* sc) const;
370
371 /// ditto
372 abstract void setMetaclass(ClassDeclaration classDeclaration, Scope* sc) const;
373
374 /**
375 * Returns Objective-C runtime metaclass of the given class declaration.
376 *
377 * `ClassDeclaration.ObjcClassDeclaration.metaclass` contains the metaclass
378 * from the semantic point of view. This function returns the metaclass from
379 * the Objective-C runtime's point of view. Here, the metaclass of a
380 * metaclass is the root metaclass, not `null`. The root metaclass's
381 * metaclass is itself.
382 *
383 * Params:
384 * classDeclaration = The class declaration to return the metaclass of
385 *
386 * Returns: the Objective-C runtime metaclass of the given class declaration
387 */
388 abstract ClassDeclaration getRuntimeMetaclass(ClassDeclaration classDeclaration) const;
389
390 ///
391 abstract void addSymbols(AttribDeclaration attribDeclaration,
392 ClassDeclarations* classes, ClassDeclarations* categories) const;
393
394 ///
395 abstract void addSymbols(ClassDeclaration classDeclaration,
396 ClassDeclarations* classes, ClassDeclarations* categories) const;
397
398 /**
399 * Issues a compile time error if the `.offsetof`/`.tupleof` property is
400 * used on a field of an Objective-C class.
401 *
402 * To solve the fragile base class problem in Objective-C, fields have a
403 * dynamic offset instead of a static offset. The compiler outputs a
404 * statically known offset which later the dynamic loader can update, if
405 * necessary, when the application is loaded. Due to this behavior it
406 * doesn't make sense to be able to get the offset of a field at compile
407 * time, because this offset might not actually be the same at runtime.
408 *
409 * To get the offset of a field that is correct at runtime, functionality
410 * from the Objective-C runtime can be used instead.
411 *
412 * Params:
413 * expression = the `.offsetof`/`.tupleof` expression
414 * aggregateDeclaration = the aggregate declaration the field of the
415 * `.offsetof`/`.tupleof` expression belongs to
416 * type = the type of the receiver of the `.tupleof` expression
417 *
418 * See_Also:
419 * $(LINK2 https://en.wikipedia.org/wiki/Fragile_binary_interface_problem,
420 * Fragile Binary Interface Problem)
421 *
422 * See_Also:
423 * $(LINK2 https://developer.apple.com/documentation/objectivec/objective_c_runtime,
424 * Objective-C Runtime)
425 */
426 abstract void checkOffsetof(Expression expression, AggregateDeclaration aggregateDeclaration) const;
427
428 /// ditto
429 abstract void checkTupleof(Expression expression, TypeClass type) const;
430 }
431
432 extern(C++) private final class Unsupported : Objc
433 {
434 extern(D) final this()
435 {
436 ObjcGlue.initialize();
437 }
438
439 override void setObjc(ClassDeclaration cd)
440 {
441 .error(cd.loc, "%s `%s` Objective-C classes not supported", cd.kind, cd.toPrettyChars);
442 }
443
444 override void setObjc(InterfaceDeclaration id)
445 {
446 .error(id.loc, "%s `%s` Objective-C interfaces not supported", id.kind, id.toPrettyChars);
447 }
448
449 override const(char)* toPrettyChars(ClassDeclaration, bool qualifyTypes) const
450 {
451 assert(0, "Should never be called when Objective-C is not supported");
452 }
453
454 override void setSelector(FuncDeclaration, Scope*)
455 {
456 // noop
457 }
458
459 override void validateSelector(FuncDeclaration)
460 {
461 // noop
462 }
463
464 override void checkLinkage(FuncDeclaration)
465 {
466 // noop
467 }
468
469 override bool isVirtual(const FuncDeclaration) const
470 {
471 assert(0, "Should never be called when Objective-C is not supported");
472 }
473
474 override void setAsOptional(FuncDeclaration, Scope*) const
475 {
476 // noop
477 }
478
479 override void validateOptional(FuncDeclaration) const
480 {
481 // noop
482 }
483
484 override ClassDeclaration getParent(FuncDeclaration, ClassDeclaration cd) const
485 {
486 return cd;
487 }
488
489 override void addToClassMethodList(FuncDeclaration, ClassDeclaration) const
490 {
491 // noop
492 }
493
494 override inout(AggregateDeclaration) isThis(inout FuncDeclaration funcDeclaration) const
495 {
496 return null;
497 }
498
499 override VarDeclaration createSelectorParameter(FuncDeclaration, Scope*) const
500 {
501 return null;
502 }
503
504 override void setMetaclass(InterfaceDeclaration, Scope*) const
505 {
506 // noop
507 }
508
509 override void setMetaclass(ClassDeclaration, Scope*) const
510 {
511 // noop
512 }
513
514 override ClassDeclaration getRuntimeMetaclass(ClassDeclaration classDeclaration) const
515 {
516 assert(0, "Should never be called when Objective-C is not supported");
517 }
518
519 override void addSymbols(AttribDeclaration attribDeclaration,
520 ClassDeclarations* classes, ClassDeclarations* categories) const
521 {
522 // noop
523 }
524
525 override void addSymbols(ClassDeclaration classDeclaration,
526 ClassDeclarations* classes, ClassDeclarations* categories) const
527 {
528 // noop
529 }
530
531 override void checkOffsetof(Expression expression, AggregateDeclaration aggregateDeclaration) const
532 {
533 // noop
534 }
535
536 override void checkTupleof(Expression expression, TypeClass type) const
537 {
538 // noop
539 }
540 }
541
542 extern(C++) private final class Supported : Objc
543 {
544 extern(D) final this()
545 {
546 VersionCondition.addPredefinedGlobalIdent("D_ObjectiveC");
547
548 ObjcGlue.initialize();
549 ObjcSelector._init();
550 }
551
552 override void setObjc(ClassDeclaration cd)
553 {
554 cd.classKind = ClassKind.objc;
555 cd.objc.isExtern = (cd.storage_class & STC.extern_) > 0;
556 }
557
558 override void setObjc(InterfaceDeclaration id)
559 {
560 id.classKind = ClassKind.objc;
561 id.objc.isExtern = true;
562 }
563
564 override const(char)* toPrettyChars(ClassDeclaration cd, bool qualifyTypes) const
565 {
566 return cd.parent.toPrettyChars(qualifyTypes);
567 }
568
569 override void setSelector(FuncDeclaration fd, Scope* sc)
570 {
571 foreachUda(fd, sc, (e) {
572 if (!e.isStructLiteralExp())
573 return 0;
574
575 auto literal = e.isStructLiteralExp();
576 assert(literal.sd);
577
578 if (!isCoreUda(literal.sd, Id.udaSelector))
579 return 0;
580
581 if (fd.objc.selector)
582 {
583 .error(fd.loc, "%s `%s` can only have one Objective-C selector per method", fd.kind, fd.toPrettyChars);
584 return 1;
585 }
586
587 assert(literal.elements.length == 1);
588 auto se = (*literal.elements)[0].toStringExp();
589 assert(se);
590
591 fd.objc.selector = ObjcSelector.lookup(se.toUTF8(sc).peekString().ptr);
592
593 return 0;
594 });
595
596 // Avoid attempting to generate selectors for template instances.
597 if (fd.parent && fd.parent.isTemplateInstance())
598 return;
599
600 // No selector declared, generate one.
601 if (fd._linkage == LINK.objc && !fd.objc.selector)
602 {
603 fd.objc.selector = ObjcSelector.create(fd);
604 }
605 }
606
607 override void validateSelector(FuncDeclaration fd)
608 {
609 if (!fd.objc.selector)
610 return;
611 auto tf = cast(TypeFunction)fd.type;
612 if (fd.objc.selector.paramCount != tf.parameterList.parameters.length)
613 .error(fd.loc, "%s `%s` number of colons in Objective-C selector must match number of parameters", fd.kind, fd.toPrettyChars);
614 if (fd.parent && fd.parent.isTemplateInstance())
615 .error(fd.loc, "%s `%s` template cannot have an Objective-C selector attached", fd.kind, fd.toPrettyChars);
616 }
617
618 override void checkLinkage(FuncDeclaration fd)
619 {
620 if (fd._linkage != LINK.objc && fd.objc.selector)
621 .error(fd.loc, "%s `%s` must have Objective-C linkage to attach a selector", fd.kind, fd.toPrettyChars);
622 }
623
624 override bool isVirtual(const FuncDeclaration fd) const
625 in
626 {
627 assert(fd.selector);
628 assert(fd.isMember);
629 }
630 do
631 {
632 if (fd.toParent.isInterfaceDeclaration && fd.isFinal)
633 return false;
634
635 // * final member functions are kept virtual with Objective-C linkage
636 // because the Objective-C runtime always use dynamic dispatch.
637 // * static member functions are kept virtual too, as they represent
638 // methods of the metaclass.
639 with (fd.visibility)
640 return !(kind == Visibility.Kind.private_ || kind == Visibility.Kind.package_);
641 }
642
643 override void setAsOptional(FuncDeclaration fd, Scope* sc) const
644 {
645 const count = declaredAsOptionalCount(fd, sc);
646 fd.objc.isOptional = count > 0;
647
648 if (count > 1)
649 .error(fd.loc, "%s `%s` can only declare a function as optional once", fd.kind, fd.toPrettyChars);
650 }
651
652 /// Returns: the number of times `fd` has been declared as optional.
653 private int declaredAsOptionalCount(FuncDeclaration fd , Scope* sc) const
654 {
655 int count;
656
657 foreachUda(fd, sc, (e) {
658 if (!e.isTypeExp())
659 return 0;
660
661 auto typeExp = e.isTypeExp();
662
663 if (typeExp.type.ty != Tenum)
664 return 0;
665
666 auto typeEnum = cast(TypeEnum) typeExp.type;
667
668 if (isCoreUda(typeEnum.sym, Id.udaOptional))
669 count++;
670
671 return 0;
672 });
673
674 return count;
675 }
676
677 override void validateOptional(FuncDeclaration fd) const
678 {
679 if (!fd.objc.isOptional)
680 return;
681
682 if (fd._linkage != LINK.objc)
683 {
684 .error(fd.loc, "%s `%s` only functions with Objective-C linkage can be declared as optional", fd.kind, fd.toPrettyChars);
685
686 const linkage = linkageToString(fd._linkage);
687
688 errorSupplemental(fd.loc, "function is declared with %.*s linkage",
689 cast(uint) linkage.length, linkage.ptr);
690 }
691
692 auto parent = fd.parent;
693
694 if (parent && parent.isTemplateInstance())
695 {
696 .error(fd.loc, "%s `%s` template cannot be optional", fd.kind, fd.toPrettyChars);
697 parent = parent.parent;
698 assert(parent);
699 }
700
701 if (parent && !parent.isInterfaceDeclaration())
702 {
703 .error(fd.loc, "%s `%s` only functions declared inside interfaces can be optional", fd.kind, fd.toPrettyChars);
704 errorSupplemental(fd.loc, "function is declared inside %s", fd.parent.kind);
705 }
706 }
707
708 override ClassDeclaration getParent(FuncDeclaration fd, ClassDeclaration cd) const
709 out(metaclass)
710 {
711 assert(metaclass);
712 }
713 do
714 {
715 if (cd.classKind == ClassKind.objc && fd.isStatic && !cd.objc.isMeta)
716 return cd.objc.metaclass;
717
718 return cd;
719 }
720
721 override void addToClassMethodList(FuncDeclaration fd, ClassDeclaration cd) const
722 in
723 {
724 assert(fd.parent.isClassDeclaration);
725 }
726 do
727 {
728 if (cd.classKind != ClassKind.objc)
729 return;
730
731 if (!fd.objc.selector)
732 return;
733
734 assert(fd.isStatic ? cd.objc.isMeta : !cd.objc.isMeta);
735
736 cd.objc.methodList ~= fd;
737 }
738
739 override inout(AggregateDeclaration) isThis(inout FuncDeclaration funcDeclaration) const
740 {
741 with(funcDeclaration)
742 {
743 if (!objc.selector)
744 return null;
745
746 // Use Objective-C class object as 'this'
747 auto cd = isMember2().isClassDeclaration();
748
749 if (cd.classKind == ClassKind.objc)
750 {
751 if (!cd.objc.isMeta)
752 return cd.objc.metaclass;
753 }
754
755 return null;
756 }
757 }
758
759 override VarDeclaration createSelectorParameter(FuncDeclaration fd, Scope* sc) const
760 in
761 {
762 assert(fd.selectorParameter is null);
763 }
764 do
765 {
766 if (!fd.objc.selector)
767 return null;
768
769 auto ident = Identifier.generateAnonymousId("_cmd");
770 auto var = new VarDeclaration(fd.loc, Type.tvoidptr, ident, null);
771 var.storage_class |= STC.parameter;
772 var.dsymbolSemantic(sc);
773 if (!sc.insert(var))
774 assert(false);
775 var.parent = fd;
776
777 return var;
778 }
779
780 override void setMetaclass(InterfaceDeclaration interfaceDeclaration, Scope* sc) const
781 {
782 auto newMetaclass(Loc loc, BaseClasses* metaBases)
783 {
784 auto ident = createMetaclassIdentifier(interfaceDeclaration);
785 return new InterfaceDeclaration(loc, ident, metaBases);
786 }
787
788 .setMetaclass!newMetaclass(interfaceDeclaration, sc);
789 }
790
791 override void setMetaclass(ClassDeclaration classDeclaration, Scope* sc) const
792 {
793 auto newMetaclass(Loc loc, BaseClasses* metaBases)
794 {
795 auto ident = createMetaclassIdentifier(classDeclaration);
796 return new ClassDeclaration(loc, ident, metaBases, new Dsymbols(), 0);
797 }
798
799 .setMetaclass!newMetaclass(classDeclaration, sc);
800 }
801
802 override ClassDeclaration getRuntimeMetaclass(ClassDeclaration classDeclaration) const
803 {
804 if (!classDeclaration.objc.metaclass && classDeclaration.objc.isMeta)
805 {
806 if (classDeclaration.baseClass)
807 return getRuntimeMetaclass(classDeclaration.baseClass);
808
809 return classDeclaration;
810 }
811 return classDeclaration.objc.metaclass;
812 }
813
814 override void addSymbols(AttribDeclaration attribDeclaration,
815 ClassDeclarations* classes, ClassDeclarations* categories) const
816 {
817 auto symbols = attribDeclaration.include(null);
818
819 if (!symbols)
820 return;
821
822 foreach (symbol; *symbols)
823 symbol.addObjcSymbols(classes, categories);
824 }
825
826 override void addSymbols(ClassDeclaration classDeclaration,
827 ClassDeclarations* classes, ClassDeclarations* categories) const
828 {
829 with (classDeclaration)
830 if (classKind == ClassKind.objc && !objc.isExtern && !objc.isMeta)
831 classes.push(classDeclaration);
832 }
833
834 override void checkOffsetof(Expression expression, AggregateDeclaration aggregateDeclaration) const
835 {
836 if (aggregateDeclaration.classKind != ClassKind.objc)
837 return;
838
839 enum errorMessage = "no property `offsetof` for member `%s` of type " ~
840 "`%s`";
841
842 enum supplementalMessage = "`offsetof` is not available for members " ~
843 "of Objective-C classes. Please use the Objective-C runtime instead";
844
845 error(expression.loc, errorMessage, expression.toChars(),
846 expression.type.toChars());
847 errorSupplemental(expression.loc, supplementalMessage);
848 }
849
850 override void checkTupleof(Expression expression, TypeClass type) const
851 {
852 if (type.sym.classKind != ClassKind.objc)
853 return;
854
855 error(expression.loc, "no property `tupleof` for type `%s`", type.toChars());
856 errorSupplemental(expression.loc, "`tupleof` is not available for members " ~
857 "of Objective-C classes. Please use the Objective-C runtime instead");
858 }
859 }
860
861 /*
862 * Creates and sets the metaclass on the given class/interface declaration.
863 *
864 * Will only be performed on regular Objective-C classes, not on metaclasses.
865 *
866 * Params:
867 * newMetaclass = a function that returns the metaclass to set. This should
868 * return the same type as `T`.
869 * classDeclaration = the class/interface declaration to set the metaclass on
870 */
871 private void setMetaclass(alias newMetaclass, T)(T classDeclaration, Scope* sc)
872 if (is(T == ClassDeclaration) || is(T == InterfaceDeclaration))
873 {
874 static if (is(T == ClassDeclaration))
875 enum errorType = "class";
876 else
877 enum errorType = "interface";
878
879 with (classDeclaration)
880 {
881 if (classKind != ClassKind.objc || objc.isMeta || objc.metaclass)
882 return;
883
884 if (!objc.identifier)
885 objc.identifier = classDeclaration.ident;
886
887 auto metaBases = new BaseClasses();
888
889 foreach (base ; baseclasses.opSlice)
890 {
891 auto baseCd = base.sym;
892 assert(baseCd);
893
894 if (baseCd.classKind == ClassKind.objc)
895 {
896 assert(baseCd.objc.metaclass);
897 assert(baseCd.objc.metaclass.objc.isMeta);
898 assert(baseCd.objc.metaclass.type.ty == Tclass);
899
900 auto metaBase = new BaseClass(baseCd.objc.metaclass.type);
901 metaBase.sym = baseCd.objc.metaclass;
902 metaBases.push(metaBase);
903 }
904 else
905 {
906 .error(classDeclaration.loc, "%s `%s` base " ~ errorType ~ " for an Objective-C " ~
907 errorType ~ " must be `extern (Objective-C)`", classDeclaration.kind, classDeclaration.toPrettyChars);
908 }
909 }
910
911 objc.metaclass = newMetaclass(loc, metaBases);
912 objc.metaclass.storage_class |= STC.static_;
913 objc.metaclass.classKind = ClassKind.objc;
914 objc.metaclass.objc.isMeta = true;
915 objc.metaclass.objc.isExtern = objc.isExtern;
916 objc.metaclass.objc.identifier = objc.identifier;
917
918 if (baseClass)
919 objc.metaclass.baseClass = baseClass.objc.metaclass;
920
921 members.push(objc.metaclass);
922 objc.metaclass.addMember(sc, classDeclaration);
923
924 objc.metaclass.members = new Dsymbols();
925 objc.metaclass.dsymbolSemantic(sc);
926 }
927 }
928
929 private Identifier createMetaclassIdentifier(ClassDeclaration classDeclaration)
930 {
931 const name = "class_" ~ classDeclaration.ident.toString ~ "_Meta";
932 return Identifier.generateAnonymousId(name);
933 }