1 /**
2 * This module contains the implementation of the C++ header generation available through
3 * the command line switch -Hc.
4 *
5 * Copyright: Copyright (C) 1999-2022 by The D Language Foundation, All Rights Reserved
6 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
7 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
8 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/dtohd, _dtoh.d)
9 * Documentation: https://dlang.org/phobos/dmd_dtoh.html
10 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dtoh.d
11 */
12 module dmd.dtoh;
13
14 import core.stdc.stdio;
15 import core.stdc.string;
16 import core.stdc.ctype;
17
18 import dmd.astcodegen;
19 import dmd.astenums;
20 import dmd.arraytypes;
21 import dmd.attrib;
22 import dmd.dsymbol;
23 import dmd.errors;
24 import dmd.globals;
25 import dmd.hdrgen;
26 import dmd.identifier;
27 import dmd.root.filename;
28 import dmd.visitor;
29 import dmd.tokens;
30
31 import dmd.common.outbuffer;
32 import dmd.utils;
33
34 //debug = Debug_DtoH;
35
36 // Generate asserts to validate the header
37 //debug = Debug_DtoH_Checks;
38
39 /**
40 * Generates a C++ header containing bindings for all `extern(C[++])` declarations
41 * found in the supplied modules.
42 *
43 * Params:
44 * ms = the modules
45 *
46 * Notes:
47 * - the header is written to `<global.params.cxxhdrdir>/<global.params.cxxhdrfile>`
48 * or `stdout` if no explicit file was specified
49 * - bindings conform to the C++ standard defined in `global.params.cplusplus`
50 * - ignored declarations are mentioned in a comment if `global.params.doCxxHdrGeneration`
51 * is set to `CxxHeaderMode.verbose`
52 */
genCppHdrFiles(ref Modules ms)53 extern(C++) void genCppHdrFiles(ref Modules ms)
54 {
55 initialize();
56
57 OutBuffer fwd;
58 OutBuffer done;
59 OutBuffer decl;
60
61 // enable indent by spaces on buffers
62 fwd.doindent = true;
63 fwd.spaces = true;
64 decl.doindent = true;
65 decl.spaces = true;
66
67 scope v = new ToCppBuffer(&fwd, &done, &decl);
68
69 // Conditionally include another buffer for sanity checks
70 debug (Debug_DtoH_Checks)
71 {
72 OutBuffer check;
73 check.doindent = true;
74 check.spaces = true;
75 v.checkbuf = ✓
76 }
77
78 OutBuffer buf;
79 buf.doindent = true;
80 buf.spaces = true;
81
82 foreach (m; ms)
83 m.accept(v);
84
85 if (global.params.doCxxHdrGeneration == CxxHeaderMode.verbose)
86 buf.printf("// Automatically generated by %s Compiler v%d", global.vendor.ptr, global.versionNumber());
87 else
88 buf.printf("// Automatically generated by %s Compiler", global.vendor.ptr);
89
90 buf.writenl();
91 buf.writenl();
92 buf.writestringln("#pragma once");
93 buf.writenl();
94 hashInclude(buf, "<assert.h>");
95 hashInclude(buf, "<stddef.h>");
96 hashInclude(buf, "<stdint.h>");
97 hashInclude(buf, "<math.h>");
98 // buf.writestring(buf, "#include <stdio.h>\n");
99 // buf.writestring("#include <string.h>\n");
100
101 // Emit array compatibility because extern(C++) types may have slices
102 // as members (as opposed to function parameters)
103 buf.writestring(`
104 #ifdef CUSTOM_D_ARRAY_TYPE
105 #define _d_dynamicArray CUSTOM_D_ARRAY_TYPE
106 #else
107 /// Represents a D [] array
108 template<typename T>
109 struct _d_dynamicArray final
110 {
111 size_t length;
112 T *ptr;
113
114 _d_dynamicArray() : length(0), ptr(NULL) { }
115
116 _d_dynamicArray(size_t length_in, T *ptr_in)
117 : length(length_in), ptr(ptr_in) { }
118
119 T& operator[](const size_t idx) {
120 assert(idx < length);
121 return ptr[idx];
122 }
123
124 const T& operator[](const size_t idx) const {
125 assert(idx < length);
126 return ptr[idx];
127 }
128 };
129 #endif
130 `);
131
132 if (v.hasReal)
133 {
134 hashIf(buf, "!defined(_d_real)");
135 {
136 hashDefine(buf, "_d_real long double");
137 }
138 hashEndIf(buf);
139 }
140 buf.writenl();
141 // buf.writestringln("// fwd:");
142 buf.write(&fwd);
143 if (fwd.length > 0)
144 buf.writenl();
145
146 // buf.writestringln("// done:");
147 buf.write(&done);
148
149 // buf.writestringln("// decl:");
150 buf.write(&decl);
151
152 debug (Debug_DtoH_Checks)
153 {
154 // buf.writestringln("// check:");
155 buf.writestring(`
156 #if OFFSETS
157 template <class T>
158 size_t getSlotNumber(int dummy, ...)
159 {
160 T c;
161 va_list ap;
162 va_start(ap, dummy);
163
164 void *f = va_arg(ap, void*);
165 for (size_t i = 0; ; i++)
166 {
167 if ( (*(void***)&c)[i] == f)
168 return i;
169 }
170 va_end(ap);
171 }
172
173 void testOffsets()
174 {
175 `);
176 buf.write(&check);
177 buf.writestring(`
178 }
179 #endif
180 `);
181 }
182
183 // prevent trailing newlines
184 version (Windows)
185 while (buf.length >= 4 && buf[$-4..$] == "\r\n\r\n")
186 buf.remove(buf.length - 2, 2);
187 else
188 while (buf.length >= 2 && buf[$-2..$] == "\n\n")
189 buf.remove(buf.length - 1, 1);
190
191
192 if (global.params.cxxhdrname is null)
193 {
194 // Write to stdout; assume it succeeds
195 size_t n = fwrite(buf[].ptr, 1, buf.length, stdout);
196 assert(n == buf.length); // keep gcc happy about return values
197 }
198 else
199 {
200 const(char)[] name = FileName.combine(global.params.cxxhdrdir, global.params.cxxhdrname);
201 writeFile(Loc.initial, name, buf[]);
202 }
203 }
204
205 private:
206
207 /****************************************************
208 * Visitor that writes bindings for `extern(C[++]` declarations.
209 */
210 extern(C++) final class ToCppBuffer : Visitor
211 {
212 alias visit = Visitor.visit;
213 public:
214 enum EnumKind
215 {
216 Int,
217 Numeric,
218 String,
219 Enum,
220 Other
221 }
222
223 /// Namespace providing the actual AST nodes
224 alias AST = ASTCodegen;
225
226 /// Visited nodes
227 bool[void*] visited;
228
229 /// Forward declared nodes (which might not be emitted yet)
230 bool[void*] forwarded;
231
232 /// Buffer for forward declarations
233 OutBuffer* fwdbuf;
234
235 /// Buffer for integrity checks
236 debug (Debug_DtoH_Checks) OutBuffer* checkbuf;
237
238 /// Buffer for declarations that must emitted before the currently
239 /// visited node but can't be forward declared (see `includeSymbol`)
240 OutBuffer* donebuf;
241
242 /// Default buffer for the currently visited declaration
243 OutBuffer* buf;
244
245 /// The generated header uses `real` emitted as `_d_real`?
246 bool hasReal;
247
248 /// The generated header should contain comments for skipped declarations?
249 const bool printIgnored;
250
251 /// State specific to the current context which depends
252 /// on the currently visited node and it's parents
253 static struct Context
254 {
255 /// Default linkage in the current scope (e.g. LINK.c inside `extern(C) { ... }`)
256 LINK linkage = LINK.d;
257
258 /// Enclosing class / struct / union
259 AST.AggregateDeclaration adparent;
260
261 /// Enclosing template declaration
262 AST.TemplateDeclaration tdparent;
263
264 /// Identifier of the currently visited `VarDeclaration`
265 /// (required to write variables of funtion pointers)
266 Identifier ident;
267
268 /// Original type of the currently visited declaration
269 AST.Type origType;
270
271 /// Last written visibility level applying to the current scope
272 AST.Visibility.Kind currentVisibility;
273
274 /// Currently applicable storage classes
275 AST.STC storageClass;
276
277 /// How many symbols were ignored
278 int ignoredCounter;
279
280 /// Currently visited types are required by another declaration
281 /// and hence must be emitted
282 bool mustEmit;
283
284 /// Processing a type that can be forward referenced
285 bool forwarding;
286
287 /// Inside of an anonymous struct/union (AnonDeclaration)
288 bool inAnonymousDecl;
289 }
290
291 /// Informations about the current context in the AST
292 Context context;
293 alias context this;
294
295 this(OutBuffer* fwdbuf, OutBuffer* donebuf, OutBuffer* buf)
296 {
297 this.fwdbuf = fwdbuf;
298 this.donebuf = donebuf;
299 this.buf = buf;
300 this.printIgnored = global.params.doCxxHdrGeneration == CxxHeaderMode.verbose;
301 }
302
303 /**
304 * Emits `dsym` into `donebuf` s.t. it is declared before the currently
305 * visited symbol that written to `buf`.
306 *
307 * Temporarily clears `context` to behave as if it was visited normally.
308 */
309 private void includeSymbol(AST.Dsymbol dsym)
310 {
311 debug (Debug_DtoH)
312 {
313 printf("[includeSymbol(AST.Dsymbol) enter] %s\n", dsym.toChars());
314 scope(exit) printf("[includeSymbol(AST.Dsymbol) exit] %s\n", dsym.toChars());
315 }
316
317 auto ptr = cast(void*) dsym in visited;
318 if (ptr && *ptr)
319 return;
320
321 // Temporary replacement for `buf` which is appended to `donebuf`
322 OutBuffer decl;
323 decl.doindent = true;
324 decl.spaces = true;
325 scope (exit) donebuf.write(&decl);
326
327 auto ctxStash = this.context;
328 auto bufStash = this.buf;
329
330 this.context = Context.init;
331 this.buf = &decl;
332 this.mustEmit = true;
333
334 dsym.accept(this);
335
336 this.context = ctxStash;
337 this.buf = bufStash;
338 }
339
340 /// Determines what kind of enum `type` is (see `EnumKind`)
341 private EnumKind getEnumKind(AST.Type type)
342 {
343 if (type) switch (type.ty)
344 {
345 case AST.Tint32:
346 return EnumKind.Int;
347 case AST.Tbool,
348 AST.Tchar, AST.Twchar, AST.Tdchar,
349 AST.Tint8, AST.Tuns8,
350 AST.Tint16, AST.Tuns16,
351 AST.Tuns32,
352 AST.Tint64, AST.Tuns64:
353 return EnumKind.Numeric;
354 case AST.Tarray:
355 if (type.isString())
356 return EnumKind.String;
357 break;
358 case AST.Tenum:
359 return EnumKind.Enum;
360 default:
361 break;
362 }
363 return EnumKind.Other;
364 }
365
366 /// Determines the type used to represent `type` in C++.
367 /// Returns: `const [w,d]char*` for `[w,d]string` or `type`
368 private AST.Type determineEnumType(AST.Type type)
369 {
370 if (auto arr = type.isTypeDArray())
371 {
372 switch (arr.next.ty)
373 {
374 case AST.Tchar: return AST.Type.tchar.constOf.pointerTo;
375 case AST.Twchar: return AST.Type.twchar.constOf.pointerTo;
376 case AST.Tdchar: return AST.Type.tdchar.constOf.pointerTo;
377 default: break;
378 }
379 }
380 return type;
381 }
382
383 /// Writes a final `;` and insert an empty line outside of aggregates
384 private void writeDeclEnd()
385 {
386 buf.writestringln(";");
387
388 if (!adparent)
389 buf.writenl();
390 }
391
392 /// Writes the corresponding access specifier if necessary
393 private void writeProtection(const AST.Visibility.Kind kind)
394 {
395 // Don't write visibility for global declarations
396 if (!adparent || inAnonymousDecl)
397 return;
398
399 string token;
400
401 switch(kind) with(AST.Visibility.Kind)
402 {
403 case none, private_:
404 if (this.currentVisibility == AST.Visibility.Kind.private_)
405 return;
406 this.currentVisibility = AST.Visibility.Kind.private_;
407 token = "private:";
408 break;
409
410 case package_, protected_:
411 if (this.currentVisibility == AST.Visibility.Kind.protected_)
412 return;
413 this.currentVisibility = AST.Visibility.Kind.protected_;
414 token = "protected:";
415 break;
416
417 case undefined, public_, export_:
418 if (this.currentVisibility == AST.Visibility.Kind.public_)
419 return;
420 this.currentVisibility = AST.Visibility.Kind.public_;
421 token = "public:";
422 break;
423
424 default:
425 printf("Unexpected visibility: %d!\n", kind);
426 assert(0);
427 }
428
429 buf.level--;
430 buf.writestringln(token);
431 buf.level++;
432 }
433
434 /**
435 * Writes an identifier into `buf` and checks for reserved identifiers. The
436 * parameter `canFix` determines how this function handles C++ keywords:
437 *
438 * `false` => Raise a warning and print the identifier as-is
439 * `true` => Append an underscore to the identifier
440 *
441 * Params:
442 * s = the symbol denoting the identifier
443 * canFixup = whether the identifier may be changed without affecting
444 * binary compatibility
445 */
446 private void writeIdentifier(const AST.Dsymbol s, const bool canFix = false)
447 {
448 if (const mn = getMangleOverride(s))
449 return buf.writestring(mn);
450
451 writeIdentifier(s.ident, s.loc, s.kind(), canFix);
452 }
453
454 /** Overload of `writeIdentifier` used for all AST nodes not descending from Dsymbol **/
455 private void writeIdentifier(const Identifier ident, const Loc loc, const char* kind, const bool canFix = false)
456 {
457 bool needsFix;
458
459 void warnCxxCompat(const(char)* reason)
460 {
461 if (canFix)
462 {
463 needsFix = true;
464 return;
465 }
466
467 __gshared bool warned = false;
468 warning(loc, "%s `%s` is a %s", kind, ident.toChars(), reason);
469
470 if (!warned)
471 {
472 warningSupplemental(loc, "The generated C++ header will contain " ~
473 "identifiers that are keywords in C++");
474 warned = true;
475 }
476 }
477
478 if (global.params.warnings != DiagnosticReporting.off || canFix)
479 {
480 // Warn about identifiers that are keywords in C++.
481 if (auto kc = keywordClass(ident))
482 warnCxxCompat(kc);
483 }
484 buf.writestring(ident.toString());
485 if (needsFix)
486 buf.writeByte('_');
487 }
488
489 /// Checks whether `t` is a type that can be exported to C++
490 private bool isSupportedType(AST.Type t)
491 {
492 if (!t)
493 {
494 assert(tdparent);
495 return true;
496 }
497
498 switch (t.ty)
499 {
500 // Nested types
501 case AST.Tarray:
502 case AST.Tsarray:
503 case AST.Tpointer:
504 case AST.Treference:
505 case AST.Tdelegate:
506 return isSupportedType((cast(AST.TypeNext) t).next);
507
508 // Function pointers
509 case AST.Tfunction:
510 {
511 auto tf = cast(AST.TypeFunction) t;
512 if (!isSupportedType(tf.next))
513 return false;
514 foreach (_, param; tf.parameterList)
515 {
516 if (!isSupportedType(param.type))
517 return false;
518 }
519 return true;
520 }
521
522 // Noreturn has a different mangling
523 case AST.Tnoreturn:
524
525 // _Imaginary is C only.
526 case AST.Timaginary32:
527 case AST.Timaginary64:
528 case AST.Timaginary80:
529 return false;
530 default:
531 return true;
532 }
533 }
534
535 override void visit(AST.Dsymbol s)
536 {
537 debug (Debug_DtoH)
538 {
539 mixin(traceVisit!s);
540 import dmd.asttypename;
541 printf("[AST.Dsymbol enter] %s\n", s.astTypeName().ptr);
542 }
543 }
544
545 override void visit(AST.Import i)
546 {
547 debug (Debug_DtoH) mixin(traceVisit!i);
548
549 /// Writes `using <alias_> = <sym.ident>` into `buf`
550 const(char*) writeImport(AST.Dsymbol sym, const Identifier alias_)
551 {
552 /// `using` was introduced in C++ 11 and only works for types...
553 if (global.params.cplusplus < CppStdRevision.cpp11)
554 return "requires C++11";
555
556 if (auto ad = sym.isAliasDeclaration())
557 {
558 sym = ad.toAlias();
559 ad = sym.isAliasDeclaration();
560
561 // Might be an alias to a basic type
562 if (ad && !ad.aliassym && ad.type)
563 goto Emit;
564 }
565
566 // Restricted to types and other aliases
567 if (!sym.isScopeDsymbol() && !sym.isAggregateDeclaration())
568 return "only supports types";
569
570 // Write `using <alias_> = `<sym>`
571 Emit:
572 buf.writestring("using ");
573 writeIdentifier(alias_, i.loc, "renamed import");
574 buf.writestring(" = ");
575 // Start at module scope to avoid collisions with local symbols
576 if (this.context.adparent)
577 buf.writestring("::");
578 buf.writestring(sym.ident.toString());
579 writeDeclEnd();
580 return null;
581 }
582
583 // Only missing without semantic analysis
584 // FIXME: Templates need work due to missing parent & imported module
585 if (!i.parent)
586 {
587 assert(tdparent);
588 ignored("`%s` because it's inside of a template declaration", i.toChars());
589 return;
590 }
591
592 // Non-public imports don't create new symbols, include as needed
593 if (i.visibility.kind < AST.Visibility.Kind.public_)
594 return;
595
596 // Symbols from static imports should be emitted inline
597 if (i.isstatic)
598 return;
599
600 const isLocal = !i.parent.isModule();
601
602 // Need module for symbol lookup
603 assert(i.mod);
604
605 // Emit an alias for each public module member
606 if (isLocal && i.names.length == 0)
607 {
608 assert(i.mod.symtab);
609
610 // Sort alphabetically s.t. slight changes in semantic don't cause
611 // massive changes in the order of declarations
612 AST.Dsymbols entries;
613 entries.reserve(i.mod.symtab.length);
614
615 foreach (entry; i.mod.symtab.tab.asRange)
616 {
617 // Skip anonymous / invisible members
618 import dmd.access : symbolIsVisible;
619 if (!entry.key.isAnonymous() && symbolIsVisible(i, entry.value))
620 entries.push(entry.value);
621 }
622
623 // Seperate function because of a spurious dual-context deprecation
624 static int compare(const AST.Dsymbol* a, const AST.Dsymbol* b)
625 {
626 return strcmp(a.ident.toChars(), b.ident.toChars());
627 }
628 entries.sort!compare();
629
630 foreach (sym; entries)
631 {
632 includeSymbol(sym);
633 if (auto err = writeImport(sym, sym.ident))
634 ignored("public import for `%s` because `using` %s", sym.ident.toChars(), err);
635 }
636 return;
637 }
638
639 // Include all public imports and emit using declarations for each alias
640 foreach (const idx, name; i.names)
641 {
642 // Search the imported symbol
643 auto sym = i.mod.search(Loc.initial, name);
644 assert(sym); // Missing imports should error during semantic
645
646 includeSymbol(sym);
647
648 // Detect the assigned name for renamed import
649 auto alias_ = i.aliases[idx];
650 if (!alias_)
651 continue;
652
653 if (auto err = writeImport(sym, alias_))
654 ignored("renamed import `%s = %s` because `using` %s", alias_.toChars(), name.toChars(), err);
655 }
656 }
657
658 override void visit(AST.AttribDeclaration pd)
659 {
660 debug (Debug_DtoH) mixin(traceVisit!pd);
661
662 Dsymbols* decl = pd.include(null);
663 if (!decl)
664 return;
665
666 foreach (s; *decl)
667 {
668 if (adparent || s.visible().kind >= AST.Visibility.Kind.public_)
669 s.accept(this);
670 }
671 }
672
673 override void visit(AST.StorageClassDeclaration scd)
674 {
675 debug (Debug_DtoH) mixin(traceVisit!scd);
676
677 const stcStash = this.storageClass;
678 this.storageClass |= scd.stc;
679 visit(cast(AST.AttribDeclaration) scd);
680 this.storageClass = stcStash;
681 }
682
683 override void visit(AST.LinkDeclaration ld)
684 {
685 debug (Debug_DtoH) mixin(traceVisit!ld);
686
687 auto save = linkage;
688 linkage = ld.linkage;
689 visit(cast(AST.AttribDeclaration)ld);
690 linkage = save;
691 }
692
693 override void visit(AST.CPPMangleDeclaration md)
694 {
695 debug (Debug_DtoH) mixin(traceVisit!md);
696
697 const oldLinkage = this.linkage;
698 this.linkage = LINK.cpp;
699 visit(cast(AST.AttribDeclaration) md);
700 this.linkage = oldLinkage;
701 }
702
703 override void visit(AST.Module m)
704 {
705 debug (Debug_DtoH) mixin(traceVisit!m);
706
707 foreach (s; *m.members)
708 {
709 if (s.visible().kind < AST.Visibility.Kind.public_)
710 continue;
711 s.accept(this);
712 }
713 }
714
715 override void visit(AST.FuncDeclaration fd)
716 {
717 debug (Debug_DtoH) mixin(traceVisit!fd);
718
719 if (cast(void*)fd in visited)
720 return;
721 // printf("FuncDeclaration %s %s\n", fd.toPrettyChars(), fd.type.toChars());
722 visited[cast(void*)fd] = true;
723
724 // silently ignore non-user-defined destructors
725 if (fd.isGenerated && fd.isDtorDeclaration())
726 return;
727
728 // Note that tf might be null for templated (member) functions
729 auto tf = cast(AST.TypeFunction)fd.type;
730 if ((tf && (tf.linkage != LINK.c || adparent) && tf.linkage != LINK.cpp) || (!tf && fd.isPostBlitDeclaration()))
731 {
732 ignored("function %s because of linkage", fd.toPrettyChars());
733 return checkFunctionNeedsPlaceholder(fd);
734 }
735 if (fd.mangleOverride && tf && tf.linkage != LINK.c)
736 {
737 ignored("function %s because C++ doesn't support explicit mangling", fd.toPrettyChars());
738 return checkFunctionNeedsPlaceholder(fd);
739 }
740 if (!adparent && !fd.fbody)
741 {
742 ignored("function %s because it is extern", fd.toPrettyChars());
743 return;
744 }
745 if (fd.visibility.kind == AST.Visibility.Kind.none || fd.visibility.kind == AST.Visibility.Kind.private_)
746 {
747 ignored("function %s because it is private", fd.toPrettyChars());
748 return;
749 }
750 if (tf && !isSupportedType(tf.next))
751 {
752 ignored("function %s because its return type cannot be mapped to C++", fd.toPrettyChars());
753 return checkFunctionNeedsPlaceholder(fd);
754 }
755 if (tf) foreach (i, fparam; tf.parameterList)
756 {
757 if (!isSupportedType(fparam.type))
758 {
759 ignored("function %s because one of its parameters has type `%s` which cannot be mapped to C++",
760 fd.toPrettyChars(), fparam.type.toChars());
761 return checkFunctionNeedsPlaceholder(fd);
762 }
763 }
764
765 writeProtection(fd.visibility.kind);
766
767 if (tf && tf.linkage == LINK.c)
768 buf.writestring("extern \"C\" ");
769 else if (!adparent)
770 buf.writestring("extern ");
771 if (adparent && fd.isStatic())
772 buf.writestring("static ");
773 else if (adparent && (
774 // Virtual functions in non-templated classes
775 (fd.vtblIndex != -1 && !fd.isOverride()) ||
776
777 // Virtual functions in templated classes (fd.vtblIndex still -1)
778 (tdparent && adparent.isClassDeclaration() && !(this.storageClass & AST.STC.final_ || fd.isFinal))))
779 buf.writestring("virtual ");
780
781 debug (Debug_DtoH_Checks)
782 if (adparent && !tdparent)
783 {
784 auto s = adparent.search(Loc.initial, fd.ident);
785 auto cd = adparent.isClassDeclaration();
786
787 if (!(adparent.storage_class & AST.STC.abstract_) &&
788 !(cd && cd.isAbstract()) &&
789 s is fd && !fd.overnext)
790 {
791 const cn = adparent.ident.toChars();
792 const fn = fd.ident.toChars();
793 const vi = fd.vtblIndex;
794
795 checkbuf.printf("assert(getSlotNumber <%s>(0, &%s::%s) == %d);",
796 cn, cn, fn, vi);
797 checkbuf.writenl();
798 }
799 }
800
801 if (adparent && fd.isDisabled && global.params.cplusplus < CppStdRevision.cpp11)
802 writeProtection(AST.Visibility.Kind.private_);
803 funcToBuffer(tf, fd);
804 // FIXME: How to determine if fd is const without tf?
805 if (adparent && tf && (tf.isConst() || tf.isImmutable()))
806 {
807 bool fdOverridesAreConst = true;
808 foreach (fdv; fd.foverrides)
809 {
810 auto tfv = cast(AST.TypeFunction)fdv.type;
811 if (!tfv.isConst() && !tfv.isImmutable())
812 {
813 fdOverridesAreConst = false;
814 break;
815 }
816 }
817
818 buf.writestring(fdOverridesAreConst ? " const" : " /* const */");
819 }
820 if (adparent && fd.isAbstract())
821 buf.writestring(" = 0");
822 if (adparent && fd.isDisabled && global.params.cplusplus >= CppStdRevision.cpp11)
823 buf.writestring(" = delete");
824 buf.writestringln(";");
825 if (adparent && fd.isDisabled && global.params.cplusplus < CppStdRevision.cpp11)
826 writeProtection(AST.Visibility.Kind.public_);
827
828 if (!adparent)
829 buf.writenl();
830
831 }
832
833 /++
834 + Checks whether `fd` is a function that requires a dummy declaration
835 + instead of simply emitting the declaration (because it would cause
836 + ABI / behaviour issues). This includes:
837 +
838 + - virtual functions to ensure proper vtable layout
839 + - destructors that would break RAII
840 +/
841 private void checkFunctionNeedsPlaceholder(AST.FuncDeclaration fd)
842 {
843 // Omit redundant declarations - the slot was already
844 // reserved in the base class
845 if (fd.isVirtual() && fd.isIntroducing())
846 {
847 // Hide placeholders because they are not ABI compatible
848 writeProtection(AST.Visibility.Kind.private_);
849
850 __gshared int counter; // Ensure unique names in all cases
851 buf.printf("virtual void __vtable_slot_%u();", counter++);
852 buf.writenl();
853 }
854 else if (fd.isDtorDeclaration())
855 {
856 // Create inaccessible dtor to prevent code from keeping instances that
857 // need to be destroyed on the C++ side (but cannot call the dtor)
858 writeProtection(AST.Visibility.Kind.private_);
859 buf.writeByte('~');
860 buf.writestring(adparent.ident.toString());
861 buf.writestringln("();");
862 }
863 }
864
865 override void visit(AST.UnitTestDeclaration utd)
866 {
867 debug (Debug_DtoH) mixin(traceVisit!utd);
868 }
869
870 override void visit(AST.VarDeclaration vd)
871 {
872 debug (Debug_DtoH) mixin(traceVisit!vd);
873
874 if (!shouldEmitAndMarkVisited(vd))
875 return;
876
877 // Tuple field are expanded into multiple VarDeclarations
878 // (we'll visit them later)
879 if (vd.type && vd.type.isTypeTuple())
880 return;
881
882 if (vd.originalType && vd.type == AST.Type.tsize_t)
883 origType = vd.originalType;
884 scope(exit) origType = null;
885
886 if (!vd.alignment.isDefault() && !vd.alignment.isUnknown())
887 {
888 buf.printf("// Ignoring var %s alignment %d", vd.toChars(), vd.alignment.get());
889 buf.writenl();
890 }
891
892 // Determine the variable type which might be missing inside of
893 // template declarations. Infer the type from the initializer then
894 AST.Type type = vd.type;
895 if (!type)
896 {
897 assert(tdparent);
898
899 // Just a precaution, implicit type without initializer should be rejected
900 if (!vd._init)
901 return;
902
903 if (auto ei = vd._init.isExpInitializer())
904 type = ei.exp.type;
905
906 // Can happen if the expression needs further semantic
907 if (!type)
908 {
909 ignored("%s because the type could not be determined", vd.toPrettyChars());
910 return;
911 }
912
913 // Apply const/immutable to the inferred type
914 if (vd.storage_class & (AST.STC.const_ | AST.STC.immutable_))
915 type = type.constOf();
916 }
917
918 if (vd.storage_class & AST.STC.manifest)
919 {
920 EnumKind kind = getEnumKind(type);
921
922 if (vd.visibility.kind == AST.Visibility.Kind.none || vd.visibility.kind == AST.Visibility.Kind.private_) {
923 ignored("enum `%s` because it is `%s`.", vd.toPrettyChars(), AST.visibilityToChars(vd.visibility.kind));
924 return;
925 }
926
927 writeProtection(vd.visibility.kind);
928
929 final switch (kind)
930 {
931 case EnumKind.Int, EnumKind.Numeric:
932 // 'enum : type' is only available from C++-11 onwards.
933 if (global.params.cplusplus < CppStdRevision.cpp11)
934 goto case;
935 buf.writestring("enum : ");
936 determineEnumType(type).accept(this);
937 buf.writestring(" { ");
938 writeIdentifier(vd, true);
939 buf.writestring(" = ");
940 auto ie = AST.initializerToExpression(vd._init).isIntegerExp();
941 visitInteger(ie.toInteger(), type);
942 buf.writestring(" };");
943 break;
944
945 case EnumKind.String, EnumKind.Enum:
946 buf.writestring("static ");
947 auto target = determineEnumType(type);
948 target.accept(this);
949 buf.writestring(" const ");
950 writeIdentifier(vd, true);
951 buf.writestring(" = ");
952 auto e = AST.initializerToExpression(vd._init);
953 printExpressionFor(target, e);
954 buf.writestring(";");
955 break;
956
957 case EnumKind.Other:
958 ignored("enum `%s` because type `%s` is currently not supported for enum constants.", vd.toPrettyChars(), type.toChars());
959 return;
960 }
961 buf.writenl();
962 buf.writenl();
963 return;
964 }
965
966 if (vd.storage_class & (AST.STC.static_ | AST.STC.extern_ | AST.STC.gshared) ||
967 vd.parent && vd.parent.isModule())
968 {
969 const vdLinkage = vd.resolvedLinkage();
970 if (vdLinkage != LINK.c && vdLinkage != LINK.cpp && !(tdparent && (this.linkage == LINK.c || this.linkage == LINK.cpp)))
971 {
972 ignored("variable %s because of linkage", vd.toPrettyChars());
973 return;
974 }
975 if (vd.mangleOverride && vdLinkage != LINK.c)
976 {
977 ignored("variable %s because C++ doesn't support explicit mangling", vd.toPrettyChars());
978 return;
979 }
980 if (!isSupportedType(type))
981 {
982 ignored("variable %s because its type cannot be mapped to C++", vd.toPrettyChars());
983 return;
984 }
985 if (auto kc = keywordClass(vd.ident))
986 {
987 ignored("variable %s because its name is a %s", vd.toPrettyChars(), kc);
988 return;
989 }
990 writeProtection(vd.visibility.kind);
991 if (vdLinkage == LINK.c)
992 buf.writestring("extern \"C\" ");
993 else if (!adparent)
994 buf.writestring("extern ");
995 if (adparent)
996 buf.writestring("static ");
997 typeToBuffer(type, vd);
998 writeDeclEnd();
999 return;
1000 }
1001
1002 if (adparent)
1003 {
1004 writeProtection(vd.visibility.kind);
1005 typeToBuffer(type, vd, true);
1006 buf.writestringln(";");
1007
1008 debug (Debug_DtoH_Checks)
1009 {
1010 checkbuf.level++;
1011 const pn = adparent.ident.toChars();
1012 const vn = vd.ident.toChars();
1013 const vo = vd.offset;
1014 checkbuf.printf("assert(offsetof(%s, %s) == %d);",
1015 pn, vn, vo);
1016 checkbuf.writenl();
1017 checkbuf.level--;
1018 }
1019 return;
1020 }
1021
1022 visit(cast(AST.Dsymbol)vd);
1023 }
1024
1025 override void visit(AST.TypeInfoDeclaration tid)
1026 {
1027 debug (Debug_DtoH) mixin(traceVisit!tid);
1028 }
1029
1030 override void visit(AST.AliasDeclaration ad)
1031 {
1032 debug (Debug_DtoH) mixin(traceVisit!ad);
1033
1034 if (!shouldEmitAndMarkVisited(ad))
1035 return;
1036
1037 writeProtection(ad.visibility.kind);
1038
1039 if (auto t = ad.type)
1040 {
1041 if (t.ty == AST.Tdelegate || t.ty == AST.Tident)
1042 {
1043 visit(cast(AST.Dsymbol)ad);
1044 return;
1045 }
1046
1047 // for function pointers we need to original type
1048 if (ad.originalType && ad.type.ty == AST.Tpointer &&
1049 (cast(AST.TypePointer)t).nextOf.ty == AST.Tfunction)
1050 {
1051 origType = ad.originalType;
1052 }
1053 scope(exit) origType = null;
1054
1055 buf.writestring("typedef ");
1056 typeToBuffer(origType !is null ? origType : t, ad);
1057 writeDeclEnd();
1058 return;
1059 }
1060 if (!ad.aliassym)
1061 {
1062 assert(0);
1063 }
1064 if (auto ti = ad.aliassym.isTemplateInstance())
1065 {
1066 visitTi(ti);
1067 return;
1068 }
1069 if (auto sd = ad.aliassym.isStructDeclaration())
1070 {
1071 buf.writestring("typedef ");
1072 sd.type.accept(this);
1073 buf.writestring(" ");
1074 writeIdentifier(ad);
1075 writeDeclEnd();
1076 return;
1077 }
1078 else if (auto td = ad.aliassym.isTemplateDeclaration())
1079 {
1080 if (global.params.cplusplus < CppStdRevision.cpp11)
1081 {
1082 ignored("%s because `using` declarations require C++ 11", ad.toPrettyChars());
1083 return;
1084 }
1085
1086 printTemplateParams(td);
1087 buf.writestring("using ");
1088 writeIdentifier(ad);
1089 buf.writestring(" = ");
1090 writeFullName(td);
1091 buf.writeByte('<');
1092
1093 foreach (const idx, const p; *td.parameters)
1094 {
1095 if (idx)
1096 buf.writestring(", ");
1097 writeIdentifier(p.ident, p.loc, "parameter", true);
1098 }
1099 buf.writestringln(">;");
1100 return;
1101 }
1102
1103 auto fd = ad.aliassym.isFuncDeclaration();
1104
1105 if (fd && (fd.isGenerated() || fd.isDtorDeclaration()))
1106 {
1107 // Ignore. It's taken care of while visiting FuncDeclaration
1108 return;
1109 }
1110
1111 // Recognize member function aliases, e.g. alias visit = Parent.visit;
1112 if (adparent && fd)
1113 {
1114 auto pd = fd.isMember();
1115 if (!pd)
1116 {
1117 ignored("%s because free functions cannot be aliased in C++", ad.toPrettyChars());
1118 }
1119 else if (global.params.cplusplus < CppStdRevision.cpp11)
1120 {
1121 ignored("%s because `using` declarations require C++ 11", ad.toPrettyChars());
1122 }
1123 else if (ad.ident != fd.ident)
1124 {
1125 ignored("%s because `using` cannot rename functions in aggregates", ad.toPrettyChars());
1126 }
1127 else if (fd.toAliasFunc().parent.isTemplateMixin())
1128 {
1129 // Member's of template mixins are directly emitted into the aggregate
1130 }
1131 else
1132 {
1133 buf.writestring("using ");
1134
1135 // Print prefix of the base class if this function originates from a superclass
1136 // because alias might be resolved through multiple classes, e.g.
1137 // e.g. for alias visit = typeof(super).visit in the visitors
1138 if (!fd.isIntroducing())
1139 printPrefix(ad.toParent().isClassDeclaration().baseClass);
1140 else
1141 printPrefix(pd);
1142
1143 buf.writestring(fd.ident.toChars());
1144 buf.writestringln(";");
1145 }
1146 return;
1147 }
1148
1149 ignored("%s %s", ad.aliassym.kind(), ad.aliassym.toPrettyChars());
1150 }
1151
1152 override void visit(AST.Nspace ns)
1153 {
1154 debug (Debug_DtoH) mixin(traceVisit!ns);
1155 handleNspace(ns, ns.members);
1156 }
1157
1158 override void visit(AST.CPPNamespaceDeclaration ns)
1159 {
1160 debug (Debug_DtoH) mixin(traceVisit!ns);
1161 handleNspace(ns, ns.decl);
1162 }
1163
1164 /// Writes the namespace declaration and visits all members
1165 private void handleNspace(AST.Dsymbol namespace, Dsymbols* members)
1166 {
1167 buf.writestring("namespace ");
1168 writeIdentifier(namespace);
1169 buf.writenl();
1170 buf.writestring("{");
1171 buf.writenl();
1172 buf.level++;
1173 foreach(decl;(*members))
1174 {
1175 decl.accept(this);
1176 }
1177 buf.level--;
1178 buf.writestring("}");
1179 buf.writenl();
1180 }
1181
1182 override void visit(AST.AnonDeclaration ad)
1183 {
1184 debug (Debug_DtoH) mixin(traceVisit!ad);
1185
1186 const anonStash = inAnonymousDecl;
1187 inAnonymousDecl = true;
1188 scope (exit) inAnonymousDecl = anonStash;
1189
1190 buf.writestringln(ad.isunion ? "union" : "struct");
1191 buf.writestringln("{");
1192 buf.level++;
1193 foreach (s; *ad.decl)
1194 {
1195 s.accept(this);
1196 }
1197 buf.level--;
1198 buf.writestringln("};");
1199 }
1200
1201 private bool memberField(AST.VarDeclaration vd)
1202 {
1203 if (!vd.type || !vd.type.deco || !vd.ident)
1204 return false;
1205 if (!vd.isField())
1206 return false;
1207 if (vd.type.ty == AST.Tfunction)
1208 return false;
1209 if (vd.type.ty == AST.Tsarray)
1210 return false;
1211 return true;
1212 }
1213
1214 override void visit(AST.StructDeclaration sd)
1215 {
1216 debug (Debug_DtoH) mixin(traceVisit!sd);
1217
1218 if (!shouldEmitAndMarkVisited(sd))
1219 return;
1220
1221 const ignoredStash = this.ignoredCounter;
1222 scope (exit) this.ignoredCounter = ignoredStash;
1223
1224 pushAlignToBuffer(sd.alignment);
1225
1226 writeProtection(sd.visibility.kind);
1227
1228 const structAsClass = sd.cppmangle == CPPMANGLE.asClass;
1229 if (sd.isUnionDeclaration())
1230 buf.writestring("union ");
1231 else
1232 buf.writestring(structAsClass ? "class " : "struct ");
1233
1234 writeIdentifier(sd);
1235 if (!sd.members)
1236 {
1237 buf.writestringln(";");
1238 buf.writenl();
1239 return;
1240 }
1241
1242 // D structs are always final
1243 if (!sd.isUnionDeclaration())
1244 buf.writestring(" final");
1245
1246 buf.writenl();
1247 buf.writestring("{");
1248
1249 const protStash = this.currentVisibility;
1250 this.currentVisibility = structAsClass ? AST.Visibility.Kind.private_ : AST.Visibility.Kind.public_;
1251 scope (exit) this.currentVisibility = protStash;
1252
1253 buf.level++;
1254 buf.writenl();
1255 auto save = adparent;
1256 adparent = sd;
1257
1258 foreach (m; *sd.members)
1259 {
1260 m.accept(this);
1261 }
1262 // Generate default ctor
1263 if (!sd.noDefaultCtor && !sd.isUnionDeclaration())
1264 {
1265 writeProtection(AST.Visibility.Kind.public_);
1266 buf.printf("%s()", sd.ident.toChars());
1267 size_t varCount;
1268 bool first = true;
1269 buf.level++;
1270 foreach (m; *sd.members)
1271 {
1272 if (auto vd = m.isVarDeclaration())
1273 {
1274 if (!memberField(vd))
1275 continue;
1276 varCount++;
1277
1278 if (!vd._init && !vd.type.isTypeBasic() && !vd.type.isTypePointer && !vd.type.isTypeStruct &&
1279 !vd.type.isTypeClass && !vd.type.isTypeDArray && !vd.type.isTypeSArray)
1280 {
1281 continue;
1282 }
1283 if (vd._init && vd._init.isVoidInitializer())
1284 continue;
1285
1286 if (first)
1287 {
1288 buf.writestringln(" :");
1289 first = false;
1290 }
1291 else
1292 {
1293 buf.writestringln(",");
1294 }
1295 writeIdentifier(vd, true);
1296 buf.writeByte('(');
1297
1298 if (vd._init)
1299 {
1300 auto e = AST.initializerToExpression(vd._init);
1301 printExpressionFor(vd.type, e, true);
1302 }
1303 buf.printf(")");
1304 }
1305 }
1306 buf.level--;
1307 buf.writenl();
1308 buf.writestringln("{");
1309 buf.writestringln("}");
1310 auto ctor = sd.ctor ? sd.ctor.isFuncDeclaration() : null;
1311 if (varCount && (!ctor || ctor.storage_class & AST.STC.disable))
1312 {
1313 buf.printf("%s(", sd.ident.toChars());
1314 first = true;
1315 foreach (m; *sd.members)
1316 {
1317 if (auto vd = m.isVarDeclaration())
1318 {
1319 if (!memberField(vd))
1320 continue;
1321 if (!first)
1322 buf.writestring(", ");
1323 assert(vd.type);
1324 assert(vd.ident);
1325 typeToBuffer(vd.type, vd, true);
1326 // Don't print default value for first parameter to not clash
1327 // with the default ctor defined above
1328 if (!first)
1329 {
1330 buf.writestring(" = ");
1331 printExpressionFor(vd.type, findDefaultInitializer(vd));
1332 }
1333 first = false;
1334 }
1335 }
1336 buf.writestring(") :");
1337 buf.level++;
1338 buf.writenl();
1339
1340 first = true;
1341 foreach (m; *sd.members)
1342 {
1343 if (auto vd = m.isVarDeclaration())
1344 {
1345 if (!memberField(vd))
1346 continue;
1347
1348 if (first)
1349 first = false;
1350 else
1351 buf.writestringln(",");
1352
1353 writeIdentifier(vd, true);
1354 buf.writeByte('(');
1355 writeIdentifier(vd, true);
1356 buf.writeByte(')');
1357 }
1358 }
1359 buf.writenl();
1360 buf.writestringln("{}");
1361 buf.level--;
1362 }
1363 }
1364
1365 buf.level--;
1366 adparent = save;
1367 buf.writestringln("};");
1368
1369 popAlignToBuffer(sd.alignment);
1370 buf.writenl();
1371
1372 // Workaround because size triggers a forward-reference error
1373 // for struct templates (the size is undetermined even if the
1374 // size doesn't depend on the parameters)
1375 debug (Debug_DtoH_Checks)
1376 if (!tdparent)
1377 {
1378 checkbuf.level++;
1379 const sn = sd.ident.toChars();
1380 const sz = sd.size(Loc.initial);
1381 checkbuf.printf("assert(sizeof(%s) == %llu);", sn, sz);
1382 checkbuf.writenl();
1383 checkbuf.level--;
1384 }
1385 }
1386
1387 /// Starts a custom alignment section using `#pragma pack` if
1388 /// `alignment` specifies a custom alignment
1389 private void pushAlignToBuffer(structalign_t alignment)
1390 {
1391 // DMD ensures alignment is a power of two
1392 //assert(alignment > 0 && ((alignment & (alignment - 1)) == 0),
1393 // "Invalid alignment size");
1394
1395 // When no alignment is specified, `uint.max` is the default
1396 // FIXME: alignment is 0 for structs templated members
1397 if (alignment.isDefault() || (tdparent && alignment.isUnknown()))
1398 {
1399 return;
1400 }
1401
1402 buf.printf("#pragma pack(push, %d)", alignment.get());
1403 buf.writenl();
1404 }
1405
1406 /// Ends a custom alignment section using `#pragma pack` if
1407 /// `alignment` specifies a custom alignment
1408 private void popAlignToBuffer(structalign_t alignment)
1409 {
1410 if (alignment.isDefault() || (tdparent && alignment.isUnknown()))
1411 return;
1412
1413 buf.writestringln("#pragma pack(pop)");
1414 }
1415
1416 override void visit(AST.ClassDeclaration cd)
1417 {
1418 debug (Debug_DtoH) mixin(traceVisit!cd);
1419
1420 if (cd.baseClass && shouldEmit(cd))
1421 includeSymbol(cd.baseClass);
1422
1423 if (!shouldEmitAndMarkVisited(cd))
1424 return;
1425
1426 writeProtection(cd.visibility.kind);
1427
1428 const classAsStruct = cd.cppmangle == CPPMANGLE.asStruct;
1429 buf.writestring(classAsStruct ? "struct " : "class ");
1430 writeIdentifier(cd);
1431
1432 if (cd.storage_class & AST.STC.final_ || (tdparent && this.storageClass & AST.STC.final_))
1433 buf.writestring(" final");
1434
1435 assert(cd.baseclasses);
1436
1437 foreach (i, base; *cd.baseclasses)
1438 {
1439 buf.writestring(i == 0 ? " : public " : ", public ");
1440
1441 // Base classes/interfaces might depend on template parameters,
1442 // e.g. class A(T) : B!T { ... }
1443 if (base.sym is null)
1444 {
1445 base.type.accept(this);
1446 }
1447 else
1448 {
1449 writeFullName(base.sym);
1450 }
1451 }
1452
1453 if (!cd.members)
1454 {
1455 buf.writestring(";");
1456 buf.writenl();
1457 buf.writenl();
1458 return;
1459 }
1460
1461 buf.writenl();
1462 buf.writestringln("{");
1463
1464 const protStash = this.currentVisibility;
1465 this.currentVisibility = classAsStruct ? AST.Visibility.Kind.public_ : AST.Visibility.Kind.private_;
1466 scope (exit) this.currentVisibility = protStash;
1467
1468 auto save = adparent;
1469 adparent = cd;
1470 buf.level++;
1471 foreach (m; *cd.members)
1472 {
1473 m.accept(this);
1474 }
1475 buf.level--;
1476 adparent = save;
1477
1478 buf.writestringln("};");
1479 buf.writenl();
1480 }
1481
1482 override void visit(AST.EnumDeclaration ed)
1483 {
1484 debug (Debug_DtoH) mixin(traceVisit!ed);
1485
1486 if (!shouldEmitAndMarkVisited(ed))
1487 return;
1488
1489 if (ed.isSpecial())
1490 {
1491 //ignored("%s because it is a special C++ type", ed.toPrettyChars());
1492 return;
1493 }
1494
1495 // we need to know a bunch of stuff about the enum...
1496 bool isAnonymous = ed.ident is null;
1497 const isOpaque = !ed.members;
1498 AST.Type type = ed.memtype;
1499 if (!type && !isOpaque)
1500 {
1501 // check all keys have matching type
1502 foreach (_m; *ed.members)
1503 {
1504 auto m = _m.isEnumMember();
1505 if (!type)
1506 type = m.type;
1507 else if (m.type !is type)
1508 {
1509 type = null;
1510 break;
1511 }
1512 }
1513 }
1514 EnumKind kind = getEnumKind(type);
1515
1516 if (isOpaque)
1517 {
1518 // Opaque enums were introduced in C++ 11 (workaround?)
1519 if (global.params.cplusplus < CppStdRevision.cpp11)
1520 {
1521 ignored("%s because opaque enums require C++ 11", ed.toPrettyChars());
1522 return;
1523 }
1524 // Opaque enum defaults to int but the type might not be set
1525 else if (!type)
1526 {
1527 kind = EnumKind.Int;
1528 }
1529 // Cannot apply namespace workaround for non-integral types
1530 else if (kind != EnumKind.Int && kind != EnumKind.Numeric)
1531 {
1532 ignored("enum %s because of its base type", ed.toPrettyChars());
1533 return;
1534 }
1535 }
1536
1537 // determine if this is an enum, or just a group of manifest constants
1538 bool manifestConstants = !isOpaque && (!type || (isAnonymous && kind == EnumKind.Other));
1539 assert(!manifestConstants || isAnonymous);
1540
1541 writeProtection(ed.visibility.kind);
1542
1543 // write the enum header
1544 if (!manifestConstants)
1545 {
1546 if (kind == EnumKind.Int || kind == EnumKind.Numeric)
1547 {
1548 buf.writestring("enum");
1549 // D enums are strong enums, but there exists only a direct mapping
1550 // with 'enum class' from C++-11 onwards.
1551 if (global.params.cplusplus >= CppStdRevision.cpp11)
1552 {
1553 if (!isAnonymous)
1554 {
1555 buf.writestring(" class ");
1556 writeIdentifier(ed);
1557 }
1558 if (kind == EnumKind.Numeric)
1559 {
1560 buf.writestring(" : ");
1561 determineEnumType(type).accept(this);
1562 }
1563 }
1564 else if (!isAnonymous)
1565 {
1566 buf.writeByte(' ');
1567 writeIdentifier(ed);
1568 }
1569 }
1570 else
1571 {
1572 buf.writestring("namespace");
1573 if(!isAnonymous)
1574 {
1575 buf.writeByte(' ');
1576 writeIdentifier(ed);
1577 }
1578 }
1579 // Opaque enums have no members, hence skip the body
1580 if (isOpaque)
1581 {
1582 buf.writestringln(";");
1583 return;
1584 }
1585 else
1586 {
1587 buf.writenl();
1588 buf.writestringln("{");
1589 }
1590 }
1591
1592 // emit constant for each member
1593 if (!manifestConstants)
1594 buf.level++;
1595
1596 foreach (_m; *ed.members)
1597 {
1598 auto m = _m.isEnumMember();
1599 AST.Type memberType = type ? type : m.type;
1600 const EnumKind memberKind = type ? kind : getEnumKind(memberType);
1601
1602 if (!manifestConstants && (kind == EnumKind.Int || kind == EnumKind.Numeric))
1603 {
1604 // C++-98 compatible enums must use the typename as a prefix to avoid
1605 // collisions with other identifiers in scope. For consistency with D,
1606 // the enum member `Type.member` is emitted as `Type_member` in C++-98.
1607 if (!isAnonymous && global.params.cplusplus < CppStdRevision.cpp11)
1608 {
1609 writeIdentifier(ed);
1610 buf.writeByte('_');
1611 }
1612 writeIdentifier(m, true);
1613 buf.writestring(" = ");
1614
1615 auto ie = cast(AST.IntegerExp)m.value;
1616 visitInteger(ie.toInteger(), memberType);
1617 buf.writestring(",");
1618 }
1619 else if (global.params.cplusplus >= CppStdRevision.cpp11 &&
1620 manifestConstants && (memberKind == EnumKind.Int || memberKind == EnumKind.Numeric))
1621 {
1622 buf.writestring("enum : ");
1623 determineEnumType(memberType).accept(this);
1624 buf.writestring(" { ");
1625 writeIdentifier(m, true);
1626 buf.writestring(" = ");
1627
1628 auto ie = cast(AST.IntegerExp)m.value;
1629 visitInteger(ie.toInteger(), memberType);
1630 buf.writestring(" };");
1631 }
1632 else
1633 {
1634 buf.writestring("static ");
1635 auto target = determineEnumType(memberType);
1636 target.accept(this);
1637 buf.writestring(" const ");
1638 writeIdentifier(m, true);
1639 buf.writestring(" = ");
1640 printExpressionFor(target, m.origValue);
1641 buf.writestring(";");
1642 }
1643 buf.writenl();
1644 }
1645
1646 if (!manifestConstants)
1647 buf.level--;
1648 // write the enum tail
1649 if (!manifestConstants)
1650 buf.writestring("};");
1651 buf.writenl();
1652 buf.writenl();
1653 }
1654
1655 override void visit(AST.EnumMember em)
1656 {
1657 assert(em.ed);
1658
1659 // Members of anonymous members are reachable without referencing the
1660 // EnumDeclaration, e.g. public import foo : someEnumMember;
1661 if (em.ed.isAnonymous())
1662 {
1663 visit(em.ed);
1664 return;
1665 }
1666
1667 assert(false, "This node type should be handled in the EnumDeclaration");
1668 }
1669
1670 /**
1671 * Prints a member/parameter/variable declaration into `buf`.
1672 *
1673 * Params:
1674 * t = the type (used if `this.origType` is null)
1675 * s = the symbol denoting the identifier
1676 * canFixup = whether the identifier may be changed without affecting
1677 * binary compatibility (forwarded to `writeIdentifier`)
1678 */
1679 private void typeToBuffer(AST.Type t, AST.Dsymbol s, const bool canFixup = false)
1680 {
1681 debug (Debug_DtoH)
1682 {
1683 printf("[typeToBuffer(AST.Type, AST.Dsymbol) enter] %s sym %s\n", t.toChars(), s.toChars());
1684 scope(exit) printf("[typeToBuffer(AST.Type, AST.Dsymbol) exit] %s sym %s\n", t.toChars(), s.toChars());
1685 }
1686
1687 // The context pointer (represented as `ThisDeclaration`) is named
1688 // `this` but accessible via `outer`
1689 if (auto td = s.isThisDeclaration())
1690 {
1691 import dmd.id;
1692 this.ident = Id.outer;
1693 }
1694 else
1695 this.ident = s.ident;
1696
1697 auto type = origType !is null ? origType : t;
1698 AST.Dsymbol customLength;
1699
1700 // Check for quirks that are usually resolved during semantic
1701 if (tdparent)
1702 {
1703 // Declarations within template declarations might use TypeAArray
1704 // instead of TypeSArray when the length is not an IntegerExp,
1705 // e.g. int[SOME_CONSTANT]
1706 if (auto taa = type.isTypeAArray())
1707 {
1708 // Try to resolve the symbol from the key if it's not an actual type
1709 Identifier id;
1710 if (auto ti = taa.index.isTypeIdentifier())
1711 id = ti.ident;
1712
1713 if (id)
1714 {
1715 auto sym = findSymbol(id, adparent ? adparent : tdparent);
1716 if (!sym)
1717 {
1718 // Couldn't resolve, assume actual AA
1719 }
1720 else if (AST.isType(sym))
1721 {
1722 // a real associative array, forward to visit
1723 }
1724 else if (auto vd = sym.isVarDeclaration())
1725 {
1726 // Actually a static array with length symbol
1727 customLength = sym;
1728 type = taa.next; // visit the element type, length is written below
1729 }
1730 else
1731 {
1732 printf("Resolved unexpected symbol while determining static array length: %s\n", sym.toChars());
1733 fflush(stdout);
1734 fatal();
1735 }
1736 }
1737 }
1738 }
1739 type.accept(this);
1740 if (this.ident)
1741 {
1742 buf.writeByte(' ');
1743 // Custom identifier doesn't need further checks
1744 if (this.ident !is s.ident)
1745 buf.writestring(this.ident.toString());
1746 else
1747 writeIdentifier(s, canFixup);
1748
1749 }
1750 this.ident = null;
1751
1752 // Size is either taken from the type or resolved above
1753 auto tsa = t.isTypeSArray();
1754 if (tsa || customLength)
1755 {
1756 buf.writeByte('[');
1757 if (tsa)
1758 tsa.dim.accept(this);
1759 else
1760 writeFullName(customLength);
1761 buf.writeByte(']');
1762 }
1763 else if (t.isTypeNoreturn())
1764 buf.writestring("[0]");
1765 }
1766
1767 override void visit(AST.Type t)
1768 {
1769 debug (Debug_DtoH) mixin(traceVisit!t);
1770 printf("Invalid type: %s\n", t.toPrettyChars());
1771 assert(0);
1772 }
1773
1774 override void visit(AST.TypeNoreturn t)
1775 {
1776 debug (Debug_DtoH) mixin(traceVisit!t);
1777
1778 buf.writestring("/* noreturn */ char");
1779 }
1780
1781 override void visit(AST.TypeIdentifier t)
1782 {
1783 debug (Debug_DtoH) mixin(traceVisit!t);
1784
1785 // Try to resolve the referenced symbol
1786 if (auto sym = findSymbol(t.ident))
1787 ensureDeclared(outermostSymbol(sym));
1788
1789 if (t.idents.length)
1790 buf.writestring("typename ");
1791
1792 writeIdentifier(t.ident, t.loc, "type", tdparent !is null);
1793
1794 foreach (arg; t.idents)
1795 {
1796 buf.writestring("::");
1797
1798 import dmd.root.rootobject;
1799 // Is this even possible?
1800 if (arg.dyncast != DYNCAST.identifier)
1801 {
1802 printf("arg.dyncast() = %d\n", arg.dyncast());
1803 assert(false);
1804 }
1805 buf.writestring((cast(Identifier) arg).toChars());
1806 }
1807 }
1808
1809 override void visit(AST.TypeNull t)
1810 {
1811 debug (Debug_DtoH) mixin(traceVisit!t);
1812
1813 if (global.params.cplusplus >= CppStdRevision.cpp11)
1814 buf.writestring("nullptr_t");
1815 else
1816 buf.writestring("void*");
1817
1818 }
1819
1820 override void visit(AST.TypeTypeof t)
1821 {
1822 debug (Debug_DtoH) mixin(traceVisit!t);
1823
1824 assert(t.exp);
1825
1826 if (t.exp.type)
1827 {
1828 t.exp.type.accept(this);
1829 }
1830 else if (t.exp.isThisExp())
1831 {
1832 // Short circuit typeof(this) => <Aggregate name>
1833 assert(adparent);
1834 buf.writestring(adparent.ident.toChars());
1835 }
1836 else
1837 {
1838 // Relying on C++'s typeof might produce wrong results
1839 // but it's the best we've got here.
1840 buf.writestring("typeof(");
1841 t.exp.accept(this);
1842 buf.writeByte(')');
1843 }
1844 }
1845
1846 override void visit(AST.TypeBasic t)
1847 {
1848 debug (Debug_DtoH) mixin(traceVisit!t);
1849
1850 if (t.isConst() || t.isImmutable())
1851 buf.writestring("const ");
1852 string typeName;
1853 switch (t.ty)
1854 {
1855 case AST.Tvoid: typeName = "void"; break;
1856 case AST.Tbool: typeName = "bool"; break;
1857 case AST.Tchar: typeName = "char"; break;
1858 case AST.Twchar: typeName = "char16_t"; break;
1859 case AST.Tdchar: typeName = "char32_t"; break;
1860 case AST.Tint8: typeName = "int8_t"; break;
1861 case AST.Tuns8: typeName = "uint8_t"; break;
1862 case AST.Tint16: typeName = "int16_t"; break;
1863 case AST.Tuns16: typeName = "uint16_t"; break;
1864 case AST.Tint32: typeName = "int32_t"; break;
1865 case AST.Tuns32: typeName = "uint32_t"; break;
1866 case AST.Tint64: typeName = "int64_t"; break;
1867 case AST.Tuns64: typeName = "uint64_t"; break;
1868 case AST.Tfloat32: typeName = "float"; break;
1869 case AST.Tfloat64: typeName = "double"; break;
1870 case AST.Tfloat80:
1871 typeName = "_d_real";
1872 hasReal = true;
1873 break;
1874 case AST.Tcomplex32: typeName = "_Complex float"; break;
1875 case AST.Tcomplex64: typeName = "_Complex double"; break;
1876 case AST.Tcomplex80:
1877 typeName = "_Complex _d_real";
1878 hasReal = true;
1879 break;
1880 // ???: This is not strictly correct, but it should be ignored
1881 // in all places where it matters most (variables, functions, ...).
1882 case AST.Timaginary32: typeName = "float"; break;
1883 case AST.Timaginary64: typeName = "double"; break;
1884 case AST.Timaginary80:
1885 typeName = "_d_real";
1886 hasReal = true;
1887 break;
1888 default:
1889 //t.print();
1890 assert(0);
1891 }
1892 buf.writestring(typeName);
1893 }
1894
1895 override void visit(AST.TypePointer t)
1896 {
1897 debug (Debug_DtoH) mixin(traceVisit!t);
1898
1899 auto ts = t.next.isTypeStruct();
1900 if (ts && !strcmp(ts.sym.ident.toChars(), "__va_list_tag"))
1901 {
1902 buf.writestring("va_list");
1903 return;
1904 }
1905
1906 // Pointer targets can be forward referenced
1907 const fwdSave = forwarding;
1908 forwarding = true;
1909 scope (exit) forwarding = fwdSave;
1910
1911 t.next.accept(this);
1912 if (t.next.ty != AST.Tfunction)
1913 buf.writeByte('*');
1914 if (t.isConst() || t.isImmutable())
1915 buf.writestring(" const");
1916 }
1917
1918 override void visit(AST.TypeSArray t)
1919 {
1920 debug (Debug_DtoH) mixin(traceVisit!t);
1921 t.next.accept(this);
1922 }
1923
1924 override void visit(AST.TypeAArray t)
1925 {
1926 debug (Debug_DtoH) mixin(traceVisit!t);
1927 AST.Type.tvoidptr.accept(this);
1928 }
1929
1930 override void visit(AST.TypeFunction tf)
1931 {
1932 debug (Debug_DtoH) mixin(traceVisit!tf);
1933
1934 tf.next.accept(this);
1935 buf.writeByte('(');
1936 buf.writeByte('*');
1937 if (ident)
1938 buf.writestring(ident.toChars());
1939 ident = null;
1940 buf.writeByte(')');
1941 buf.writeByte('(');
1942 foreach (i, fparam; tf.parameterList)
1943 {
1944 if (i)
1945 buf.writestring(", ");
1946 fparam.accept(this);
1947 }
1948 if (tf.parameterList.varargs)
1949 {
1950 if (tf.parameterList.parameters.dim && tf.parameterList.varargs == 1)
1951 buf.writestring(", ");
1952 buf.writestring("...");
1953 }
1954 buf.writeByte(')');
1955 }
1956
1957 /// Writes the type that represents `ed` into `buf`.
1958 /// (Might not be `ed` for special enums or enums that were emitted as namespaces)
1959 private void enumToBuffer(AST.EnumDeclaration ed)
1960 {
1961 debug (Debug_DtoH) mixin(traceVisit!ed);
1962
1963 if (ed.isSpecial())
1964 {
1965 if (ed.ident == DMDType.c_long)
1966 buf.writestring("long");
1967 else if (ed.ident == DMDType.c_ulong)
1968 buf.writestring("unsigned long");
1969 else if (ed.ident == DMDType.c_longlong)
1970 buf.writestring("long long");
1971 else if (ed.ident == DMDType.c_ulonglong)
1972 buf.writestring("unsigned long long");
1973 else if (ed.ident == DMDType.c_long_double)
1974 buf.writestring("long double");
1975 else if (ed.ident == DMDType.c_char)
1976 buf.writestring("char");
1977 else if (ed.ident == DMDType.c_wchar_t)
1978 buf.writestring("wchar_t");
1979 else if (ed.ident == DMDType.c_complex_float)
1980 buf.writestring("_Complex float");
1981 else if (ed.ident == DMDType.c_complex_double)
1982 buf.writestring("_Complex double");
1983 else if (ed.ident == DMDType.c_complex_real)
1984 buf.writestring("_Complex long double");
1985 else
1986 {
1987 //ed.print();
1988 assert(0);
1989 }
1990 return;
1991 }
1992
1993 const kind = getEnumKind(ed.memtype);
1994
1995 // Check if the enum was emitted as a real enum
1996 if (kind == EnumKind.Int || kind == EnumKind.Numeric)
1997 {
1998 writeFullName(ed);
1999 }
2000 else
2001 {
2002 // Use the base type if the enum was emitted as a namespace
2003 buf.printf("/* %s */ ", ed.ident.toChars());
2004 ed.memtype.accept(this);
2005 }
2006 }
2007
2008 override void visit(AST.TypeEnum t)
2009 {
2010 debug (Debug_DtoH) mixin(traceVisit!t);
2011
2012 if (t.isConst() || t.isImmutable())
2013 buf.writestring("const ");
2014 enumToBuffer(t.sym);
2015 }
2016
2017 override void visit(AST.TypeStruct t)
2018 {
2019 debug (Debug_DtoH) mixin(traceVisit!t);
2020
2021 if (t.isConst() || t.isImmutable())
2022 buf.writestring("const ");
2023 writeFullName(t.sym);
2024 }
2025
2026 override void visit(AST.TypeDArray t)
2027 {
2028 debug (Debug_DtoH) mixin(traceVisit!t);
2029
2030 if (t.isConst() || t.isImmutable())
2031 buf.writestring("const ");
2032 buf.writestring("_d_dynamicArray< ");
2033 t.next.accept(this);
2034 buf.writestring(" >");
2035 }
2036
2037 override void visit(AST.TypeInstance t)
2038 {
2039 visitTi(t.tempinst);
2040 }
2041
2042 private void visitTi(AST.TemplateInstance ti)
2043 {
2044 debug (Debug_DtoH) mixin(traceVisit!ti);
2045
2046 // Ensure that the TD appears before the instance
2047 if (auto td = findTemplateDeclaration(ti))
2048 ensureDeclared(td);
2049
2050 foreach (o; *ti.tiargs)
2051 {
2052 if (!AST.isType(o))
2053 return;
2054 }
2055 buf.writestring(ti.name.toChars());
2056 buf.writeByte('<');
2057 foreach (i, o; *ti.tiargs)
2058 {
2059 if (i)
2060 buf.writestring(", ");
2061 if (auto tt = AST.isType(o))
2062 {
2063 tt.accept(this);
2064 }
2065 else
2066 {
2067 //ti.print();
2068 //o.print();
2069 assert(0);
2070 }
2071 }
2072 buf.writestring(" >");
2073 }
2074
2075 override void visit(AST.TemplateDeclaration td)
2076 {
2077 debug (Debug_DtoH) mixin(traceVisit!td);
2078
2079 if (!shouldEmitAndMarkVisited(td))
2080 return;
2081
2082 if (!td.parameters || !td.onemember || (!td.onemember.isStructDeclaration && !td.onemember.isClassDeclaration && !td.onemember.isFuncDeclaration))
2083 {
2084 visit(cast(AST.Dsymbol)td);
2085 return;
2086 }
2087
2088 // Explicitly disallow templates with non-type parameters or specialization.
2089 foreach (p; *td.parameters)
2090 {
2091 if (!p.isTemplateTypeParameter() || p.specialization())
2092 {
2093 visit(cast(AST.Dsymbol)td);
2094 return;
2095 }
2096 }
2097
2098 auto save = tdparent;
2099 tdparent = td;
2100 const bookmark = buf.length;
2101 printTemplateParams(td);
2102
2103 const oldIgnored = this.ignoredCounter;
2104 td.onemember.accept(this);
2105
2106 // Remove "template<...>" if the symbol could not be emitted
2107 if (oldIgnored != this.ignoredCounter)
2108 buf.setsize(bookmark);
2109
2110 tdparent = save;
2111 }
2112
2113 /// Writes the template<...> header for the supplied template declaration
2114 private void printTemplateParams(const AST.TemplateDeclaration td)
2115 {
2116 buf.writestring("template <");
2117 bool first = true;
2118 foreach (p; *td.parameters)
2119 {
2120 if (first)
2121 first = false;
2122 else
2123 buf.writestring(", ");
2124 buf.writestring("typename ");
2125 writeIdentifier(p.ident, p.loc, "template parameter", true);
2126 }
2127 buf.writestringln(">");
2128 }
2129
2130 /// Emit declarations of the TemplateMixin in the current scope
2131 override void visit(AST.TemplateMixin tm)
2132 {
2133 debug (Debug_DtoH) mixin(traceVisit!tm);
2134
2135 auto members = tm.members;
2136
2137 // members are missing for instances inside of TemplateDeclarations, e.g.
2138 // template Foo(T) { mixin Bar!T; }
2139 if (!members)
2140 {
2141 if (auto td = findTemplateDeclaration(tm))
2142 members = td.members; // Emit members of the template
2143 else
2144 return; // Cannot emit mixin
2145 }
2146
2147 foreach (s; *members)
2148 {
2149 // kind is undefined without semantic
2150 const kind = s.visible().kind;
2151 if (kind == AST.Visibility.Kind.public_ || kind == AST.Visibility.Kind.undefined)
2152 s.accept(this);
2153 }
2154 }
2155
2156 /**
2157 * Finds a symbol with the identifier `name` by iterating the linked list of parent
2158 * symbols, starting from `context`.
2159 *
2160 * Returns: the symbol or `null` if missing
2161 */
2162 private AST.Dsymbol findSymbol(Identifier name, AST.Dsymbol context)
2163 {
2164 // Follow the declaration context
2165 for (auto par = context; par; par = par.toParentDecl())
2166 {
2167 // Check that `name` doesn't refer to a template parameter
2168 if (auto td = par.isTemplateDeclaration())
2169 {
2170 foreach (const p; *td.parameters)
2171 {
2172 if (p.ident == name)
2173 return null;
2174 }
2175 }
2176
2177 if (auto mem = findMember(par, name))
2178 {
2179 return mem;
2180 }
2181 }
2182 return null;
2183 }
2184
2185 /// ditto
2186 private AST.Dsymbol findSymbol(Identifier name)
2187 {
2188 AST.Dsymbol sym;
2189 if (adparent)
2190 sym = findSymbol(name, adparent);
2191
2192 if (!sym && tdparent)
2193 sym = findSymbol(name, tdparent);
2194
2195 return sym;
2196 }
2197
2198 /// Finds the template declaration for instance `ti`
2199 private AST.TemplateDeclaration findTemplateDeclaration(AST.TemplateInstance ti)
2200 {
2201 if (ti.tempdecl)
2202 return ti.tempdecl.isTemplateDeclaration();
2203
2204 assert(tdparent); // Only missing inside of templates
2205
2206 // Search for the TemplateDeclaration, starting from the enclosing scope
2207 // if known or the enclosing template.
2208 auto sym = findSymbol(ti.name, ti.parent ? ti.parent : tdparent);
2209 return sym ? sym.isTemplateDeclaration() : null;
2210 }
2211
2212 override void visit(AST.TypeClass t)
2213 {
2214 debug (Debug_DtoH) mixin(traceVisit!t);
2215
2216 // Classes are emitted as pointer and hence can be forwarded
2217 const fwdSave = forwarding;
2218 forwarding = true;
2219 scope (exit) forwarding = fwdSave;
2220
2221 if (t.isConst() || t.isImmutable())
2222 buf.writestring("const ");
2223 writeFullName(t.sym);
2224 buf.writeByte('*');
2225 if (t.isConst() || t.isImmutable())
2226 buf.writestring(" const");
2227 }
2228
2229 /**
2230 * Writes the function signature to `buf`.
2231 *
2232 * Params:
2233 * fd = the function to print
2234 * tf = fd's type
2235 */
2236 private void funcToBuffer(AST.TypeFunction tf, AST.FuncDeclaration fd)
2237 {
2238 debug (Debug_DtoH)
2239 {
2240 printf("[funcToBuffer(AST.TypeFunction) enter] %s\n", fd.toChars());
2241 scope(exit) printf("[funcToBuffer(AST.TypeFunction) exit] %s\n", fd.toChars());
2242 }
2243
2244 auto originalType = cast(AST.TypeFunction)fd.originalType;
2245
2246 if (fd.isCtorDeclaration() || fd.isDtorDeclaration())
2247 {
2248 if (fd.isDtorDeclaration())
2249 {
2250 buf.writeByte('~');
2251 }
2252 buf.writestring(adparent.toChars());
2253 if (!tf)
2254 {
2255 assert(fd.isDtorDeclaration());
2256 buf.writestring("()");
2257 return;
2258 }
2259 }
2260 else
2261 {
2262 import dmd.root.string : toDString;
2263 assert(tf.next, fd.loc.toChars().toDString());
2264
2265 tf.next == AST.Type.tsize_t ? originalType.next.accept(this) : tf.next.accept(this);
2266 if (tf.isref)
2267 buf.writeByte('&');
2268 buf.writeByte(' ');
2269 writeIdentifier(fd);
2270 }
2271
2272 buf.writeByte('(');
2273 foreach (i, fparam; tf.parameterList)
2274 {
2275 if (i)
2276 buf.writestring(", ");
2277 if (fparam.type == AST.Type.tsize_t && originalType)
2278 {
2279 fparam = originalType.parameterList[i];
2280 }
2281 fparam.accept(this);
2282 }
2283 if (tf.parameterList.varargs)
2284 {
2285 if (tf.parameterList.parameters.dim && tf.parameterList.varargs == 1)
2286 buf.writestring(", ");
2287 buf.writestring("...");
2288 }
2289 buf.writeByte(')');
2290 }
2291
2292 override void visit(AST.Parameter p)
2293 {
2294 debug (Debug_DtoH) mixin(traceVisit!p);
2295
2296 ident = p.ident;
2297
2298 {
2299 // Reference parameters can be forwarded
2300 const fwdStash = this.forwarding;
2301 this.forwarding = !!(p.storageClass & AST.STC.ref_);
2302 p.type.accept(this);
2303 this.forwarding = fwdStash;
2304 }
2305
2306 if (p.storageClass & AST.STC.ref_)
2307 buf.writeByte('&');
2308 buf.writeByte(' ');
2309 if (ident)
2310 // FIXME: Parameter is missing a Loc
2311 writeIdentifier(ident, Loc.initial, "parameter", true);
2312 ident = null;
2313
2314 if (p.defaultArg)
2315 {
2316 //printf("%s %d\n", p.defaultArg.toChars, p.defaultArg.op);
2317 buf.writestring(" = ");
2318 printExpressionFor(p.type, p.defaultArg);
2319 }
2320 }
2321
2322 /**
2323 * Prints `exp` as an expression of type `target` while inserting
2324 * appropriate code when implicit conversion does not translate
2325 * directly to C++, e.g. from an enum to its base type.
2326 *
2327 * Params:
2328 * target = the type `exp` is converted to
2329 * exp = the expression to print
2330 * isCtor = if `exp` is a ctor argument
2331 */
2332 private void printExpressionFor(AST.Type target, AST.Expression exp, const bool isCtor = false)
2333 {
2334 /// Determines if a static_cast is required
2335 static bool needsCast(AST.Type target, AST.Expression exp)
2336 {
2337 // import std.stdio;
2338 // writefln("%s:%s: target = %s, type = %s (%s)", exp.loc.linnum, exp.loc.charnum, target, exp.type, exp.op);
2339
2340 auto source = exp.type;
2341
2342 // DotVarExp resolve conversions, e.g from an enum to its base type
2343 if (auto dve = exp.isDotVarExp())
2344 source = dve.var.type;
2345
2346 if (!source)
2347 // Defensively assume that the cast is required
2348 return true;
2349
2350 // Conversions from enum class to base type require static_cast
2351 if (global.params.cplusplus >= CppStdRevision.cpp11 &&
2352 source.isTypeEnum && !target.isTypeEnum)
2353 return true;
2354
2355 return false;
2356 }
2357
2358 // Slices are emitted as a special struct, hence we need to fix up
2359 // any expression initialising a slice variable/member
2360 if (auto ta = target.isTypeDArray())
2361 {
2362 if (exp.isNullExp())
2363 {
2364 if (isCtor)
2365 {
2366 // Don't emit, use default ctor
2367 }
2368 else if (global.params.cplusplus >= CppStdRevision.cpp11)
2369 {
2370 // Prefer initializer list
2371 buf.writestring("{}");
2372 }
2373 else
2374 {
2375 // Write __d_dynamic_array<TYPE>()
2376 visit(ta);
2377 buf.writestring("()");
2378 }
2379 return;
2380 }
2381
2382 if (auto se = exp.isStringExp())
2383 {
2384 // Rewrite as <length> + <literal> pair optionally
2385 // wrapped in a initializer list/ctor call
2386
2387 const initList = global.params.cplusplus >= CppStdRevision.cpp11;
2388 if (!isCtor)
2389 {
2390 if (initList)
2391 buf.writestring("{ ");
2392 else
2393 {
2394 visit(ta);
2395 buf.writestring("( ");
2396 }
2397 }
2398
2399 buf.printf("%zu, ", se.len);
2400 visit(se);
2401
2402 if (!isCtor)
2403 buf.writestring(initList ? " }" : " )");
2404
2405 return;
2406 }
2407 }
2408 else if (auto ce = exp.isCastExp())
2409 {
2410 buf.writeByte('(');
2411 if (ce.to)
2412 ce.to.accept(this);
2413 else if (ce.e1.type)
2414 // Try the expression type with modifiers in case of cast(const) in templates
2415 ce.e1.type.castMod(ce.mod).accept(this);
2416 else
2417 // Fallback, not necessarily correct but the best we've got here
2418 target.accept(this);
2419 buf.writestring(") ");
2420 ce.e1.accept(this);
2421 }
2422 else if (needsCast(target, exp))
2423 {
2424 buf.writestring("static_cast<");
2425 target.accept(this);
2426 buf.writestring(">(");
2427 exp.accept(this);
2428 buf.writeByte(')');
2429 }
2430 else
2431 {
2432 exp.accept(this);
2433 }
2434 }
2435
2436 override void visit(AST.Expression e)
2437 {
2438 debug (Debug_DtoH) mixin(traceVisit!e);
2439
2440 // Valid in most cases, others should be overriden below
2441 // to use the appropriate operators (:: and ->)
2442 buf.writestring(e.toString());
2443 }
2444
2445 override void visit(AST.UnaExp e)
2446 {
2447 debug (Debug_DtoH) mixin(traceVisit!e);
2448
2449 buf.writestring(expToString(e.op));
2450 e.e1.accept(this);
2451 }
2452
2453 override void visit(AST.BinExp e)
2454 {
2455 debug (Debug_DtoH) mixin(traceVisit!e);
2456
2457 e.e1.accept(this);
2458 buf.writeByte(' ');
2459 buf.writestring(expToString(e.op));
2460 buf.writeByte(' ');
2461 e.e2.accept(this);
2462 }
2463
2464 /// Translates operator `op` into the C++ representation
2465 private extern(D) static string expToString(const EXP op)
2466 {
2467 switch (op) with (EXP)
2468 {
2469 case identity: return "==";
2470 case notIdentity: return "!=";
2471 default:
2472 return EXPtoString(op);
2473 }
2474 }
2475
2476 override void visit(AST.VarExp e)
2477 {
2478 debug (Debug_DtoH) mixin(traceVisit!e);
2479
2480 // Local members don't need another prefix and might've been renamed
2481 if (e.var.isThis())
2482 {
2483 includeSymbol(e.var);
2484 writeIdentifier(e.var, true);
2485 }
2486 else
2487 writeFullName(e.var);
2488 }
2489
2490 /// Partially prints the FQN including parent aggregates
2491 private void printPrefix(AST.Dsymbol var)
2492 {
2493 if (!var || var is adparent || var.isModule())
2494 return;
2495
2496 writeFullName(var);
2497 buf.writestring("::");
2498 }
2499
2500 override void visit(AST.CallExp e)
2501 {
2502 debug (Debug_DtoH) mixin(traceVisit!e);
2503
2504 // Dereferencing function pointers requires additional braces: (*f)(args)
2505 const isFp = e.e1.isPtrExp();
2506 if (isFp)
2507 buf.writeByte('(');
2508 else if (e.f)
2509 includeSymbol(outermostSymbol(e.f));
2510
2511 e.e1.accept(this);
2512
2513 if (isFp) buf.writeByte(')');
2514
2515 assert(e.arguments);
2516 buf.writeByte('(');
2517 foreach (i, arg; *e.arguments)
2518 {
2519 if (i)
2520 buf.writestring(", ");
2521 arg.accept(this);
2522 }
2523 buf.writeByte(')');
2524 }
2525
2526 override void visit(AST.DotVarExp e)
2527 {
2528 debug (Debug_DtoH) mixin(traceVisit!e);
2529
2530 if (auto sym = symbolFromType(e.e1.type))
2531 includeSymbol(outermostSymbol(sym));
2532
2533 // Accessing members through a pointer?
2534 if (auto pe = e.e1.isPtrExp)
2535 {
2536 pe.e1.accept(this);
2537 buf.writestring("->");
2538 }
2539 else
2540 {
2541 e.e1.accept(this);
2542 buf.writeByte('.');
2543 }
2544
2545 // Should only be used to access non-static members
2546 assert(e.var.isThis());
2547
2548 writeIdentifier(e.var, true);
2549 }
2550
2551 override void visit(AST.DotIdExp e)
2552 {
2553 debug (Debug_DtoH) mixin(traceVisit!e);
2554
2555 e.e1.accept(this);
2556 buf.writestring("::");
2557 buf.writestring(e.ident.toChars());
2558 }
2559
2560 override void visit(AST.ScopeExp e)
2561 {
2562 debug (Debug_DtoH) mixin(traceVisit!e);
2563
2564 // Usually a template instance in a TemplateDeclaration
2565 if (auto ti = e.sds.isTemplateInstance())
2566 visitTi(ti);
2567 else
2568 writeFullName(e.sds);
2569 }
2570
2571 override void visit(AST.NullExp e)
2572 {
2573 debug (Debug_DtoH) mixin(traceVisit!e);
2574
2575 if (global.params.cplusplus >= CppStdRevision.cpp11)
2576 buf.writestring("nullptr");
2577 else
2578 buf.writestring("NULL");
2579 }
2580
2581 override void visit(AST.ArrayLiteralExp e)
2582 {
2583 debug (Debug_DtoH) mixin(traceVisit!e);
2584 buf.writestring("arrayliteral");
2585 }
2586
2587 override void visit(AST.StringExp e)
2588 {
2589 debug (Debug_DtoH) mixin(traceVisit!e);
2590
2591 if (e.sz == 2)
2592 buf.writeByte('u');
2593 else if (e.sz == 4)
2594 buf.writeByte('U');
2595 buf.writeByte('"');
2596
2597 foreach (i; 0 .. e.len)
2598 {
2599 writeCharLiteral(*buf, e.getCodeUnit(i));
2600 }
2601 buf.writeByte('"');
2602 }
2603
2604 override void visit(AST.RealExp e)
2605 {
2606 debug (Debug_DtoH) mixin(traceVisit!e);
2607
2608 import dmd.root.ctfloat : CTFloat;
2609
2610 // Special case NaN and Infinity because floatToBuffer
2611 // uses D literals (`nan` and `infinity`)
2612 if (CTFloat.isNaN(e.value))
2613 {
2614 buf.writestring("NAN");
2615 }
2616 else if (CTFloat.isInfinity(e.value))
2617 {
2618 if (e.value < CTFloat.zero)
2619 buf.writeByte('-');
2620 buf.writestring("INFINITY");
2621 }
2622 else
2623 {
2624 import dmd.hdrgen;
2625 // Hex floating point literals were introduced in C++ 17
2626 const allowHex = global.params.cplusplus >= CppStdRevision.cpp17;
2627 floatToBuffer(e.type, e.value, buf, allowHex);
2628 }
2629 }
2630
2631 override void visit(AST.IntegerExp e)
2632 {
2633 debug (Debug_DtoH) mixin(traceVisit!e);
2634 visitInteger(e.toInteger, e.type);
2635 }
2636
2637 /// Writes `v` as type `t` into `buf`
2638 private void visitInteger(dinteger_t v, AST.Type t)
2639 {
2640 debug (Debug_DtoH) mixin(traceVisit!t);
2641
2642 switch (t.ty)
2643 {
2644 case AST.Tenum:
2645 auto te = cast(AST.TypeEnum)t;
2646 buf.writestring("(");
2647 enumToBuffer(te.sym);
2648 buf.writestring(")");
2649 visitInteger(v, te.sym.memtype);
2650 break;
2651 case AST.Tbool:
2652 buf.writestring(v ? "true" : "false");
2653 break;
2654 case AST.Tint8:
2655 buf.printf("%d", cast(byte)v);
2656 break;
2657 case AST.Tuns8:
2658 buf.printf("%uu", cast(ubyte)v);
2659 break;
2660 case AST.Tint16:
2661 buf.printf("%d", cast(short)v);
2662 break;
2663 case AST.Tuns16:
2664 case AST.Twchar:
2665 buf.printf("%uu", cast(ushort)v);
2666 break;
2667 case AST.Tint32:
2668 case AST.Tdchar:
2669 buf.printf("%d", cast(int)v);
2670 break;
2671 case AST.Tuns32:
2672 buf.printf("%uu", cast(uint)v);
2673 break;
2674 case AST.Tint64:
2675 buf.printf("%lldLL", v);
2676 break;
2677 case AST.Tuns64:
2678 buf.printf("%lluLLU", v);
2679 break;
2680 case AST.Tchar:
2681 if (v > 0x20 && v < 0x80)
2682 buf.printf("'%c'", cast(int)v);
2683 else
2684 buf.printf("%uu", cast(ubyte)v);
2685 break;
2686 default:
2687 //t.print();
2688 assert(0);
2689 }
2690 }
2691
2692 override void visit(AST.StructLiteralExp sle)
2693 {
2694 debug (Debug_DtoH) mixin(traceVisit!sle);
2695
2696 const isUnion = sle.sd.isUnionDeclaration();
2697 sle.sd.type.accept(this);
2698 buf.writeByte('(');
2699 foreach(i, e; *sle.elements)
2700 {
2701 if (i)
2702 buf.writestring(", ");
2703
2704 auto vd = sle.sd.fields[i];
2705
2706 // Expression may be null for unspecified elements
2707 if (!e)
2708 e = findDefaultInitializer(vd);
2709
2710 printExpressionFor(vd.type, e);
2711
2712 // Only emit the initializer of the first union member
2713 if (isUnion)
2714 break;
2715 }
2716 buf.writeByte(')');
2717 }
2718
2719 /// Finds the default initializer for the given VarDeclaration
2720 private static AST.Expression findDefaultInitializer(AST.VarDeclaration vd)
2721 {
2722 if (vd._init && !vd._init.isVoidInitializer())
2723 return AST.initializerToExpression(vd._init);
2724 else if (auto ts = vd.type.isTypeStruct())
2725 {
2726 if (!ts.sym.noDefaultCtor && !ts.sym.isUnionDeclaration())
2727 {
2728 // Generate a call to the default constructor that we've generated.
2729 auto sle = new AST.StructLiteralExp(Loc.initial, ts.sym, new AST.Expressions(0));
2730 sle.type = vd.type;
2731 return sle;
2732 }
2733 else
2734 return vd.type.defaultInitLiteral(Loc.initial);
2735 }
2736 else
2737 return vd.type.defaultInitLiteral(Loc.initial);
2738 }
2739
2740 static if (__VERSION__ < 2092)
2741 {
2742 private void ignored(const char* format, ...) nothrow
2743 {
2744 this.ignoredCounter++;
2745
2746 import core.stdc.stdarg;
2747 if (!printIgnored)
2748 return;
2749
2750 va_list ap;
2751 va_start(ap, format);
2752 buf.writestring("// Ignored ");
2753 buf.vprintf(format, ap);
2754 buf.writenl();
2755 va_end(ap);
2756 }
2757 }
2758 else
2759 {
2760 /// Writes a formatted message into `buf` if `printIgnored` is true
2761 /// and increments `ignoredCounter`
2762 pragma(printf)
2763 private void ignored(const char* format, ...) nothrow
2764 {
2765 this.ignoredCounter++;
2766
2767 import core.stdc.stdarg;
2768 if (!printIgnored)
2769 return;
2770
2771 va_list ap;
2772 va_start(ap, format);
2773 buf.writestring("// Ignored ");
2774 buf.vprintf(format, ap);
2775 buf.writenl();
2776 va_end(ap);
2777 }
2778 }
2779
2780 /**
2781 * Determines whether `s` should be emitted. This requires that `sym`
2782 * - is `extern(C[++]`)
2783 * - is not instantiated from a template (visits the `TemplateDeclaration` instead)
2784 *
2785 * Params:
2786 * sym = the symbol
2787 *
2788 * Returns: whether `sym` should be emitted
2789 */
2790 private bool shouldEmit(AST.Dsymbol sym)
2791 {
2792 import dmd.aggregate : ClassKind;
2793 debug (Debug_DtoH)
2794 {
2795 printf("[shouldEmitAndMarkVisited enter] %s\n", sym.toPrettyChars());
2796 scope(exit) printf("[shouldEmitAndMarkVisited exit] %s\n", sym.toPrettyChars());
2797 }
2798
2799 // Template *instances* should not be emitted
2800 if (sym.isInstantiated())
2801 return false;
2802
2803 // Matching linkage (except extern(C) classes which don't make sense)
2804 if (linkage == LINK.cpp || (linkage == LINK.c && !sym.isClassDeclaration()))
2805 return true;
2806
2807 // Check against the internal information which might be missing, e.g. inside of template declarations
2808 if (auto dec = sym.isDeclaration())
2809 {
2810 const l = dec.resolvedLinkage();
2811 return l == LINK.cpp || l == LINK.c;
2812 }
2813
2814 if (auto ad = sym.isAggregateDeclaration())
2815 return ad.classKind == ClassKind.cpp;
2816
2817 return false;
2818 }
2819
2820 /**
2821 * Determines whether `s` should be emitted. This requires that `sym`
2822 * - was not visited before
2823 * - is `extern(C[++]`)
2824 * - is not instantiated from a template (visits the `TemplateDeclaration` instead)
2825 * The result is cached in the visited nodes array.
2826 *
2827 * Params:
2828 * sym = the symbol
2829 *
2830 * Returns: whether `sym` should be emitted
2831 **/
2832 private bool shouldEmitAndMarkVisited(AST.Dsymbol sym)
2833 {
2834 debug (Debug_DtoH)
2835 {
2836 printf("[shouldEmitAndMarkVisited enter] %s\n", sym.toPrettyChars());
2837 scope(exit) printf("[shouldEmitAndMarkVisited exit] %s\n", sym.toPrettyChars());
2838 }
2839
2840 auto statePtr = (cast(void*) sym) in visited;
2841
2842 // `sym` was already emitted or skipped and isn't required
2843 if (statePtr && (*statePtr || !mustEmit))
2844 return false;
2845
2846 // Template *instances* should not be emitted, forward to the declaration
2847 if (auto ti = sym.isInstantiated())
2848 {
2849 auto td = findTemplateDeclaration(ti);
2850 assert(td);
2851 visit(td);
2852 return false;
2853 }
2854
2855 // Required or matching linkage (except extern(C) classes which don't make sense)
2856 bool res = mustEmit || linkage == LINK.cpp || (linkage == LINK.c && !sym.isClassDeclaration());
2857 if (!res)
2858 {
2859 // Check against the internal information which might be missing, e.g. inside of template declarations
2860 if (auto dec = sym.isDeclaration())
2861 {
2862 const l = dec.resolvedLinkage();
2863 res = (l == LINK.cpp || l == LINK.c);
2864 }
2865 }
2866
2867 // Remember result for later calls
2868 if (statePtr)
2869 *statePtr = res;
2870 else
2871 visited[(cast(void*) sym)] = res;
2872
2873 // Print a warning when the symbol is ignored for the first time
2874 // Might not be correct if it is required by symbol the is visited
2875 // AFTER the current node
2876 if (!statePtr && !res)
2877 ignored("%s %s because of linkage", sym.kind(), sym.toPrettyChars());
2878
2879 return res;
2880 }
2881
2882 /**
2883 * Ensures that `sym` is declared before the current position in `buf` by
2884 * either creating a forward reference in `fwdbuf` if possible or
2885 * calling `includeSymbol` to emit the entire declaration into `donebuf`.
2886 */
2887 private void ensureDeclared(AST.Dsymbol sym)
2888 {
2889 auto par = sym.toParent2();
2890 auto ed = sym.isEnumDeclaration();
2891
2892 // Eagerly include the symbol if we cannot create a valid forward declaration
2893 // Forwarding of scoped enums requires C++11 or above
2894 if (!forwarding || (par && !par.isModule()) || (ed && global.params.cplusplus < CppStdRevision.cpp11))
2895 {
2896 // Emit the entire enclosing declaration if any
2897 includeSymbol(outermostSymbol(sym));
2898 return;
2899 }
2900
2901 auto ti = sym.isInstantiated();
2902 auto td = ti ? findTemplateDeclaration(ti) : null;
2903 auto check = cast(void*) (td ? td : sym);
2904
2905 // Omit redundant fwd-declaration if we already emitted the entire declaration
2906 if (visited.get(check, false))
2907 return;
2908
2909 // Already created a fwd-declaration?
2910 if (check in forwarded)
2911 return;
2912 forwarded[check] = true;
2913
2914 // Print template<...>
2915 if (ti)
2916 {
2917 auto bufSave = buf;
2918 buf = fwdbuf;
2919 printTemplateParams(td);
2920 buf = bufSave;
2921 }
2922
2923 // Determine the kind of symbol that is forwared: struct, ...
2924 const(char)* kind;
2925
2926 if (auto ad = sym.isAggregateDeclaration())
2927 {
2928 // Look for extern(C++, class) <some aggregate>
2929 if (ad.cppmangle == CPPMANGLE.def)
2930 kind = ad.kind();
2931 else if (ad.cppmangle == CPPMANGLE.asStruct)
2932 kind = "struct";
2933 else
2934 kind = "class";
2935 }
2936 else if (ed)
2937 {
2938 // Only called from enumToBuffer, so should always be emitted as an actual enum
2939 kind = "enum class";
2940 }
2941 else
2942 kind = sym.kind(); // Should be unreachable but just to be sure
2943
2944 fwdbuf.writestring(kind);
2945 fwdbuf.writeByte(' ');
2946 fwdbuf.writestring(sym.toChars());
2947 fwdbuf.writestringln(";");
2948 }
2949
2950 /**
2951 * Writes the qualified name of `sym` into `buf` including parent
2952 * symbols and template parameters.
2953 *
2954 * Params:
2955 * sym = the symbol
2956 * mustInclude = whether sym may not be forward declared
2957 */
2958 private void writeFullName(AST.Dsymbol sym, const bool mustInclude = false)
2959 in
2960 {
2961 assert(sym);
2962 assert(sym.ident, sym.toString());
2963 // Should never be called directly with a TI, only onemember
2964 assert(!sym.isTemplateInstance(), sym.toString());
2965 }
2966 do
2967 {
2968 debug (Debug_DtoH)
2969 {
2970 printf("[writeFullName enter] %s\n", sym.toPrettyChars());
2971 scope(exit) printf("[writeFullName exit] %s\n", sym.toPrettyChars());
2972 }
2973
2974 // Explicit `pragma(mangle, "<some string>` overrides the declared name
2975 if (auto mn = getMangleOverride(sym))
2976 return buf.writestring(mn);
2977
2978 /// Checks whether `sym` is nested in `par` and hence doesn't need the FQN
2979 static bool isNestedIn(AST.Dsymbol sym, AST.Dsymbol par)
2980 {
2981 while (par)
2982 {
2983 if (sym is par)
2984 return true;
2985 par = par.toParent();
2986 }
2987 return false;
2988 }
2989 AST.TemplateInstance ti;
2990 bool nested;
2991
2992 // Check if the `sym` is nested into another symbol and hence requires `Parent::sym`
2993 if (auto par = sym.toParent())
2994 {
2995 // toParent() yields the template instance if `sym` is the onemember of a TI
2996 ti = par.isTemplateInstance();
2997
2998 // Skip the TI because Foo!int.Foo is folded into Foo<int>
2999 if (ti) par = ti.toParent();
3000
3001 // Prefix the name with any enclosing declaration
3002 // Stop at either module or enclosing aggregate
3003 nested = !par.isModule();
3004 if (nested && !isNestedIn(par, adparent))
3005 {
3006 writeFullName(par, true);
3007 buf.writestring("::");
3008 }
3009 }
3010
3011 if (!nested)
3012 {
3013 // Cannot forward the symbol when called recursively
3014 // for a nested symbol
3015 if (mustInclude)
3016 includeSymbol(sym);
3017 else
3018 ensureDeclared(sym);
3019 }
3020
3021 if (ti)
3022 visitTi(ti);
3023 else
3024 buf.writestring(sym.ident.toString());
3025 }
3026
3027 /// Returns: Explicit mangling for `sym` if present
3028 extern(D) static const(char)[] getMangleOverride(const AST.Dsymbol sym)
3029 {
3030 if (auto decl = sym.isDeclaration())
3031 return decl.mangleOverride;
3032
3033 return null;
3034 }
3035 }
3036
3037 /// Namespace for identifiers used to represent special enums in C++
3038 struct DMDType
3039 {
3040 __gshared Identifier c_long;
3041 __gshared Identifier c_ulong;
3042 __gshared Identifier c_longlong;
3043 __gshared Identifier c_ulonglong;
3044 __gshared Identifier c_long_double;
3045 __gshared Identifier c_char;
3046 __gshared Identifier c_wchar_t;
3047 __gshared Identifier c_complex_float;
3048 __gshared Identifier c_complex_double;
3049 __gshared Identifier c_complex_real;
3050
3051 static void _init()
3052 {
3053 c_long = Identifier.idPool("__c_long");
3054 c_ulong = Identifier.idPool("__c_ulong");
3055 c_longlong = Identifier.idPool("__c_longlong");
3056 c_ulonglong = Identifier.idPool("__c_ulonglong");
3057 c_long_double = Identifier.idPool("__c_long_double");
3058 c_wchar_t = Identifier.idPool("__c_wchar_t");
3059 c_char = Identifier.idPool("__c_char");
3060 c_complex_float = Identifier.idPool("__c_complex_float");
3061 c_complex_double = Identifier.idPool("__c_complex_double");
3062 c_complex_real = Identifier.idPool("__c_complex_real");
3063 }
3064 }
3065
3066 /// Initializes all data structures used by the header generator
3067 void initialize()
3068 {
3069 __gshared bool initialized;
3070
3071 if (!initialized)
3072 {
3073 initialized = true;
3074
3075 DMDType._init();
3076 }
3077 }
3078
3079 /// Writes `#if <content>` into the supplied buffer
3080 void hashIf(ref OutBuffer buf, string content)
3081 {
3082 buf.writestring("#if ");
3083 buf.writestringln(content);
3084 }
3085
3086 /// Writes `#elif <content>` into the supplied buffer
3087 void hashElIf(ref OutBuffer buf, string content)
3088 {
3089 buf.writestring("#elif ");
3090 buf.writestringln(content);
3091 }
3092
3093 /// Writes `#endif` into the supplied buffer
3094 void hashEndIf(ref OutBuffer buf)
3095 {
3096 buf.writestringln("#endif");
3097 }
3098
3099 /// Writes `#define <content>` into the supplied buffer
3100 void hashDefine(ref OutBuffer buf, string content)
3101 {
3102 buf.writestring("#define ");
3103 buf.writestringln(content);
3104 }
3105
3106 /// Writes `#include <content>` into the supplied buffer
3107 void hashInclude(ref OutBuffer buf, string content)
3108 {
3109 buf.writestring("#include ");
3110 buf.writestringln(content);
3111 }
3112
3113 /// Determines whether `ident` is a reserved keyword in C++
3114 /// Returns: the kind of keyword or `null`
3115 const(char*) keywordClass(const Identifier ident)
3116 {
3117 if (!ident)
3118 return null;
3119
3120 const name = ident.toString();
3121 switch (name)
3122 {
3123 // C++ operators
3124 case "and":
3125 case "and_eq":
3126 case "bitand":
3127 case "bitor":
3128 case "compl":
3129 case "not":
3130 case "not_eq":
3131 case "or":
3132 case "or_eq":
3133 case "xor":
3134 case "xor_eq":
3135 return "special operator in C++";
3136
3137 // C++ keywords
3138 case "_Complex":
3139 case "const_cast":
3140 case "delete":
3141 case "dynamic_cast":
3142 case "explicit":
3143 case "friend":
3144 case "inline":
3145 case "mutable":
3146 case "namespace":
3147 case "operator":
3148 case "register":
3149 case "reinterpret_cast":
3150 case "signed":
3151 case "static_cast":
3152 case "typedef":
3153 case "typename":
3154 case "unsigned":
3155 case "using":
3156 case "virtual":
3157 case "volatile":
3158 return "keyword in C++";
3159
3160 // Common macros imported by this header
3161 // stddef.h
3162 case "offsetof":
3163 case "NULL":
3164 return "default macro in C++";
3165
3166 // C++11 keywords
3167 case "alignas":
3168 case "alignof":
3169 case "char16_t":
3170 case "char32_t":
3171 case "constexpr":
3172 case "decltype":
3173 case "noexcept":
3174 case "nullptr":
3175 case "static_assert":
3176 case "thread_local":
3177 case "wchar_t":
3178 if (global.params.cplusplus >= CppStdRevision.cpp11)
3179 return "keyword in C++11";
3180 return null;
3181
3182 // C++20 keywords
3183 case "char8_t":
3184 case "consteval":
3185 case "constinit":
3186 // Concepts-related keywords
3187 case "concept":
3188 case "requires":
3189 // Coroutines-related keywords
3190 case "co_await":
3191 case "co_yield":
3192 case "co_return":
3193 if (global.params.cplusplus >= CppStdRevision.cpp20)
3194 return "keyword in C++20";
3195 return null;
3196
3197 default:
3198 // Identifiers starting with __ are reserved
3199 if (name.length >= 2 && name[0..2] == "__")
3200 return "reserved identifier in C++";
3201
3202 return null;
3203 }
3204 }
3205
3206 /// Finds the outermost symbol if `sym` is nested.
3207 /// Returns `sym` if it appears at module scope
3208 ASTCodegen.Dsymbol outermostSymbol(ASTCodegen.Dsymbol sym)
3209 {
3210 assert(sym);
3211 while (true)
3212 {
3213 auto par = sym.toParent();
3214 if (!par || par.isModule())
3215 return sym;
3216 sym = par;
3217 }
3218 }
3219
3220 /// Fetches the symbol for user-defined types from the type `t`
3221 /// if `t` is either `TypeClass`, `TypeStruct` or `TypeEnum`
3222 ASTCodegen.Dsymbol symbolFromType(ASTCodegen.Type t)
3223 {
3224 if (auto tc = t.isTypeClass())
3225 return tc.sym;
3226 if (auto ts = t.isTypeStruct())
3227 return ts.sym;
3228 if (auto te = t.isTypeEnum())
3229 return te.sym;
3230 return null;
3231 }
3232
3233 /**
3234 * Searches `sym` for a member with the given name.
3235 *
3236 * This method usually delegates to `Dsymbol.search` but might also
3237 * manually check the members if the symbol did not receive semantic
3238 * analysis.
3239 *
3240 * Params:
3241 * sym = symbol to search
3242 * name = identifier of the requested symbol
3243 *
3244 * Returns: the symbol or `null` if not found
3245 */
3246 ASTCodegen.Dsymbol findMember(ASTCodegen.Dsymbol sym, Identifier name)
3247 {
3248 if (auto mem = sym.search(Loc.initial, name, ASTCodegen.IgnoreErrors))
3249 return mem;
3250
3251 // search doesn't work for declarations inside of uninstantiated
3252 // `TemplateDeclaration`s due to the missing symtab.
3253 if (sym.semanticRun >= ASTCodegen.PASS.semanticdone)
3254 return null;
3255
3256 // Manually check the members if present
3257 auto sds = sym.isScopeDsymbol();
3258 if (!sds || !sds.members)
3259 return null;
3260
3261 /// Recursively searches for `name` without entering nested aggregates, ...
3262 static ASTCodegen.Dsymbol search(ASTCodegen.Dsymbols* members, Identifier name)
3263 {
3264 foreach (mem; *members)
3265 {
3266 if (mem.ident == name)
3267 return mem;
3268
3269 // Look inside of private:, ...
3270 if (auto ad = mem.isAttribDeclaration())
3271 {
3272 if (auto s = search(ad.decl, name))
3273 return s;
3274 }
3275 }
3276 return null;
3277 }
3278
3279 return search(sds.members, name);
3280 }
3281
3282 debug (Debug_DtoH)
3283 {
3284 /// Generates code to trace the entry and exit of the enclosing `visit` function
3285 string traceVisit(alias node)()
3286 {
3287 const type = typeof(node).stringof;
3288 const method = __traits(hasMember, node, "toPrettyChars") ? "toPrettyChars" : "toChars";
3289 const arg = __traits(identifier, node) ~ '.' ~ method;
3290
3291 return `printf("[` ~ type ~ ` enter] %s\n", ` ~ arg ~ `());
3292 scope(exit) printf("[` ~ type ~ ` exit] %s\n", ` ~ arg ~ `());`;
3293 }
3294 }
3295