d: Merge dmd, druntime d8e3976a58, phobos 7a6e95688
[official-gcc.git] / gcc / d / dmd / dtoh.d
blob30991c9171a0a1093a27bba5e6b3cb75a95ef043
1 /**
2 * This module contains the implementation of the C++ header generation available through
3 * the command line switch -Hc.
5 * Copyright: Copyright (C) 1999-2024 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
12 module dmd.dtoh;
14 import core.stdc.stdio;
15 import core.stdc.string;
16 import core.stdc.ctype;
18 import dmd.astcodegen;
19 import dmd.astenums;
20 import dmd.arraytypes;
21 import dmd.attrib;
22 import dmd.dsymbol;
23 import dmd.dsymbolsem;
24 import dmd.errors;
25 import dmd.globals;
26 import dmd.hdrgen;
27 import dmd.id;
28 import dmd.identifier;
29 import dmd.location;
30 import dmd.root.filename;
31 import dmd.visitor;
32 import dmd.tokens;
34 import dmd.common.outbuffer;
35 import dmd.utils;
37 //debug = Debug_DtoH;
39 // Generate asserts to validate the header
40 //debug = Debug_DtoH_Checks;
42 /**
43 * Generates a C++ header containing bindings for all `extern(C[++])` declarations
44 * found in the supplied modules.
46 * Params:
47 * ms = the modules
49 * Notes:
50 * - the header is written to `<global.params.cxxhdrdir>/<global.params.cxxhdrfile>`
51 * or `stdout` if no explicit file was specified
52 * - bindings conform to the C++ standard defined in `global.params.cplusplus`
53 * - ignored declarations are mentioned in a comment if `global.params.doCxxHdrGeneration`
54 * is set to `CxxHeaderMode.verbose`
56 extern(C++) void genCppHdrFiles(ref Modules ms)
58 initialize();
60 OutBuffer fwd;
61 OutBuffer done;
62 OutBuffer decl;
64 // enable indent by spaces on buffers
65 fwd.doindent = true;
66 fwd.spaces = true;
67 decl.doindent = true;
68 decl.spaces = true;
70 scope v = new ToCppBuffer(&fwd, &done, &decl);
72 // Conditionally include another buffer for sanity checks
73 debug (Debug_DtoH_Checks)
75 OutBuffer check;
76 check.doindent = true;
77 check.spaces = true;
78 v.checkbuf = &check;
81 OutBuffer buf;
82 buf.doindent = true;
83 buf.spaces = true;
85 foreach (m; ms)
86 m.accept(v);
88 if (global.params.cxxhdr.fullOutput)
89 buf.printf("// Automatically generated by %s Compiler v%d", global.compileEnv.vendor.ptr, global.versionNumber());
90 else
91 buf.printf("// Automatically generated by %s Compiler", global.compileEnv.vendor.ptr);
93 buf.writenl();
94 buf.writenl();
95 buf.writestringln("#pragma once");
96 buf.writenl();
97 hashInclude(buf, "<assert.h>");
98 hashInclude(buf, "<math.h>");
99 hashInclude(buf, "<stddef.h>");
100 hashInclude(buf, "<stdint.h>");
101 // buf.writestring(buf, "#include <stdio.h>\n");
102 // buf.writestring("#include <string.h>\n");
104 // Emit array compatibility because extern(C++) types may have slices
105 // as members (as opposed to function parameters)
106 buf.writestring(`
107 #ifdef CUSTOM_D_ARRAY_TYPE
108 #define _d_dynamicArray CUSTOM_D_ARRAY_TYPE
109 #else
110 /// Represents a D [] array
111 template<typename T>
112 struct _d_dynamicArray final
114 size_t length;
115 T *ptr;
117 _d_dynamicArray() : length(0), ptr(NULL) { }
119 _d_dynamicArray(size_t length_in, T *ptr_in)
120 : length(length_in), ptr(ptr_in) { }
122 T& operator[](const size_t idx) {
123 assert(idx < length);
124 return ptr[idx];
127 const T& operator[](const size_t idx) const {
128 assert(idx < length);
129 return ptr[idx];
132 #endif
135 if (v.hasReal)
137 hashIf(buf, "!defined(_d_real)");
139 hashDefine(buf, "_d_real long double");
141 hashEndIf(buf);
143 buf.writenl();
144 // buf.writestringln("// fwd:");
145 buf.write(&fwd);
146 if (fwd.length > 0)
147 buf.writenl();
149 // buf.writestringln("// done:");
150 buf.write(&done);
152 // buf.writestringln("// decl:");
153 buf.write(&decl);
155 debug (Debug_DtoH_Checks)
157 // buf.writestringln("// check:");
158 buf.writestring(`
159 #if OFFSETS
160 template <class T>
161 size_t getSlotNumber(int dummy, ...)
163 T c;
164 va_list ap;
165 va_start(ap, dummy);
167 void *f = va_arg(ap, void*);
168 for (size_t i = 0; ; i++)
170 if ( (*(void***)&c)[i] == f)
171 return i;
173 va_end(ap);
176 void testOffsets()
179 buf.write(&check);
180 buf.writestring(`
182 #endif
186 // prevent trailing newlines
187 version (Windows)
188 while (buf.length >= 4 && buf[$-4..$] == "\r\n\r\n")
189 buf.remove(buf.length - 2, 2);
190 else
191 while (buf.length >= 2 && buf[$-2..$] == "\n\n")
192 buf.remove(buf.length - 1, 1);
195 if (global.params.cxxhdr.name is null)
197 // Write to stdout; assume it succeeds
198 size_t n = fwrite(buf[].ptr, 1, buf.length, stdout);
199 assert(n == buf.length); // keep gcc happy about return values
201 else
203 const(char)[] name = FileName.combine(global.params.cxxhdr.dir, global.params.cxxhdr.name);
204 if (!writeFile(Loc.initial, name, buf[]))
205 return fatal();
209 private:
211 /****************************************************
212 * Visitor that writes bindings for `extern(C[++]` declarations.
214 extern(C++) final class ToCppBuffer : Visitor
216 alias visit = Visitor.visit;
217 public:
218 enum EnumKind
220 Int,
221 Numeric,
222 String,
223 Enum,
224 Other
227 /// Namespace providing the actual AST nodes
228 alias AST = ASTCodegen;
230 /// Visited nodes
231 bool[void*] visited;
233 /// Forward declared nodes (which might not be emitted yet)
234 bool[void*] forwarded;
236 /// Buffer for forward declarations
237 OutBuffer* fwdbuf;
239 /// Buffer for integrity checks
240 debug (Debug_DtoH_Checks) OutBuffer* checkbuf;
242 /// Buffer for declarations that must emitted before the currently
243 /// visited node but can't be forward declared (see `includeSymbol`)
244 OutBuffer* donebuf;
246 /// Default buffer for the currently visited declaration
247 OutBuffer* buf;
249 /// The generated header uses `real` emitted as `_d_real`?
250 bool hasReal;
252 /// The generated header should contain comments for skipped declarations?
253 const bool printIgnored;
255 /// State specific to the current context which depends
256 /// on the currently visited node and it's parents
257 static struct Context
259 /// Default linkage in the current scope (e.g. LINK.c inside `extern(C) { ... }`)
260 LINK linkage = LINK.d;
262 /// Enclosing class / struct / union
263 AST.AggregateDeclaration adparent;
265 /// Enclosing template declaration
266 AST.TemplateDeclaration tdparent;
268 /// Identifier of the currently visited `VarDeclaration`
269 /// (required to write variables of funtion pointers)
270 Identifier ident;
272 /// Original type of the currently visited declaration
273 AST.Type origType;
275 /// Last written visibility level applying to the current scope
276 AST.Visibility.Kind currentVisibility;
278 /// Currently applicable storage classes
279 AST.STC storageClass;
281 /// How many symbols were ignored
282 int ignoredCounter;
284 /// Currently visited types are required by another declaration
285 /// and hence must be emitted
286 bool mustEmit;
288 /// Processing a type that can be forward referenced
289 bool forwarding;
291 /// Inside of an anonymous struct/union (AnonDeclaration)
292 bool inAnonymousDecl;
295 /// Informations about the current context in the AST
296 Context context;
298 // Generates getter-setter methods to replace the use of alias this
299 // This should be replaced by a `static foreach` once the gdc tester
300 // gets upgraded to version 10 (to support `static foreach`).
301 private extern(D) static string generateMembers() @safe
303 string result = "";
304 foreach(member; __traits(allMembers, Context))
306 result ~= "ref auto " ~ member ~ "() { return context." ~ member ~ "; }\n";
308 return result;
310 mixin(generateMembers());
312 this(OutBuffer* fwdbuf, OutBuffer* donebuf, OutBuffer* buf) scope
314 this.fwdbuf = fwdbuf;
315 this.donebuf = donebuf;
316 this.buf = buf;
317 this.printIgnored = global.params.cxxhdr.fullOutput;
321 * Emits `dsym` into `donebuf` s.t. it is declared before the currently
322 * visited symbol that written to `buf`.
324 * Temporarily clears `context` to behave as if it was visited normally.
326 private void includeSymbol(AST.Dsymbol dsym)
328 debug (Debug_DtoH)
330 printf("[includeSymbol(AST.Dsymbol) enter] %s\n", dsym.toChars());
331 scope(exit) printf("[includeSymbol(AST.Dsymbol) exit] %s\n", dsym.toChars());
334 auto ptr = cast(void*) dsym in visited;
335 if (ptr && *ptr)
336 return;
338 // Temporary replacement for `buf` which is appended to `donebuf`
339 OutBuffer decl;
340 decl.doindent = true;
341 decl.spaces = true;
342 scope (exit) donebuf.write(&decl);
344 auto ctxStash = this.context;
345 auto bufStash = this.buf;
347 this.context = Context.init;
348 this.buf = &decl;
349 this.mustEmit = true;
351 dsym.accept(this);
353 this.context = ctxStash;
354 this.buf = bufStash;
357 /// Determines what kind of enum `type` is (see `EnumKind`)
358 private EnumKind getEnumKind(AST.Type type)
360 if (type) switch (type.ty)
362 case AST.Tint32:
363 return EnumKind.Int;
364 case AST.Tbool,
365 AST.Tchar, AST.Twchar, AST.Tdchar,
366 AST.Tint8, AST.Tuns8,
367 AST.Tint16, AST.Tuns16,
368 AST.Tuns32,
369 AST.Tint64, AST.Tuns64:
370 return EnumKind.Numeric;
371 case AST.Tarray:
372 if (type.isString())
373 return EnumKind.String;
374 break;
375 case AST.Tenum:
376 return EnumKind.Enum;
377 default:
378 break;
380 return EnumKind.Other;
383 /// Determines the type used to represent `type` in C++.
384 /// Returns: `const [w,d]char*` for `[w,d]string` or `type`
385 private AST.Type determineEnumType(AST.Type type)
387 if (auto arr = type.isTypeDArray())
389 switch (arr.next.ty)
391 case AST.Tchar: return AST.Type.tchar.constOf.pointerTo;
392 case AST.Twchar: return AST.Type.twchar.constOf.pointerTo;
393 case AST.Tdchar: return AST.Type.tdchar.constOf.pointerTo;
394 default: break;
397 return type;
400 /// Writes a final `;` and insert an empty line outside of aggregates
401 private void writeDeclEnd() @safe
403 buf.writestringln(";");
405 if (!adparent)
406 buf.writenl();
409 /// Writes the corresponding access specifier if necessary
410 private void writeProtection(const AST.Visibility.Kind kind)
412 // Don't write visibility for global declarations
413 if (!adparent || inAnonymousDecl)
414 return;
416 string token;
418 switch(kind) with(AST.Visibility.Kind)
420 case none, private_:
421 if (this.currentVisibility == AST.Visibility.Kind.private_)
422 return;
423 this.currentVisibility = AST.Visibility.Kind.private_;
424 token = "private:";
425 break;
427 case package_, protected_:
428 if (this.currentVisibility == AST.Visibility.Kind.protected_)
429 return;
430 this.currentVisibility = AST.Visibility.Kind.protected_;
431 token = "protected:";
432 break;
434 case undefined, public_, export_:
435 if (this.currentVisibility == AST.Visibility.Kind.public_)
436 return;
437 this.currentVisibility = AST.Visibility.Kind.public_;
438 token = "public:";
439 break;
441 default:
442 printf("Unexpected visibility: %d!\n", kind);
443 assert(0);
446 buf.level--;
447 buf.writestringln(token);
448 buf.level++;
452 * Writes an identifier into `buf` and checks for reserved identifiers. The
453 * parameter `canFix` determines how this function handles C++ keywords:
455 * `false` => Raise a warning and print the identifier as-is
456 * `true` => Append an underscore to the identifier
458 * Params:
459 * s = the symbol denoting the identifier
460 * canFixup = whether the identifier may be changed without affecting
461 * binary compatibility
463 private void writeIdentifier(const AST.Dsymbol s, const bool canFix = false)
465 if (const mn = getMangleOverride(s))
466 return buf.writestring(mn);
468 writeIdentifier(s.ident, s.loc, s.kind(), canFix);
471 /** Overload of `writeIdentifier` used for all AST nodes not descending from Dsymbol **/
472 private void writeIdentifier(const Identifier ident, const Loc loc, const char* kind, const bool canFix = false)
474 bool needsFix;
476 void warnCxxCompat(const(char)* reason)
478 if (canFix)
480 needsFix = true;
481 return;
484 __gshared bool warned = false;
485 warning(loc, "%s `%s` is a %s", kind, ident.toChars(), reason);
487 if (!warned)
489 warningSupplemental(loc, "The generated C++ header will contain " ~
490 "identifiers that are keywords in C++");
491 warned = true;
495 if (global.params.warnings != DiagnosticReporting.off || canFix)
497 // Warn about identifiers that are keywords in C++.
498 if (auto kc = keywordClass(ident))
499 warnCxxCompat(kc);
501 buf.writestring(ident.toString());
502 if (needsFix)
503 buf.writeByte('_');
506 /// Checks whether `t` is a type that can be exported to C++
507 private bool isSupportedType(AST.Type t)
509 if (!t)
511 assert(tdparent);
512 return true;
515 switch (t.ty)
517 // Nested types
518 case AST.Tarray:
519 case AST.Tsarray:
520 case AST.Tpointer:
521 case AST.Treference:
522 case AST.Tdelegate:
523 return isSupportedType((cast(AST.TypeNext) t).next);
525 // Function pointers
526 case AST.Tfunction:
528 auto tf = cast(AST.TypeFunction) t;
529 if (!isSupportedType(tf.next))
530 return false;
531 foreach (_, param; tf.parameterList)
533 if (!isSupportedType(param.type))
534 return false;
536 return true;
539 // Noreturn has a different mangling
540 case AST.Tnoreturn:
542 // _Imaginary is C only.
543 case AST.Timaginary32:
544 case AST.Timaginary64:
545 case AST.Timaginary80:
546 return false;
547 default:
548 return true;
552 override void visit(AST.Dsymbol s)
554 debug (Debug_DtoH)
556 mixin(traceVisit!s);
557 import dmd.asttypename;
558 printf("[AST.Dsymbol enter] %s\n", s.astTypeName().ptr);
562 override void visit(AST.Import i)
564 debug (Debug_DtoH) mixin(traceVisit!i);
566 /// Writes `using <alias_> = <sym.ident>` into `buf`
567 const(char*) writeImport(AST.Dsymbol sym, const Identifier alias_)
569 /// `using` was introduced in C++ 11 and only works for types...
570 if (global.params.cplusplus < CppStdRevision.cpp11)
571 return "requires C++11";
573 if (auto ad = sym.isAliasDeclaration())
575 sym = ad.toAlias();
576 ad = sym.isAliasDeclaration();
578 // Might be an alias to a basic type
579 if (ad && !ad.aliassym && ad.type)
580 goto Emit;
583 // Restricted to types and other aliases
584 if (!sym.isScopeDsymbol() && !sym.isAggregateDeclaration())
585 return "only supports types";
587 // Write `using <alias_> = `<sym>`
588 Emit:
589 buf.writestring("using ");
590 writeIdentifier(alias_, i.loc, "renamed import");
591 buf.writestring(" = ");
592 // Start at module scope to avoid collisions with local symbols
593 if (this.context.adparent)
594 buf.writestring("::");
595 buf.writestring(sym.ident.toString());
596 writeDeclEnd();
597 return null;
600 // Only missing without semantic analysis
601 // FIXME: Templates need work due to missing parent & imported module
602 if (!i.parent)
604 assert(tdparent);
605 ignored("`%s` because it's inside of a template declaration", i.toChars());
606 return;
609 // Non-public imports don't create new symbols, include as needed
610 if (i.visibility.kind < AST.Visibility.Kind.public_)
611 return;
613 // Symbols from static imports should be emitted inline
614 if (i.isstatic)
615 return;
617 const isLocal = !i.parent.isModule();
619 // Need module for symbol lookup
620 assert(i.mod);
622 // Emit an alias for each public module member
623 if (isLocal && i.names.length == 0)
625 assert(i.mod.symtab);
627 // Sort alphabetically s.t. slight changes in semantic don't cause
628 // massive changes in the order of declarations
629 AST.Dsymbols entries;
630 entries.reserve(i.mod.symtab.length);
632 foreach (entry; i.mod.symtab.tab.asRange)
634 // Skip anonymous / invisible members
635 import dmd.access : symbolIsVisible;
636 if (!entry.key.isAnonymous() && symbolIsVisible(i, entry.value))
637 entries.push(entry.value);
640 // Seperate function because of a spurious dual-context deprecation
641 static int compare(const AST.Dsymbol* a, const AST.Dsymbol* b)
643 return strcmp(a.ident.toChars(), b.ident.toChars());
645 entries.sort!compare();
647 foreach (sym; entries)
649 includeSymbol(sym);
650 if (auto err = writeImport(sym, sym.ident))
651 ignored("public import for `%s` because `using` %s", sym.ident.toChars(), err);
653 return;
656 // Include all public imports and emit using declarations for each alias
657 foreach (const idx, name; i.names)
659 // Search the imported symbol
660 auto sym = i.mod.search(Loc.initial, name);
661 assert(sym); // Missing imports should error during semantic
663 includeSymbol(sym);
665 // Detect the assigned name for renamed import
666 auto alias_ = i.aliases[idx];
667 if (!alias_)
668 continue;
670 if (auto err = writeImport(sym, alias_))
671 ignored("renamed import `%s = %s` because `using` %s", alias_.toChars(), name.toChars(), err);
675 override void visit(AST.AttribDeclaration pd)
677 debug (Debug_DtoH) mixin(traceVisit!pd);
679 Dsymbols* decl = pd.include(null);
680 if (!decl)
681 return;
683 foreach (s; *decl)
685 if (adparent || s.visible().kind >= AST.Visibility.Kind.public_)
686 s.accept(this);
690 override void visit(AST.StorageClassDeclaration scd)
692 debug (Debug_DtoH) mixin(traceVisit!scd);
694 const stcStash = this.storageClass;
695 this.storageClass |= scd.stc;
696 visit(cast(AST.AttribDeclaration) scd);
697 this.storageClass = stcStash;
700 override void visit(AST.LinkDeclaration ld)
702 debug (Debug_DtoH) mixin(traceVisit!ld);
704 auto save = linkage;
705 linkage = ld.linkage;
706 visit(cast(AST.AttribDeclaration)ld);
707 linkage = save;
710 override void visit(AST.CPPMangleDeclaration md)
712 debug (Debug_DtoH) mixin(traceVisit!md);
714 const oldLinkage = this.linkage;
715 this.linkage = LINK.cpp;
716 visit(cast(AST.AttribDeclaration) md);
717 this.linkage = oldLinkage;
720 override void visit(AST.Module m)
722 debug (Debug_DtoH) mixin(traceVisit!m);
724 foreach (s; *m.members)
726 if (s.visible().kind < AST.Visibility.Kind.public_)
727 continue;
728 s.accept(this);
732 override void visit(AST.FuncDeclaration fd)
734 debug (Debug_DtoH) mixin(traceVisit!fd);
736 if (cast(void*)fd in visited)
737 return;
738 // printf("FuncDeclaration %s %s\n", fd.toPrettyChars(), fd.type.toChars());
739 visited[cast(void*)fd] = true;
741 // silently ignore non-user-defined destructors
742 if (fd.isGenerated && fd.isDtorDeclaration())
743 return;
745 // Note that tf might be null for templated (member) functions
746 auto tf = cast(AST.TypeFunction)fd.type;
747 if ((tf && (tf.linkage != LINK.c || adparent) && tf.linkage != LINK.cpp) || (!tf && fd.isPostBlitDeclaration()))
749 ignored("function %s because of linkage", fd.toPrettyChars());
750 return checkFunctionNeedsPlaceholder(fd);
752 if (fd.mangleOverride && tf && tf.linkage != LINK.c)
754 ignored("function %s because C++ doesn't support explicit mangling", fd.toPrettyChars());
755 return checkFunctionNeedsPlaceholder(fd);
757 if (!adparent && !fd.fbody)
759 ignored("function %s because it is extern", fd.toPrettyChars());
760 return;
762 if (fd.visibility.kind == AST.Visibility.Kind.none || fd.visibility.kind == AST.Visibility.Kind.private_)
764 ignored("function %s because it is private", fd.toPrettyChars());
765 return;
767 if (tf && !isSupportedType(tf.next))
769 ignored("function %s because its return type cannot be mapped to C++", fd.toPrettyChars());
770 return checkFunctionNeedsPlaceholder(fd);
772 if (tf) foreach (i, fparam; tf.parameterList)
774 if (!isSupportedType(fparam.type))
776 ignored("function %s because one of its parameters has type `%s` which cannot be mapped to C++",
777 fd.toPrettyChars(), fparam.type.toChars());
778 return checkFunctionNeedsPlaceholder(fd);
782 writeProtection(fd.visibility.kind);
784 if (tf && tf.linkage == LINK.c)
785 buf.writestring("extern \"C\" ");
786 else if (!adparent)
787 buf.writestring("extern ");
788 if (adparent && fd.isStatic())
789 buf.writestring("static ");
790 else if (adparent && (
791 // Virtual functions in non-templated classes
792 (fd.vtblIndex != -1 && !fd.isOverride()) ||
794 // Virtual functions in templated classes (fd.vtblIndex still -1)
795 (tdparent && adparent.isClassDeclaration() && !(this.storageClass & AST.STC.final_ || fd.isFinal))))
796 buf.writestring("virtual ");
798 debug (Debug_DtoH_Checks)
799 if (adparent && !tdparent)
801 auto s = adparent.search(Loc.initial, fd.ident);
802 auto cd = adparent.isClassDeclaration();
804 if (!(adparent.storage_class & AST.STC.abstract_) &&
805 !(cd && cd.isAbstract()) &&
806 s is fd && !fd.overnext)
808 const cn = adparent.ident.toChars();
809 const fn = fd.ident.toChars();
810 const vi = fd.vtblIndex;
812 checkbuf.printf("assert(getSlotNumber <%s>(0, &%s::%s) == %d);",
813 cn, cn, fn, vi);
814 checkbuf.writenl();
818 if (adparent && fd.isDisabled && global.params.cplusplus < CppStdRevision.cpp11)
819 writeProtection(AST.Visibility.Kind.private_);
820 funcToBuffer(tf, fd);
821 if (adparent)
823 if (tf && (tf.isConst() || tf.isImmutable()))
824 buf.writestring(" const");
825 if (global.params.cplusplus >= CppStdRevision.cpp11)
827 if (fd.vtblIndex != -1 && !(adparent.storage_class & AST.STC.final_) && fd.isFinalFunc())
828 buf.writestring(" final");
829 if (fd.isOverride())
830 buf.writestring(" override");
832 if (fd.isAbstract())
833 buf.writestring(" = 0");
834 else if (global.params.cplusplus >= CppStdRevision.cpp11 && fd.isDisabled())
835 buf.writestring(" = delete");
837 buf.writestringln(";");
838 if (adparent && fd.isDisabled && global.params.cplusplus < CppStdRevision.cpp11)
839 writeProtection(AST.Visibility.Kind.public_);
841 if (!adparent)
842 buf.writenl();
847 + Checks whether `fd` is a function that requires a dummy declaration
848 + instead of simply emitting the declaration (because it would cause
849 + ABI / behaviour issues). This includes:
851 + - virtual functions to ensure proper vtable layout
852 + - destructors that would break RAII
854 private void checkFunctionNeedsPlaceholder(AST.FuncDeclaration fd)
856 // Omit redundant declarations - the slot was already
857 // reserved in the base class
858 if (fd.isVirtual() && fd.isIntroducing())
860 // Hide placeholders because they are not ABI compatible
861 writeProtection(AST.Visibility.Kind.private_);
863 __gshared int counter; // Ensure unique names in all cases
864 buf.printf("virtual void __vtable_slot_%u();", counter++);
865 buf.writenl();
867 else if (fd.isDtorDeclaration())
869 // Create inaccessible dtor to prevent code from keeping instances that
870 // need to be destroyed on the C++ side (but cannot call the dtor)
871 writeProtection(AST.Visibility.Kind.private_);
872 buf.writeByte('~');
873 buf.writestring(adparent.ident.toString());
874 buf.writestringln("();");
878 override void visit(AST.UnitTestDeclaration utd)
880 debug (Debug_DtoH) mixin(traceVisit!utd);
883 override void visit(AST.VarDeclaration vd)
885 debug (Debug_DtoH) mixin(traceVisit!vd);
887 if (!shouldEmitAndMarkVisited(vd))
888 return;
890 // Tuple field are expanded into multiple VarDeclarations
891 // (we'll visit them later)
892 if (vd.type && vd.type.isTypeTuple())
894 assert(vd.aliasTuple);
895 vd.toAlias().accept(this);
896 return;
899 if (vd.originalType && vd.type == AST.Type.tsize_t)
900 origType = vd.originalType;
901 scope(exit) origType = null;
903 if (!vd.alignment.isDefault() && !vd.alignment.isUnknown())
905 buf.printf("// Ignoring var %s alignment %d", vd.toChars(), vd.alignment.get());
906 buf.writenl();
909 // Determine the variable type which might be missing inside of
910 // template declarations. Infer the type from the initializer then
911 AST.Type type = vd.type;
912 if (!type)
914 assert(tdparent);
916 // Just a precaution, implicit type without initializer should be rejected
917 if (!vd._init)
918 return;
920 if (auto ei = vd._init.isExpInitializer())
921 type = ei.exp.type;
923 // Can happen if the expression needs further semantic
924 if (!type)
926 ignored("%s because the type could not be determined", vd.toPrettyChars());
927 return;
930 // Apply const/immutable to the inferred type
931 if (vd.storage_class & (AST.STC.const_ | AST.STC.immutable_))
932 type = type.constOf();
935 if (vd.storage_class & AST.STC.manifest)
937 EnumKind kind = getEnumKind(type);
939 if (vd.visibility.kind == AST.Visibility.Kind.none || vd.visibility.kind == AST.Visibility.Kind.private_) {
940 ignored("enum `%s` because it is `%s`.", vd.toPrettyChars(), AST.visibilityToChars(vd.visibility.kind));
941 return;
944 writeProtection(vd.visibility.kind);
946 final switch (kind)
948 case EnumKind.Int, EnumKind.Numeric:
949 // 'enum : type' is only available from C++-11 onwards.
950 if (global.params.cplusplus < CppStdRevision.cpp11)
951 goto case;
952 buf.writestring("enum : ");
953 determineEnumType(type).accept(this);
954 buf.writestring(" { ");
955 writeIdentifier(vd, true);
956 buf.writestring(" = ");
957 auto ie = AST.initializerToExpression(vd._init).isIntegerExp();
958 visitInteger(ie.toInteger(), type);
959 buf.writestring(" };");
960 break;
962 case EnumKind.String, EnumKind.Enum:
963 buf.writestring("static ");
964 auto target = determineEnumType(type);
965 target.accept(this);
966 buf.writestring(" const ");
967 writeIdentifier(vd, true);
968 buf.writestring(" = ");
969 auto e = AST.initializerToExpression(vd._init);
970 printExpressionFor(target, e);
971 buf.writestring(";");
972 break;
974 case EnumKind.Other:
975 ignored("enum `%s` because type `%s` is currently not supported for enum constants.", vd.toPrettyChars(), type.toChars());
976 return;
978 buf.writenl();
979 buf.writenl();
980 return;
983 if (vd.storage_class & (AST.STC.static_ | AST.STC.extern_ | AST.STC.gshared) ||
984 vd.parent && vd.parent.isModule())
986 const vdLinkage = vd.resolvedLinkage();
987 if (vdLinkage != LINK.c && vdLinkage != LINK.cpp && !(tdparent && (this.linkage == LINK.c || this.linkage == LINK.cpp)))
989 ignored("variable %s because of linkage", vd.toPrettyChars());
990 return;
992 if (vd.mangleOverride && vdLinkage != LINK.c)
994 ignored("variable %s because C++ doesn't support explicit mangling", vd.toPrettyChars());
995 return;
997 if (!isSupportedType(type))
999 ignored("variable %s because its type cannot be mapped to C++", vd.toPrettyChars());
1000 return;
1002 if (auto kc = keywordClass(vd.ident))
1004 ignored("variable %s because its name is a %s", vd.toPrettyChars(), kc);
1005 return;
1007 writeProtection(vd.visibility.kind);
1008 if (vdLinkage == LINK.c)
1009 buf.writestring("extern \"C\" ");
1010 else if (!adparent)
1011 buf.writestring("extern ");
1012 if (adparent)
1013 buf.writestring("static ");
1014 typeToBuffer(type, vd);
1015 writeDeclEnd();
1016 return;
1019 if (adparent)
1021 writeProtection(vd.visibility.kind);
1022 typeToBuffer(type, vd, true);
1023 buf.writestringln(";");
1025 debug (Debug_DtoH_Checks)
1027 checkbuf.level++;
1028 const pn = adparent.ident.toChars();
1029 const vn = vd.ident.toChars();
1030 const vo = vd.offset;
1031 checkbuf.printf("assert(offsetof(%s, %s) == %d);",
1032 pn, vn, vo);
1033 checkbuf.writenl();
1034 checkbuf.level--;
1036 return;
1039 visit(cast(AST.Dsymbol)vd);
1042 override void visit(AST.TypeInfoDeclaration tid)
1044 debug (Debug_DtoH) mixin(traceVisit!tid);
1047 override void visit(AST.AliasDeclaration ad)
1049 debug (Debug_DtoH) mixin(traceVisit!ad);
1051 // Declared in object.d but already included in `#include`s
1052 if (ad.ident == Id._size_t || ad.ident == Id._ptrdiff_t)
1053 return;
1055 if (!shouldEmitAndMarkVisited(ad))
1056 return;
1058 writeProtection(ad.visibility.kind);
1060 if (auto t = ad.type)
1062 if (t.ty == AST.Tdelegate || t.ty == AST.Tident)
1064 visit(cast(AST.Dsymbol)ad);
1065 return;
1068 // for function pointers we need to original type
1069 if (ad.originalType && ad.type.ty == AST.Tpointer &&
1070 (cast(AST.TypePointer)t).nextOf.ty == AST.Tfunction)
1072 origType = ad.originalType;
1074 scope(exit) origType = null;
1076 buf.writestring("typedef ");
1077 typeToBuffer(origType !is null ? origType : t, ad);
1078 writeDeclEnd();
1079 return;
1081 if (!ad.aliassym)
1083 assert(0);
1085 if (auto ti = ad.aliassym.isTemplateInstance())
1087 visitTi(ti);
1088 return;
1090 if (auto sd = ad.aliassym.isStructDeclaration())
1092 buf.writestring("typedef ");
1093 sd.type.accept(this);
1094 buf.writestring(" ");
1095 writeIdentifier(ad);
1096 writeDeclEnd();
1097 return;
1099 else if (auto td = ad.aliassym.isTemplateDeclaration())
1101 if (global.params.cplusplus < CppStdRevision.cpp11)
1103 ignored("%s because `using` declarations require C++ 11", ad.toPrettyChars());
1104 return;
1107 printTemplateParams(td);
1108 buf.writestring("using ");
1109 writeIdentifier(ad);
1110 buf.writestring(" = ");
1111 writeFullName(td);
1112 buf.writeByte('<');
1114 foreach (const idx, const p; *td.parameters)
1116 if (idx)
1117 buf.writestring(", ");
1118 writeIdentifier(p.ident, p.loc, "parameter", true);
1120 buf.writestringln(">;");
1121 return;
1124 auto fd = ad.aliassym.isFuncDeclaration();
1126 if (fd && (fd.isGenerated() || fd.isDtorDeclaration()))
1128 // Ignore. It's taken care of while visiting FuncDeclaration
1129 return;
1132 // Recognize member function aliases, e.g. alias visit = Parent.visit;
1133 if (adparent && fd)
1135 auto pd = fd.isMember();
1136 if (!pd)
1138 ignored("%s because free functions cannot be aliased in C++", ad.toPrettyChars());
1140 else if (global.params.cplusplus < CppStdRevision.cpp11)
1142 ignored("%s because `using` declarations require C++ 11", ad.toPrettyChars());
1144 else if (ad.ident != fd.ident)
1146 ignored("%s because `using` cannot rename functions in aggregates", ad.toPrettyChars());
1148 else if (fd.toAliasFunc().parent.isTemplateMixin())
1150 // Member's of template mixins are directly emitted into the aggregate
1152 else
1154 buf.writestring("using ");
1156 // Print prefix of the base class if this function originates from a superclass
1157 // because alias might be resolved through multiple classes, e.g.
1158 // e.g. for alias visit = typeof(super).visit in the visitors
1159 if (!fd.isIntroducing())
1160 printPrefix(ad.toParent().isClassDeclaration().baseClass);
1161 else
1162 printPrefix(pd);
1164 buf.writestring(fd.ident.toChars());
1165 buf.writestringln(";");
1167 return;
1170 ignored("%s %s", ad.aliassym.kind(), ad.aliassym.toPrettyChars());
1173 override void visit(AST.Nspace ns)
1175 debug (Debug_DtoH) mixin(traceVisit!ns);
1176 handleNspace(ns, ns.members);
1179 override void visit(AST.CPPNamespaceDeclaration ns)
1181 debug (Debug_DtoH) mixin(traceVisit!ns);
1182 handleNspace(ns, ns.decl);
1185 /// Writes the namespace declaration and visits all members
1186 private void handleNspace(AST.Dsymbol namespace, Dsymbols* members)
1188 buf.writestring("namespace ");
1189 writeIdentifier(namespace);
1190 buf.writenl();
1191 buf.writestring("{");
1192 buf.writenl();
1193 buf.level++;
1194 foreach(decl;(*members))
1196 decl.accept(this);
1198 buf.level--;
1199 buf.writestring("}");
1200 buf.writenl();
1203 override void visit(AST.AnonDeclaration ad)
1205 debug (Debug_DtoH) mixin(traceVisit!ad);
1207 const anonStash = inAnonymousDecl;
1208 inAnonymousDecl = true;
1209 scope (exit) inAnonymousDecl = anonStash;
1211 buf.writestringln(ad.isunion ? "union" : "struct");
1212 buf.writestringln("{");
1213 buf.level++;
1214 foreach (s; *ad.decl)
1216 s.accept(this);
1218 buf.level--;
1219 buf.writestringln("};");
1222 private bool memberField(AST.VarDeclaration vd) @safe
1224 if (!vd.type || !vd.type.deco || !vd.ident)
1225 return false;
1226 if (!vd.isField())
1227 return false;
1228 if (vd.type.ty == AST.Tfunction)
1229 return false;
1230 if (vd.type.ty == AST.Tsarray)
1231 return false;
1232 return true;
1235 override void visit(AST.StructDeclaration sd)
1237 debug (Debug_DtoH) mixin(traceVisit!sd);
1239 if (!shouldEmitAndMarkVisited(sd))
1240 return;
1242 const ignoredStash = this.ignoredCounter;
1243 scope (exit) this.ignoredCounter = ignoredStash;
1245 pushAlignToBuffer(sd.alignment);
1247 writeProtection(sd.visibility.kind);
1249 const structAsClass = sd.cppmangle == CPPMANGLE.asClass;
1250 if (sd.isUnionDeclaration())
1251 buf.writestring("union ");
1252 else
1253 buf.writestring(structAsClass ? "class " : "struct ");
1255 writeIdentifier(sd);
1256 if (!sd.members)
1258 buf.writestringln(";");
1259 buf.writenl();
1260 return;
1263 // D structs are always final
1264 if (!sd.isUnionDeclaration())
1265 buf.writestring(" final");
1267 buf.writenl();
1268 buf.writestring("{");
1270 const protStash = this.currentVisibility;
1271 this.currentVisibility = structAsClass ? AST.Visibility.Kind.private_ : AST.Visibility.Kind.public_;
1272 scope (exit) this.currentVisibility = protStash;
1274 buf.level++;
1275 buf.writenl();
1276 auto save = adparent;
1277 adparent = sd;
1279 foreach (m; *sd.members)
1281 m.accept(this);
1283 // Generate default ctor
1284 if (!sd.noDefaultCtor && !sd.isUnionDeclaration())
1286 writeProtection(AST.Visibility.Kind.public_);
1287 buf.printf("%s()", sd.ident.toChars());
1288 size_t varCount;
1289 bool first = true;
1290 buf.level++;
1291 foreach (vd; sd.fields)
1293 if (!memberField(vd) || vd.overlapped)
1294 continue;
1295 varCount++;
1297 if (!vd._init && !vd.type.isTypeBasic() && !vd.type.isTypePointer && !vd.type.isTypeStruct &&
1298 !vd.type.isTypeClass && !vd.type.isTypeDArray && !vd.type.isTypeSArray)
1300 continue;
1302 if (vd._init && vd._init.isVoidInitializer())
1303 continue;
1305 if (first)
1307 buf.writestringln(" :");
1308 first = false;
1310 else
1312 buf.writestringln(",");
1314 writeIdentifier(vd, true);
1315 buf.writeByte('(');
1317 if (vd._init)
1319 auto e = AST.initializerToExpression(vd._init);
1320 printExpressionFor(vd.type, e, true);
1322 buf.printf(")");
1324 buf.level--;
1325 buf.writenl();
1326 buf.writestringln("{");
1327 buf.writestringln("}");
1328 auto ctor = sd.ctor ? sd.ctor.isFuncDeclaration() : null;
1329 if (varCount && (!ctor || ctor.storage_class & AST.STC.disable))
1331 buf.printf("%s(", sd.ident.toChars());
1332 first = true;
1333 foreach (vd; sd.fields)
1335 if (!memberField(vd) || vd.overlapped)
1336 continue;
1337 if (!first)
1338 buf.writestring(", ");
1339 assert(vd.type);
1340 assert(vd.ident);
1341 typeToBuffer(vd.type, vd, true);
1342 // Don't print default value for first parameter to not clash
1343 // with the default ctor defined above
1344 if (!first)
1346 buf.writestring(" = ");
1347 printExpressionFor(vd.type, findDefaultInitializer(vd));
1349 first = false;
1351 buf.writestring(") :");
1352 buf.level++;
1353 buf.writenl();
1355 first = true;
1356 foreach (vd; sd.fields)
1358 if (!memberField(vd) || vd.overlapped)
1359 continue;
1361 if (first)
1362 first = false;
1363 else
1364 buf.writestringln(",");
1366 writeIdentifier(vd, true);
1367 buf.writeByte('(');
1368 writeIdentifier(vd, true);
1369 buf.writeByte(')');
1371 buf.writenl();
1372 buf.writestringln("{}");
1373 buf.level--;
1377 buf.level--;
1378 adparent = save;
1379 buf.writestringln("};");
1381 popAlignToBuffer(sd.alignment);
1382 buf.writenl();
1384 // Workaround because size triggers a forward-reference error
1385 // for struct templates (the size is undetermined even if the
1386 // size doesn't depend on the parameters)
1387 debug (Debug_DtoH_Checks)
1388 if (!tdparent)
1390 checkbuf.level++;
1391 const sn = sd.ident.toChars();
1392 const sz = sd.size(Loc.initial);
1393 checkbuf.printf("assert(sizeof(%s) == %llu);", sn, sz);
1394 checkbuf.writenl();
1395 checkbuf.level--;
1399 /// Starts a custom alignment section using `#pragma pack` if
1400 /// `alignment` specifies a custom alignment
1401 private void pushAlignToBuffer(structalign_t alignment)
1403 // DMD ensures alignment is a power of two
1404 //assert(alignment > 0 && ((alignment & (alignment - 1)) == 0),
1405 // "Invalid alignment size");
1407 // When no alignment is specified, `uint.max` is the default
1408 // FIXME: alignment is 0 for structs templated members
1409 if (alignment.isDefault() || (tdparent && alignment.isUnknown()))
1411 return;
1414 buf.printf("#pragma pack(push, %d)", alignment.get());
1415 buf.writenl();
1418 /// Ends a custom alignment section using `#pragma pack` if
1419 /// `alignment` specifies a custom alignment
1420 private void popAlignToBuffer(structalign_t alignment) @safe
1422 if (alignment.isDefault() || (tdparent && alignment.isUnknown()))
1423 return;
1425 buf.writestringln("#pragma pack(pop)");
1428 override void visit(AST.ClassDeclaration cd)
1430 debug (Debug_DtoH) mixin(traceVisit!cd);
1432 if (cd.baseClass && shouldEmit(cd))
1433 includeSymbol(cd.baseClass);
1435 if (!shouldEmitAndMarkVisited(cd))
1436 return;
1438 writeProtection(cd.visibility.kind);
1440 const classAsStruct = cd.cppmangle == CPPMANGLE.asStruct;
1441 buf.writestring(classAsStruct ? "struct " : "class ");
1442 writeIdentifier(cd);
1444 if (cd.storage_class & AST.STC.final_ || (tdparent && this.storageClass & AST.STC.final_))
1445 buf.writestring(" final");
1447 assert(cd.baseclasses);
1449 foreach (i, base; *cd.baseclasses)
1451 buf.writestring(i == 0 ? " : public " : ", public ");
1453 // Base classes/interfaces might depend on template parameters,
1454 // e.g. class A(T) : B!T { ... }
1455 if (base.sym is null)
1457 base.type.accept(this);
1459 else
1461 writeFullName(base.sym);
1465 if (!cd.members)
1467 buf.writestring(";");
1468 buf.writenl();
1469 buf.writenl();
1470 return;
1473 buf.writenl();
1474 buf.writestringln("{");
1476 const protStash = this.currentVisibility;
1477 this.currentVisibility = classAsStruct ? AST.Visibility.Kind.public_ : AST.Visibility.Kind.private_;
1478 scope (exit) this.currentVisibility = protStash;
1480 auto save = adparent;
1481 adparent = cd;
1482 buf.level++;
1483 foreach (m; *cd.members)
1485 m.accept(this);
1487 buf.level--;
1488 adparent = save;
1490 buf.writestringln("};");
1491 buf.writenl();
1494 override void visit(AST.EnumDeclaration ed)
1496 debug (Debug_DtoH) mixin(traceVisit!ed);
1498 if (!shouldEmitAndMarkVisited(ed))
1499 return;
1501 if (ed.isSpecial())
1503 //ignored("%s because it is a special C++ type", ed.toPrettyChars());
1504 return;
1507 // we need to know a bunch of stuff about the enum...
1508 bool isAnonymous = ed.ident is null;
1509 const isOpaque = !ed.members;
1510 AST.Type type = ed.memtype;
1511 if (!type && !isOpaque)
1513 // check all keys have matching type
1514 foreach (_m; *ed.members)
1516 auto m = _m.isEnumMember();
1517 if (!type)
1518 type = m.type;
1519 else if (m.type !is type)
1521 type = null;
1522 break;
1526 EnumKind kind = getEnumKind(type);
1528 if (isOpaque)
1530 // Opaque enums were introduced in C++ 11 (workaround?)
1531 if (global.params.cplusplus < CppStdRevision.cpp11)
1533 ignored("%s because opaque enums require C++ 11", ed.toPrettyChars());
1534 return;
1536 // Opaque enum defaults to int but the type might not be set
1537 else if (!type)
1539 kind = EnumKind.Int;
1541 // Cannot apply namespace workaround for non-integral types
1542 else if (kind != EnumKind.Int && kind != EnumKind.Numeric)
1544 ignored("enum %s because of its base type", ed.toPrettyChars());
1545 return;
1549 // determine if this is an enum, or just a group of manifest constants
1550 bool manifestConstants = !isOpaque && (!type || (isAnonymous && kind == EnumKind.Other));
1551 assert(!manifestConstants || isAnonymous);
1553 writeProtection(ed.visibility.kind);
1555 // write the enum header
1556 if (!manifestConstants)
1558 if (kind == EnumKind.Int || kind == EnumKind.Numeric)
1560 buf.writestring("enum");
1561 // D enums are strong enums, but there exists only a direct mapping
1562 // with 'enum class' from C++-11 onwards.
1563 if (global.params.cplusplus >= CppStdRevision.cpp11)
1565 if (!isAnonymous)
1567 buf.writestring(" class ");
1568 writeIdentifier(ed);
1570 if (kind == EnumKind.Numeric)
1572 buf.writestring(" : ");
1573 determineEnumType(type).accept(this);
1576 else if (!isAnonymous)
1578 buf.writeByte(' ');
1579 writeIdentifier(ed);
1582 else
1584 buf.writestring("namespace");
1585 if(!isAnonymous)
1587 buf.writeByte(' ');
1588 writeIdentifier(ed);
1591 // Opaque enums have no members, hence skip the body
1592 if (isOpaque)
1594 buf.writestringln(";");
1595 return;
1597 else
1599 buf.writenl();
1600 buf.writestringln("{");
1604 // emit constant for each member
1605 if (!manifestConstants)
1606 buf.level++;
1608 foreach (_m; *ed.members)
1610 auto m = _m.isEnumMember();
1611 AST.Type memberType = type ? type : m.type;
1612 const EnumKind memberKind = type ? kind : getEnumKind(memberType);
1614 if (!manifestConstants && (kind == EnumKind.Int || kind == EnumKind.Numeric))
1616 // C++-98 compatible enums must use the typename as a prefix to avoid
1617 // collisions with other identifiers in scope. For consistency with D,
1618 // the enum member `Type.member` is emitted as `Type_member` in C++-98.
1619 if (!isAnonymous && global.params.cplusplus < CppStdRevision.cpp11)
1621 writeIdentifier(ed);
1622 buf.writeByte('_');
1624 writeIdentifier(m, true);
1625 buf.writestring(" = ");
1627 auto ie = cast(AST.IntegerExp)m.value;
1628 visitInteger(ie.toInteger(), memberType);
1629 buf.writestring(",");
1631 else if (global.params.cplusplus >= CppStdRevision.cpp11 &&
1632 manifestConstants && (memberKind == EnumKind.Int || memberKind == EnumKind.Numeric))
1634 buf.writestring("enum : ");
1635 determineEnumType(memberType).accept(this);
1636 buf.writestring(" { ");
1637 writeIdentifier(m, true);
1638 buf.writestring(" = ");
1640 auto ie = cast(AST.IntegerExp)m.value;
1641 visitInteger(ie.toInteger(), memberType);
1642 buf.writestring(" };");
1644 else
1646 buf.writestring("static ");
1647 auto target = determineEnumType(memberType);
1648 target.accept(this);
1649 buf.writestring(" const ");
1650 writeIdentifier(m, true);
1651 buf.writestring(" = ");
1652 printExpressionFor(target, m.origValue);
1653 buf.writestring(";");
1655 buf.writenl();
1658 if (!manifestConstants)
1659 buf.level--;
1660 // write the enum tail
1661 if (!manifestConstants)
1662 buf.writestring("};");
1663 buf.writenl();
1664 buf.writenl();
1667 override void visit(AST.EnumMember em)
1669 assert(em.ed);
1671 // Members of anonymous members are reachable without referencing the
1672 // EnumDeclaration, e.g. public import foo : someEnumMember;
1673 if (em.ed.isAnonymous())
1675 visit(em.ed);
1676 return;
1679 assert(false, "This node type should be handled in the EnumDeclaration");
1682 override void visit(AST.TupleDeclaration tup)
1684 debug (Debug_DtoH) mixin(traceVisit!tup);
1686 tup.foreachVar((s) { s.accept(this); });
1690 * Prints a member/parameter/variable declaration into `buf`.
1692 * Params:
1693 * t = the type (used if `this.origType` is null)
1694 * s = the symbol denoting the identifier
1695 * canFixup = whether the identifier may be changed without affecting
1696 * binary compatibility (forwarded to `writeIdentifier`)
1698 private void typeToBuffer(AST.Type t, AST.Dsymbol s, const bool canFixup = false)
1700 debug (Debug_DtoH)
1702 printf("[typeToBuffer(AST.Type, AST.Dsymbol) enter] %s sym %s\n", t.toChars(), s.toChars());
1703 scope(exit) printf("[typeToBuffer(AST.Type, AST.Dsymbol) exit] %s sym %s\n", t.toChars(), s.toChars());
1706 // The context pointer (represented as `ThisDeclaration`) is named
1707 // `this` but accessible via `outer`
1708 if (auto td = s.isThisDeclaration())
1710 import dmd.id;
1711 this.ident = Id.outer;
1713 else
1714 this.ident = s.ident;
1716 auto type = origType !is null ? origType : t;
1717 AST.Dsymbol customLength;
1719 // Check for quirks that are usually resolved during semantic
1720 if (tdparent)
1722 // Declarations within template declarations might use TypeAArray
1723 // instead of TypeSArray when the length is not an IntegerExp,
1724 // e.g. int[SOME_CONSTANT]
1725 if (auto taa = type.isTypeAArray())
1727 // Try to resolve the symbol from the key if it's not an actual type
1728 Identifier id;
1729 if (auto ti = taa.index.isTypeIdentifier())
1730 id = ti.ident;
1732 if (id)
1734 auto sym = findSymbol(id, adparent ? adparent : tdparent);
1735 if (!sym)
1737 // Couldn't resolve, assume actual AA
1739 else if (AST.isType(sym))
1741 // a real associative array, forward to visit
1743 else if (auto vd = sym.isVarDeclaration())
1745 // Actually a static array with length symbol
1746 customLength = sym;
1747 type = taa.next; // visit the element type, length is written below
1749 else
1751 printf("Resolved unexpected symbol while determining static array length: %s\n", sym.toChars());
1752 fflush(stdout);
1753 fatal();
1758 type.accept(this);
1759 if (this.ident)
1761 buf.writeByte(' ');
1762 // Custom identifier doesn't need further checks
1763 if (this.ident !is s.ident)
1764 buf.writestring(this.ident.toString());
1765 else
1766 writeIdentifier(s, canFixup);
1769 this.ident = null;
1771 // Size is either taken from the type or resolved above
1772 auto tsa = t.isTypeSArray();
1773 if (tsa || customLength)
1775 buf.writeByte('[');
1776 if (tsa)
1777 tsa.dim.accept(this);
1778 else
1779 writeFullName(customLength);
1780 buf.writeByte(']');
1782 else if (t.isTypeNoreturn())
1783 buf.writestring("[0]");
1786 override void visit(AST.Type t)
1788 debug (Debug_DtoH) mixin(traceVisit!t);
1789 printf("Invalid type: %s\n", t.toPrettyChars());
1790 assert(0);
1793 override void visit(AST.TypeNoreturn t)
1795 debug (Debug_DtoH) mixin(traceVisit!t);
1797 buf.writestring("/* noreturn */ char");
1800 override void visit(AST.TypeIdentifier t)
1802 debug (Debug_DtoH) mixin(traceVisit!t);
1804 // Try to resolve the referenced symbol
1805 if (auto sym = findSymbol(t.ident))
1806 ensureDeclared(outermostSymbol(sym));
1808 if (t.idents.length)
1809 buf.writestring("typename ");
1811 writeIdentifier(t.ident, t.loc, "type", tdparent !is null);
1813 foreach (arg; t.idents)
1815 buf.writestring("::");
1817 import dmd.rootobject;
1818 // Is this even possible?
1819 if (arg.dyncast != DYNCAST.identifier)
1821 printf("arg.dyncast() = %d\n", arg.dyncast());
1822 assert(false);
1824 buf.writestring((cast(Identifier) arg).toChars());
1828 override void visit(AST.TypeNull t)
1830 debug (Debug_DtoH) mixin(traceVisit!t);
1832 if (global.params.cplusplus >= CppStdRevision.cpp11)
1833 buf.writestring("nullptr_t");
1834 else
1835 buf.writestring("void*");
1839 override void visit(AST.TypeTypeof t)
1841 debug (Debug_DtoH) mixin(traceVisit!t);
1843 assert(t.exp);
1845 if (t.exp.type)
1847 t.exp.type.accept(this);
1849 else if (t.exp.isThisExp())
1851 // Short circuit typeof(this) => <Aggregate name>
1852 assert(adparent);
1853 buf.writestring(adparent.ident.toChars());
1855 else
1857 // Relying on C++'s typeof might produce wrong results
1858 // but it's the best we've got here.
1859 buf.writestring("typeof(");
1860 t.exp.accept(this);
1861 buf.writeByte(')');
1865 override void visit(AST.TypeBasic t)
1867 debug (Debug_DtoH) mixin(traceVisit!t);
1869 if (t.isConst() || t.isImmutable())
1870 buf.writestring("const ");
1871 string typeName;
1872 switch (t.ty)
1874 case AST.Tvoid: typeName = "void"; break;
1875 case AST.Tbool: typeName = "bool"; break;
1876 case AST.Tchar: typeName = "char"; break;
1877 case AST.Twchar: typeName = "char16_t"; break;
1878 case AST.Tdchar: typeName = "char32_t"; break;
1879 case AST.Tint8: typeName = "int8_t"; break;
1880 case AST.Tuns8: typeName = "uint8_t"; break;
1881 case AST.Tint16: typeName = "int16_t"; break;
1882 case AST.Tuns16: typeName = "uint16_t"; break;
1883 case AST.Tint32: typeName = "int32_t"; break;
1884 case AST.Tuns32: typeName = "uint32_t"; break;
1885 case AST.Tint64: typeName = "int64_t"; break;
1886 case AST.Tuns64: typeName = "uint64_t"; break;
1887 case AST.Tfloat32: typeName = "float"; break;
1888 case AST.Tfloat64: typeName = "double"; break;
1889 case AST.Tfloat80:
1890 typeName = "_d_real";
1891 hasReal = true;
1892 break;
1893 case AST.Tcomplex32: typeName = "_Complex float"; break;
1894 case AST.Tcomplex64: typeName = "_Complex double"; break;
1895 case AST.Tcomplex80:
1896 typeName = "_Complex _d_real";
1897 hasReal = true;
1898 break;
1899 // ???: This is not strictly correct, but it should be ignored
1900 // in all places where it matters most (variables, functions, ...).
1901 case AST.Timaginary32: typeName = "float"; break;
1902 case AST.Timaginary64: typeName = "double"; break;
1903 case AST.Timaginary80:
1904 typeName = "_d_real";
1905 hasReal = true;
1906 break;
1907 default:
1908 //t.print();
1909 assert(0);
1911 buf.writestring(typeName);
1914 override void visit(AST.TypePointer t)
1916 debug (Debug_DtoH) mixin(traceVisit!t);
1918 auto ts = t.next.isTypeStruct();
1919 if (ts && !strcmp(ts.sym.ident.toChars(), "__va_list_tag"))
1921 buf.writestring("va_list");
1922 return;
1925 // Pointer targets can be forward referenced
1926 const fwdSave = forwarding;
1927 forwarding = true;
1928 scope (exit) forwarding = fwdSave;
1930 t.next.accept(this);
1931 if (t.next.ty != AST.Tfunction)
1932 buf.writeByte('*');
1933 if (t.isConst() || t.isImmutable())
1934 buf.writestring(" const");
1937 override void visit(AST.TypeSArray t)
1939 debug (Debug_DtoH) mixin(traceVisit!t);
1940 t.next.accept(this);
1943 override void visit(AST.TypeAArray t)
1945 debug (Debug_DtoH) mixin(traceVisit!t);
1946 AST.Type.tvoidptr.accept(this);
1949 override void visit(AST.TypeFunction tf)
1951 debug (Debug_DtoH) mixin(traceVisit!tf);
1953 tf.next.accept(this);
1954 buf.writeByte('(');
1955 buf.writeByte('*');
1956 if (ident)
1957 buf.writestring(ident.toChars());
1958 ident = null;
1959 buf.writeByte(')');
1960 buf.writeByte('(');
1961 foreach (i, fparam; tf.parameterList)
1963 if (i)
1964 buf.writestring(", ");
1965 fparam.accept(this);
1967 if (tf.parameterList.varargs)
1969 if (tf.parameterList.parameters.length && tf.parameterList.varargs == 1)
1970 buf.writestring(", ");
1971 buf.writestring("...");
1973 buf.writeByte(')');
1976 /// Writes the type that represents `ed` into `buf`.
1977 /// (Might not be `ed` for special enums or enums that were emitted as namespaces)
1978 private void enumToBuffer(AST.EnumDeclaration ed)
1980 debug (Debug_DtoH) mixin(traceVisit!ed);
1982 if (ed.isSpecial())
1984 if (ed.ident == DMDType.c_long)
1985 buf.writestring("long");
1986 else if (ed.ident == DMDType.c_ulong)
1987 buf.writestring("unsigned long");
1988 else if (ed.ident == DMDType.c_longlong)
1989 buf.writestring("long long");
1990 else if (ed.ident == DMDType.c_ulonglong)
1991 buf.writestring("unsigned long long");
1992 else if (ed.ident == DMDType.c_long_double)
1993 buf.writestring("long double");
1994 else if (ed.ident == DMDType.c_char)
1995 buf.writestring("char");
1996 else if (ed.ident == DMDType.c_wchar_t)
1997 buf.writestring("wchar_t");
1998 else if (ed.ident == DMDType.c_complex_float)
1999 buf.writestring("_Complex float");
2000 else if (ed.ident == DMDType.c_complex_double)
2001 buf.writestring("_Complex double");
2002 else if (ed.ident == DMDType.c_complex_real)
2003 buf.writestring("_Complex long double");
2004 else
2006 //ed.print();
2007 assert(0);
2009 return;
2012 const kind = getEnumKind(ed.memtype);
2014 // Check if the enum was emitted as a real enum
2015 if (kind == EnumKind.Int || kind == EnumKind.Numeric)
2017 writeFullName(ed);
2019 else
2021 // Use the base type if the enum was emitted as a namespace
2022 buf.printf("/* %s */ ", ed.ident.toChars());
2023 ed.memtype.accept(this);
2027 override void visit(AST.TypeEnum t)
2029 debug (Debug_DtoH) mixin(traceVisit!t);
2031 if (t.isConst() || t.isImmutable())
2032 buf.writestring("const ");
2033 enumToBuffer(t.sym);
2036 override void visit(AST.TypeStruct t)
2038 debug (Debug_DtoH) mixin(traceVisit!t);
2040 if (t.isConst() || t.isImmutable())
2041 buf.writestring("const ");
2042 writeFullName(t.sym);
2045 override void visit(AST.TypeDArray t)
2047 debug (Debug_DtoH) mixin(traceVisit!t);
2049 if (t.isConst() || t.isImmutable())
2050 buf.writestring("const ");
2051 buf.writestring("_d_dynamicArray< ");
2052 t.next.accept(this);
2053 buf.writestring(" >");
2056 override void visit(AST.TypeInstance t)
2058 visitTi(t.tempinst);
2061 private void visitTi(AST.TemplateInstance ti)
2063 debug (Debug_DtoH) mixin(traceVisit!ti);
2065 // Ensure that the TD appears before the instance
2066 if (auto td = findTemplateDeclaration(ti))
2067 ensureDeclared(td);
2069 foreach (o; *ti.tiargs)
2071 if (!AST.isType(o))
2072 return;
2074 buf.writestring(ti.name.toChars());
2075 buf.writeByte('<');
2076 foreach (i, o; *ti.tiargs)
2078 if (i)
2079 buf.writestring(", ");
2080 if (auto tt = AST.isType(o))
2082 tt.accept(this);
2084 else
2086 //ti.print();
2087 //o.print();
2088 assert(0);
2091 buf.writestring(" >");
2094 override void visit(AST.TemplateDeclaration td)
2096 debug (Debug_DtoH) mixin(traceVisit!td);
2098 if (!shouldEmitAndMarkVisited(td))
2099 return;
2101 if (!td.parameters || !td.onemember || (!td.onemember.isStructDeclaration && !td.onemember.isClassDeclaration && !td.onemember.isFuncDeclaration))
2103 visit(cast(AST.Dsymbol)td);
2104 return;
2107 // Explicitly disallow templates with non-type parameters or specialization.
2108 foreach (p; *td.parameters)
2110 if (!p.isTemplateTypeParameter() || p.specialization())
2112 visit(cast(AST.Dsymbol)td);
2113 return;
2117 auto save = tdparent;
2118 tdparent = td;
2119 const bookmark = buf.length;
2120 printTemplateParams(td);
2122 const oldIgnored = this.ignoredCounter;
2123 td.onemember.accept(this);
2125 // Remove "template<...>" if the symbol could not be emitted
2126 if (oldIgnored != this.ignoredCounter)
2127 buf.setsize(bookmark);
2129 tdparent = save;
2132 /// Writes the template<...> header for the supplied template declaration
2133 private void printTemplateParams(const AST.TemplateDeclaration td)
2135 buf.writestring("template <");
2136 bool first = true;
2137 foreach (p; *td.parameters)
2139 if (first)
2140 first = false;
2141 else
2142 buf.writestring(", ");
2143 buf.writestring("typename ");
2144 writeIdentifier(p.ident, p.loc, "template parameter", true);
2146 buf.writestringln(">");
2149 /// Emit declarations of the TemplateMixin in the current scope
2150 override void visit(AST.TemplateMixin tm)
2152 debug (Debug_DtoH) mixin(traceVisit!tm);
2154 auto members = tm.members;
2156 // members are missing for instances inside of TemplateDeclarations, e.g.
2157 // template Foo(T) { mixin Bar!T; }
2158 if (!members)
2160 if (auto td = findTemplateDeclaration(tm))
2161 members = td.members; // Emit members of the template
2162 else
2163 return; // Cannot emit mixin
2166 foreach (s; *members)
2168 // kind is undefined without semantic
2169 const kind = s.visible().kind;
2170 if (kind == AST.Visibility.Kind.public_ || kind == AST.Visibility.Kind.undefined)
2171 s.accept(this);
2176 * Finds a symbol with the identifier `name` by iterating the linked list of parent
2177 * symbols, starting from `context`.
2179 * Returns: the symbol or `null` if missing
2181 private AST.Dsymbol findSymbol(Identifier name, AST.Dsymbol context)
2183 // Follow the declaration context
2184 for (auto par = context; par; par = par.toParentDecl())
2186 // Check that `name` doesn't refer to a template parameter
2187 if (auto td = par.isTemplateDeclaration())
2189 foreach (const p; *td.parameters)
2191 if (p.ident == name)
2192 return null;
2196 if (auto mem = findMember(par, name))
2198 return mem;
2201 return null;
2204 /// ditto
2205 private AST.Dsymbol findSymbol(Identifier name)
2207 AST.Dsymbol sym;
2208 if (adparent)
2209 sym = findSymbol(name, adparent);
2211 if (!sym && tdparent)
2212 sym = findSymbol(name, tdparent);
2214 return sym;
2217 /// Finds the template declaration for instance `ti`
2218 private AST.TemplateDeclaration findTemplateDeclaration(AST.TemplateInstance ti)
2220 if (ti.tempdecl)
2221 return ti.tempdecl.isTemplateDeclaration();
2223 assert(tdparent); // Only missing inside of templates
2225 // Search for the TemplateDeclaration, starting from the enclosing scope
2226 // if known or the enclosing template.
2227 auto sym = findSymbol(ti.name, ti.parent ? ti.parent : tdparent);
2228 return sym ? sym.isTemplateDeclaration() : null;
2231 override void visit(AST.TypeClass t)
2233 debug (Debug_DtoH) mixin(traceVisit!t);
2235 // Classes are emitted as pointer and hence can be forwarded
2236 const fwdSave = forwarding;
2237 forwarding = true;
2238 scope (exit) forwarding = fwdSave;
2240 if (t.isConst() || t.isImmutable())
2241 buf.writestring("const ");
2242 writeFullName(t.sym);
2243 buf.writeByte('*');
2244 if (t.isConst() || t.isImmutable())
2245 buf.writestring(" const");
2249 * Writes the function signature to `buf`.
2251 * Params:
2252 * fd = the function to print
2253 * tf = fd's type
2255 private void funcToBuffer(AST.TypeFunction tf, AST.FuncDeclaration fd)
2257 debug (Debug_DtoH)
2259 printf("[funcToBuffer(AST.TypeFunction) enter] %s\n", fd.toChars());
2260 scope(exit) printf("[funcToBuffer(AST.TypeFunction) exit] %s\n", fd.toChars());
2263 auto originalType = cast(AST.TypeFunction)fd.originalType;
2265 if (fd.isCtorDeclaration() || fd.isDtorDeclaration())
2267 if (fd.isDtorDeclaration())
2269 buf.writeByte('~');
2271 buf.writestring(adparent.toChars());
2272 if (!tf)
2274 assert(fd.isDtorDeclaration());
2275 buf.writestring("()");
2276 return;
2279 else
2281 import dmd.root.string : toDString;
2282 assert(tf.next, fd.loc.toChars().toDString());
2284 tf.next == AST.Type.tsize_t ? originalType.next.accept(this) : tf.next.accept(this);
2285 if (tf.isref)
2286 buf.writeByte('&');
2287 buf.writeByte(' ');
2288 writeIdentifier(fd);
2291 buf.writeByte('(');
2292 foreach (i, fparam; tf.parameterList)
2294 if (i)
2295 buf.writestring(", ");
2296 if (fparam.type == AST.Type.tsize_t && originalType)
2298 fparam = originalType.parameterList[i];
2300 fparam.accept(this);
2302 if (tf.parameterList.varargs)
2304 if (tf.parameterList.parameters.length && tf.parameterList.varargs == 1)
2305 buf.writestring(", ");
2306 buf.writestring("...");
2308 buf.writeByte(')');
2311 override void visit(AST.Parameter p)
2313 debug (Debug_DtoH) mixin(traceVisit!p);
2315 ident = p.ident;
2318 // Reference parameters can be forwarded
2319 const fwdStash = this.forwarding;
2320 this.forwarding = !!(p.storageClass & AST.STC.ref_);
2321 p.type.accept(this);
2322 this.forwarding = fwdStash;
2325 if (p.storageClass & (AST.STC.ref_ | AST.STC.out_))
2326 buf.writeByte('&');
2327 buf.writeByte(' ');
2328 if (ident)
2329 // FIXME: Parameter is missing a Loc
2330 writeIdentifier(ident, Loc.initial, "parameter", true);
2331 ident = null;
2333 if (p.defaultArg)
2335 //printf("%s %d\n", p.defaultArg.toChars, p.defaultArg.op);
2336 buf.writestring(" = ");
2337 // Always emit the FDN of a symbol for the default argument,
2338 // to avoid generating an ambiguous assignment.
2339 auto save = adparent;
2340 adparent = null;
2341 printExpressionFor(p.type, p.defaultArg);
2342 adparent = save;
2347 * Prints `exp` as an expression of type `target` while inserting
2348 * appropriate code when implicit conversion does not translate
2349 * directly to C++, e.g. from an enum to its base type.
2351 * Params:
2352 * target = the type `exp` is converted to
2353 * exp = the expression to print
2354 * isCtor = if `exp` is a ctor argument
2356 private void printExpressionFor(AST.Type target, AST.Expression exp, const bool isCtor = false)
2358 /// Determines if a static_cast is required
2359 static bool needsCast(AST.Type target, AST.Expression exp)
2361 // import std.stdio;
2362 // writefln("%s:%s: target = %s, type = %s (%s)", exp.loc.linnum, exp.loc.charnum, target, exp.type, exp.op);
2364 auto source = exp.type;
2366 // DotVarExp resolve conversions, e.g from an enum to its base type
2367 if (auto dve = exp.isDotVarExp())
2368 source = dve.var.type;
2370 if (!source)
2371 // Defensively assume that the cast is required
2372 return true;
2374 // Conversions from enum class to base type require static_cast
2375 if (global.params.cplusplus >= CppStdRevision.cpp11 &&
2376 source.isTypeEnum && !target.isTypeEnum)
2377 return true;
2379 return false;
2382 // Slices are emitted as a special struct, hence we need to fix up
2383 // any expression initialising a slice variable/member
2384 if (auto ta = target.isTypeDArray())
2386 if (exp.isNullExp())
2388 if (isCtor)
2390 // Don't emit, use default ctor
2392 else if (global.params.cplusplus >= CppStdRevision.cpp11)
2394 // Prefer initializer list
2395 buf.writestring("{}");
2397 else
2399 // Write __d_dynamic_array<TYPE>()
2400 visit(ta);
2401 buf.writestring("()");
2403 return;
2406 if (auto se = exp.isStringExp())
2408 // Rewrite as <length> + <literal> pair optionally
2409 // wrapped in a initializer list/ctor call
2411 const initList = global.params.cplusplus >= CppStdRevision.cpp11;
2412 if (!isCtor)
2414 if (initList)
2415 buf.writestring("{ ");
2416 else
2418 visit(ta);
2419 buf.writestring("( ");
2423 buf.printf("%zu, ", se.len);
2424 visit(se);
2426 if (!isCtor)
2427 buf.writestring(initList ? " }" : " )");
2429 return;
2432 else if (auto ce = exp.isCastExp())
2434 buf.writeByte('(');
2435 if (ce.to)
2436 ce.to.accept(this);
2437 else if (ce.e1.type)
2438 // Try the expression type with modifiers in case of cast(const) in templates
2439 ce.e1.type.castMod(ce.mod).accept(this);
2440 else
2441 // Fallback, not necessarily correct but the best we've got here
2442 target.accept(this);
2443 buf.writestring(") ");
2444 ce.e1.accept(this);
2446 else if (needsCast(target, exp))
2448 buf.writestring("static_cast<");
2449 target.accept(this);
2450 buf.writestring(">(");
2451 exp.accept(this);
2452 buf.writeByte(')');
2454 else
2456 exp.accept(this);
2460 override void visit(AST.Expression e)
2462 debug (Debug_DtoH) mixin(traceVisit!e);
2464 // Valid in most cases, others should be overridden below
2465 // to use the appropriate operators (:: and ->)
2466 buf.writestring(e.toString());
2469 override void visit(AST.UnaExp e)
2471 debug (Debug_DtoH) mixin(traceVisit!e);
2473 buf.writestring(expToString(e.op));
2474 e.e1.accept(this);
2477 override void visit(AST.BinExp e)
2479 debug (Debug_DtoH) mixin(traceVisit!e);
2481 e.e1.accept(this);
2482 buf.writeByte(' ');
2483 buf.writestring(expToString(e.op));
2484 buf.writeByte(' ');
2485 e.e2.accept(this);
2488 /// Translates operator `op` into the C++ representation
2489 private extern(D) static string expToString(const EXP op)
2491 switch (op) with (EXP)
2493 case identity: return "==";
2494 case notIdentity: return "!=";
2495 default:
2496 return EXPtoString(op);
2500 override void visit(AST.VarExp e)
2502 debug (Debug_DtoH) mixin(traceVisit!e);
2504 // Local members don't need another prefix and might've been renamed
2505 if (e.var.isThis())
2507 includeSymbol(e.var);
2508 writeIdentifier(e.var, true);
2510 else
2511 writeFullName(e.var);
2514 /// Partially prints the FQN including parent aggregates
2515 private void printPrefix(AST.Dsymbol var)
2517 if (!var || var is adparent || var.isModule())
2518 return;
2520 writeFullName(var);
2521 buf.writestring("::");
2524 override void visit(AST.CallExp e)
2526 debug (Debug_DtoH) mixin(traceVisit!e);
2528 // Dereferencing function pointers requires additional braces: (*f)(args)
2529 const isFp = e.e1.isPtrExp();
2530 if (isFp)
2531 buf.writeByte('(');
2532 else if (e.f)
2533 includeSymbol(outermostSymbol(e.f));
2535 e.e1.accept(this);
2537 if (isFp) buf.writeByte(')');
2539 assert(e.arguments);
2540 buf.writeByte('(');
2541 foreach (i, arg; *e.arguments)
2543 if (i)
2544 buf.writestring(", ");
2545 arg.accept(this);
2547 buf.writeByte(')');
2550 override void visit(AST.DotVarExp e)
2552 debug (Debug_DtoH) mixin(traceVisit!e);
2554 if (auto sym = symbolFromType(e.e1.type))
2555 includeSymbol(outermostSymbol(sym));
2557 // Accessing members through a pointer?
2558 if (auto pe = e.e1.isPtrExp)
2560 pe.e1.accept(this);
2561 buf.writestring("->");
2563 else
2565 e.e1.accept(this);
2566 buf.writeByte('.');
2569 // Should only be used to access non-static members
2570 assert(e.var.isThis());
2572 writeIdentifier(e.var, true);
2575 override void visit(AST.DotIdExp e)
2577 debug (Debug_DtoH) mixin(traceVisit!e);
2579 e.e1.accept(this);
2580 buf.writestring("::");
2581 buf.writestring(e.ident.toChars());
2584 override void visit(AST.ScopeExp e)
2586 debug (Debug_DtoH) mixin(traceVisit!e);
2588 // Usually a template instance in a TemplateDeclaration
2589 if (auto ti = e.sds.isTemplateInstance())
2590 visitTi(ti);
2591 else
2592 writeFullName(e.sds);
2595 override void visit(AST.NullExp e)
2597 debug (Debug_DtoH) mixin(traceVisit!e);
2599 if (global.params.cplusplus >= CppStdRevision.cpp11)
2600 buf.writestring("nullptr");
2601 else
2602 buf.writestring("NULL");
2605 override void visit(AST.ArrayLiteralExp e)
2607 debug (Debug_DtoH) mixin(traceVisit!e);
2608 buf.writestring("arrayliteral");
2611 override void visit(AST.StringExp e)
2613 debug (Debug_DtoH) mixin(traceVisit!e);
2615 if (e.sz == 2)
2616 buf.writeByte('u');
2617 else if (e.sz == 4)
2618 buf.writeByte('U');
2619 buf.writeByte('"');
2621 foreach (i; 0 .. e.len)
2623 writeCharLiteral(*buf, e.getCodeUnit(i));
2625 buf.writeByte('"');
2628 override void visit(AST.RealExp e)
2630 debug (Debug_DtoH) mixin(traceVisit!e);
2632 import dmd.root.ctfloat : CTFloat;
2634 // Special case NaN and Infinity because floatToBuffer
2635 // uses D literals (`nan` and `infinity`)
2636 if (CTFloat.isNaN(e.value))
2638 buf.writestring("NAN");
2640 else if (CTFloat.isInfinity(e.value))
2642 if (e.value < CTFloat.zero)
2643 buf.writeByte('-');
2644 buf.writestring("INFINITY");
2646 else
2648 import dmd.hdrgen;
2649 // Hex floating point literals were introduced in C++ 17
2650 const allowHex = global.params.cplusplus >= CppStdRevision.cpp17;
2651 floatToBuffer(e.type, e.value, *buf, allowHex);
2655 override void visit(AST.IntegerExp e)
2657 debug (Debug_DtoH) mixin(traceVisit!e);
2658 visitInteger(e.toInteger, e.type);
2661 /// Writes `v` as type `t` into `buf`
2662 private void visitInteger(dinteger_t v, AST.Type t)
2664 debug (Debug_DtoH) mixin(traceVisit!t);
2666 switch (t.ty)
2668 case AST.Tenum:
2669 auto te = cast(AST.TypeEnum)t;
2670 buf.writestring("(");
2671 enumToBuffer(te.sym);
2672 buf.writestring(")");
2673 visitInteger(v, te.sym.memtype);
2674 break;
2675 case AST.Tbool:
2676 buf.writestring(v ? "true" : "false");
2677 break;
2678 case AST.Tint8:
2679 buf.printf("%d", cast(byte)v);
2680 break;
2681 case AST.Tuns8:
2682 buf.printf("%uu", cast(ubyte)v);
2683 break;
2684 case AST.Tint16:
2685 buf.printf("%d", cast(short)v);
2686 break;
2687 case AST.Tuns16:
2688 case AST.Twchar:
2689 buf.printf("%uu", cast(ushort)v);
2690 break;
2691 case AST.Tint32:
2692 case AST.Tdchar:
2693 buf.printf("%d", cast(int)v);
2694 break;
2695 case AST.Tuns32:
2696 buf.printf("%uu", cast(uint)v);
2697 break;
2698 case AST.Tint64:
2699 buf.printf("%lldLL", v);
2700 break;
2701 case AST.Tuns64:
2702 buf.printf("%lluLLU", v);
2703 break;
2704 case AST.Tchar:
2705 if (v > 0x20 && v < 0x80)
2706 buf.printf("'%c'", cast(int)v);
2707 else
2708 buf.printf("%uu", cast(ubyte)v);
2709 break;
2710 default:
2711 //t.print();
2712 assert(0);
2716 override void visit(AST.StructLiteralExp sle)
2718 debug (Debug_DtoH) mixin(traceVisit!sle);
2720 const isUnion = sle.sd.isUnionDeclaration();
2721 sle.sd.type.accept(this);
2722 buf.writeByte('(');
2723 foreach(i, e; *sle.elements)
2725 if (i)
2726 buf.writestring(", ");
2728 auto vd = sle.sd.fields[i];
2730 // Expression may be null for unspecified elements
2731 if (!e)
2732 e = findDefaultInitializer(vd);
2734 printExpressionFor(vd.type, e);
2736 // Only emit the initializer of the first union member
2737 if (isUnion)
2738 break;
2740 buf.writeByte(')');
2743 /// Finds the default initializer for the given VarDeclaration
2744 private static AST.Expression findDefaultInitializer(AST.VarDeclaration vd)
2746 if (vd._init && !vd._init.isVoidInitializer())
2747 return AST.initializerToExpression(vd._init);
2748 else if (auto ts = vd.type.isTypeStruct())
2750 if (!ts.sym.noDefaultCtor && !ts.sym.isUnionDeclaration())
2752 // Generate a call to the default constructor that we've generated.
2753 auto sle = new AST.StructLiteralExp(Loc.initial, ts.sym, new AST.Expressions(0));
2754 sle.type = vd.type;
2755 return sle;
2757 else
2758 return vd.type.defaultInitLiteral(Loc.initial);
2760 else
2761 return vd.type.defaultInitLiteral(Loc.initial);
2764 static if (__VERSION__ < 2092)
2766 private void ignored(const char* format, ...) nothrow
2768 this.ignoredCounter++;
2770 import core.stdc.stdarg;
2771 if (!printIgnored)
2772 return;
2774 va_list ap;
2775 va_start(ap, format);
2776 buf.writestring("// Ignored ");
2777 buf.vprintf(format, ap);
2778 buf.writenl();
2779 va_end(ap);
2782 else
2784 /// Writes a formatted message into `buf` if `printIgnored` is true
2785 /// and increments `ignoredCounter`
2786 pragma(printf)
2787 private void ignored(const char* format, ...) nothrow
2789 this.ignoredCounter++;
2791 import core.stdc.stdarg;
2792 if (!printIgnored)
2793 return;
2795 va_list ap;
2796 va_start(ap, format);
2797 buf.writestring("// Ignored ");
2798 buf.vprintf(format, ap);
2799 buf.writenl();
2800 va_end(ap);
2805 * Determines whether `s` should be emitted. This requires that `sym`
2806 * - is `extern(C[++]`)
2807 * - is not instantiated from a template (visits the `TemplateDeclaration` instead)
2809 * Params:
2810 * sym = the symbol
2812 * Returns: whether `sym` should be emitted
2814 private bool shouldEmit(AST.Dsymbol sym)
2816 import dmd.aggregate : ClassKind;
2817 debug (Debug_DtoH)
2819 printf("[shouldEmitAndMarkVisited enter] %s\n", sym.toPrettyChars());
2820 scope(exit) printf("[shouldEmitAndMarkVisited exit] %s\n", sym.toPrettyChars());
2823 // Template *instances* should not be emitted
2824 if (sym.isInstantiated())
2825 return false;
2827 // Matching linkage (except extern(C) classes which don't make sense)
2828 if (linkage == LINK.cpp || (linkage == LINK.c && !sym.isClassDeclaration()))
2829 return true;
2831 // Check against the internal information which might be missing, e.g. inside of template declarations
2832 if (auto dec = sym.isDeclaration())
2834 const l = dec.resolvedLinkage();
2835 return l == LINK.cpp || l == LINK.c;
2838 if (auto ad = sym.isAggregateDeclaration())
2839 return ad.classKind == ClassKind.cpp;
2841 return false;
2845 * Determines whether `s` should be emitted. This requires that `sym`
2846 * - was not visited before
2847 * - is `extern(C[++]`)
2848 * - is not instantiated from a template (visits the `TemplateDeclaration` instead)
2849 * The result is cached in the visited nodes array.
2851 * Params:
2852 * sym = the symbol
2854 * Returns: whether `sym` should be emitted
2856 private bool shouldEmitAndMarkVisited(AST.Dsymbol sym)
2858 debug (Debug_DtoH)
2860 printf("[shouldEmitAndMarkVisited enter] %s\n", sym.toPrettyChars());
2861 scope(exit) printf("[shouldEmitAndMarkVisited exit] %s\n", sym.toPrettyChars());
2864 auto statePtr = (cast(void*) sym) in visited;
2866 // `sym` was already emitted or skipped and isn't required
2867 if (statePtr && (*statePtr || !mustEmit))
2868 return false;
2870 // Template *instances* should not be emitted, forward to the declaration
2871 if (auto ti = sym.isInstantiated())
2873 auto td = findTemplateDeclaration(ti);
2874 assert(td);
2875 visit(td);
2876 return false;
2879 // Required or matching linkage (except extern(C) classes which don't make sense)
2880 bool res = mustEmit || linkage == LINK.cpp || (linkage == LINK.c && !sym.isClassDeclaration());
2881 if (!res)
2883 // Check against the internal information which might be missing, e.g. inside of template declarations
2884 if (auto dec = sym.isDeclaration())
2886 const l = dec.resolvedLinkage();
2887 res = (l == LINK.cpp || l == LINK.c);
2891 // Remember result for later calls
2892 if (statePtr)
2893 *statePtr = res;
2894 else
2895 visited[(cast(void*) sym)] = res;
2897 // Print a warning when the symbol is ignored for the first time
2898 // Might not be correct if it is required by symbol the is visited
2899 // AFTER the current node
2900 if (!statePtr && !res)
2901 ignored("%s %s because of linkage", sym.kind(), sym.toPrettyChars());
2903 return res;
2907 * Ensures that `sym` is declared before the current position in `buf` by
2908 * either creating a forward reference in `fwdbuf` if possible or
2909 * calling `includeSymbol` to emit the entire declaration into `donebuf`.
2911 private void ensureDeclared(AST.Dsymbol sym)
2913 auto par = sym.toParent2();
2914 auto ed = sym.isEnumDeclaration();
2916 // Eagerly include the symbol if we cannot create a valid forward declaration
2917 // Forwarding of scoped enums requires C++11 or above
2918 if (!forwarding || (par && !par.isModule()) || (ed && global.params.cplusplus < CppStdRevision.cpp11))
2920 // Emit the entire enclosing declaration if any
2921 includeSymbol(outermostSymbol(sym));
2922 return;
2925 auto ti = sym.isInstantiated();
2926 auto td = ti ? findTemplateDeclaration(ti) : null;
2927 auto check = cast(void*) (td ? td : sym);
2929 // Omit redundant fwd-declaration if we already emitted the entire declaration
2930 if (visited.get(check, false))
2931 return;
2933 // Already created a fwd-declaration?
2934 if (check in forwarded)
2935 return;
2936 forwarded[check] = true;
2938 // Print template<...>
2939 if (ti)
2941 auto bufSave = buf;
2942 buf = fwdbuf;
2943 printTemplateParams(td);
2944 buf = bufSave;
2947 // Determine the kind of symbol that is forwared: struct, ...
2948 const(char)* kind;
2950 if (auto ad = sym.isAggregateDeclaration())
2952 // Look for extern(C++, class) <some aggregate>
2953 if (ad.cppmangle == CPPMANGLE.def)
2954 kind = ad.kind();
2955 else if (ad.cppmangle == CPPMANGLE.asStruct)
2956 kind = "struct";
2957 else
2958 kind = "class";
2960 else if (ed)
2962 // Only called from enumToBuffer, so should always be emitted as an actual enum
2963 kind = "enum class";
2965 else
2966 kind = sym.kind(); // Should be unreachable but just to be sure
2968 fwdbuf.writestring(kind);
2969 fwdbuf.writeByte(' ');
2970 fwdbuf.writestring(sym.toChars());
2971 fwdbuf.writestringln(";");
2975 * Writes the qualified name of `sym` into `buf` including parent
2976 * symbols and template parameters.
2978 * Params:
2979 * sym = the symbol
2980 * mustInclude = whether sym may not be forward declared
2982 private void writeFullName(AST.Dsymbol sym, const bool mustInclude = false)
2985 assert(sym);
2986 assert(sym.ident, sym.toString());
2987 // Should never be called directly with a TI, only onemember
2988 assert(!sym.isTemplateInstance(), sym.toString());
2992 debug (Debug_DtoH)
2994 printf("[writeFullName enter] %s\n", sym.toPrettyChars());
2995 scope(exit) printf("[writeFullName exit] %s\n", sym.toPrettyChars());
2998 // Explicit `pragma(mangle, "<some string>` overrides the declared name
2999 if (auto mn = getMangleOverride(sym))
3000 return buf.writestring(mn);
3002 /// Checks whether `sym` is nested in `par` and hence doesn't need the FQN
3003 static bool isNestedIn(AST.Dsymbol sym, AST.Dsymbol par)
3005 while (par)
3007 if (sym is par)
3008 return true;
3009 par = par.toParent();
3011 return false;
3013 AST.TemplateInstance ti;
3014 bool nested;
3016 // Check if the `sym` is nested into another symbol and hence requires `Parent::sym`
3017 if (auto par = sym.toParent())
3019 // toParent() yields the template instance if `sym` is the onemember of a TI
3020 ti = par.isTemplateInstance();
3022 // Skip the TI because Foo!int.Foo is folded into Foo<int>
3023 if (ti) par = ti.toParent();
3025 // Prefix the name with any enclosing declaration
3026 // Stop at either module or enclosing aggregate
3027 nested = !par.isModule();
3028 if (nested && !isNestedIn(par, adparent))
3030 writeFullName(par, true);
3031 buf.writestring("::");
3035 if (!nested)
3037 // Cannot forward the symbol when called recursively
3038 // for a nested symbol
3039 if (mustInclude)
3040 includeSymbol(sym);
3041 else
3042 ensureDeclared(sym);
3045 if (ti)
3046 visitTi(ti);
3047 else
3048 buf.writestring(sym.ident.toString());
3051 /// Returns: Explicit mangling for `sym` if present
3052 extern(D) static const(char)[] getMangleOverride(const AST.Dsymbol sym) @safe
3054 if (auto decl = sym.isDeclaration())
3055 return decl.mangleOverride;
3057 return null;
3061 /// Namespace for identifiers used to represent special enums in C++
3062 struct DMDType
3064 __gshared Identifier c_long;
3065 __gshared Identifier c_ulong;
3066 __gshared Identifier c_longlong;
3067 __gshared Identifier c_ulonglong;
3068 __gshared Identifier c_long_double;
3069 __gshared Identifier c_char;
3070 __gshared Identifier c_wchar_t;
3071 __gshared Identifier c_complex_float;
3072 __gshared Identifier c_complex_double;
3073 __gshared Identifier c_complex_real;
3075 static void _init()
3077 c_long = Identifier.idPool("__c_long");
3078 c_ulong = Identifier.idPool("__c_ulong");
3079 c_longlong = Identifier.idPool("__c_longlong");
3080 c_ulonglong = Identifier.idPool("__c_ulonglong");
3081 c_long_double = Identifier.idPool("__c_long_double");
3082 c_wchar_t = Identifier.idPool("__c_wchar_t");
3083 c_char = Identifier.idPool("__c_char");
3084 c_complex_float = Identifier.idPool("__c_complex_float");
3085 c_complex_double = Identifier.idPool("__c_complex_double");
3086 c_complex_real = Identifier.idPool("__c_complex_real");
3090 /// Initializes all data structures used by the header generator
3091 void initialize()
3093 __gshared bool initialized;
3095 if (!initialized)
3097 initialized = true;
3099 DMDType._init();
3103 /// Writes `#if <content>` into the supplied buffer
3104 void hashIf(ref OutBuffer buf, string content) @safe
3106 buf.writestring("#if ");
3107 buf.writestringln(content);
3110 /// Writes `#elif <content>` into the supplied buffer
3111 void hashElIf(ref OutBuffer buf, string content) @safe
3113 buf.writestring("#elif ");
3114 buf.writestringln(content);
3117 /// Writes `#endif` into the supplied buffer
3118 void hashEndIf(ref OutBuffer buf) @safe
3120 buf.writestringln("#endif");
3123 /// Writes `#define <content>` into the supplied buffer
3124 void hashDefine(ref OutBuffer buf, string content) @safe
3126 buf.writestring("#define ");
3127 buf.writestringln(content);
3130 /// Writes `#include <content>` into the supplied buffer
3131 void hashInclude(ref OutBuffer buf, string content) @safe
3133 buf.writestring("#include ");
3134 buf.writestringln(content);
3137 /// Determines whether `ident` is a reserved keyword in C++
3138 /// Returns: the kind of keyword or `null`
3139 const(char*) keywordClass(const Identifier ident)
3141 if (!ident)
3142 return null;
3144 const name = ident.toString();
3145 switch (name)
3147 // C++ operators
3148 case "and":
3149 case "and_eq":
3150 case "bitand":
3151 case "bitor":
3152 case "compl":
3153 case "not":
3154 case "not_eq":
3155 case "or":
3156 case "or_eq":
3157 case "xor":
3158 case "xor_eq":
3159 return "special operator in C++";
3161 // C++ keywords
3162 case "_Complex":
3163 case "const_cast":
3164 case "delete":
3165 case "dynamic_cast":
3166 case "explicit":
3167 case "friend":
3168 case "inline":
3169 case "mutable":
3170 case "namespace":
3171 case "operator":
3172 case "register":
3173 case "reinterpret_cast":
3174 case "signed":
3175 case "static_cast":
3176 case "typedef":
3177 case "typename":
3178 case "unsigned":
3179 case "using":
3180 case "virtual":
3181 case "volatile":
3182 return "keyword in C++";
3184 // Common macros imported by this header
3185 // stddef.h
3186 case "offsetof":
3187 case "NULL":
3188 return "default macro in C++";
3190 // C++11 keywords
3191 case "alignas":
3192 case "alignof":
3193 case "char16_t":
3194 case "char32_t":
3195 case "constexpr":
3196 case "decltype":
3197 case "noexcept":
3198 case "nullptr":
3199 case "static_assert":
3200 case "thread_local":
3201 case "wchar_t":
3202 if (global.params.cplusplus >= CppStdRevision.cpp11)
3203 return "keyword in C++11";
3204 return null;
3206 // C++20 keywords
3207 case "char8_t":
3208 case "consteval":
3209 case "constinit":
3210 // Concepts-related keywords
3211 case "concept":
3212 case "requires":
3213 // Coroutines-related keywords
3214 case "co_await":
3215 case "co_yield":
3216 case "co_return":
3217 if (global.params.cplusplus >= CppStdRevision.cpp20)
3218 return "keyword in C++20";
3219 return null;
3220 case "restrict":
3221 case "_Alignas":
3222 case "_Alignof":
3223 case "_Atomic":
3224 case "_Bool":
3225 //case "_Complex": // handled above in C++
3226 case "_Generic":
3227 case "_Imaginary":
3228 case "_Noreturn":
3229 case "_Static_assert":
3230 case "_Thread_local":
3231 case "_assert":
3232 case "_import":
3233 //case "__...": handled in default case below
3234 return "Keyword in C";
3236 default:
3237 // Identifiers starting with __ are reserved
3238 if (name.length >= 2 && name[0..2] == "__")
3239 return "reserved identifier in C++";
3241 return null;
3245 /// Finds the outermost symbol if `sym` is nested.
3246 /// Returns `sym` if it appears at module scope
3247 ASTCodegen.Dsymbol outermostSymbol(ASTCodegen.Dsymbol sym)
3249 assert(sym);
3250 while (true)
3252 auto par = sym.toParent();
3253 if (!par || par.isModule())
3254 return sym;
3255 sym = par;
3259 /// Fetches the symbol for user-defined types from the type `t`
3260 /// if `t` is either `TypeClass`, `TypeStruct` or `TypeEnum`
3261 ASTCodegen.Dsymbol symbolFromType(ASTCodegen.Type t) @safe
3263 if (auto tc = t.isTypeClass())
3264 return tc.sym;
3265 if (auto ts = t.isTypeStruct())
3266 return ts.sym;
3267 if (auto te = t.isTypeEnum())
3268 return te.sym;
3269 return null;
3273 * Searches `sym` for a member with the given name.
3275 * This method usually delegates to `Dsymbol.search` but might also
3276 * manually check the members if the symbol did not receive semantic
3277 * analysis.
3279 * Params:
3280 * sym = symbol to search
3281 * name = identifier of the requested symbol
3283 * Returns: the symbol or `null` if not found
3285 ASTCodegen.Dsymbol findMember(ASTCodegen.Dsymbol sym, Identifier name)
3287 if (auto mem = sym.search(Loc.initial, name, ASTCodegen.SearchOpt.ignoreErrors))
3288 return mem;
3290 // search doesn't work for declarations inside of uninstantiated
3291 // `TemplateDeclaration`s due to the missing symtab.
3292 if (sym.semanticRun >= ASTCodegen.PASS.semanticdone)
3293 return null;
3295 // Manually check the members if present
3296 auto sds = sym.isScopeDsymbol();
3297 if (!sds || !sds.members)
3298 return null;
3300 /// Recursively searches for `name` without entering nested aggregates, ...
3301 static ASTCodegen.Dsymbol search(ASTCodegen.Dsymbols* members, Identifier name)
3303 foreach (mem; *members)
3305 if (mem.ident == name)
3306 return mem;
3308 // Look inside of private:, ...
3309 if (auto ad = mem.isAttribDeclaration())
3311 if (auto s = search(ad.decl, name))
3312 return s;
3315 return null;
3318 return search(sds.members, name);
3321 debug (Debug_DtoH)
3323 /// Generates code to trace the entry and exit of the enclosing `visit` function
3324 string traceVisit(alias node)()
3326 const type = typeof(node).stringof;
3327 const method = __traits(hasMember, node, "toPrettyChars") ? "toPrettyChars" : "toChars";
3328 const arg = __traits(identifier, node) ~ '.' ~ method;
3330 return `printf("[` ~ type ~ ` enter] %s\n", ` ~ arg ~ `());
3331 scope(exit) printf("[` ~ type ~ ` exit] %s\n", ` ~ arg ~ `());`;